repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
BrandonYates/sherlock | Java/src/test/java/clue/knowledge/KnowledgeTest.java | 1376 | package clue.knowledge;
import clue.logic.Card;
import clue.logic.CardName;
import clue.logic.Character;
import clue.logic.Game;
import clue.logic.Player;
import clue.logic.Room;
import clue.logic.Weapon;
import org.junit.Assert;
import org.junit.Before;
import org.junit.jupiter.api.Test;
import java.util.ArrayList;
import java.util.List;
public class KnowledgeTest {
@Before
public void setup() {
ownPlayer1 = new Player("Own Player 1");
otherPlayers1 = new ArrayList<>();
for(int i = 0; i < 4; ++i) {
otherPlayers1.add(new Player("Other Player " + i));
}
testDeck1 = new ArrayList<>();
for(Character.Name name: Character.Name.values()) {
testDeck1.add(new Character(name));
}
for(Room.Name name : Room.Name.values()) {
testDeck1.add(new Room(name));
}
for(Weapon.Name name: Weapon.Name.values()) {
testDeck1.add(new Weapon(name));
}
}
@Test
public void TestMcTest() {
System.out.println("TestMcTest");
Assert.assertTrue(true);
Assert.assertFalse(false);
}
private Player ownPlayer1;
private List<Player> otherPlayers1;
private List<Card> testDeck1;
private Character solutionCharacter1 = new Character(Character.Name.MRGREEN);
private Room solutionRoom1 = new Room(Room.Name.LOUNGE);
private Weapon SolutionWeapon1 = new Weapon(Weapon.Name.REVOLVER);
} | gpl-3.0 |
solefaucet/jackpot-server | wallet.go | 6952 | package main
import (
"time"
"github.com/Sirupsen/logrus"
"github.com/solefaucet/jackpot-server/jerrors"
"github.com/solefaucet/jackpot-server/models"
w "github.com/solefaucet/jackpot-server/services/wallet"
"github.com/solefaucet/jackpot-server/utils"
)
var (
blockHeightChan = make(chan int64, 2)
previousBlockCreatedAt = time.Time{}
)
func initWork() {
go fetchBlocksJob()
go updateConfirmationsJob()
go drawGamesJob()
// get latest block from db
block, err := storage.GetLatestBlock()
if err == jerrors.ErrNotFound {
blockHeightChan <- -1
return
}
if err != nil {
logger.Panicf("fail to get latest block from database: %#v\n", err)
return
}
previousBlockCreatedAt = block.BlockCreatedAt
blockHeightChan <- block.Height + 1
}
func fetchBlocksJob() {
for {
height := <-blockHeightChan
fetchBlocks(height)
}
}
func updateConfirmationsJob() {
for {
updateConfirmations()
time.Sleep(time.Minute)
}
}
func drawGamesJob() {
for {
drawGames()
time.Sleep(time.Minute)
}
}
func fetchBlocks(height int64) {
var err error
defer func() {
if err != nil {
time.Sleep(5 * time.Second)
}
blockHeightChan <- height
}()
entry := logrus.WithFields(logrus.Fields{
"event": models.LogEventSaveBlockAndTransactions,
"block_height": height,
})
// get new block from blockchain
bestBlock := height < 0
block, err := wallet.GetBlock(bestBlock, height)
if err == jerrors.ErrNoNewBlock {
entry.Info("no new block ahead")
return
}
if err != nil {
entry.WithField("error", err.Error()).Error("fail to get block from blockchain")
return
}
gameOf := block.BlockCreatedAt.Truncate(config.Jackpot.Duration)
entry.WithFields(logrus.Fields{
"previous_hash": block.PrevHash,
"height": block.Height,
"game_of": gameOf,
})
// get receive transactions
transactions, err := wallet.GetReceivedSince(block.PrevHash, block.Hash)
if err != nil {
entry.WithField("error", err.Error()).Error("fail to list transactions from blockchain")
return
}
// check if it's time to find out the winner
previousGameOf := previousBlockCreatedAt.Truncate(config.Jackpot.Duration)
var updatedGame *models.Game
if previousGameOf.Add(config.Jackpot.Duration).Equal(gameOf) {
updatedGame = &models.Game{
Hash: block.Hash,
Height: block.Height,
GameOf: previousGameOf,
}
}
// save block, transactions
if err := storage.SaveBlockAndTransactions(
gameOf,
walletBlockToModelBlock(block),
walletTxsToModelTxs(gameOf, transactions),
updatedGame,
); err != nil {
entry.WithField("error", err.Error()).Error("fail to save block and transactions to db")
return
}
entry.Info("save block and transactions successfully")
height = block.Height + 1
previousBlockCreatedAt = block.BlockCreatedAt
}
func walletTxsToModelTxs(gameOf time.Time, txs []w.Transaction) []models.Transaction {
transactions := make([]models.Transaction, len(txs))
for i, v := range txs {
transactions[i] = models.Transaction{
Address: v.Address,
Amount: v.Amount,
TransactionID: v.TransactionID,
Hash: v.Hash,
Confirmations: v.Confirmations,
GameOf: gameOf,
BlockCreatedAt: v.BlockCreatedAt,
}
}
return transactions
}
func walletBlockToModelBlock(blockchainBlock *w.Block) models.Block {
return models.Block{
Hash: blockchainBlock.Hash,
Height: blockchainBlock.Height,
BlockCreatedAt: blockchainBlock.BlockCreatedAt,
}
}
func updateConfirmations() {
minConfirmations := config.Wallet.MinConfirms
entry := logrus.WithFields(logrus.Fields{
"event": models.LogEventUpdateConfirmations,
"min_confirmations": minConfirmations,
})
transactions, err := storage.GetUnconfirmedTransactions(minConfirmations)
if err != nil {
entry.WithField("error", err.Error()).Error("fail to get unconfirmed transactions")
return
}
for _, transaction := range transactions {
confirmations, err := wallet.GetConfirmationsFromTxID(transaction.TransactionID)
if err != nil {
entry.WithFields(logrus.Fields{
"error": err.Error(),
"tx_id": transaction.TransactionID,
}).Error("fail to get confirmations by tx id")
return
}
if err := storage.UpdateTransactionConfirmationByID(transaction.ID, confirmations); err != nil {
entry.WithFields(logrus.Fields{
"error": err.Error(),
"tx_id": transaction.TransactionID,
}).Error("fail to update transaction confirmation")
return
}
}
}
func drawGames() {
entry := logrus.WithFields(logrus.Fields{
"event": models.LogEventDrawGames,
})
games, err := storage.GetDrawingNeededGames()
if err != nil {
entry.WithField("error", err.Error()).Error("fail to get drawing needed games")
return
}
for _, game := range games {
transactions, err := storage.GetTransactionsByGameOfs(game.GameOf)
if err != nil {
entry.WithFields(logrus.Fields{
"error": err.Error(),
"game_of": game.GameOf,
}).Error("fail to get transactions by game_of")
return
}
if !allTransactionsConfirmed(transactions) {
continue
}
winnerAddress, transactionID, winAmount, fee, err := findWinnerAndSendCoins(game.GameOf, game.Hash)
if err != nil {
entry.WithFields(logrus.Fields{
"game_of": game.GameOf,
"hash": game.Hash,
"error": err.Error(),
}).Error("fail to find winner and send coins")
return
}
g := models.Game{
Address: winnerAddress,
WinAmount: winAmount,
Fee: fee,
TransactionID: transactionID,
GameOf: game.GameOf,
}
if err := storage.UpdateGameToEndedStatus(g); err != nil {
entry.WithFields(logrus.Fields{
"winner_address": winnerAddress,
"win_amount": winAmount,
"fee": fee,
"tx_id": transactionID,
"game_of": game.GameOf,
}).Panic("fail to update game status to ended")
return
}
}
}
func allTransactionsConfirmed(transactions []models.Transaction) bool {
for _, transaction := range transactions {
if config.Wallet.MinConfirms > transaction.Confirmations {
return false
}
}
return true
}
func findWinnerAndSendCoins(gameOf time.Time, hash string) (winnerAddress, transactionID string, winAmount, fee float64, err error) {
transactions, err := storage.GetTransactionsByGameOfs(gameOf)
if err != nil {
return
}
// no transactions, no winner
if len(transactions) == 0 {
return
}
totalAmount := totalAmountOfTransactions(transactions)
fee = totalAmount * config.Jackpot.TransactionFee
winAmount = totalAmount - fee
winnerAddress = utils.FindWinner(transactions, hash)
transactionID, err = wallet.SendFromAccountToAddress(config.Wallet.SentFromAccount, winnerAddress, winAmount)
if err != nil {
return
}
return
}
func totalAmountOfTransactions(transactions []models.Transaction) float64 {
totalAmount := 0.0
for _, tx := range transactions {
totalAmount += tx.Amount
}
return totalAmount
}
| gpl-3.0 |
nbouteme/mmpd | assets/js/events.js | 1200 | function initInterface() {
$("#time-slider").slider({
change: setTime,
range: "min",
step: 0.1
});
}
function initEventHandlers() {
$("#time-slider").hover(onHoverTimeSliderIn,
onHoverTimeSliderOut);
$("#time-slider").mousemove(onMoveOverTimeSlider);
$("#ctrl-btn").click(togglePlayback);
$("#prev-btn").click(gotoPrev);
$("#next-btn").click(gotoNext);
$("#gl-opt-btn").click(globalOptMenu);
$("#page-sel-btn").click(pageMenu);
// mobile // jquerymobile est pas mal *fat*, donc vaut mieux le charger qu'en cas de besoin
if (navigator.userAgent.match('Android'))
$.getScript("/assets/js/jquery.mobile.custom.js",
function() {
$("#music-ctrl").on("swipeleft", gotoPrev);
$("#music-ctrl").on("swiperight", gotoNext);
});
}
function init() {
if (!sessionStorage.getItem('page'))
sessionStorage.setItem('page', 'Bibliothèque');
askFullScreen();
initInterface();
initEventHandlers();
updateOptions();
//updateSongs(makeMusicElem, 'songs');
setPage(sessionStorage.getItem('page'));
updatePlayer();
refreshTime();
} | gpl-3.0 |
dkasak/notify-osd-customizable | examples/icon-only.cs | 2035 | ////////////////////////////////////////////////////////////////////////////////
//3456789 123456789 123456789 123456789 123456789 123456789 123456789 123456789
// 10 20 30 40 50 60 70 80
//
// Info:
// Example of how to use libnotify correctly and at the same time comply to
// the new jaunty notification spec (read: visual guidelines)
//
// Compile and run:
// gmcs -pkg:notify-sharp example-util.cs icon-only.cs -out:icon-only.exe
// mono icon-only.exe
//
// Copyright 2009 Canonical Ltd.
//
// Author:
// Mirco "MacSlow" Mueller <[email protected]>
//
// 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 warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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 System;
using Notifications;
public class IconOnly
{
public static void Main ()
{
// call this so we can savely use the m_capabilities array later
ExampleUtil.InitCaps ();
// show what's supported
ExampleUtil.PrintCaps ();
// try the icon-sonly case
if (ExampleUtil.HasCap (ExampleUtil.Capability.CAP_LAYOUT_ICON_ONLY))
{
Notification n = new Notification ("Eject", // for a11y-reasons supply something meaning full
"", // this needs to be empty!
"notification-device-eject");
n.AddHint ("x-canonical-private-icon-only", "");
n.Show ();
}
else
Console.WriteLine ("The daemon does not support the x-canonical-private-icon-only hint!");
}
}
| gpl-3.0 |
mycncart/mycncart | catalog/controller/mail/forgotten.php | 2575 | <?php
class ControllerMailForgotten extends Controller {
//catalog/model/account/customer/editCode/after
public function index(&$route, &$args, &$output) {
if ($args[0] && $args[1]) {
$this->load->model('account/customer');
$customer_info = $this->model_account_customer->getCustomerByEmail($args[0]);
if ($customer_info) {
$this->load->language('mail/forgotten');
$this->load->model('tool/image');
if (is_file(DIR_IMAGE . html_entity_decode($this->config->get('config_logo'), ENT_QUOTES, 'UTF-8'))) {
$data['logo'] = $this->model_tool_image->resize(html_entity_decode($this->config->get('config_logo'), ENT_QUOTES, 'UTF-8'), $this->config->get('theme_default_image_location_width'), $this->config->get('theme_default_image_cart_height'));
} else {
$data['logo'] = '';
}
$data['text_greeting'] = sprintf($this->language->get('text_greeting'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
$data['text_change'] = $this->language->get('text_change');
$data['text_ip'] = $this->language->get('text_ip');
$data['button_reset'] = $this->language->get('button_reset');
$data['reset'] = str_replace('&', '&', $this->url->link('account/reset', 'language=' . $this->config->get('config_language') . '&email=' . urlencode($args[0]) . '&code=' . $args[1]));
$data['ip'] = $this->request->server['REMOTE_ADDR'];
$data['store_url'] = $this->config->get('config_url');
$data['store'] = html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8');
$mail = new Mail($this->config->get('config_mail_engine'));
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->smtp_hostname = $this->config->get('config_mail_smtp_hostname');
$mail->smtp_username = $this->config->get('config_mail_smtp_username');
$mail->smtp_password = html_entity_decode($this->config->get('config_mail_smtp_password'), ENT_QUOTES, 'UTF-8');
$mail->smtp_port = $this->config->get('config_mail_smtp_port');
$mail->smtp_timeout = $this->config->get('config_mail_smtp_timeout');
$mail->setTo($args[0]);
$mail->setFrom($this->config->get('config_email'));
$mail->setSender(html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8'));
$mail->setSubject(html_entity_decode(sprintf($this->language->get('text_subject'), html_entity_decode($this->config->get('config_name'), ENT_QUOTES, 'UTF-8')), ENT_QUOTES, 'UTF-8'));
$mail->setHtml($this->load->view('mail/forgotten', $data));
$mail->send();
}
}
}
}
| gpl-3.0 |
cmongis/psfj | src/knop/psfj/locator/BeadLocator3D.java | 2804 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package knop.psfj.locator;
import Objects3D.Object3D;
import ij.ImagePlus;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;
import knop.psfj.BeadFrame2D;
import knop.psfj.BeadFrameList;
import knop.psfj.BeadImage;
import knop.psfj.resolution.Counter3D;
/**
*
* @author cyril
*/
public class BeadLocator3D extends BeadLocator implements Observer{
Counter3D counter;
@Override
public ArrayList<Rectangle> getBeadLocation() {
ArrayList<Rectangle> beadLocation = new ArrayList<Rectangle>();
System.out.println("Searching for centroids");
counter = new Counter3D(new ImagePlus("",getImage().getStack()),getImage().getThresholdValue(),1,65000);
counter.addObserver(this);
try {
counter.getObjects();
}
catch(Exception e) {
e.printStackTrace();
}
//counter.getCentroidList();
System.out.println(counter.getFound() + " objects found.");
Vector<Object3D> objectList = counter.getObjectsList();
for(Object3D o : objectList) {
Rectangle r = new Rectangle();
double x = o.c_mass[0] - (1.0*o.bound_cube_width/2.0);
double y = o.c_mass[1] - (1.0*o.bound_cube_height/2.0);
double width = o.bound_cube_width;
double height = o.bound_cube_height;
r.setRect(x, y, width, height);
beadLocation.add(r);
}
image.setFrameNumber(beadLocation.size());
image.setIgnoredFrameNumber(0);
System.out.println("Search finihsed");
return beadLocation;
}
@Override
public BeadFrameList getBeadFrameList() {
BeadFrameList beadFrames = new BeadFrameList();
int id = 1;
for(Rectangle rectangle : image.getBeadLocation()) {
BeadFrame2D frame = new BeadFrame2D(id++,image.getEnlargedFrame(rectangle));
beadFrames.add(frame);
frame.setSource(getImage());
}
return beadFrames;
}
@Override
public boolean isFocusPlaneDependent() {
return false;
}
@Override
public void update(Observable o, Object arg) {
BeadImage image = getImage();
if(image.getProgress()!= counter.getProgress())
image.setProgress(counter.getProgress());
}
}
| gpl-3.0 |
widowild/messcripts | exercice/python2/solutions/exercice_7_11.py | 360 | #! /usr/bin/env python
# -*- coding: Latin-1 -*-
def nomMois(n):
"renvoie le nom du n-ième mois de l'année"
mois = ['Janvier,', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet',
'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre']
return mois[n -1] # les indices sont numérotés à partir de zéro
# test :
print nomMois(4)
| gpl-3.0 |
mkuron/espresso | src/script_interface/cluster_analysis/ClusterStructure.hpp | 3844 | /*
Copyright (C) 2010-2018 The ESPResSo project
Copyright (C) 2002,2003,2004,2005,2006,2007,2008,2009,2010
Max-Planck-Institute for Polymer Research, Theory Group
This file is part of ESPResSo.
ESPResSo 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.
ESPResSo 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/>.
*/
#ifndef SCRIPT_INTERFACE_CLUSTER_ANALYSIS_CLUSTER_STRUCTURE_HPP
#define SCRIPT_INTERFACE_CLUSTER_ANALYSIS_CLUSTER_STRUCTURE_HPP
#include "../pair_criteria/pair_criteria.hpp"
#include "ScriptInterface.hpp"
#include "core/cluster_analysis/ClusterStructure.hpp"
#include <utils/Factory.hpp>
namespace ScriptInterface {
namespace ClusterAnalysis {
class ClusterStructure : public AutoParameters<ClusterStructure> {
public:
ClusterStructure() : m_pc(nullptr) {
add_parameters(
{{"pair_criterion",
[this](Variant const &value) {
m_pc =
get_value<std::shared_ptr<PairCriteria::PairCriterion>>(value);
if (m_pc) {
m_cluster_structure.set_pair_criterion(m_pc->pair_criterion());
};
},
[this]() { return (m_pc != nullptr) ? m_pc->id() : ObjectId(); }}});
};
Variant call_method(std::string const &method,
VariantMap const ¶meters) override {
if (method == "get_cluster") {
// Note: Cluster objects are generated on the fly, to avoid having to
// store a script interface object for all clusters (which can by
// thousands)
auto c =
std::dynamic_pointer_cast<Cluster>(ScriptInterfaceBase::make_shared(
"ClusterAnalysis::Cluster",
ScriptInterfaceBase::CreationPolicy::LOCAL));
c->set_cluster(m_cluster_structure.clusters.at(
boost::get<int>(parameters.at("id"))));
// Store a temporary copy of the most recent cluster being returned.
// This ensures, that the reference count of the shared_ptr doesn't go
// to zero, while it is passed to Python.
// (At some point, it is converted to an ObjectId, which is passed
// to Python, where a new script object is constructed. While it is
// passed as ObjectId, no one holds an instance of the shared_ptr)
m_tmp_cluster = c;
return m_tmp_cluster->id();
}
if (method == "cluster_ids") {
std::vector<int> cluster_ids;
for (const auto &it : m_cluster_structure.clusters) {
cluster_ids.push_back(it.first);
}
return cluster_ids;
}
if (method == "n_clusters") {
return int(m_cluster_structure.clusters.size());
}
if (method == "cid_for_particle") {
return m_cluster_structure.cluster_id.at(
boost::get<int>(parameters.at("pid")));
}
if (method == "clear") {
m_cluster_structure.clear();
return true;
}
if (method == "run_for_all_pairs") {
m_cluster_structure.run_for_all_pairs();
return true;
}
if (method == "run_for_bonded_particles") {
m_cluster_structure.run_for_bonded_particles();
return true;
}
return true;
}
private:
::ClusterAnalysis::ClusterStructure m_cluster_structure;
std::shared_ptr<PairCriteria::PairCriterion> m_pc;
std::shared_ptr<Cluster> m_tmp_cluster;
};
} /* namespace ClusterAnalysis */
} /* namespace ScriptInterface */
#endif
| gpl-3.0 |
jike2016/308b-2016 | ledgercenter/person/quizledger.php | 2049 | <script>
$('.lockpage').hide();
</script>
<?php
require_once("../../config.php");
$timeid = optional_param('timeid', 1, PARAM_INT);//1周2月3总
$personid = optional_param('personid', 0, PARAM_INT);
global $DB;
$user = $DB -> get_records_sql('select id,lastname,firstname from mdl_user where id='.$personid);
echo '</br><div align="center" style="margin-left: auto;margin-right: auto;">'.$user[$personid]->lastname.$user[$personid]->firstname.':考试统计</div>';
$mytime = 0;
if($timeid==1){
$mytime= time()-3600*24*7;
// $sql='and a.timecreated>'.$mytime;
}
elseif($timeid==2){
$mytime= time()-3600*24*30;
// $sql='and a.timecreated>'.$mytime;
}
elseif($timeid==3){
// $sql='';
}
echo_quiztabel($personid,$mytime);
function echo_quiztabel($personid,$mytime){
global $DB;
$quizcounts = $DB -> get_records_sql('
select
d.id,c.fullname,d.typeofquiz,e.timefinish, d.name,h.grade
from mdl_user_enrolments a
join mdl_enrol b on b.id=a.enrolid
join mdl_course c on c.id=b.courseid
join mdl_quiz d on d.course=c.id
join mdl_quiz_attempts e on e.quiz=d.id and e.userid='.$personid.' and e.state=\'finished\'
join mdl_quiz_grades h on h.quiz=d.id and h.userid='.$personid.' and h.timemodified>'.$mytime.'
where a.userid='.$personid.' and d.timeopen!=0 and d.timeclose!=0 and d.attempts=1 and d.typeofquiz in (1,2)
order by e.timefinish desc
');
echo '
<table class="table table-striped table-bordered">
<thead>
<tr>
<td>序号</td>
<td>课程名称</td>
<td>考试名称</td>
<td>考试类型</td>
<td>考试时间</td>
<td>成绩</td>
</tr>
</thead>
<tbody>
';
$n=1;
foreach($quizcounts as $quiz){
if($quiz->typeofquiz==1){
$quiz->typeofquiz='统一考试';
}else{
$quiz->typeofquiz='自主考试';
}
echo '<tr>
<td>'.$n.'</td>
<td>'.$quiz->fullname.'</td>
<td>'.$quiz->name.'</td>
<td>'.$quiz->typeofquiz.'</td>
<td>'.userdate($quiz->timefinish,'%Y-%m-%d %H:%M').'</td>
<td>'.$quiz->grade.'</td>
</tr>
';
$n++;
}
echo '
</tbody>
</table>';
}
?>
| gpl-3.0 |
gammalib/gammalib | src/test/GTestSuite.cpp | 35209 | /***************************************************************************
* GTestSuite.cpp - Abstract test suite base class *
* ----------------------------------------------------------------------- *
* copyright (C) 2012-2016 by Jean-Baptiste Cayrou *
* ----------------------------------------------------------------------- *
* *
* 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 GTestSuite.cpp
* @brief Abstract test suite base class implementation
* @author Jean-Baptiste Cayrou
*/
/* __ Includes ___________________________________________________________ */
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <typeinfo>
#include "GTestSuite.hpp"
#include "GTools.hpp"
#include "GLog.hpp"
/* __ OpenMP section _____________________________________________________ */
#ifdef _OPENMP
#include <omp.h>
#ifdef HAVE_OPENMP_DARWIN_KLUGE
#include <pthread.h>
pthread_attr_t gomp_thread_attr;
#endif
#endif
/* __ Method name definitions ____________________________________________ */
#define G_OP_ACCESS "GTestSuite::operator[](int&)"
#define G_TRY_SUCCESS "GTestSuite::test_try_success()"
#define G_TRY_FAILURE1 "GTestSuite::test_try_failure(std::string&,"\
" std::string&)"
#define G_TRY_FAILURE2 "GTestSuite::test_try_failure(std::exception&)"
/* __ Macros _____________________________________________________________ */
/* __ Coding definitions _________________________________________________ */
/* __ Debug definitions __________________________________________________ */
/*==========================================================================
= =
= Constructors/destructors =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Void constructor
***************************************************************************/
GTestSuite::GTestSuite(void)
{
// Initialise members
init_members();
//Return
return;
}
/***********************************************************************//**
* @brief Copy constructor
*
* @param[in] suite Test Suite.
***************************************************************************/
GTestSuite::GTestSuite(const GTestSuite& suite)
{
// Initialise members
init_members();
// Copy members
copy_members(suite);
//Return
return;
}
/***********************************************************************//**
* @brief Name constructor
*
* @param[in] name Test suite name.
***************************************************************************/
GTestSuite::GTestSuite(const std::string& name)
{
// Initialise members
init_members();
// Set name
m_name = name;
//Return
return;
}
/***********************************************************************//**
* @brief Destructor
***************************************************************************/
GTestSuite::~GTestSuite(void)
{
// Free members
free_members();
// Return
return;
}
/*==========================================================================
= =
= Operators =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Assignment operator
*
* @param[in] suite Test suite.
* @return Test suite.
***************************************************************************/
GTestSuite& GTestSuite::operator=(const GTestSuite& suite)
{
// Execute only if object is not identical
if (this != &suite) {
// Free members
free_members();
// Initialise members
init_members();
// Copy members
copy_members(suite);
} // endif: object was not identical
// Return
return *this;
}
/***********************************************************************//**
* @brief Returns reference to test case
*
* @param[in] index Test case index [0,...,size()-1].
*
* @exception GException::out_of_range
* Test case index is out of range.
***************************************************************************/
GTestCase& GTestSuite::operator[](const int& index)
{
// Compile option: raise exception if index is out of range
#if defined(G_RANGE_CHECK)
if (index < 0 || index >= size()) {
throw GException::out_of_range(G_OP_ACCESS, "Test case index", index, size());
}
#endif
// Return reference
return *(m_tests[index]);
}
/***********************************************************************//**
* @brief Returns reference to test case
*
* @param[in] index Test case index [0,...,size()-1].
*
* @exception GException::out_of_range
* Test case index is out of range.
***************************************************************************/
const GTestCase& GTestSuite::operator[](const int& index) const
{
// Compile option: raise exception if index is out of range
#if defined(G_RANGE_CHECK)
if (index < 0 || index >= size()) {
throw GException::out_of_range(G_OP_ACCESS, "Test case index", index, size());
}
#endif
// Return reference
return *(m_tests[index]);
}
/*==========================================================================
= =
= Public methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Clear test suite
***************************************************************************/
void GTestSuite::clear(void)
{
// Free members
free_members();
// Initialise members
init_members();
// Return
return;
}
/***********************************************************************//**
* @brief Append test functions to test suite
*
* @param[in] function Test function pointer.
* @param[in] name Test name.
*
* This method adds test functions to the test suite. The test functions will
* be executed when the run method is called.
***************************************************************************/
void GTestSuite::append(const pfunction function, const std::string& name)
{
// Add test function pointer and name to suite
m_functions.push_back(function);
m_names.push_back(name);
// Return
return;
}
/***********************************************************************//**
* @brief Run all tests in test suite
*
* @return True if all tests were successful, false otherwise.
*
* Executes all test functions that have been appended to the test suite.
* For each test function a test case is added to the test suite.
***************************************************************************/
bool GTestSuite::run(void)
{
// Setup the test functions. This is a pure virtual function that needs
// to be implemented in the derived class. It sets the function
// pointers and function names for all test functions that should be
// executed.
set();
// Initialise success flag
bool success = true;
// Loop over all functions in suite
for (m_index = 0; m_index < m_functions.size(); ++m_index) {
// Continue only if function is valid
if (m_functions[m_index] != NULL) {
// Save the number of errors and failures before test
// execution. We use this after the test to see if
// any failures occured.
int old_errors = errors();
int old_failures = failures();
// Log the name of the test
std::cout << m_names[m_index] << ": ";
// Create a test of error type for function testing
GTestCase* test = new GTestCase(GTestCase::ERROR_TEST, m_names[m_index]);
// Add test case to test suite
m_tests.push_back(test);
// Set start time
#ifdef _OPENMP
double t_start = omp_get_wtime();
#else
clock_t t_start = clock();
#endif
// Execute test function
try {
(this->*(m_functions[m_index]))();
}
catch (std::exception& e) {
// Signal that test did not succeed
test->has_passed(false);
// Set test message to exception message
test->message(e.what());
// Set type as class name
test->type(typeid(e).name());
}
catch (...)
{
// For other exceptions
test->has_passed(false);
test->message("Non-standard C++ exception thrown");
}
// Compute elapsed time
#ifdef _OPENMP
double t_elapse = omp_get_wtime()-t_start;
#else
double t_elapse = (double)(clock() - t_start) / (double)CLOCKS_PER_SEC;
#endif
// Set test duration
test->duration(t_elapse);
// Increment number of errors if the test did not pass
if (!test->has_passed()) {
m_errors++;
}
// Log the result (".","F" or, "E")
std::cout << test->print();
// Log if there are errors or failures
if ((m_errors == old_errors && m_failures == old_failures)) {
std::cout << " ok" << std::endl;
}
else {
std::cout << " NOK" << std::endl;
success = false;
}
} // endif: test case has a function pointer
} // endfor: looped over tests on the stack
// Reset index
m_index = 0;
// Return success flag
return success;
}
/***********************************************************************//**
* @brief Test an assert
*
* @param[in] assert Assert (true/false).
* @param[in] name Test case name.
* @param[in] message Test case name (defaults to "").
*
* Tests if a condition is true or false. This method adds a test case of
* type "failure" to the test suite.
*
* Examples:
* test_assert(x>3, "Test if x > 3");
* test_assert(x>3 && x<10, "Test if 3 < x < 10 ");
***************************************************************************/
void GTestSuite::test_assert(const bool& assert,
const std::string& name,
const std::string& message)
{
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, format_name(name));
// If assert is false then signal that the test is not passed and
// increment the number of failures in this test suite
if (!assert) {
testcase->has_passed(false);
m_failures++;
}
// Set message
testcase->message(message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test an integer value
*
* @param[in] value Integer value to test.
* @param[in] expected Expected integer value.
* @param[in] name Test case name.
* @param[in] message Test case message.
*
* Test if integer @p value is the @p expected value.
***************************************************************************/
void GTestSuite::test_value(const int& value,
const int& expected,
const std::string& name,
const std::string& message)
{
// Set test case name. If no name is specify then build the name from
// the actual test parameters.
std::string formated_name;
if (name != "") {
formated_name = format_name(name);
}
else {
formated_name = format_name("Test if "+gammalib::str(value)+" is "+
gammalib::str(expected));
}
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, formated_name);
// If value is not the expected one then signal test as failed and
// increment the number of failures
if (value != expected) {
testcase->has_passed(false);
m_failures++;
}
// If no message is specified then build message from test result
std::string formated_message;
if (message != "") {
formated_message = message;
}
else {
formated_message = "Value "+gammalib::str(value)+" equals not the "+
"expected value of "+gammalib::str(expected)+".";
}
// Set message
testcase->message(formated_message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test a double precision value
*
* @param[in] value Double precision value to test.
* @param[in] expected Expected double precision value.
* @param[in] name Test case name.
* @param[in] message Test case message.
*
* Test if the @p value is equal to the @p expected value within a relative
* precision of 1.0e-7.
***************************************************************************/
void GTestSuite::test_value(const double& value,
const double& expected,
const std::string& name,
const std::string& message)
{
// Compute precision
double eps = (expected != 0.0) ? 1.0e-7 * std::abs(expected) : 1.0e-7;
// Test double precision value
test_value(value, expected, eps, name, message);
// Return
return;
}
/***********************************************************************//**
* @brief Test a double precision value
*
* @param[in] value Double precision value to test.
* @param[in] expected Expected double precision value.
* @param[in] eps Precision of the test.
* @param[in] name Test case name.
* @param[in] message Test case message.
*
* Test if the value is comprised in the interval
* [expected-eps, expected+eps].
***************************************************************************/
void GTestSuite::test_value(const double& value,
const double& expected,
const double& eps,
const std::string& name,
const std::string& message)
{
// Set test case name. If no name is specify then build the name from
// the actual test parameters.
std::string formated_name;
if (name != "") {
formated_name = format_name(name);
}
else {
formated_name = format_name("Test if "+gammalib::str(value)+
" is comprised within "+
gammalib::str(expected)+" +/- "+
gammalib::str(eps));
}
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, formated_name);
// If value is not between in interval [expected-eps, expected+eps]
// then signal test as failed and increment the number of failures
if (value > expected + eps || value < expected - eps) {
testcase->has_passed(false);
m_failures++;
}
// If no message is specified then build message from test result
std::string formated_message;
if (message != "") {
formated_message = message;
}
else {
formated_message = "Value "+gammalib::str(value)+" not within "+
gammalib::str(expected)+" +/- "+gammalib::str(eps)+
" (value-expected = "+gammalib::str(value-expected)+
").";
}
// Set message
testcase->message(formated_message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test a complex value
*
* @param[in] value Complex value to test.
* @param[in] expected Expected complex value.
* @param[in] name Test case name.
* @param[in] message Test case message.
*
* Test if the @p value is equal to the @p expected value within a relative
* precision of 1.0e-7.
***************************************************************************/
void GTestSuite::test_value(const std::complex<double>& value,
const std::complex<double>& expected,
const std::string& name,
const std::string& message)
{
// Compute precision
double eps = (expected != 0.0) ? 1.0e-7 * std::abs(expected) : 1.0e-7;
// Test double precision value
test_value(value, expected, eps, name, message);
// Return
return;
}
/***********************************************************************//**
* @brief Test a complex value
*
* @param[in] value Complex value to test.
* @param[in] expected Expected complex value.
* @param[in] eps Precision of the test.
* @param[in] name Test case name.
* @param[in] message Test case message.
*
* Test if the value is comprised in the interval
* [expected-eps, expected+eps].
***************************************************************************/
void GTestSuite::test_value(const std::complex<double>& value,
const std::complex<double>& expected,
const double& eps,
const std::string& name,
const std::string& message)
{
// Set test case name. If no name is specify then build the name from
// the actual test parameters.
std::string formated_name;
if (name != "") {
formated_name = format_name(name);
}
else {
formated_name = format_name("Test if "+gammalib::str(value)+
" is comprised within "+
gammalib::str(expected)+" +/- "+
gammalib::str(eps));
}
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, formated_name);
// If value is not between in interval [expected-eps, expected+eps]
// then signal test as failed and increment the number of failures
if ((value.real() > expected.real() + eps) ||
(value.real() < expected.real() - eps) ||
(value.imag() > expected.imag() + eps) ||
(value.imag() < expected.imag() - eps)) {
testcase->has_passed(false);
m_failures++;
}
// If no message is specified then build message from test result
std::string formated_message;
if (message != "") {
formated_message = message;
}
else {
formated_message = "Value "+gammalib::str(value)+" not within "+
gammalib::str(expected)+" +/- "+gammalib::str(eps)+
" (value-expected = "+gammalib::str(value-expected)+
").";
}
// Set message
testcase->message(formated_message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test a string value
*
* @param[in] value String value to test.
* @param[in] expected Expected string value.
* @param[in] name Test case name (defaults to "").
* @param[in] message Test case message (defaults to "").
*
* Test if the string @p value corresponds to the @p expected value.
***************************************************************************/
void GTestSuite::test_value(const std::string& value,
const std::string& expected,
const std::string& name,
const std::string& message)
{
// Set test case name. If no name is specify then build the name from
// the actual test parameters.
std::string formated_name;
if (name != "") {
formated_name = format_name(name);
}
else {
formated_name = format_name("Test if \""+value+"\" is \""+expected+"\"");
}
// Create a test case of failure type
GTestCase* testcase = new GTestCase(GTestCase::FAIL_TEST, formated_name);
// If value is not the expected one then signal test as failed and
// increment the number of failures
if (value != expected) {
testcase->has_passed(false);
m_failures++;
}
// If no message is specified then build message from test result
std::string formated_message;
if (message != "") {
formated_message = message;
}
else {
formated_message = "String \""+value+"\" is not equal to the "+
"expected string \""+expected+"\".";
}
// Set message
testcase->message(formated_message);
// Log the result (".","F" or, "E")
std::cout << testcase->print();
// Add test case to test suite
m_tests.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Test an try block
*
* @param[in] name Test case name (defaults to "").
*
* @see test_try_sucess()
* @see test_try_failure(const std::string& message,const std::string& type)
* @see test_try_failure(const std::exception& e)
*
* Call before testing a try/catch block.
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(...) {
* test_try_failure();
* }
***************************************************************************/
void GTestSuite::test_try(const std::string& name)
{
// Create a test case of error type
GTestCase* testcase = new GTestCase(GTestCase::ERROR_TEST, format_name(name));
// Add test case to try stack of test suite
m_stack_try.push_back(testcase);
// Return
return;
}
/***********************************************************************//**
* @brief Notice when a try block succeeded
*
* @exception GException::test_nested_try_error
* Test case index is out of range.
*
* @see test_try(const std::string& name)
* @see test_try_failure(const std::string& message, const std::string& type)
* @see test_try_failure(const std::exception& e)
*
* Call this method at the last line of a try
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(...) {
* test_try_failure();
* }
***************************************************************************/
void GTestSuite::test_try_success(void)
{
// If the stack is empty
if (m_stack_try.empty()) {
throw GException::test_nested_try_error(G_TRY_SUCCESS,
"Called \"G_TRY_SUCCESS\" without a previous call to test_try()");
}
// Add test case to test suite
m_tests.push_back(m_stack_try.back());
// Delete the test case from the try stack
m_stack_try.pop_back();
// Log the result (".","F" or, "E")
std::cout << m_tests.back()->print();
// Return
return;
}
/***********************************************************************//**
* @brief Notice when a try block failed
*
* @param[in] message Message to explain why test failed (defaults to "").
* @param[in] type Type of message (defaults to "").
*
* @exception GException::test_nested_try_error
* Test case index is out of range.
*
* @see test_try_sucess()
* @see test_try(const std::string& name)
* @see test_try_failure(const std::exception& e)
*
* Call this method in the catch block.
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(...) {
* test_try_failure();
* }
***************************************************************************/
void GTestSuite::test_try_failure(const std::string& message,
const std::string& type)
{
// If the stack is empty then create an eception test case
if (m_stack_try.empty()) {
GTestCase* testcase = new GTestCase(GTestCase::ERROR_TEST, "Exception test");
m_stack_try.push_back(testcase);
}
// Signal that test is not ok
m_stack_try.back()->has_passed(false);
// Increment the number of errors
m_errors++;
// Set test type
m_stack_try.back()->kind(GTestCase::ERROR_TEST);
// Set message
m_stack_try.back()->message(message);
// Set type of message
m_stack_try.back()->type(type);
// Add test case to test suite
m_tests.push_back(m_stack_try.back());
// Delete the test case from the stack
m_stack_try.pop_back();
// Log the result ( ".","F" or, "E")
std::cout << m_tests.back()->print();
//Return
return;
}
/***********************************************************************//**
* @brief Notice when a try block failed
*
* @param[in] e Exception.
*
* @exception GException::test_nested_try_error
* Test case index is out of range.
*
* @see test_try_sucess()
* @see test_try(const std::string& name)
* @see test_try_failure(const std::string& message, const std::string& type)
*
* Call this method in a catch block.
*
* Example:
* test_try("Test a try block");
* try {
* ... //someting to test
* test_try_success();
* }
* catch(exception& e) {
* test_try_failure(e);
* }
***************************************************************************/
void GTestSuite::test_try_failure(const std::exception& e)
{
// Extract message of exception and class name
test_try_failure(e.what(), typeid(e).name());
// Return
return;
}
/***********************************************************************//**
* @brief Return a failure exception
*
* @param[in] message Message.
*
* @see test_try()
* @see test_error(const std::string& message)
*
* It can be use in a try test
*
* Example:
* test_try("Test a try block");
* try {
* throw exception_failure("a failure");
* test_try_success();
* }
* catch(exception& e) {
* test_try_failure(e);
* }
***************************************************************************/
GException::test_failure& GTestSuite::exception_failure(const std::string& message)
{
// Return exception
return *(new GException::test_failure(m_stack_try.back()->name(), message));
}
/***********************************************************************//**
* @brief Return an error exception
*
* @param[in] message Message.
*
* @see test_try()
* @see test_failure(const std::string& message)
*
* It can be use in a try test
*
* Example:
* test_try("Test a try block");
* try {
* throw exception_error("an error");
* test_try_success();
* }
* catch(exception& e) {
* test_try_failure(e);
* }
***************************************************************************/
GException::test_error& GTestSuite::exception_error(const std::string& message)
{
// Return exception
return *(new GException::test_error(m_stack_try.back()->name(),message));
}
/***********************************************************************//**
* @brief Return the number of successful tests
***************************************************************************/
int GTestSuite::success(void) const
{
// Return successes
return size()-(m_errors+m_failures);
}
/***********************************************************************//**
* @brief Return the total duration of all tests
*
* This method sums up all test durations and returns the result.
***************************************************************************/
double GTestSuite::duration(void) const
{
// Initialise duration
double duration = 0.0;
// Add up the durations of all tests
for (int i = 0; i < m_tests.size(); ++i) {
duration += m_tests[i]->duration();
}
// Return duration
return duration;
}
/***********************************************************************//**
* @brief Print test suite information
*
* @param[in] chatter Chattiness (defaults to NORMAL).
* @return String containing test suite information.
***************************************************************************/
std::string GTestSuite::print(const GChatter& chatter) const
{
// Initialise result string
std::string result;
// Continue only if chatter is not silent
if (chatter != SILENT) {
// Append header
result.append("=== GTestSuite ===");
// Append information
result.append("\n"+gammalib::parformat("Name")+m_name);
result.append("\n"+gammalib::parformat("Number of functions"));
result.append(gammalib::str(m_names.size()));
result.append("\n"+gammalib::parformat("Number of executed tests"));
result.append(gammalib::str(size()));
result.append("\n"+gammalib::parformat("Number of errors"));
result.append(gammalib::str(errors()));
result.append("\n"+gammalib::parformat("Number of failures"));
result.append(gammalib::str(failures()));
} // endif: chatter was not silent
// Return result
return result;
}
/*==========================================================================
= =
= Private methods =
= =
==========================================================================*/
/***********************************************************************//**
* @brief Initialise class members
***************************************************************************/
void GTestSuite::init_members(void)
{
// Initialise members
m_name = "Unnamed Test Suite";
m_names.clear();
m_functions.clear();
m_tests.clear();
m_stack_try.clear();
m_index = 0;
m_failures = 0;
m_errors = 0;
m_log.clear();
m_timestamp = time(NULL);
// Set logger parameters
cout(true);
m_log.buffer_size(1);
// Return
return;
}
/***********************************************************************//**
* @brief Copy class members
*
* @param[in] suite Test suite.
*
* This method just clone the container not the test case.
***************************************************************************/
void GTestSuite::copy_members(const GTestSuite& suite)
{
// Copy members
m_name = suite.m_name;
m_names = suite.m_names;
m_functions = suite.m_functions;
m_index = suite.m_index;
m_failures = suite.m_failures;
m_errors = suite.m_errors;
m_log = suite.m_log;
m_timestamp = suite.m_timestamp;
// Clone test cases
for (int i = 0; i < suite.m_tests.size(); ++i) {
m_tests[i] = suite.m_tests[i]->clone();
}
// Clone try stack
for (int i = 0; i < suite.m_stack_try.size(); ++i) {
m_stack_try[i] = suite.m_stack_try[i]->clone();
}
// Return
return;
}
/***********************************************************************//**
* @brief Delete class members
***************************************************************************/
void GTestSuite::free_members(void)
{
// Delete test cases
for (int i = 0; i < m_tests.size(); ++i) {
delete m_tests[i];
m_tests[i] = NULL;
}
// Delete try stack
for (int i = 0; i < m_stack_try.size(); ++i) {
delete m_stack_try[i];
m_stack_try[i] = NULL;
}
// Close logger
m_log.close();
// Return
return;
}
/***********************************************************************//**
* @brief Format Name
*
* Return a string with the format
* "TestFunctionName:TestTryname1:TestTryName2: name"
***************************************************************************/
std::string GTestSuite::format_name(const std::string& name)
{
// Initialise format name
std::string format_name;
// Set name of the try blocks
if (!m_stack_try.empty()) {
format_name = m_stack_try.back()->name();
}
else {
// Set name of the test
format_name = m_names[m_index];
}
// Append test suite name
format_name += ": " + name;
// Return format
return format_name;
}
| gpl-3.0 |
sandipmurmu/Templates | falcon/src/main/java/com/work/falcon/LoadSetup.java | 855 | package com.work.falcon;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.routing.RoundRobinPool;
public class LoadSetup {
private ActorSystem system;
private ActorRef router;
private final static int no_of_msgs = 10 * 1000000;
public LoadSetup() {
system = ActorSystem.create("loadGen");
ActorRef appManager = system.actorOf(Props.create(JobControllerActor.class, no_of_msgs), "jobController");
router = system.actorOf(new RoundRobinPool(5).props(Props.create(WorkerActor.class, appManager)),"workerRouter");
}
private void generateLoad() {
for (int i = no_of_msgs; i >= 0; i--) {
router.tell("Job Id " + i + "# send", null);
}
System.out.println("All jobs sent successfully");
}
public static void main(String[] args) {
new LoadSetup().generateLoad();
}
}
| gpl-3.0 |
junwan6/cdhpoodll | mod/liveclassroom/db/access.php | 1826 | <?php
//
// Capability definitions for the Wimba Classroom module.
//
// The capabilities are loaded into the database table when the module is
// installed or updated. Whenever the capability definitions are updated,
// the module version number should be bumped up.
//
// The system has four possible values for a capability:
// CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT, and inherit (not set).
//
//
// CAPABILITY NAMING CONVENTION
//
// It is important that capability names are unique. The naming convention
// for capabilities that are specific to modules and blocks is as follows:
// [mod/block]/<component_name>:<capabilityname>
//
// component_name should be the same as the directory name of the mod or block.
//
// Core moodle capabilities are defined thus:
// moodle/<capabilityclass>:<capabilityname>
//
// Examples: mod/forum:viewpost
// block/recent_activity:view
// moodle/site:deleteuser
//
// The variable name for the capability definitions array follows the format
// $<componenttype>_<component_name>_capabilities
//
// For the core capabilities, the variable is $moodle_capabilities.
$capabilities = array(
'mod/liveclassroom:presenter' => array(
'riskbitmask' => RISK_SPAM,
'captype' => 'write',
'contextlevel' => CONTEXT_MODULE,
'legacy' => array(
'teacher' => CAP_ALLOW,
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW
)
),
'mod/liveclassroom:addinstance' => array(
'riskbitmask' => RISK_SPAM | RISK_XSS,
'captype' => 'write',
'contextlevel' => CONTEXT_BLOCK,
'archetypes' => array(
'editingteacher' => CAP_ALLOW,
'manager' => CAP_ALLOW
),
'clonepermissionsfrom' => 'moodle/site:manageblocks'
)
);
?>
| gpl-3.0 |
sklintyg/webcert | test/acceptance/features/steps/webcertRehabstod.js | 10241 | /*
* Copyright (C) 2021 Inera AB (http://www.inera.se)
*
* This file is part of sklintyg (https://github.com/sklintyg).
*
* sklintyg 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.
*
* sklintyg 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/>.
*/
/*global browser, logger, pages, wcTestTools, Promise, protractor */
'use strict';
/*jshint newcap:false */
//TODO Uppgradera Jshint p.g.a. newcap kommer bli depricated. (klarade inte att ignorera i grunt-task)
/*
* Stödlib och ramverk
*
*/
const {
Given, // jshint ignore:line
When, // jshint ignore:line
Then // jshint ignore:line
} = require('cucumber');
var helpers = require('./helpers');
var fillIn = require('./fillIn/').fillIn;
var loginHelper = require('./inloggning/login.helpers.js');
var loginHelperRehabstod = require('./inloggning/login.helpers.rehabstod.js');
var logInAsUserRole = loginHelper.logInAsUserRole;
var sokSkrivIntygPage = pages.sokSkrivIntyg.pickPatient;
var logInAsUserRoleRehabstod = loginHelperRehabstod.logInAsUserRoleRehabstod;
var testdataHelpers = wcTestTools.helpers.testdata;
/*
* Stödfunktioner
*
*/
// match personNr, startDate, endDate, noOfIntyg
var TABLEROW_REGEX = /.*(\d{8}\-\d{4}).*(\d{4}\-\d{2}\-\d{2})\s(\d{4}\-\d{2}\-\d{2}).*(dagar \d{1,3}).*/g;
var TABLEROW_SUBST = '\$1, \$2, \$3, \$4';
var getObjFromList;
function createPatient(id) {
var date = new Date();
var startDate = createDateString(date);
var endDate = createDateString(date, 30);
return createObj('19121212-1212,' + startDate + ',' + endDate + ',0');
}
function createObj(row) {
logger.silly('row:');
logger.silly(row);
var elements = row.split(',');
var id = elements[0].trim();
logger.silly('id: ' + id);
var startDate = elements[1].trim();
logger.silly('startDate: ' + startDate);
var endDate = elements[2].trim();
logger.silly('endDate: ' + endDate);
var noOfIntyg = extractDigit(elements[3]);
logger.silly('noOfIntyg: ' + noOfIntyg);
var obj = {
id: id,
startDate: startDate,
endDate: endDate,
noOfIntyg: noOfIntyg
};
return obj;
}
function extractDigit(intyg) {
var regex = /dagar (\d{1,2})/g;
var subst = '\$1';
var result = intyg.replace(regex, subst).trim();
return parseInt(result, 10);
}
function gotoPatient(patient, user) { //förutsätter att personen finns i PU-tjänsten
if (user.origin !== 'DJUPINTEGRATION') {
element(by.id('menu-skrivintyg')).click().then(function() {
return helpers.pageReloadDelay();
});
}
return sokSkrivIntygPage.selectPersonnummer(patient.id).then(function() {
return helpers.pageReloadDelay();
})
.then(function() {
logger.info('Går in på patient ' + patient.id);
//Patientuppgifter visas
var patientUppgifter = sokSkrivIntygPage.patientNamn;
return expect(patientUppgifter.getText()).to.eventually.contain(helpers.insertDashInPnr(patient.id)).then(function() {
return helpers.smallDelay();
});
});
}
function createDateString(date, daysToAdd, subtraction) {
var tmpDate = new Date(date);
if (daysToAdd) {
var modifiedTmpDate = (subtraction) ? new Date(tmpDate).getDate() - daysToAdd : new Date(tmpDate).getDate() + daysToAdd;
tmpDate.setDate(modifiedTmpDate);
}
var newDateString = tmpDate.getFullYear() + '-' + ('0' + (tmpDate.getMonth() + 1)).slice(-2) + '-' + ('0' + tmpDate.getDate()).slice(-2);
return newDateString;
}
function createPatientArr(getObjFromList) {
var patientArr = [];
return element.all(by.css('.rhs-table-row')).getText().then(function(tableRows) {
tableRows.forEach(function(row) {
if (getObjFromList) {
var savedObj = getObjFromList();
var newObj = createObj(row.replace(TABLEROW_REGEX, TABLEROW_SUBST));
if (savedObj.id === newObj.id) {
patientArr.push(newObj);
}
logger.silly(newObj);
} else {
var obj = createObj(row.replace(TABLEROW_REGEX, TABLEROW_SUBST));
patientArr.push(obj);
logger.silly(obj);
}
});
}).then(function() {
return Promise.resolve(patientArr);
});
}
/*function objList(arr) {
return function() {
function findid(obj) {
return obj.id === glob.rehabstod.patient.id;
}
return arr.find(findid);
};
}*/
/*
* Test steg
*
*/
When(/^jag går in på Rehabstöd$/, function() {
var url = process.env.REHABSTOD_URL + 'welcome.html';
return helpers.getUrl(url).then(function() {
logger.info('Går till url: ' + url);
});
});
When(/^jag väljer enhet "([^"]*)"$/, function(enhet) {
let elementId = 'rhs-vardenhet-selector-select-active-unit-' + enhet + '-link';
let user = this.user;
let headerboxUser = element(by.css('.header-user'));
return element(by.id(elementId)).click().then(function() {
return browser.sleep(2000);
}).then(function() {
return headerboxUser.getText();
}).then(function(txt) {
if (user.roleName !== 'rehabkoordinator') {
expect(txt).to.contain(user.roleName);
}
expect(txt).to.contain(user.forNamn);
expect(txt).to.contain(user.efterNamn);
}).then(function() {
return element(by.id('verksamhetsNameLabel')).getText();
}).then(function(txt) {
logger.info('Inloggad på: ');
logger.info(txt);
});
});
When(/^jag går till pågående sjukfall i Rehabstöd$/, function() {
return element(by.id('navbar-link-sjukfall')).click().then(function() {
return element(by.id('rhs-pdlconsent-modal-checkbox-label')).isPresent().then(function(isPresent) {
if (isPresent) {
return element(by.id('rhs-pdlconsent-modal-give-consent-checkbox')).sendKeys(protractor.Key.SPACE).then(function() {
return element(by.id('rhs-pdlconsent-modal-give-consent-btn')).sendKeys(protractor.Key.SPACE);
});
}
});
});
});
Then(/^ska jag inte se patientens personnummer bland pågående sjukfall$/, function() {
let patient = this.patient;
return element.all(by.css('.rhs-table-row')).getText().then(function(tableRows) {
return tableRows.forEach(function(row) {
row = row.replace('-', '');
logger.info('letar efter "' + patient.id + '" i :');
logger.debug(row);
return expect(row).to.not.contain(patient.id);
});
});
});
When(/^jag söker efter slumpvald patient och sparar antal intyg$/, function(callback) {
let world = this;
createPatientArr().then(function(patientArr) {
//getObjFromList = objList(patientArr);
getObjFromList = function() {
return patientArr.find(function(obj) {
return obj.id === world.rehabstod.patient.id;
});
};
//console.log(JSON.stringify(getObjFromList));
var usrObj = testdataHelpers.shuffle(patientArr)[0];
world.rehabstod = {};
if (usrObj) {
world.rehabstod.patient = usrObj;
} else {
world.rehabstod.patient = createPatient();
}
logger.info('Saved rehab patient ( id: ' + world.rehabstod.patient.id + ', noOfIntyg: ' + world.rehabstod.patient.noOfIntyg
+ '). Saved for next steps.');
}).then(callback);
});
When(/^jag går in på en patient som sparats från Rehabstöd$/, function() {
this.patient = {
id: this.rehabstod.patient.id.replace('-', '')
};
return gotoPatient(this.patient, this.user);
});
When(/^jag är inloggad som läkare i Rehabstöd$/, function() {
// Setting rehabstod to new bas url
browser.baseUrl = process.env.REHABSTOD_URL;
this.user = {
forNamn: 'Johan',
efterNamn: 'Johansson',
hsaId: 'TSTNMT2321000156-107V',
enhetId: 'TSTNMT2321000156-107P'
};
return logInAsUserRoleRehabstod(this.user, 'Läkare', true);
});
When(/^jag är inloggad som rehabkoordinator$/, function() {
// Setting rehabstod to new bas url
browser.baseUrl = process.env.REHABSTOD_URL;
this.user = {
forNamn: 'Automatkoordinator',
efterNamn: 'Rehab',
hsaId: 'TSTNMT2321000156-REKO',
enhetId: 'TSTNMT2321000156-107Q'
};
return logInAsUserRoleRehabstod(this.user, 'rehabkoordinator', true);
});
When(/^jag är inloggad som läkare i Webcert med enhet "([^"]*)"$/, function(enhetsId) {
// Setting webcert to new bas url
browser.baseUrl = process.env.WEBCERT_URL;
var userObj = {
forNamn: 'Johan',
efterNamn: 'Johansson',
hsaId: 'TSTNMT2321000156-107V',
enhetId: enhetsId,
lakare: true
};
return logInAsUserRole(userObj, 'Läkare', true);
});
When(/^jag fyller i ett "([^"]*)" intyg som inte är smitta med ny sjukskrivningsperiod$/, function(intygsTyp) {
this.intyg.typ = intygsTyp;
this.rehabstod.patient.intygId = this.intyg.id;
//sattNySjukskrivningsPeriod(this.intyg);
logger.info(this.intyg);
return fillIn(this);
});
Then(/^ska antalet intyg ökat med (\d+) på patient som sparats från Rehabstöd$/, function(antal) {
let world = this;
return createPatientArr(getObjFromList).then(function(patientArr) {
logger.info('Rehabpatient: ( id: ' + world.rehabstod.patient.id + ', Antal intyg: ' + patientArr[0].noOfIntyg + ').');
logger.info('Förväntar oss att world.rehabstod.patient.noOfIntyg + ' + antal + ' => ');
logger.info(world.rehabstod.patient.noOfIntyg + parseInt(antal, 10));
logger.info('Ska vara lika mycket som patientArr[0].noOfIntyg => ');
logger.info(patientArr[0].noOfIntyg);
return expect(world.rehabstod.patient.noOfIntyg + parseInt(antal, 10)).to.equal(patientArr[0].noOfIntyg);
});
});
When(/^jag går in på intyget som tidigare skapats$/, function() {
var url;
if (this.rehabstod) {
url = process.env.WEBCERT_URL + '#/intyg/lisjp/' + this.intyg.id + '/';
} else if (global.statistik) {
url = process.env.WEBCERT_URL + '#/intyg/lisjp/' + global.statistik.intygsId + '/';
}
return helpers.getUrl(url);
});
| gpl-3.0 |
projectestac/alexandria | html/langpacks/fr/format_topics.php | 1829 | <?php
// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
/**
* Strings for component 'format_topics', language 'fr', version '3.11'.
*
* @package format_topics
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['addsections'] = 'Ajouter des sections';
$string['currentsection'] = 'Cette section';
$string['deletesection'] = 'Supprimer la section';
$string['editsection'] = 'Modifier la section';
$string['editsectionname'] = 'Modifier le nom de la section';
$string['hidefromothers'] = 'Cacher la section';
$string['newsectionname'] = 'Nouveau nom pour la section {$a}';
$string['page-course-view-topics'] = 'Toutes les pages principales de cours au format thématique';
$string['page-course-view-topics-x'] = 'Toutes les pages de cours au format thématique';
$string['pluginname'] = 'Thématique';
$string['privacy:metadata'] = 'Le plugin format thématique n\'enregistre aucune donnée personnelle.';
$string['section0name'] = 'Généralités';
$string['sectionname'] = 'Section';
$string['showfromothers'] = 'Afficher la section';
| gpl-3.0 |
IanCal/leonard | src/TestingHarness.cpp | 3319 | /*
* This file is part of Leonard.
*
* Leonard 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.
*
* Leonard 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 Leonard. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TestingHarness.h"
#include "include/InputSource.h"
#include <math.h>
#include <stdio.h>
TestingHarness::TestingHarness(InputSource *testInput, ParameterController *parameterController){
this->testingInput = testInput;
this->parameterUpdater = parameterController;
};
float TestingHarness::train(RBM *RBMToTest, int iterations){
parameterUpdater->initialise(RBMToTest);
for (int i = 0; i < iterations / (RBMToTest->batchSize) ; i++) {
testingInput->getNextInput(RBMToTest);
testingInput->getNextLabel(RBMToTest);
RBMToTest->updateWeights();
parameterUpdater->updateParameters(RBMToTest);
}
};
float TestingHarness::test(RBM *RBMToTest, int iterations){
float mse=0.0;
float errorProportion=0.0;
int maxItem, actual, bestv;
int location;
float maxValue;
int batchSize = RBMToTest->batchSize;
iterations /= batchSize;
float initial[batchSize * testingInput->maxLabels];
float reconstruction[batchSize * testingInput->maxLabels];
for( int i=0 ; i<iterations ; i++ )
{
testingInput->getNextInput(RBMToTest);
testingInput->getNextLabel(RBMToTest);
RBMToTest->classify();
for( int layer=0 ; layer<RBMToTest->numberOfNeuronLayers ; layer++ )
{
if( RBMToTest->labelSizes[layer]!=0 )
{
//get initial and reconstruction
RBMToTest->getLabels(layer,initial,false);
RBMToTest->getLabels(layer,reconstruction,true);
// Look at individual classifications
for( int batch=0 ; batch<batchSize ; batch++ )
{
maxValue=-1.0;
maxItem=0;
actual=0;
bestv=0;
for( int pos=0 ; pos<(RBMToTest->labelSizes[layer]) ; pos++ )
{
location=batch+(pos*batchSize);
//if (i<2)
// printf("(%2.4f.%2.4f), ",initial[location],reconstruction[location]);
if (initial[location]>0.0)
actual=pos;
if (reconstruction[location]>maxValue)
{
maxValue = reconstruction[location];
maxItem = location;
bestv=pos;
}
}
if (initial[maxItem]<0.5f){
errorProportion+=1.;
//if (i<2)
// printf("\n%d .. %d - %d XXX\n", batch+(i*batchSize), actual, bestv);
}
else{
//if (i<2)
// printf("\n%d .. %d - %d\n", batch+(i*batchSize), actual, bestv);
}
}
//printf("\n");
// Look at the MSE
for( int pos=0 ; pos<RBMToTest->labelSizes[layer] * batchSize; pos++ )
{
mse+=pow(initial[pos]-reconstruction[pos],2);
}
}
}
}
printf("Total errors: %f\n",errorProportion);
mse /= batchSize*iterations;
errorProportion /= batchSize*iterations;
return errorProportion;
};
| gpl-3.0 |
andoniaf/DefGrafana.py | DefGrafana.py | 1130 | #!/usr/bin/python3
# -*- coding: utf-8 -*-
# [ES] DefGrafana.py - Script para capturar imagenes dentro de Grafana.
#
# Modo de uso: - Modificar seccion "VARS"
# - Ejecutar: python3 DefGrafana.py '<URL Dashboard>'
# - Usar la opcion '--cut-panel' para añadir otra imagen con el panel recortado:
# python3 DefGrafana.py --cut-panel '<URL Dashboard>'
#
# https://github.com/andoniaf
#### VARS ####
username = 'admin'
password = 'secret'
# Necesario sobretodo en consultas pesadas
timeout = 5
imgName = 'grafImg_'
# Resolucion de la "ventana"
hWin = 1200
wWin = 800
##############
import sys
from graf2png import graf2png
if len(sys.argv) == 1:
mensaje = "Uso:\n - Modificar seccion \"VARS\"\n"
mensaje += " - Ejecutar: python3 DefGrafana.py '<URL Dashboard>'"
print(mensaje)
else:
if (sys.argv[1] == '--cut-panel'):
onlyPanel = True
webUrl = sys.argv[2]
else:
onlyPanel = False
webUrl = sys.argv[1]
print("URL a capturar: " + webUrl)
graf2png(webUrl, username, password, timeout, imgName, hWin, wWin, onlyPanel)
| gpl-3.0 |
ribbons/RadioDownloader | Classes/FileUtils.cs | 1785 | /*
* Copyright © 2007-2020 Matt Robinson
*
* SPDX-License-Identifier: GPL-3.0-or-later
*/
namespace RadioDld
{
using System;
using System.Configuration;
using System.IO;
using System.Windows.Forms;
internal static class FileUtils
{
public static string GetSaveFolder()
{
const string DefaultFolder = "Downloaded Radio";
string saveFolder;
if (!string.IsNullOrEmpty(Settings.SaveFolder))
{
if (!new DirectoryInfo(Settings.SaveFolder).Exists)
{
throw new DirectoryNotFoundException();
}
return Settings.SaveFolder;
}
try
{
saveFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), DefaultFolder);
}
catch (DirectoryNotFoundException)
{
// The user's Documents folder could not be found, so fall back to a folder under the system drive
saveFolder = Path.Combine(Path.GetPathRoot(Environment.SystemDirectory), DefaultFolder);
}
Directory.CreateDirectory(saveFolder);
return saveFolder;
}
public static string GetAppDataFolder()
{
string folderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Application.CompanyName, Application.ProductName);
if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["AppDataDir"]))
{
folderPath = ConfigurationManager.AppSettings["AppDataDir"];
}
Directory.CreateDirectory(folderPath);
return folderPath;
}
}
}
| gpl-3.0 |
jalombar/starsmasher | misc/SPHgravtree_lib/libSequoia/src/scanFunctions.cpp | 16843 | #include "octree.h"
//Compacts an array of integers, the values in srcValid indicate if a
//value is valid (1 == valid anything else is UNvalid) returns the
//compacted values in the output array and the total
//number of valid items is stored in 'count'
void octree::gpuCompact(my_dev::context &devContext,
my_dev::dev_mem<uint> &srcValues,
my_dev::dev_mem<uint> &output,
int N, int *validCount)
{
// In the next step we associate the GPU memory with the Kernel arguments
// my_dev::dev_mem<uint> counts(devContext, 512), countx(devContext, 512);
//Memory that should be alloced outside the function:
//devMemCounts and devMemCountsx
//Kernel configuration parameters
setupParams sParam;
sParam.jobs = (N / 64) / 480 ; //64=32*2 2 items per look, 480 is 120*4, number of procs
sParam.blocksWithExtraJobs = (N / 64) % 480;
sParam.extraElements = N % 64;
sParam.extraOffset = N - sParam.extraElements;
compactCount.set_arg<cl_mem>(0, srcValues.p());
compactCount.set_arg<cl_mem>(1, this->devMemCounts.p());
compactCount.set_arg<uint>(2, &N);
compactCount.set_arg<int>(3, NULL, 128);
compactCount.set_arg<setupParams>(4, &sParam);
vector<size_t> localWork(2), globalWork(2);
globalWork[0] = 32*120; globalWork[1] = 4;
localWork [0] = 32; localWork[1] = 4;
compactCount.setWork(globalWork, localWork);
///////////////
exScanBlock.set_arg<cl_mem>(0, this->devMemCounts.p());
int blocks = 120*4;
exScanBlock.set_arg<int>(1, &blocks);
exScanBlock.set_arg<cl_mem>(2, this->devMemCountsx.p());
exScanBlock.set_arg<int>(3, NULL, 512); //shared memory allocation
globalWork[0] = 512; globalWork[1] = 1;
localWork [0] = 512; localWork [1] = 1;
exScanBlock.setWork(globalWork, localWork);
//////////////
compactMove.set_arg<cl_mem>(0, srcValues.p());
compactMove.set_arg<cl_mem>(1, output.p());
compactMove.set_arg<cl_mem>(2, this->devMemCounts.p());
compactMove.set_arg<uint>(3, &N);
compactMove.set_arg<uint>(4, NULL, 192); //Dynamic shared memory
compactMove.set_arg<setupParams>(5, &sParam);
globalWork[0] = 120*32; globalWork[1] = 4;
localWork [0] = 32; localWork [1] = 4;
compactMove.setWork(globalWork, localWork);
////////////////////
compactCount.execute();
exScanBlock.execute();
//
compactMove.execute();
#ifdef USE_CUDA
cuCtxSynchronize();
#else
clFinish(devContext.get_command_queue());
#endif
this->devMemCountsx.d2h();
*validCount = this->devMemCountsx[0];
//printf("Total number of valid items: %d \n", countx[0]);
}
//Splits an array of integers, the values in srcValid indicate if a
//value is valid (1 == valid anything else is UNvalid) returns the
//splitted values in the output array (first all valid
//number and then the invalid ones) and the total
//number of valid items is stored in 'count'
void octree::gpuSplit(my_dev::context &devContext,
my_dev::dev_mem<uint> &srcValues,
my_dev::dev_mem<uint> &output,
int N, int *validCount)
{
// In the next step we associate the GPU memory with the Kernel arguments
// my_dev::dev_mem<uint> counts(devContext, 512), countx(devContext, 512);
//Memory that should be alloced outside the function:
//devMemCounts and devMemCountsx
//Kernel configuration parameters
setupParams sParam;
sParam.jobs = (N / 64) / 480 ; //64=32*2 2 items per look, 480 is 120*4, number of procs
sParam.blocksWithExtraJobs = (N / 64) % 480;
sParam.extraElements = N % 64;
sParam.extraOffset = N - sParam.extraElements;
// printf("Param info: %d %d %d %d \n", sParam.jobs, sParam.blocksWithExtraJobs, sParam.extraElements, sParam.extraOffset);
compactCount.set_arg<cl_mem>(0, srcValues.p());
compactCount.set_arg<cl_mem>(1, this->devMemCounts.p());
compactCount.set_arg<uint>(2, &N);
compactCount.set_arg<int>(3, NULL, 128);
compactCount.set_arg<setupParams>(4, &sParam);
vector<size_t> localWork(2), globalWork(2);
globalWork[0] = 32*120; globalWork[1] = 4;
localWork [0] = 32; localWork[1] = 4;
compactCount.setWork(globalWork, localWork);
///////////////
exScanBlock.set_arg<cl_mem>(0, this->devMemCounts.p());
int blocks = 120*4;
exScanBlock.set_arg<int>(1, &blocks);
exScanBlock.set_arg<cl_mem>(2, this->devMemCountsx.p());
exScanBlock.set_arg<int>(3, NULL, 512); //shared memory allocation
globalWork[0] = 512; globalWork[1] = 1;
localWork [0] = 512; localWork [1] = 1;
exScanBlock.setWork(globalWork, localWork);
//////////////
splitMove.set_arg<cl_mem>(0, srcValues.p());
splitMove.set_arg<cl_mem>(1, output.p());
splitMove.set_arg<cl_mem>(2, this->devMemCounts.p());
splitMove.set_arg<uint>(3, &N);
splitMove.set_arg<uint>(4, NULL, 192); //Dynamic shared memory
splitMove.set_arg<setupParams>(5, &sParam);
globalWork[0] = 120*32; globalWork[1] = 4;
localWork [0] = 32; localWork [1] = 4;
splitMove.setWork(globalWork, localWork);
////////////////////
compactCount.execute();
// exit(0);
// counts.d2h();
// for(int i=0; i < 482; i++)
// {
// printf("%d\t%d\n", i, counts[i]);
// }
//
exScanBlock.execute();
splitMove.execute();
//TODO fix the damn clFinish function
#ifdef USE_CUDA
cuCtxSynchronize();
#else
clFinish(devContext.get_command_queue());
#endif
this->devMemCountsx.d2h();
*validCount = this->devMemCountsx[0];
//printf("Total number of valid items: %d \n", countx[0]);
}
/*
Sort an array of int4, the idea is that the key is somehow moved into x/y/z and the
value is put in w...
Sorts values based on the last item so order becomes something like:
z y x
2 2 1
2 1 2
2 3 3
2 5 3
*/
// If srcValues and buffer are different, then the original values
// are preserved, if they are the same srcValues will be overwritten
void octree::gpuSort(my_dev::context &devContext,
my_dev::dev_mem<uint4> &srcValues,
my_dev::dev_mem<uint4> &output,
my_dev::dev_mem<uint4> &buffer,
int N, int numberOfBits, int subItems,
tree_structure &tree) {
//Extra buffer values
// my_dev::dev_mem<uint> simpleKeys(devContext, N); //Int keys,
// my_dev::dev_mem<uint> permutation(devContext, N); //Permutation values, for sorting the int4 data
// my_dev::dev_mem<int> output32b(devContext, N); //Permutation values, for sorting the int4 data
// my_dev::dev_mem<uint> valuesOutput(devContext, N); //Buffers for the values which are the indexes
my_dev::dev_mem<uint> simpleKeys(devContext); //Int keys,
my_dev::dev_mem<uint> permutation(devContext); //Permutation values, for sorting the int4 data
my_dev::dev_mem<int> output32b(devContext); //Permutation values, for sorting the int4 data
my_dev::dev_mem<uint> valuesOutput(devContext); //Buffers for the values which are the indexes
int prevOffsetSum = getAllignmentOffset(4*N); //The offset of output
simpleKeys.cmalloc_copy(tree.generalBuffer1.get_pinned(),
tree.generalBuffer1.get_flags(),
tree.generalBuffer1.get_devMem(),
&tree.generalBuffer1[8*N], 8*N,
N, prevOffsetSum + getAllignmentOffset(8*N + prevOffsetSum)); //Ofset 8 since we have 2 uint4 before
prevOffsetSum += getAllignmentOffset(8*N + prevOffsetSum);
permutation.cmalloc_copy(tree.generalBuffer1.get_pinned(),
tree.generalBuffer1.get_flags(),
tree.generalBuffer1.get_devMem(),
&tree.generalBuffer1[9*N], 9*N,
N, prevOffsetSum + getAllignmentOffset(9*N + prevOffsetSum)); //N elements after simpleKeys
prevOffsetSum += getAllignmentOffset(9*N + prevOffsetSum);
output32b.cmalloc_copy(tree.generalBuffer1.get_pinned(),
tree.generalBuffer1.get_flags(),
tree.generalBuffer1.get_devMem(),
&tree.generalBuffer1[10*N], 10*N,
N, prevOffsetSum + getAllignmentOffset(10*N + prevOffsetSum)); //N elements after permutation
prevOffsetSum += getAllignmentOffset(10*N + prevOffsetSum);
valuesOutput.cmalloc_copy(tree.generalBuffer1.get_pinned(),
tree.generalBuffer1.get_flags(),
tree.generalBuffer1.get_devMem(),
&tree.generalBuffer1[11*N], 11*N,
N, prevOffsetSum + getAllignmentOffset(11*N + prevOffsetSum)); //N elements after output32b
//Dimensions for the kernels that shuffle and extract data
const int blockSize = 256;
int ng = (N)/blockSize + 1;
int nx = (int)sqrt(ng);
int ny = (ng-1)/nx + 1;
vector<size_t> localWork(2), globalWork(2);
globalWork[0] = nx*blockSize; globalWork[1] = ny;
localWork [0] = blockSize; localWork[1] = 1;
extractInt.setWork(globalWork, localWork);
fillSequence.setWork(globalWork, localWork);
reOrderKeysValues.setWork(globalWork, localWork);
//Idx depends on subitems, z goes first, x last if subitems = 3
//subitems = 3, than idx=2
//subitems = 2, than idx=1
//subitems = 1, than idx=0
//intIdx = subItems-1
int intIdx = subItems-1;
extractInt.set_arg<cl_mem>(0, srcValues.p());
extractInt.set_arg<cl_mem>(1, simpleKeys.p());
extractInt.set_arg<uint>(2, &N);
extractInt.set_arg<int>(3, &intIdx);//bit idx
fillSequence.set_arg<cl_mem>(0, permutation.p());
fillSequence.set_arg<uint>(1, &N);
reOrderKeysValues.set_arg<cl_mem>(0, srcValues.p());
reOrderKeysValues.set_arg<cl_mem>(1, output.p());
reOrderKeysValues.set_arg<cl_mem>(2, valuesOutput.p());
reOrderKeysValues.set_arg<uint>(3, &N);
extractInt.execute();
fillSequence.execute();
//Now sort the first 32bit keys
//Using 32bit sort with key and value seperated
gpuSort_32b(devContext,
simpleKeys, permutation,
// output32b, aPing32b,
output32b, simpleKeys,
// valuesOutput,valuesAPing,
valuesOutput,permutation,
// count,
N, 32);
//Now reorder the main keys
//Use output as the new output/src value thing buffer
reOrderKeysValues.execute();
if(subItems == 1)
{
//Only doing one 32bit sort. Data is already in output so done
return;
}
//2nd set of 32bit keys
//Idx depends on subitems, z goes first, x last if subitems = 3
//subitems = 3, than idx=1
//subitems = 2, than idx=0
//subitems = 1, completed previous round
//intIdx = subItems-2
intIdx = subItems-2;
extractInt.set_arg<cl_mem>(0, output.p());
extractInt.set_arg<int>(3, &intIdx);//smem size
reOrderKeysValues.set_arg<cl_mem>(0, output.p());
reOrderKeysValues.set_arg<cl_mem>(1, buffer.p());
extractInt.execute();
fillSequence.execute();
//Now sort the 2nd 32bit keys
//Using 32bit sort with key and value seperated
gpuSort_32b(devContext,
simpleKeys, permutation,
output32b, simpleKeys,
// output32b, aPing32b,
// valuesOutput,valuesAPing,
valuesOutput,permutation,
//count,
N, 32);
reOrderKeysValues.execute();
if(subItems == 2)
{
//Doing two 32bit sorts. Data is in buffer
//so move the data from buffer to output
output.copy(buffer, buffer.get_size());
return;
}
//3th set of 32bit keys
//Idx depends on subitems, z goes first, x last if subitems = 3
//subitems = 3, than idx=0
//subitems = 2, completed previous round
//subitems = 1, completed previous round
//intIdx = subItems-2
intIdx = 0;
extractInt.set_arg<cl_mem>(0, buffer.p());
extractInt.set_arg<int>(3, &intIdx);//integer idx
reOrderKeysValues.set_arg<cl_mem>(0, buffer.p());
reOrderKeysValues.set_arg<cl_mem>(1, output.p());
extractInt.execute();
fillSequence.execute();
//Now sort the 32bit keys
//Using int2 with key and value combined
//See sortArray4
//Using key and value in a seperate array
//Now sort the 2nd 32bit keys
//Using 32bit sort with key and value seperated
gpuSort_32b(devContext,
simpleKeys, permutation,
output32b, simpleKeys,
// output32b, aPing32b,
// valuesOutput,valuesAPing,
valuesOutput,permutation,
//count,
N, 32);
reOrderKeysValues.execute();
clFinish(devContext.get_command_queue());
// fprintf(stderr, "sortArray2 done in %g sec (Without memory alloc & compilation) \n", get_time() - t0);
}
void octree::gpuSort_32b(my_dev::context &devContext,
my_dev::dev_mem<uint> &srcKeys, my_dev::dev_mem<uint> &srcValues,
my_dev::dev_mem<int> &keysOutput, my_dev::dev_mem<uint> &keysAPing,
my_dev::dev_mem<uint> &valuesOutput,my_dev::dev_mem<uint> &valuesAPing,
int N, int numberOfBits)
{
int bitIdx = 0;
//Step 1, do the count
//Memory that should be alloced outside the function:
setupParams sParam;
sParam.jobs = (N / 64) / 480 ; //64=32*2 2 items per look, 480 is 120*4, number of procs
sParam.blocksWithExtraJobs = (N / 64) % 480;
sParam.extraElements = N % 64;
sParam.extraOffset = N - sParam.extraElements;
sortCount.set_arg<cl_mem>(0, srcKeys.p());
sortCount.set_arg<cl_mem>(1, this->devMemCounts.p());
sortCount.set_arg<uint>(2, &N);
sortCount.set_arg<int>(3, NULL, 128);//smem size
sortCount.set_arg<setupParams>(4, &sParam);
sortCount.set_arg<int>(5, &bitIdx);
vector<size_t> localWork(2), globalWork(2);
globalWork[0] = 32*120; globalWork[1] = 4;
localWork [0] = 32; localWork[1] = 4;
sortCount.setWork(globalWork, localWork);
///////////////
exScanBlock.set_arg<cl_mem>(0, this->devMemCounts.p());
int blocks = 120*4;
exScanBlock.set_arg<int>(1, &blocks);
exScanBlock.set_arg<cl_mem>(2, this->devMemCountsx.p());
exScanBlock.set_arg<int>(3, NULL, 512); //shared memory allocation
globalWork[0] = 512; globalWork[1] = 1;
localWork [0] = 512; localWork [1] = 1;
exScanBlock.setWork(globalWork, localWork);
//////////////
sortMove.set_arg<cl_mem>(0, srcKeys.p());
sortMove.set_arg<cl_mem>(1, keysOutput.p());
sortMove.set_arg<cl_mem>(2, srcValues.p());
sortMove.set_arg<cl_mem>(3, valuesOutput.p());
sortMove.set_arg<cl_mem>(4, this->devMemCounts.p());
sortMove.set_arg<uint>(5, &N);
sortMove.set_arg<uint>(6, NULL, 192); //Dynamic shared memory 128+64 , prefux sum buffer
sortMove.set_arg<uint>(7, NULL, 64*4); //Dynamic shared memory stage buffer
sortMove.set_arg<uint>(8, NULL, 64*4); //Dynamic shared memory stage_values buffer
sortMove.set_arg<setupParams>(9, &sParam);
sortMove.set_arg<int>(10, &bitIdx);
globalWork[0] = 120*32; globalWork[1] = 4;
localWork [0] = 32; localWork [1] = 4;
sortMove.setWork(globalWork, localWork);
bool pingPong = false;
//Execute bitIdx 0
sortCount.execute();
exScanBlock.execute();
sortMove.execute();
//Swap buffers
sortCount.set_arg<cl_mem>(0, keysOutput.p());
sortMove.set_arg<cl_mem>(0, keysOutput.p());
sortMove.set_arg<cl_mem>(1, keysAPing.p());
sortMove.set_arg<cl_mem>(2, valuesOutput.p());
sortMove.set_arg<cl_mem>(3, valuesAPing.p());
//Remaining bits, ping ponging buffers
for(int i=1; i < numberOfBits; i++)
{
bitIdx = i;
sortCount.set_arg<int>(5, &bitIdx);
sortMove.set_arg<int>(10, &bitIdx);
sortCount.execute();
exScanBlock.execute();
sortMove.execute();
//Switch buffers
if(pingPong)
{
sortCount.set_arg<cl_mem>(0, keysOutput.p());
sortMove.set_arg<cl_mem>(0, keysOutput.p());
sortMove.set_arg<cl_mem>(1, keysAPing.p());
sortMove.set_arg<cl_mem>(2, valuesOutput.p());
sortMove.set_arg<cl_mem>(3, valuesAPing.p());
pingPong = false;
}
else
{
sortCount.set_arg<cl_mem>(0, keysAPing.p());
sortMove.set_arg<cl_mem>(0, keysAPing.p());
sortMove.set_arg<cl_mem>(1, keysOutput.p());
sortMove.set_arg<cl_mem>(2, valuesAPing.p());
sortMove.set_arg<cl_mem>(3, valuesOutput.p());
pingPong = true;
}
}
#ifdef USE_CUDA
cuCtxSynchronize();
#else
clFinish(devContext.get_command_queue());
#endif
// fprintf(stderr, "sortArray2_32b done in %g sec\n", get_time() - t0);
}
| gpl-3.0 |
l33tRS/E2Power | lua/entities/gmod_wire_expression2/core/custom/particles.lua | 9240 | local ParticlesThisSecond = {}
local Grav = {}
local Particles = {}
local rad2deg = 180 / math.pi
local asin = math.asin
local atan2 = math.atan2
local AlwaysRender = 1
local MaxParticlesPerSecond = CreateConVar( "sbox_e2_maxParticlesPerSecond", "100", FCVAR_ARCHIVE )
local function bearing(pos, plyer)
pos = plyer:WorldToLocal(Vector(pos[1],pos[2],pos[3]))
return rad2deg*-atan2(pos.y, pos.x)
end
local function elevation(pos, plyer)
pos = plyer:WorldToLocal(Vector(pos[1],pos[2],pos[3]))
local len = pos:Length()
if len < delta then return 0 end
return rad2deg*asin(pos.z / len)
end
local function message(Duration, StartSize, EndSize, RGB, Position, Velocity, String, nom, Pitch, RollDelta, StartAlpha, EndAlpha)
local eplayers = RecipientFilter()
if(AlwaysRender==0) then
for k, v in pairs(player.GetAll()) do
local ply = v
if(IsValid(ply)) then
if(Grav[nom]==nil) then Grav[nom] = Vector(0,0,-9.8) end
Gravi = Vector(Grav[nom][1],Grav[nom][2],Grav[nom][3])
local Posi = Vector(Position[1],Position[2],Position[3])
for i=1,5 do
local Velo = Vector(Velocity[1],Velocity[2],Velocity[3])-(Gravi*i)
local P = bearing(Posi+(Velo*i),ply)
local Y = elevation(Posi+(Velo*i),ply)
if (math.abs(Y) < 100) then
if (math.abs(P) < 100) then
eplayers:AddPlayer(ply)
break
end
end
end
end
end
else
eplayers:AddAllPlayers()
end
umsg.Start("e2p_pm",eplayers)
umsg.Entity(nom)
umsg.Char(RollDelta)
umsg.Char(StartAlpha)
umsg.Char(EndAlpha)
umsg.Short(StartSize)
umsg.Float(Duration)
umsg.Float(EndSize)
umsg.Float(Pitch)
umsg.Vector(Vector(Position[1],Position[2],Position[3]))
umsg.Vector(Vector(RGB[1],RGB[2],RGB[3]))
umsg.Vector(Vector(Velocity[1],Velocity[2],Velocity[3]))
umsg.String(String)
umsg.End()
eplayers:RemoveAllPlayers()
end
local function SetMaxE2Particles( player, command, arguments)
if(player:IsSuperAdmin()) then
MaxParticlesPerSecond = tonumber(arguments[1])
end
end
local function SetAlwaysRenderParticles( player, command, arguments)
if(player:IsSuperAdmin()) then
AlwaysRender = tonumber(arguments[1])
end
end
local function ParticlesTimer(timerName,PlyID)
timer.Destroy(timerName)
ParticlesThisSecond[PlyID] = 0
end
concommand.Add("wire_e2_SetAlwaysRenderParticles",SetAlwaysRenderParticles)
concommand.Add("wire_e2_maxParticlesPerSecond",SetMaxE2Particles)
for k=1, game.MaxPlayers() do ParticlesThisSecond[k]=0 end
local function SpawnParticle(self, Duration, StartSize, EndSize, Mat, RGB, Position, Velocity, Pitch, RollDelta, StartAlpha, EndAlpha)
local PlyID = self.player:EntIndex()
local timerName = "e2p_"..PlyID
if ParticlesThisSecond[PlyID] <= MaxParticlesPerSecond:GetInt() then
if Pitch==nil then Pitch=0 end
if string.find(Mat:lower(),"pp",1,true) then return end
if string.find(Mat:lower(),"comshieldwall",1,true) then return end
if RollDelta==nil then RollDelta=0 end
if StartAlpha==nil then StartAlpha=255 end
if EndAlpha==nil then EndAlpha=StartAlpha end
message(Duration, StartSize, EndSize, RGB, Position, Velocity, Mat, self.entity, Pitch, RollDelta, StartAlpha-128, EndAlpha-128)
ParticlesThisSecond[PlyID] = ParticlesThisSecond[PlyID] + 1
if !timer.Exists(timerName) then
timer.Create(timerName, 1, 0, function() ParticlesTimer(timerName,PlyID) end)
end
end
end
__e2setcost(20)
e2function void particle(Duration, StartSize, EndSize, string Mat, vector RGB, vector Position, vector Velocity, Pitch, RollDelta, StartAlpha, EndAlpha)
SpawnParticle(self, Duration, StartSize, EndSize, Mat, RGB, Position, Velocity, Pitch, RollDelta, StartAlpha, EndAlpha)
end
e2function void particle(Duration, StartSize, EndSize, string Mat, vector RGB, vector Position, vector Velocity, Pitch, RollDelta)
SpawnParticle(self, Duration, StartSize, EndSize, Mat, RGB, Position, Velocity, Pitch, RollDelta)
end
e2function void particle(Duration, StartSize, EndSize, string Mat, vector RGB, vector Position, vector Velocity, Pitch)
SpawnParticle(self, Duration, StartSize, EndSize, Mat, RGB, Position, Velocity, Pitch)
end
e2function void particle(Duration, StartSize, EndSize, string Mat, vector RGB, vector Position, vector Velocity)
SpawnParticle(self, Duration, StartSize, EndSize, Mat, RGB, Position, Velocity)
end
__e2setcost(5)
e2function void particleBounce(Bounce)
umsg.Start("e2p_bounce")
umsg.Entity(self.entity)
umsg.Long(math.Round(Bounce))
umsg.End()
end
e2function void particleGravity(vector Gravity)
umsg.Start("e2p_gravity")
umsg.Entity(self.entity)
umsg.Vector(Vector(Gravity[1],Gravity[2],Gravity[3]))
umsg.End()
Grav[self.entity] = Gravity
end
e2function void particleCollision(Number)
umsg.Start("e2p_collide")
umsg.Entity(self.entity)
umsg.Long(Number)
umsg.End()
end
e2function array particlesList()
return Particles
end
__e2setcost(nil)
Particles[0]="effects/blooddrop"
Particles[1]="effects/bloodstream"
Particles[2]="effects/laser_tracer"
Particles[3]="effects/select_dot"
Particles[4]="effects/select_ring"
Particles[5]="effects/tool_tracer"
Particles[6]="effects/wheel_ring"
Particles[7]="effects/base"
Particles[8]="effects/blood"
Particles[9]="effects/blood2"
Particles[10]="effects/blood_core"
Particles[11]="effects/blood_drop"
Particles[12]="effects/blood_gore"
Particles[13]="effects/blood_puff"
Particles[14]="effects/blueblackflash"
Particles[15]="effects/blueblacklargebeam"
Particles[16]="effects/blueflare1"
Particles[17]="effects/bluelaser1"
Particles[18]="effects/bluemuzzle"
Particles[19]="effects/bluespark"
Particles[20]="effects/bubble"
Particles[21]="effects/combinemuzzle1"
Particles[22]="effects/combinemuzzle1_dark"
Particles[23]="effects/combinemuzzle2"
Particles[24]="effects/combinemuzzle2_dark"
Particles[25]="effects/energyball"
Particles[26]="effects/energysplash"
Particles[27]="effects/exit1"
Particles[28]="effects/fire_cloud1"
Particles[29]="effects/fire_cloud2"
Particles[30]="effects/fire_embers1"
Particles[31]="effects/fire_embers2"
Particles[32]="effects/fire_embers3"
Particles[33]="effects/fleck_glass1"
Particles[34]="effects/fleck_glass2"
Particles[35]="effects/fleck_glass3"
Particles[36]="effects/fleck_tile1"
Particles[37]="effects/fleck_tile2"
Particles[38]="effects/fleck_wood1"
Particles[39]="effects/fleck_wood2"
Particles[40]="effects/fog_d1_trainstation_02"
Particles[41]="effects/gunshipmuzzle"
Particles[42]="effects/gunshiptracer"
Particles[43]="effects/hydragutbeam"
Particles[44]="effects/hydragutbeamcap"
Particles[45]="effects/hydraspinalcord"
Particles[46]="effects/laser1"
Particles[47]="effects/laser_citadel1"
Particles[48]="effects/mh_blood1"
Particles[49]="effects/mh_blood2"
Particles[50]="effects/mh_blood3"
Particles[51]="effects/muzzleflash1"
Particles[52]="effects/muzzleflash2"
Particles[53]="effects/muzzleflash3"
Particles[54]="effects/muzzleflash4"
Particles[55]="effects/redflare"
Particles[56]="effects/rollerglow"
Particles[57]="effects/slime1"
Particles[59]="effects/spark"
Particles[59]="effects/splash1"
Particles[60]="effects/splash2"
Particles[61]="effects/splash3"
Particles[62]="effects/splash4"
Particles[63]="effects/splashwake1"
Particles[64]="effects/splashwake3"
Particles[65]="effects/splashwake4"
Particles[66]="effects/strider_bulge_dudv"
Particles[67]="effects/strider_muzzle"
Particles[68]="effects/strider_pinch_dudv"
Particles[69]="effects/strider_tracer"
Particles[70]="effects/stunstick"
Particles[71]="effects/tracer_cap"
Particles[72]="effects/tracer_middle"
Particles[73]="effects/tracer_middle2"
Particles[74]="effects/water_highlight"
Particles[75]="effects/yellowflare"
Particles[76]="effects/muzzleflashX"
Particles[77]="effects/ember_swirling001"
Particles[78]="shadertest/eyeball"
Particles[79]="sprites/bloodparticle"
Particles[80]="sprites/animglow02"
Particles[81]="sprites/ar2_muzzle1"
Particles[82]="sprites/ar2_muzzle3"
Particles[83]="sprites/ar2_muzzle4"
Particles[84]="sprites/flamelet1"
Particles[85]="sprites/flamelet2"
Particles[86]="sprites/flamelet3"
Particles[87]="sprites/flamelet4"
Particles[88]="sprites/flamelet5"
Particles[89]="sprites/glow03"
Particles[90]="sprites/light_glow02"
Particles[91]="sprites/orangecore1"
Particles[92]="sprites/orangecore2"
Particles[93]="sprites/orangeflare1"
Particles[94]="sprites/plasmaember"
Particles[95]="sprites/redglow1"
Particles[96]="sprites/redglow2"
Particles[97]="sprites/rico1"
Particles[98]="sprites/strider_blackball"
Particles[99]="sprites/strider_bluebeam"
Particles[100]="sprites/tp_beam001"
Particles[101]="sprites/yellowflare"
Particles[102]="sprites/frostbreath"
Particles[103]="sprites/sent_ball"
| gpl-3.0 |
joemckie/horizon-framework | horizon/_theme/templates/shortcodes/divider/divider.php | 313 | <?php
global $shortcode_atts;
extract( shortcode_atts( array(
"scroll_text" => ""
), $shortcode_atts['atts'] ) );
?>
<div class="horizon-divider">
<div class="horizon-divider-colour"></div>
<?php if ( $scroll_text !== "" ) {
echo '<div class="horizon-scroll-to-top">' . $scroll_text . '</div>';
} ?>
</div> | gpl-3.0 |
PvtTony/wechatlab | src/main/java/me/songt/wechatlab/handler/StoreCheckNotifyHandler.java | 717 | package me.songt.wechatlab.handler;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;
import java.util.Map;
@Component
public class StoreCheckNotifyHandler extends AbstractHandler
{
@Override
public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
Map<String, Object> context, WxMpService wxMpService,
WxSessionManager sessionManager)
{
// TODO 处理门店审核事件
return null;
}
}
| gpl-3.0 |
thomasahle/TrinityProject | core/src/main/java/com/github/thomasahle/trainbox/trainbox/uimodel/UISeparateComponent.java | 6841 | package com.github.thomasahle.trainbox.trainbox.uimodel;
import static playn.core.PlayN.assets;
import static playn.core.PlayN.graphics;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import playn.core.CanvasImage;
import playn.core.Image;
import playn.core.Layer;
import playn.core.PlayN;
import pythagoras.f.Dimension;
import pythagoras.f.Point;
public class UISeparateComponent extends AbstractComponent {
private static final float DOWN_LEVEL = 0.15f;
private static final float UP_LEVEL = 0.95f;
private Layer mBackLayer, mFrontLayer;
private int mWidth, mHeight;
private LinkedList<UITrain> mLeftSide = new LinkedList<UITrain>();
private LinkedList<UITrain> mRightSide = new LinkedList<UITrain>();
private final static int KNIFE_WIDTH = 10;
private final static float KNIFE_CYCLE = 1000f;
private Layer mKnifeLayer;
private float mKnifeT = 0;
public UISeparateComponent() {
Image concatComponentImage = assets().getImage("images/pngs/concatComponent.png");
mBackLayer = graphics().createImageLayer(concatComponentImage);
mWidth = concatComponentImage.width();
mHeight = concatComponentImage.height();
CanvasImage knifeImage = graphics().createImage(KNIFE_WIDTH, mHeight);
playn.core.Path knifePath = knifeImage.canvas().createPath();
knifePath.moveTo(KNIFE_WIDTH/2, 0);
knifePath.lineTo(KNIFE_WIDTH, mHeight);
knifePath.lineTo(0, mHeight);
knifePath.lineTo(KNIFE_WIDTH/2, 0);
knifeImage.canvas().setFillColor(0xff000000).fillPath(knifePath);
mKnifeLayer = graphics().createImageLayer(knifeImage);
mFrontLayer = mKnifeLayer;
}
@Override
public Layer getBackLayer() {
return mBackLayer;
}
@Override
public Layer getFrontLayer() {
return mFrontLayer;
}
@Override
public List<UITrain> getTrains() {
List<UITrain> trains = new ArrayList<UITrain>(mLeftSide);
trains.addAll(mRightSide);
return trains;
}
@Override
public Dimension getSize() {
return new Dimension(mWidth, mHeight);
}
@Override public void setPosition(Point position) {
super.setPosition(position);
updateKnife();
}
/**
* @param percentage 0.05 if the gate must be at least 5% up.
* @return whether the gate is now that much up.
*/
private boolean isUp(float percentage) {
return percentage <= 1-gateY(mKnifeT)/mHeight;
}
@Override
public void update(float delta) {
if (paused())
return;
mKnifeT += delta;
float knifeX = getSize().width/2 + getDeepPosition().x;
float compLeft = getDeepPosition().x;
float compRight = compLeft + getSize().width;
// Check if the front left train is ready to be cut
if (mLeftSide.size() >= 1) {
UITrain train = mLeftSide.getFirst();
float trainLeft = train.getPosition().x;
float carLeft = trainLeft + train.getCarriages().get(0).getPosition().x;
if (train.getCarriages().size() > 1 && carLeft-knifeX > -1) {
// Wait for the knife to go up.
// XXX: This would be nicer if the train remembered what time it
// started to wait, so we don't risk livelocks due to evil delta values.
if (isUp(UP_LEVEL)) {
UITrain head = train.cutOffHead();
fireTrainCreated(head);
mLeftSide.addFirst(head);
}
}
}
// First make sure all the trains that belong in mRightSide are there
for (Iterator<UITrain> it = mLeftSide.iterator(); it.hasNext(); ) {
UITrain train = it.next();
float trainLeft = train.getPosition().x;
float trainRight = trainLeft + train.getSize().width;
// If the train has passed (only small trains can pass)
if (trainLeft >= knifeX - 1) {
assert train.getCarriages().size() == 1;
it.remove();
if (trainRight > compRight) {
getTrainTaker().takeTrain(train);
if (trainLeft < compRight) {
mRightSide.add(train);
}
}
}
}
// The right side is easy to move
float rightBorder = moveTrains(mRightSide, delta);
int actualLefties = 0;
// The left side requires more thought
for (UITrain train : mLeftSide) {
float trainLeft = train.getPosition().x;
float trainRight = trainLeft + train.getSize().width;
float carLeft = trainLeft + train.getCarriages().get(0).getPosition().x;
// We don't enforce the PADDING between two trains seperated by the knife.
// If we did that the left part of a train would jump back, when seperated from its head.
if (trainRight <= knifeX + 0.1f)
actualLefties += 1;
if (actualLefties == 1)
rightBorder = Math.max(rightBorder, knifeX);
float newRight = Math.min(rightBorder, trainRight + train.speed*delta);
// If we are already on the knife, hold it down
if (carLeft + 1f < knifeX && knifeX <= trainRight - 1f) {
mKnifeT = 0;
}
// If we are on the left side of the knife, and its up, we have to wait
if (trainRight - 0.1f < knifeX && isUp(DOWN_LEVEL)) {
newRight = Math.min(newRight, knifeX);
}
// If we are a big train, we can't go too far even if its down
if (train.getCarriages().size() > 1) {
newRight = Math.min(newRight, knifeX + UICarriage.WIDTH);
}
// Note: if the train is small, we may let it go all the way to rightBorder.
// The next update should take care of moving it to rightSide and then takeTrain if necessary.
float newLeft = newRight - train.getSize().width;
//newLeft = Math.max(trainLeft, newLeft);
//assert newLeft >= trainLeft;
train.setPosition(new Point(newLeft, train.getPosition().y));
rightBorder = Math.min(rightBorder, newLeft-UITrain.PADDING);
}
// Animate the knife
updateKnife();
}
private void updateKnife() {
float x = getSize().width/2-KNIFE_WIDTH/2.f;
float y = gateY(mKnifeT);
mKnifeLayer.setTranslation(x + getPosition().x, y + getPosition().y);
mKnifeLayer.setScale(1, (mHeight-y)/mHeight+1e-9f);
}
private float gateY(float t) {
return (float)(mHeight*(Math.cos(t/KNIFE_CYCLE*(2*Math.PI))+1)/2);
}
@Override
public void takeTrain(UITrain train) {
assert train.getPosition().x + train.getSize().width <= leftBlock();
mLeftSide.add(train);
}
@Override
public float leftBlock() {
// Never go further than the knife
float res = getSize().width/2 + getDeepPosition().x - 0.1f;
// Unless it is down.
// Really we should handle single trains differently, as they may move
// even further, but we have no way to do that.
if (!isUp(DOWN_LEVEL))
res += UICarriage.WIDTH;
// Don't overlap trains we currently manage
if (!mLeftSide.isEmpty())
res = Math.min(res, mLeftSide.getLast().getPosition().x - UITrain.PADDING);
return res;
}
@Override
public void reset() {
mLeftSide.clear();
mRightSide.clear();
}
@Override
public void updateMaxLengthTrainExpected(int compNum, int len){
this.maxExpectedLength = len;
mTrainTaker.updateMaxLengthTrainExpected(compNum+1, 1);
}
}
| gpl-3.0 |
JBerkvens/SE42 | Auction_Server/src/main/java/auction/dao/ItemDAOJPAImpl.java | 2092 | package auction.dao;
import auction.domain.Bid;
import auction.domain.Item;
import auction.domain.User;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
/**
*
* @author Jeroen
*/
public class ItemDAOJPAImpl implements ItemDAO {
private final EntityManager em;
private final UserDAO userdao;
public ItemDAOJPAImpl(EntityManager em) {
this.em = em;
this.userdao = new UserDAOJPAImpl(em);
}
@Override
public int count() {
Query q = em.createNamedQuery("Item.count", Item.class);
return ((Long) q.getSingleResult()).intValue();
}
@Override
public void create(Item item) {
User user = userdao.findByEmail(item.getSeller().getEmail());
if (user == null) {
userdao.create(item.getSeller());
}
em.persist(item);
}
@Override
public void edit(Item item) {
em.merge(item);
}
@Override
public Item find(Long id) {
try {
return em.find(Item.class, id);
} catch (Exception ex) {
return null;
}
}
@Override
public List<Item> findAll() {
Query q = em.createNamedQuery("Item.getAll", Item.class);
try {
List<Item> items = q.getResultList();
return items;
} catch (Exception ex) {
return null;
}
}
@Override
public List<Item> findByDescription(String description) {
Query q = em.createNamedQuery("Item.findByDescription", Item.class);
q.setParameter("description", description);
try {
return new ArrayList<>(q.getResultList());
} catch (Exception ex) {
return null;
}
}
@Override
public void remove(Item item) {
em.remove(em.merge(item));
}
@Override
public boolean addBid(Item item, Bid bid) {
em.persist(bid);
return true;
}
}
| gpl-3.0 |
MailCleaner/MailCleaner | www/framework/Zend/Json/Decoder.php | 18937 | <?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 [email protected] so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Json
* @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: Decoder.php,v 1.1.2.3 2011-05-30 08:31:07 root Exp $
*/
/**
* @see Zend_Json
*/
require_once 'Zend/Json.php';
/**
* Decode JSON encoded string to PHP variable constructs
*
* @category Zend
* @package Zend_Json
* @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_Json_Decoder
{
/**
* Parse tokens used to decode the JSON object. These are not
* for public consumption, they are just used internally to the
* class.
*/
const EOF = 0;
const DATUM = 1;
const LBRACE = 2;
const LBRACKET = 3;
const RBRACE = 4;
const RBRACKET = 5;
const COMMA = 6;
const COLON = 7;
/**
* Use to maintain a "pointer" to the source being decoded
*
* @var string
*/
protected $_source;
/**
* Caches the source length
*
* @var int
*/
protected $_sourceLength;
/**
* The offset within the souce being decoded
*
* @var int
*
*/
protected $_offset;
/**
* The current token being considered in the parser cycle
*
* @var int
*/
protected $_token;
/**
* Flag indicating how objects should be decoded
*
* @var int
* @access protected
*/
protected $_decodeType;
/**
* Constructor
*
* @param string $source String source to decode
* @param int $decodeType How objects should be decoded -- see
* {@link Zend_Json::TYPE_ARRAY} and {@link Zend_Json::TYPE_OBJECT} for
* valid values
* @return void
*/
protected function __construct($source, $decodeType)
{
// Set defaults
$this->_source = self::decodeUnicodeString($source);
$this->_sourceLength = strlen($this->_source);
$this->_token = self::EOF;
$this->_offset = 0;
// Normalize and set $decodeType
if (!in_array($decodeType, array(Zend_Json::TYPE_ARRAY, Zend_Json::TYPE_OBJECT)))
{
$decodeType = Zend_Json::TYPE_ARRAY;
}
$this->_decodeType = $decodeType;
// Set pointer at first token
$this->_getNextToken();
}
/**
* Decode a JSON source string
*
* Decodes a JSON encoded string. The value returned will be one of the
* following:
* - integer
* - float
* - boolean
* - null
* - StdClass
* - array
* - array of one or more of the above types
*
* By default, decoded objects will be returned as associative arrays; to
* return a StdClass object instead, pass {@link Zend_Json::TYPE_OBJECT} to
* the $objectDecodeType parameter.
*
* Throws a Zend_Json_Exception if the source string is null.
*
* @static
* @access public
* @param string $source String to be decoded
* @param int $objectDecodeType How objects should be decoded; should be
* either or {@link Zend_Json::TYPE_ARRAY} or
* {@link Zend_Json::TYPE_OBJECT}; defaults to TYPE_ARRAY
* @return mixed
* @throws Zend_Json_Exception
*/
public static function decode($source = null, $objectDecodeType = Zend_Json::TYPE_ARRAY)
{
if (null === $source) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Must specify JSON encoded source for decoding');
} elseif (!is_string($source)) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Can only decode JSON encoded strings');
}
$decoder = new self($source, $objectDecodeType);
return $decoder->_decodeValue();
}
/**
* Recursive driving rountine for supported toplevel tops
*
* @return mixed
*/
protected function _decodeValue()
{
switch ($this->_token) {
case self::DATUM:
$result = $this->_tokenValue;
$this->_getNextToken();
return($result);
break;
case self::LBRACE:
return($this->_decodeObject());
break;
case self::LBRACKET:
return($this->_decodeArray());
break;
default:
return null;
break;
}
}
/**
* Decodes an object of the form:
* { "attribute: value, "attribute2" : value,...}
*
* If Zend_Json_Encoder was used to encode the original object then
* a special attribute called __className which specifies a class
* name that should wrap the data contained within the encoded source.
*
* Decodes to either an array or StdClass object, based on the value of
* {@link $_decodeType}. If invalid $_decodeType present, returns as an
* array.
*
* @return array|StdClass
*/
protected function _decodeObject()
{
$members = array();
$tok = $this->_getNextToken();
while ($tok && $tok != self::RBRACE) {
if ($tok != self::DATUM || ! is_string($this->_tokenValue)) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing key in object encoding: ' . $this->_source);
}
$key = $this->_tokenValue;
$tok = $this->_getNextToken();
if ($tok != self::COLON) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing ":" in object encoding: ' . $this->_source);
}
$tok = $this->_getNextToken();
$members[$key] = $this->_decodeValue();
$tok = $this->_token;
if ($tok == self::RBRACE) {
break;
}
if ($tok != self::COMMA) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing "," in object encoding: ' . $this->_source);
}
$tok = $this->_getNextToken();
}
switch ($this->_decodeType) {
case Zend_Json::TYPE_OBJECT:
// Create new StdClass and populate with $members
$result = new StdClass();
foreach ($members as $key => $value) {
$result->$key = $value;
}
break;
case Zend_Json::TYPE_ARRAY:
default:
$result = $members;
break;
}
$this->_getNextToken();
return $result;
}
/**
* Decodes a JSON array format:
* [element, element2,...,elementN]
*
* @return array
*/
protected function _decodeArray()
{
$result = array();
$starttok = $tok = $this->_getNextToken(); // Move past the '['
$index = 0;
while ($tok && $tok != self::RBRACKET) {
$result[$index++] = $this->_decodeValue();
$tok = $this->_token;
if ($tok == self::RBRACKET || !$tok) {
break;
}
if ($tok != self::COMMA) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Missing "," in array encoding: ' . $this->_source);
}
$tok = $this->_getNextToken();
}
$this->_getNextToken();
return($result);
}
/**
* Removes whitepsace characters from the source input
*/
protected function _eatWhitespace()
{
if (preg_match(
'/([\t\b\f\n\r ])*/s',
$this->_source,
$matches,
PREG_OFFSET_CAPTURE,
$this->_offset)
&& $matches[0][1] == $this->_offset)
{
$this->_offset += strlen($matches[0][0]);
}
}
/**
* Retrieves the next token from the source stream
*
* @return int Token constant value specified in class definition
*/
protected function _getNextToken()
{
$this->_token = self::EOF;
$this->_tokenValue = null;
$this->_eatWhitespace();
if ($this->_offset >= $this->_sourceLength) {
return(self::EOF);
}
$str = $this->_source;
$str_length = $this->_sourceLength;
$i = $this->_offset;
$start = $i;
switch ($str{$i}) {
case '{':
$this->_token = self::LBRACE;
break;
case '}':
$this->_token = self::RBRACE;
break;
case '[':
$this->_token = self::LBRACKET;
break;
case ']':
$this->_token = self::RBRACKET;
break;
case ',':
$this->_token = self::COMMA;
break;
case ':':
$this->_token = self::COLON;
break;
case '"':
$result = '';
do {
$i++;
if ($i >= $str_length) {
break;
}
$chr = $str{$i};
if ($chr == '\\') {
$i++;
if ($i >= $str_length) {
break;
}
$chr = $str{$i};
switch ($chr) {
case '"' :
$result .= '"';
break;
case '\\':
$result .= '\\';
break;
case '/' :
$result .= '/';
break;
case 'b' :
$result .= "\x08";
break;
case 'f' :
$result .= "\x0c";
break;
case 'n' :
$result .= "\x0a";
break;
case 'r' :
$result .= "\x0d";
break;
case 't' :
$result .= "\x09";
break;
case '\'' :
$result .= '\'';
break;
default:
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("Illegal escape "
. "sequence '" . $chr . "'");
}
} elseif($chr == '"') {
break;
} else {
$result .= $chr;
}
} while ($i < $str_length);
$this->_token = self::DATUM;
//$this->_tokenValue = substr($str, $start + 1, $i - $start - 1);
$this->_tokenValue = $result;
break;
case 't':
if (($i+ 3) < $str_length && substr($str, $start, 4) == "true") {
$this->_token = self::DATUM;
}
$this->_tokenValue = true;
$i += 3;
break;
case 'f':
if (($i+ 4) < $str_length && substr($str, $start, 5) == "false") {
$this->_token = self::DATUM;
}
$this->_tokenValue = false;
$i += 4;
break;
case 'n':
if (($i+ 3) < $str_length && substr($str, $start, 4) == "null") {
$this->_token = self::DATUM;
}
$this->_tokenValue = NULL;
$i += 3;
break;
}
if ($this->_token != self::EOF) {
$this->_offset = $i + 1; // Consume the last token character
return($this->_token);
}
$chr = $str{$i};
if ($chr == '-' || $chr == '.' || ($chr >= '0' && $chr <= '9')) {
if (preg_match('/-?([0-9])*(\.[0-9]*)?((e|E)((-|\+)?)[0-9]+)?/s',
$str, $matches, PREG_OFFSET_CAPTURE, $start) && $matches[0][1] == $start) {
$datum = $matches[0][0];
if (is_numeric($datum)) {
if (preg_match('/^0\d+$/', $datum)) {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("Octal notation not supported by JSON (value: $datum)");
} else {
$val = intval($datum);
$fVal = floatval($datum);
$this->_tokenValue = ($val == $fVal ? $val : $fVal);
}
} else {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception("Illegal number format: $datum");
}
$this->_token = self::DATUM;
$this->_offset = $start + strlen($datum);
}
} else {
require_once 'Zend/Json/Exception.php';
throw new Zend_Json_Exception('Illegal Token');
}
return($this->_token);
}
/**
* Decode Unicode Characters from \u0000 ASCII syntax.
*
* This algorithm was originally developed for the
* Solar Framework by Paul M. Jones
*
* @link http://solarphp.com/
* @link http://svn.solarphp.com/core/trunk/Solar/Json.php
* @param string $value
* @return string
*/
public static function decodeUnicodeString($chrs)
{
$delim = substr($chrs, 0, 1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for($i = 0; $i < $strlen_chrs; $i++) {
$substr_chrs_c_2 = substr($chrs, $i, 2);
$ord_chrs_c = ord($chrs[$i]);
switch (true) {
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $i, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($i + 2), 2)))
. chr(hexdec(substr($chrs, ($i + 4), 2)));
$utf8 .= self::_utf162utf8($utf16);
$i += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$i};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 2);
++$i;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 3);
$i += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 4);
$i += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 5);
$i += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $i, 6);
$i += 5;
break;
}
}
return $utf8;
}
/**
* Convert a string from one UTF-16 char to one UTF-8 char.
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* This method is from the Solar Framework by Paul M. Jones
*
* @link http://solarphp.com
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
*/
protected static function _utf162utf8($utf16)
{
// Check for mb extension otherwise do by hand.
if( function_exists('mb_convert_encoding') ) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch (true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
}
| gpl-3.0 |
MattBridgeman/drum-machine | src/js/reducers/__tests__/drum.machine.test.js | 9496 | import { expect } from "chai";
import drumMachine from "../drum.machine.reducer";
import {
CHANGE_SELECTED_CHANNEL,
TOGGLE_SOLO_CHANNEL,
TOGGLE_MUTE_CHANNEL,
CHANGE_VOLUME_TO_AMOUNT,
CHANGE_PITCH_TO_AMOUNT,
CHANGE_DECAY_TO_AMOUNT,
CHANGE_PAN_TO_AMOUNT,
TOGGLE_REVERB,
TOGGLE_BEAT_STATE,
NEW_BANK_INDEX,
CHANGE_SWING_TO_AMOUNT,
CHANGE_SELECTED_SOUND
} from "../../constants/drum.machine.constants";
import {
NEW_TRACK_LOADING,
LOAD_DEFAULT_TRACK,
NEW_TRACK_LOADED
} from "../../constants/track.constants";
describe("Drum Machine reducer", function() {
function getInitialState(){
return {
0: {
swing: 0,
currentBankIndex: 0,
channels: [{
sound: 0,
patterns: {
0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
5: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
volume: 50,
pitch: 50,
decay: 100,
pan: 50,
reverb: true,
selected: true,
solo: true,
mute: false
},
{
sound: 1,
patterns: {
0: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
1: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
2: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
3: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
4: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
5: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
},
volume: 50,
pitch: 50,
decay: 100,
pan: 50,
reverb: false,
solo: false,
mute: false
}]
}
};
}
it("Expect volume value to change to amount", function() {
const channelId = 0;
const machineId = 0;
const value = 20;
const initialState = getInitialState();
const action = {
type: CHANGE_VOLUME_TO_AMOUNT,
channelId,
machineId,
value
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].volume).to.equal(20);
});
it("Expect pitch value to change to amount", function() {
const channelId = 0;
const machineId = 0;
const value = 20;
const initialState = getInitialState();
const action = {
type: CHANGE_PITCH_TO_AMOUNT,
channelId,
machineId,
value
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].pitch).to.equal(20);
});
it("Expect decay value to change to amount", function() {
const channelId = 0;
const machineId = 0;
const value = 20;
const initialState = getInitialState();
const action = {
type: CHANGE_DECAY_TO_AMOUNT,
channelId,
machineId,
value
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].decay).to.equal(20);
});
it("Expect pan value to change to amount", function() {
const channelId = 0;
const machineId = 0;
const value = 20;
const initialState = getInitialState();
const action = {
type: CHANGE_PAN_TO_AMOUNT,
channelId,
machineId,
value
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].pan).to.equal(20);
});
it("Expect reverb value to toggle from true to false", function() {
const channelId = 0;
const machineId = 0;
const initialState = getInitialState();
const action = {
type: TOGGLE_REVERB,
machineId,
channelId
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].reverb).to.equal(false);
});
it("Expect reverb value to toggle from false to true", function() {
const channelId = 1;
const machineId = 0;
const initialState = getInitialState();
const action = {
type: TOGGLE_REVERB,
machineId,
channelId
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].reverb).to.equal(true);
});
it("Expect selected channel to change", function() {
const machineId = 0;
const initialState = getInitialState();
const action = {
type: CHANGE_SELECTED_CHANNEL,
machineId,
value: 1
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels["0"].selected).to.not.equal(true);
expect(nextState[machineId].channels["1"].selected).to.equal(true);
});
it("Expect unsolo'd channel to be solo'd", function() {
const machineId = 0;
const initialState = getInitialState();
const action = {
type: TOGGLE_SOLO_CHANNEL,
machineId,
value: 1
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels["0"].solo).to.equal(true);
expect(nextState[machineId].channels["1"].solo).to.equal(true);
});
it("Expect solo'd channel to be unsolo'd", function() {
const machineId = 0;
const initialState = getInitialState();
const action = {
type: TOGGLE_SOLO_CHANNEL,
machineId,
value: 0
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels["0"].solo).to.equal(false);
expect(nextState[machineId].channels["1"].solo).to.equal(false);
});
it("Expect unmuted channel to be muted", function() {
const machineId = 0;
const initialState = getInitialState();
const action = {
type: TOGGLE_MUTE_CHANNEL,
machineId,
value: 1
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels["0"].mute).to.equal(false);
expect(nextState[machineId].channels["1"].mute).to.equal(true);
});
it("Expect muted channel to be unmuted", function() {
const machineId = 0;
const initialState = getInitialState();
const action = {
type: TOGGLE_MUTE_CHANNEL,
machineId,
value: 0
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels["0"].mute).to.equal(true);
expect(nextState[machineId].channels["1"].mute).to.equal(false);
});
it("toggles the beat for the 0 pattern bank", function() {
const machineId = 0;
const channelId = 1;
const bankId = 4;
const index = 7;
const initialState = getInitialState();
const action = {
type: TOGGLE_BEAT_STATE,
machineId,
channelId,
bankId,
index,
value: 1
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].channels[channelId].patterns[bankId][index]).to.equal(1);
});
it("changes the current bank index to the new index", function() {
const machineId = 0;
const bankId = 4;
const initialState = getInitialState();
const action = {
type: NEW_BANK_INDEX,
machineId,
value: bankId
};
const nextState = drumMachine(initialState, action);
expect(initialState).to.deep.equal(getInitialState());
expect(nextState[machineId].currentBankIndex).to.equal(bankId);
});
it("Expect swing to change to set amount", function() {
const machineId = 0;
const initialState = getInitialState();
const action = {
type: CHANGE_SWING_TO_AMOUNT,
machineId,
value: 55
};
const nextState = drumMachine(initialState, action);
expect(initialState[machineId].swing).to.equal(0);
expect(nextState[machineId].swing).to.equal(55);
});
it("clears the drum machine state on new track", function() {
const initialState = getInitialState();
const action = {
type: NEW_TRACK_LOADING
};
const nextState = drumMachine(initialState, action);
expect(nextState).to.deep.equal({});
});
it("loads the default track state", function() {
const initialState = getInitialState();
const action = {
type: LOAD_DEFAULT_TRACK
};
const nextState = drumMachine({}, action);
expect(nextState[0].currentBankIndex).to.equal(0);
expect(nextState[0].swing).to.equal(0);
});
it("loads the new track loaded state", function() {
const _drumMachine = {
0: {
currentBankIndex: 0,
swing: 0
}
};
const action = {
type: NEW_TRACK_LOADED,
drumMachine: _drumMachine
};
const nextState = drumMachine({}, action);
expect(nextState).to.deep.equal(_drumMachine);
});
it("changes the selected sound", function() {
const initialState = getInitialState();
const action = {
type: CHANGE_SELECTED_SOUND,
machineId: 0,
channelId: 0,
value: 1234
};
const nextState = drumMachine(initialState, action);
expect(nextState[0].channels[0].sound).to.deep.equal(1234);
expect(nextState[0].channels[1].sound).to.deep.equal(1);
});
}); | gpl-3.0 |
avz-cmf/zaboy-utils | src/DataStore/Email.php | 3013 | <?php
namespace zaboy\utils\DataStore;
use zaboy\rest\DataStore\DbTable;
use Zend\Db\TableGateway\TableGateway;
use zaboy\utils\Api\Gmail as ApiGmail;
use zaboy\utils\Json\Coder as JsonCoder;
use Zend\Db\Adapter\AdapterInterface;
use zaboy\res\Di\InsideConstruct;
/**
*
* time GMT
* @see http://stackoverflow.com/questions/33912834/gmail-api-not-returning-correct-emails-compared-to-gmail-web-ui-for-date-queries/33919375#33919375
* @see http://stackoverflow.com/questions/33552890/why-does-search-in-gmail-api-return-different-result-than-search-in-gmail-websit
*
* @see http://stackoverflow.com/search?q=PHP%2C+Gmail+API+read
* @see https://github.com/adevait/GmailPHP/blob/master/examples/messages.php
* @see https://developers.google.com/gmail/api/quickstart/php#step_1_install_the_google_client_library
*/
class Email extends DbTable
{
const TABLE_NAME = 'emails';
//
const MESSAGE_ID = 'id';
const SUBJECT = 'subject';
const SENDING_TIME = 'sending_time';
const BODY_HTML = 'body_html';
const BODY_TXT = 'body_txt';
const HEADERS = 'headers';
const STATUS = 'status';
//
const STATUS_IS_PARSED = 'PARSED';
const STATUS_IS_NOT_PARSED = 'NOT PARSED';
/**
*
* @var ApiGmail
*/
protected $apiEmail;
/**
*
* @var AdapterInterface
*/
protected $emailDbAdapter;
public function __construct($emailDbAdapter = null)
{
//set $this->emailDbAdapter as $cotainer->get('emailDbAdapter');
InsideConstruct::initServices();
$dbTable = new TableGateway(static::TABLE_NAME, $this->emailDbAdapter);
parent::__construct($dbTable);
$this->apiEmail = new ApiGmail;
}
public function getApiGmail()
{
return $this->apiEmail;
}
public function setApiGmail(ApiGmail $apiEmail)
{
$this->apiEmail = $apiEmail;
}
public function addMessageData($message)
{
$messageId = is_object($message) ? $message->getId() : $message;
$item[self::MESSAGE_ID] = $messageId;
$item[self::SUBJECT] = $this->apiEmail->getSubject($message);
$item[self::SENDING_TIME] = strtotime($this->apiEmail->getDate($message)) + 8 * 60 * 60;
$bodyHtml = $this->apiEmail->getBodyHtml($message);
$item[self::BODY_HTML] = is_array($bodyHtml) ? implode(' ', $bodyHtml) : $bodyHtml;
$bodyTxt = $this->apiEmail->getBodyTxt($message);
$item[self::BODY_TXT] = is_array($bodyTxt) ? implode(' ', $bodyTxt) : $bodyTxt;
$item[self::HEADERS] = JsonCoder::jsonEncode($this->apiEmail->getHeader($message));
$item[self::STATUS] = self::STATUS_IS_NOT_PARSED;
return $this->create($item, true);
}
public function addMessageId($message)
{
$messageId = is_object($message) ? $message->getId() : $message;
$item[self::MESSAGE_ID] = $messageId;
$item[self::STATUS] = self::STATUS_IS_NOT_PARSED;
return $this->create($item, true);
}
}
| gpl-3.0 |
rivetlogic/liferay-elasticsearch-integration | portlets/elasticsearch-portlet/docroot/WEB-INF/src/com/rivetlogic/elasticsearch/portlet/exception/ElasticsearchAutocompleteException.java | 1807 | /**
* Copyright (C) 2005-2014 Rivet Logic Corporation.
*
* 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; version 3 of the License.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.rivetlogic.elasticsearch.portlet.exception;
/**
* The Class ElasticsearchAutocompleteException.
*/
public class ElasticsearchAutocompleteException extends Exception{
/**
* Instantiates a new elasticsearch autocomplete exception.
*/
public ElasticsearchAutocompleteException() {
}
/**
* Instantiates a new elasticsearch autocomplete exception.
*
* @param msg the msg
*/
public ElasticsearchAutocompleteException(String msg) {
super(msg);
}
/**
* Instantiates a new elasticsearch autocomplete exception.
*
* @param t the t
*/
public ElasticsearchAutocompleteException(Throwable t) {
super(t);
}
/**
* Instantiates a new elasticsearch autocomplete exception.
*
* @param msg the msg
* @param t the t
*/
public ElasticsearchAutocompleteException(String msg, Throwable t) {
super(msg, t);
}
/** The Constant serialVersionUID. */
private static final long serialVersionUID = -4419932835671285078L;
}
| gpl-3.0 |
m3rlin87/darkstar | scripts/globals/mobskills/the_wrath_of_gudha.lua | 665 | require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.WEIGHT
local numhits = 1
local accmod = 1
local dmgmod = 5
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,0,1,2,3)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,0,info.hitslanded)
MobStatusEffectMove(mob, target, typeEffect, 80, 0, 10)
target:delHP(dmg)
return dmg
end
| gpl-3.0 |
elitegreg/mudpy | mudpy/command.py | 2009 | from mudpy import logging
import pprint
__all__ = [
'command',
'CommandError',
'register_system_command',
'register_gameplay_command'
]
__gameplay_commands = dict()
__system_commands = dict()
class CommandError(RuntimeError):
pass
def command(cmd, requestor, depth=0):
assert(len(cmd) > 0)
logging.trace('Dispatch command "{}" for {}', cmd, requestor.name)
if depth > 4:
raise CommandError('Recursive aliases detected.')
aliases = getattr(requestor, 'aliases', None)
firstword = cmd.split(' ')[0] # TODO handle \t
if aliases:
try:
alias = aliases[firstword]
except KeyError:
pass
else:
command(aliases[firstword], requestor, depth + 1)
return
if firstword[0] == '@':
try:
syscommand = __system_commands[firstword]
except KeyError:
pass
else:
syscommand(cmd, requestor)
return
else:
try:
gamecommand = __gameplay_commands[firstword]
except KeyError:
pass
else:
gamecommand(cmd, requestor)
return
logging.trace('Command not found!')
logging.trace(' __system_commands = {} __gameplay_commands = {}',
pprint.pformat(__system_commands.keys()),
pprint.pformat(__gameplay_commands.keys()))
raise CommandError('Unknown command!')
def register_system_command(name, cmd):
assert(cmd)
if len(name) == 0 or name[0] != '@':
raise RuntimeError("Invalid cmd name '%s' at command registration" % name)
global __system_commands
__system_commands[name] = cmd
def register_gameplay_command(name, cmd):
assert(cmd)
if len(name) == 0 or name[0] == '@':
raise RuntimeError("Invalid cmd name '%s' at command registration" % name)
global __system_commands
__gameplay_commands[name] = cmd
# import plugins
from .commands import *
| gpl-3.0 |
napsternxg/gensim | gensim/summarization/commons.py | 1565 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""This module provides functions of creating graph from sequence of values and removing of unreachable nodes.
Examples
--------
Create simple graph and add edges. Let's take a look at nodes.
.. sourcecode:: pycon
>>> gg = build_graph(['Felidae', 'Lion', 'Tiger', 'Wolf'])
>>> gg.add_edge(("Felidae", "Lion"))
>>> gg.add_edge(("Felidae", "Tiger"))
>>> sorted(gg.nodes())
['Felidae', 'Lion', 'Tiger', 'Wolf']
Remove nodes with no edges.
.. sourcecode:: pycon
>>> remove_unreachable_nodes(gg)
>>> sorted(gg.nodes())
['Felidae', 'Lion', 'Tiger']
"""
from gensim.summarization.graph import Graph
def build_graph(sequence):
"""Creates and returns undirected graph with given sequence of values.
Parameters
----------
sequence : list of hashable
Sequence of values.
Returns
-------
:class:`~gensim.summarization.graph.Graph`
Created graph.
"""
graph = Graph()
for item in sequence:
if not graph.has_node(item):
graph.add_node(item)
return graph
def remove_unreachable_nodes(graph):
"""Removes unreachable nodes (nodes with no edges), inplace.
Parameters
----------
graph : :class:`~gensim.summarization.graph.Graph`
Given graph.
"""
for node in graph.nodes():
if all(graph.edge_weight((node, other)) == 0 for other in graph.neighbors(node)):
graph.del_node(node)
| gpl-3.0 |
MichalMizak/ObchodnaSiet | obchodna_siet/src/main/java/sk/upjs/ics/paz1c/obchodnaSiet/other/enums/TableName.java | 210 | package sk.upjs.ics.paz1c.obchodnaSiet.other.enums;
/**
*
* @author Mikey
*/
public enum TableName {
prijem, prijem_history, prevadzka, prevadzka_history, produkt, produkt_history, naklad_na_produkty
}
| gpl-3.0 |
Sworken/RagSWC | src/server/game/Movement/Waypoints/WaypointManager.cpp | 4493 | /*
* Copyright (C)
* Copyright (C)
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DatabaseEnv.h"
#include "GridDefines.h"
#include "WaypointManager.h"
#include "MapManager.h"
#include "Log.h"
WaypointMgr::WaypointMgr()
{
}
WaypointMgr::~WaypointMgr()
{
for (WaypointPathContainer::iterator itr = _waypointStore.begin(); itr != _waypointStore.end(); ++itr)
{
for (WaypointPath::const_iterator it = itr->second.begin(); it != itr->second.end(); ++it)
delete *it;
itr->second.clear();
}
_waypointStore.clear();
}
void WaypointMgr::Load()
{
uint32 oldMSTime = getMSTime();
// 0 1 2 3 4 5 6 7 8 9
QueryResult result = WorldDatabase.Query("SELECT id, point, position_x, position_y, position_z, orientation, move_type, delay, action, action_chance FROM waypoint_data ORDER BY id, point");
if (!result)
{
sLog->outErrorDb(">> Loaded 0 waypoints. DB table `waypoint_data` is empty!");
sLog->outString();
return;
}
uint32 count = 0;
do
{
Field* fields = result->Fetch();
WaypointData* wp = new WaypointData();
uint32 pathId = fields[0].GetUInt32();
WaypointPath& path = _waypointStore[pathId];
float x = fields[2].GetFloat();
float y = fields[3].GetFloat();
float z = fields[4].GetFloat();
float o = fields[5].GetFloat();
Trinity::NormalizeMapCoord(x);
Trinity::NormalizeMapCoord(y);
wp->id = fields[1].GetUInt32();
wp->x = x;
wp->y = y;
wp->z = z;
wp->orientation = o;
wp->move_type = fields[6].GetUInt32();
if (wp->move_type >= WAYPOINT_MOVE_TYPE_MAX)
{
//TC_LOG_ERROR("sql.sql", "Waypoint %u in waypoint_data has invalid move_type, ignoring", wp->id);
delete wp;
continue;
}
wp->delay = fields[7].GetUInt32();
wp->event_id = fields[8].GetUInt32();
wp->event_chance = fields[9].GetInt16();
path.push_back(wp);
++count;
}
while (result->NextRow());
sLog->outString(">> Loaded %u waypoints in %u ms", count, GetMSTimeDiffToNow(oldMSTime));
sLog->outString();
}
void WaypointMgr::ReloadPath(uint32 id)
{
WaypointPathContainer::iterator itr = _waypointStore.find(id);
if (itr != _waypointStore.end())
{
for (WaypointPath::const_iterator it = itr->second.begin(); it != itr->second.end(); ++it)
delete *it;
_waypointStore.erase(itr);
}
PreparedStatement* stmt = WorldDatabase.GetPreparedStatement(WORLD_SEL_WAYPOINT_DATA_BY_ID);
stmt->setUInt32(0, id);
PreparedQueryResult result = WorldDatabase.Query(stmt);
if (!result)
return;
WaypointPath& path = _waypointStore[id];
do
{
Field* fields = result->Fetch();
WaypointData* wp = new WaypointData();
float x = fields[1].GetFloat();
float y = fields[2].GetFloat();
float z = fields[3].GetFloat();
float o = fields[4].GetFloat();
Trinity::NormalizeMapCoord(x);
Trinity::NormalizeMapCoord(y);
wp->id = fields[0].GetUInt32();
wp->x = x;
wp->y = y;
wp->z = z;
wp->orientation = o;
wp->move_type = fields[5].GetUInt32();
if (wp->move_type >= WAYPOINT_MOVE_TYPE_MAX)
{
//TC_LOG_ERROR("sql.sql", "Waypoint %u in waypoint_data has invalid move_type, ignoring", wp->id);
delete wp;
continue;
}
wp->delay = fields[6].GetUInt32();
wp->event_id = fields[7].GetUInt32();
wp->event_chance = fields[8].GetUInt8();
path.push_back(wp);
}
while (result->NextRow());
}
| gpl-3.0 |
SamTebbs33/myrmecology | src/minecraft/vivadaylight3/myrmecology/client/gui/GuiIncubator.java | 4934 | package vivadaylight3.myrmecology.client.gui;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.util.ArrayList;
import net.minecraft.client.entity.EntityClientPlayerMP;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.inventory.GuiContainer;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.util.StatCollector;
import net.minecraft.world.World;
import org.lwjgl.opengl.GL11;
import vivadaylight3.myrmecology.api.util.Metadata;
import vivadaylight3.myrmecology.common.Reference;
import vivadaylight3.myrmecology.common.Register;
import vivadaylight3.myrmecology.common.inventory.ContainerIncubator;
import vivadaylight3.myrmecology.common.lib.Resources;
import vivadaylight3.myrmecology.common.tileentity.TileEntityIncubator;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
@SideOnly(Side.CLIENT)
public class GuiIncubator extends GuiContainer {
private GuiButtonSizeable buttonQueen;
private GuiButtonSizeable buttonDrone;
private GuiButtonSizeable buttonWorker;
private int buttonWidth = 10;
private int buttonHeight = 15;
private World world;
public TileEntityIncubator tile;
private EntityPlayer player;
private ArrayList<EntityPlayer> players = new ArrayList<EntityPlayer>();
public GuiIncubator(EntityPlayer parPlayer, InventoryPlayer inventory,
TileEntityIncubator tileEntity, World parWorld, int x, int y, int z) {
super(new ContainerIncubator(inventory, tileEntity));
this.world = parWorld;
this.tile = tileEntity;
this.players.add(parPlayer);
parPlayer.addStat(Register.achieveIncubateAnts, 1);
}
@Override
public void initGui() {
super.initGui();
/*
* this.buttonList.clear();
*
* this.buttonList.add(this.buttonQueen = new GuiButtonSizeable(2,
* this.width / 2 - 80, this.height / 2 - 65, "Q", buttonWidth + 8,
* buttonHeight)); this.buttonList.add(this.buttonDrone = new
* GuiButtonSizeable(2, this.width / 2 - 83 + (buttonWidth * 2),
* this.height / 2 - 65, "D", buttonWidth + 8, buttonHeight));
*
* this.buttonList.add(this.buttonWorker = new GuiButtonSizeable(2,
* this.width / 2 - 65 + (buttonWidth * 2), this.height / 2 - 65, "W",
* buttonWidth + 8, buttonHeight));
*/
}
@Override
protected void actionPerformed(GuiButton par1GuiButton) {
if (par1GuiButton == this.buttonQueen) {
this.sendResultAntMetaPacket(Metadata.getMetaQueen());
} else if (par1GuiButton == this.buttonDrone) {
this.sendResultAntMetaPacket(Metadata.getMetaDrone());
} else if (par1GuiButton == this.buttonWorker) {
this.sendResultAntMetaPacket(Metadata.getMetaWorker());
}
}
@SideOnly(Side.CLIENT)
private void sendResultAntMetaPacket(int meta) {
ByteArrayOutputStream bos = new ByteArrayOutputStream(8);
DataOutputStream outputStream = new DataOutputStream(bos);
try {
outputStream.writeInt(meta);
} catch (Exception ex) {
ex.printStackTrace();
}
Packet packet = new Packet250CustomPayload();
packet.channel = Reference.MOD_CHANNEL_INCUBATOR;
packet.data = bos.toByteArray();
packet.length = bos.size();
Side side = FMLCommonHandler.instance().getEffectiveSide();
if (side == Side.SERVER) {
// We are on the server side.
EntityPlayerMP player2 = (EntityPlayerMP) this.player;
} else if (side == Side.CLIENT) {
EntityClientPlayerMP player2 = (EntityClientPlayerMP) this.player;
player2.sendQueue.addToSendQueue(packet);
} else {
}
}
/**
* Draw the foreground layer for the GuiContainer (everything in front of
* the items)
*/
@Override
protected void drawGuiContainerForegroundLayer(int par1, int par2) {
String s = this.tile.isInvNameLocalized() ? this.tile.getInvName()
: StatCollector.translateToLocal(this.tile.getInvName());
this.fontRendererObj.drawString(s,
this.xSize / 2 - this.fontRendererObj.getStringWidth(s) / 2, 6,
4210752);
this.fontRendererObj.drawString(
StatCollector.translateToLocal("container.inventory"), 8,
this.ySize - 96 + 2, 4210752);
}
/**
* Draw the background layer for the GuiContainer (everything behind the
* items)
*/
@Override
protected void drawGuiContainerBackgroundLayer(float par1, int par2,
int par3) {
GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F);
this.mc.renderEngine.bindTexture(Resources.GUI_INCUBATOR);
int k = (this.width - this.xSize) / 2;
int l = (this.height - this.ySize) / 2;
this.drawTexturedModalRect(k, l, 0, 0, this.xSize, this.ySize);
}
@Override
public void onGuiClosed() {
if (this.mc.thePlayer != null) {
this.inventorySlots.onContainerClosed(this.mc.thePlayer);
this.players.remove(this.mc.thePlayer);
}
}
}
| gpl-3.0 |
SlightQuartz/Tactical-Commander | Assets/Scripts/Map/MapBoard_Animator.cs | 2999 | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MapBoard_Animator : MonoBehaviour {
public Animator[] animators;
public void SetAnimator(bool active)
{
animators = GetComponentsInChildren<Animator>();
foreach (Animator animator in animators)
{
if (animator != null)
{
animator.enabled = active;
}
}
}
public void SetItem(bool active)
{
ItemShow_ClickToAddCase[] itemShow_ClickToAddCases = GetComponentsInChildren<ItemShow_ClickToAddCase>();
foreach (ItemShow_ClickToAddCase itemShow_ClickToAddCase in itemShow_ClickToAddCases)
itemShow_ClickToAddCase.isShow = active;
ItemShow_ClickToAddStory[] itemShow_ClickToAddStorys = GetComponentsInChildren<ItemShow_ClickToAddStory>();
foreach (ItemShow_ClickToAddStory itemShow_ClickToAddStory in itemShow_ClickToAddStorys)
itemShow_ClickToAddStory.isShow = active;
ItemShow_ClickToChangeObject[] itemShow_ClickToChangeObjects = GetComponentsInChildren<ItemShow_ClickToChangeObject>();
foreach (ItemShow_ClickToChangeObject itemShow_ClickToChangeObject in itemShow_ClickToChangeObjects)
itemShow_ClickToChangeObject.isShow = active;
ItemShow_ClickToChangeSprite[] itemShow_ClickToChangeSprites = GetComponentsInChildren<ItemShow_ClickToChangeSprite>();
foreach (ItemShow_ClickToChangeSprite itemShow_ClickToChangeSprite in itemShow_ClickToChangeSprites)
itemShow_ClickToChangeSprite.isShow = active;
ItemShow_ClickToDestoryObject[] itemShow_ClickToDestoryObjects = GetComponentsInChildren<ItemShow_ClickToDestoryObject>();
foreach (ItemShow_ClickToDestoryObject itemShow_ClickToDestoryObject in itemShow_ClickToDestoryObjects)
itemShow_ClickToDestoryObject.isShow = active;
ItemShow_ClickToMove[] itemShow_ClickToMoves = GetComponentsInChildren<ItemShow_ClickToMove>();
foreach (ItemShow_ClickToMove itemShow_ClickToMove in itemShow_ClickToMoves)
itemShow_ClickToMove.isShow = active;
ItemShow_ClickToShowMoreInfo[] itemShow_ClickToShowMoreInfos = GetComponentsInChildren<ItemShow_ClickToShowMoreInfo>();
foreach (ItemShow_ClickToShowMoreInfo itemShow_ClickToShowMoreInfo in itemShow_ClickToShowMoreInfos)
itemShow_ClickToShowMoreInfo.isShow = active;
ItemShow_PlayAnimator[] itemShow_PlayAnimators = GetComponentsInChildren<ItemShow_PlayAnimator>();
foreach (ItemShow_PlayAnimator itemShow_PlayAnimator in itemShow_PlayAnimators)
itemShow_PlayAnimator.isShow = active;
ItemShow_ChangeObjectByItems[] itemShow_ChangeObjectByItems = GetComponentsInChildren<ItemShow_ChangeObjectByItems>();
foreach (ItemShow_ChangeObjectByItems itemShow_ChangeObjectByItem in itemShow_ChangeObjectByItems)
itemShow_ChangeObjectByItem.UpdateState();
}
}
| gpl-3.0 |
1036-app/pttbased-app | src/ro/ui/pttdroid/myApplication.java | 420 | package ro.ui.pttdroid;
import ro.ui.pttdroid.Main.MyHandler;
import android.app.Application;
public class myApplication extends Application
{
// ¹²Ïí±äÁ¿
private MyHandler handler = null;
public void setHandler(MyHandler handler)
{
this.handler = handler;
}
public MyHandler getHandler()
{
return handler;
}
}
| gpl-3.0 |
Crypt0s/Ramen | fs_libs/ftputil/test/test_stat.py | 20112 | # Copyright (C) 2003-2013, Stefan Schwarzer <[email protected]>
# See the file LICENSE for licensing terms.
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
import stat
import time
import unittest
import ftputil
import ftputil.error
import ftputil.stat
from test import test_base
from test import mock_ftplib
def _test_stat(session_factory):
host = test_base.ftp_host_factory(session_factory=session_factory)
stat = ftputil.stat._Stat(host)
# Use Unix format parser explicitly. This doesn't exclude switching
# to the MS format parser later if the test allows this switching.
stat._parser = ftputil.stat.UnixParser()
return stat
def stat_tuple_to_seconds(t):
"""
Return a float number representing the local time associated with
the six-element tuple `t`.
"""
assert len(t) == 6, \
"need a six-element tuple (year, month, day, hour, min, sec)"
return time.mktime(t + (0, 0, -1))
class TestParsers(unittest.TestCase):
#
# Helper methods
#
def _test_valid_lines(self, parser_class, lines, expected_stat_results):
parser = parser_class()
for line, expected_stat_result in zip(lines, expected_stat_results):
# Convert to list to compare with the list `expected_stat_results`.
parse_result = parser.parse_line(line)
stat_result = list(parse_result) + [parse_result._st_name,
parse_result._st_target]
# Convert time tuple to seconds.
expected_stat_result[8] = \
stat_tuple_to_seconds(expected_stat_result[8])
# Compare lists.
self.assertEqual(stat_result, expected_stat_result)
def _test_invalid_lines(self, parser_class, lines):
parser = parser_class()
for line in lines:
self.assertRaises(ftputil.error.ParserError,
parser.parse_line, line)
def _expected_year(self):
"""
Return the expected year for the second line in the
listing in `test_valid_unix_lines`.
"""
# If in this year it's after Dec 19, 23:11, use the current
# year, else use the previous year. This datetime value
# corresponds to the hard-coded value in the string lists
# below.
now = time.localtime()
# We need only month, day, hour and minute.
current_time_parts = now[1:5]
time_parts_in_listing = (12, 19, 23, 11)
if current_time_parts > time_parts_in_listing:
return now[0]
else:
return now[0] - 1
#
# Unix parser
#
def test_valid_unix_lines(self):
lines = [
"drwxr-sr-x 2 45854 200 512 May 4 2000 "
"chemeng link -> chemeng target",
# The year value for this line will change with the actual time.
"-rw-r--r-- 1 45854 200 4604 Dec 19 23:11 index.html",
"drwxr-sr-x 2 45854 200 512 May 29 2000 os2",
"lrwxrwxrwx 2 45854 200 512 May 29 2000 osup -> "
"../os2"
]
expected_stat_results = [
[17901, None, None, 2, "45854", "200", 512, None,
(2000, 5, 4, 0, 0, 0), None, "chemeng link", "chemeng target"],
[33188, None, None, 1, "45854", "200", 4604, None,
(self._expected_year(), 12, 19, 23, 11, 0), None,
"index.html", None],
[17901, None, None, 2, "45854", "200", 512, None,
(2000, 5, 29, 0, 0, 0), None, "os2", None],
[41471, None, None, 2, "45854", "200", 512, None,
(2000, 5, 29, 0, 0, 0), None, "osup", "../os2"]
]
self._test_valid_lines(ftputil.stat.UnixParser, lines,
expected_stat_results)
def test_invalid_unix_lines(self):
lines = [
# Not intended to be parsed. Should have been filtered out by
# `ignores_line`.
"total 14",
# Invalid month abbreviation
"drwxr-sr-x 2 45854 200 512 Max 4 2000 chemeng",
# Incomplete mode
"drwxr-sr- 2 45854 200 512 May 4 2000 chemeng",
# Invalid first letter in mode
"xrwxr-sr-x 2 45854 200 512 May 4 2000 chemeng",
# Ditto, plus invalid size value
"xrwxr-sr-x 2 45854 200 51x May 4 2000 chemeng",
# Is this `os1 -> os2` pointing to `os3`, or `os1` pointing
# to `os2 -> os3` or the plain name `os1 -> os2 -> os3`? We
# don't know, so we consider the line invalid.
"drwxr-sr-x 2 45854 200 512 May 29 2000 "
"os1 -> os2 -> os3",
# Missing name
"-rwxr-sr-x 2 45854 200 51x May 4 2000 ",
]
self._test_invalid_lines(ftputil.stat.UnixParser, lines)
def test_alternative_unix_format(self):
# See http://ftputil.sschwarzer.net/trac/ticket/12 for a
# description for the need for an alternative format.
lines = [
"drwxr-sr-x 2 200 512 May 4 2000 "
"chemeng link -> chemeng target",
# The year value for this line will change with the actual time.
"-rw-r--r-- 1 200 4604 Dec 19 23:11 index.html",
"drwxr-sr-x 2 200 512 May 29 2000 os2",
"lrwxrwxrwx 2 200 512 May 29 2000 osup -> ../os2"
]
expected_stat_results = [
[17901, None, None, 2, None, "200", 512, None,
(2000, 5, 4, 0, 0, 0), None, "chemeng link", "chemeng target"],
[33188, None, None, 1, None, "200", 4604, None,
(self._expected_year(), 12, 19, 23, 11, 0), None,
"index.html", None],
[17901, None, None, 2, None, "200", 512, None,
(2000, 5, 29, 0, 0, 0), None, "os2", None],
[41471, None, None, 2, None, "200", 512, None,
(2000, 5, 29, 0, 0, 0), None, "osup", "../os2"]
]
self._test_valid_lines(ftputil.stat.UnixParser, lines,
expected_stat_results)
#
# Microsoft parser
#
def test_valid_ms_lines_two_digit_year(self):
lines = [
"07-27-01 11:16AM <DIR> Test",
"10-23-95 03:25PM <DIR> WindowsXP",
"07-17-00 02:08PM 12266720 test.exe",
"07-17-09 12:08AM 12266720 test.exe",
"07-17-09 12:08PM 12266720 test.exe"
]
expected_stat_results = [
[16640, None, None, None, None, None, None, None,
(2001, 7, 27, 11, 16, 0), None, "Test", None],
[16640, None, None, None, None, None, None, None,
(1995, 10, 23, 15, 25, 0), None, "WindowsXP", None],
[33024, None, None, None, None, None, 12266720, None,
(2000, 7, 17, 14, 8, 0), None, "test.exe", None],
[33024, None, None, None, None, None, 12266720, None,
(2009, 7, 17, 0, 8, 0), None, "test.exe", None],
[33024, None, None, None, None, None, 12266720, None,
(2009, 7, 17, 12, 8, 0), None, "test.exe", None]
]
self._test_valid_lines(ftputil.stat.MSParser, lines,
expected_stat_results)
def test_valid_ms_lines_four_digit_year(self):
# See http://ftputil.sschwarzer.net/trac/ticket/67
lines = [
"10-19-2012 03:13PM <DIR> SYNCDEST",
"10-19-2012 03:13PM <DIR> SYNCSOURCE"
]
expected_stat_results = [
[16640, None, None, None, None, None, None, None,
(2012, 10, 19, 15, 13, 0), None, "SYNCDEST", None],
[16640, None, None, None, None, None, None, None,
(2012, 10, 19, 15, 13, 0), None, "SYNCSOURCE", None],
]
self._test_valid_lines(ftputil.stat.MSParser, lines,
expected_stat_results)
def test_invalid_ms_lines(self):
lines = [
# Neither "<DIR>" nor a size present
"07-27-01 11:16AM Test",
# "AM"/"PM" missing
"07-17-00 02:08 12266720 test.exe",
# Invalid size value
"07-17-00 02:08AM 1226672x test.exe"
]
self._test_invalid_lines(ftputil.stat.MSParser, lines)
#
# The following code checks if the decision logic in the Unix
# line parser for determining the year works.
#
def datetime_string(self, time_float):
"""
Return a datetime string generated from the value in
`time_float`. The parameter value is a floating point value
as returned by `time.time()`. The returned string is built as
if it were from a Unix FTP server (format: MMM dd hh:mm")
"""
time_tuple = time.localtime(time_float)
return time.strftime("%b %d %H:%M", time_tuple)
def dir_line(self, time_float):
"""
Return a directory line as from a Unix FTP server. Most of
the contents are fixed, but the timestamp is made from
`time_float` (seconds since the epoch, as from `time.time()`).
"""
line_template = \
"-rw-r--r-- 1 45854 200 4604 {0} index.html"
return line_template.format(self.datetime_string(time_float))
def assert_equal_times(self, time1, time2):
"""
Check if both times (seconds since the epoch) are equal. For
the purpose of this test, two times are "equal" if they
differ no more than one minute from each other.
"""
abs_difference = abs(time1 - time2)
try:
self.assertFalse(abs_difference > 60.0)
except AssertionError:
print("Difference is", abs_difference, "seconds")
raise
def _test_time_shift(self, supposed_time_shift, deviation=0.0):
"""
Check if the stat parser considers the time shift value
correctly. `deviation` is the difference between the actual
time shift and the supposed time shift, which is rounded
to full hours.
"""
host = test_base.ftp_host_factory()
# Explicitly use Unix format parser here.
host._stat._parser = ftputil.stat.UnixParser()
host.set_time_shift(supposed_time_shift)
server_time = time.time() + supposed_time_shift + deviation
stat_result = host._stat._parser.parse_line(self.dir_line(server_time),
host.time_shift())
self.assert_equal_times(stat_result.st_mtime, server_time)
def test_time_shifts(self):
"""Test correct year depending on time shift value."""
# 1. test: Client and server share the same local time
self._test_time_shift(0.0)
# 2. test: Server is three hours ahead of client
self._test_time_shift(3 * 60 * 60)
# 3. test: Client is three hours ahead of server
self._test_time_shift(- 3 * 60 * 60)
# 4. test: Server is supposed to be three hours ahead, but
# is ahead three hours and one minute
self._test_time_shift(3 * 60 * 60, 60)
# 5. test: Server is supposed to be three hours ahead, but
# is ahead three hours minus one minute
self._test_time_shift(3 * 60 * 60, -60)
# 6. test: Client is supposed to be three hours ahead, but
# is ahead three hours and one minute
self._test_time_shift(-3 * 60 * 60, -60)
# 7. test: Client is supposed to be three hours ahead, but
# is ahead three hours minus one minute
self._test_time_shift(-3 * 60 * 60, 60)
class TestLstatAndStat(unittest.TestCase):
"""
Test `FTPHost.lstat` and `FTPHost.stat` (test currently only
implemented for Unix server format).
"""
def setUp(self):
# Most tests in this class need the mock session class with
# Unix format, so make this the default. Tests which need
# the MS format can overwrite `self.stat` later.
self.stat = \
_test_stat(session_factory=mock_ftplib.MockUnixFormatSession)
def test_failing_lstat(self):
"""Test whether `lstat` fails for a nonexistent path."""
self.assertRaises(ftputil.error.PermanentError,
self.stat._lstat, "/home/sschw/notthere")
self.assertRaises(ftputil.error.PermanentError,
self.stat._lstat, "/home/sschwarzer/notthere")
def test_lstat_for_root(self):
"""
Test `lstat` for `/` .
Note: `(l)stat` works by going one directory up and parsing
the output of an FTP `LIST` command. Unfortunately, it's not
possible to do this for the root directory `/`.
"""
self.assertRaises(ftputil.error.RootDirError, self.stat._lstat, "/")
try:
self.stat._lstat("/")
except ftputil.error.RootDirError as exc:
self.assertFalse(isinstance(exc, ftputil.error.FTPOSError))
def test_lstat_one_unix_file(self):
"""Test `lstat` for a file described in Unix-style format."""
stat_result = self.stat._lstat("/home/sschwarzer/index.html")
# Second form is needed for Python 3
self.assertTrue(oct(stat_result.st_mode) in ("0100644", "0o100644"))
self.assertEqual(stat_result.st_size, 4604)
self.assertEqual(stat_result._st_mtime_precision, 60)
def test_lstat_one_ms_file(self):
"""Test `lstat` for a file described in DOS-style format."""
self.stat = _test_stat(session_factory=mock_ftplib.MockMSFormatSession)
stat_result = self.stat._lstat("/home/msformat/abcd.exe")
self.assertEqual(stat_result._st_mtime_precision, 60)
def test_lstat_one_unix_dir(self):
"""Test `lstat` for a directory described in Unix-style format."""
stat_result = self.stat._lstat("/home/sschwarzer/scios2")
# Second form is needed for Python 3
self.assertTrue(oct(stat_result.st_mode) in ("042755", "0o42755"))
self.assertEqual(stat_result.st_ino, None)
self.assertEqual(stat_result.st_dev, None)
self.assertEqual(stat_result.st_nlink, 6)
self.assertEqual(stat_result.st_uid, "45854")
self.assertEqual(stat_result.st_gid, "200")
self.assertEqual(stat_result.st_size, 512)
self.assertEqual(stat_result.st_atime, None)
self.assertTrue(stat_result.st_mtime ==
stat_tuple_to_seconds((1999, 9, 20, 0, 0, 0)))
self.assertEqual(stat_result.st_ctime, None)
self.assertEqual(stat_result._st_mtime_precision, 24*60*60)
self.assertTrue(stat_result ==
(17901, None, None, 6, "45854", "200", 512, None,
stat_tuple_to_seconds((1999, 9, 20, 0, 0, 0)), None))
def test_lstat_one_ms_dir(self):
"""Test `lstat` for a directory described in DOS-style format."""
self.stat = _test_stat(session_factory=mock_ftplib.MockMSFormatSession)
stat_result = self.stat._lstat("/home/msformat/WindowsXP")
self.assertEqual(stat_result._st_mtime_precision, 60)
def test_lstat_via_stat_module(self):
"""Test `lstat` indirectly via `stat` module."""
stat_result = self.stat._lstat("/home/sschwarzer/")
self.assertTrue(stat.S_ISDIR(stat_result.st_mode))
def test_stat_following_link(self):
"""Test `stat` when invoked on a link."""
# Simple link
stat_result = self.stat._stat("/home/link")
self.assertEqual(stat_result.st_size, 4604)
# Link pointing to a link
stat_result = self.stat._stat("/home/python/link_link")
self.assertEqual(stat_result.st_size, 4604)
stat_result = self.stat._stat("../python/link_link")
self.assertEqual(stat_result.st_size, 4604)
# Recursive link structures
self.assertRaises(ftputil.error.PermanentError,
self.stat._stat, "../python/bad_link")
self.assertRaises(ftputil.error.PermanentError,
self.stat._stat, "/home/bad_link")
#
# Test automatic switching of Unix/MS parsers
#
def test_parser_switching_with_permanent_error(self):
"""Test non-switching of parser format with `PermanentError`."""
self.stat = _test_stat(session_factory=mock_ftplib.MockMSFormatSession)
self.assertEqual(self.stat._allow_parser_switching, True)
# With these directory contents, we get a `ParserError` for
# the Unix parser first, so `_allow_parser_switching` can be
# switched off no matter whether we got a `PermanentError`
# afterward or not.
self.assertRaises(ftputil.error.PermanentError,
self.stat._lstat, "/home/msformat/nonexistent")
self.assertEqual(self.stat._allow_parser_switching, False)
def test_parser_switching_default_to_unix(self):
"""Test non-switching of parser format; stay with Unix."""
self.assertEqual(self.stat._allow_parser_switching, True)
self.assertTrue(isinstance(self.stat._parser, ftputil.stat.UnixParser))
stat_result = self.stat._lstat("/home/sschwarzer/index.html")
# The Unix parser worked, so keep it.
self.assertTrue(isinstance(self.stat._parser, ftputil.stat.UnixParser))
self.assertEqual(self.stat._allow_parser_switching, False)
def test_parser_switching_to_ms(self):
"""Test switching of parser from Unix to MS format."""
self.stat = _test_stat(session_factory=mock_ftplib.MockMSFormatSession)
self.assertEqual(self.stat._allow_parser_switching, True)
self.assertTrue(isinstance(self.stat._parser, ftputil.stat.UnixParser))
# Parsing the directory `/home/msformat` with the Unix parser
# fails, so switch to the MS parser.
stat_result = self.stat._lstat("/home/msformat/abcd.exe")
self.assertTrue(isinstance(self.stat._parser, ftputil.stat.MSParser))
self.assertEqual(self.stat._allow_parser_switching, False)
self.assertEqual(stat_result._st_name, "abcd.exe")
self.assertEqual(stat_result.st_size, 12266720)
def test_parser_switching_regarding_empty_dir(self):
"""Test switching of parser if a directory is empty."""
self.stat = _test_stat(session_factory=mock_ftplib.MockMSFormatSession)
self.assertEqual(self.stat._allow_parser_switching, True)
# When the directory we're looking into doesn't give us any
# lines we can't decide whether the first parser worked,
# because it wasn't applied. So keep the parser for now.
result = self.stat._listdir("/home/msformat/XPLaunch/empty")
self.assertEqual(result, [])
self.assertEqual(self.stat._allow_parser_switching, True)
self.assertTrue(isinstance(self.stat._parser, ftputil.stat.UnixParser))
class TestListdir(unittest.TestCase):
"""Test `FTPHost.listdir`."""
def setUp(self):
self.stat = \
_test_stat(session_factory=mock_ftplib.MockUnixFormatSession)
def test_failing_listdir(self):
"""Test failing `FTPHost.listdir`."""
self.assertRaises(ftputil.error.PermanentError,
self.stat._listdir, "notthere")
def test_succeeding_listdir(self):
"""Test succeeding `FTPHost.listdir`."""
# Do we have all expected "files"?
self.assertEqual(len(self.stat._listdir(".")), 9)
# Have they the expected names?
expected = ("chemeng download image index.html os2 "
"osup publications python scios2").split()
remote_file_list = self.stat._listdir(".")
for file in expected:
self.assertTrue(file in remote_file_list)
if __name__ == "__main__":
unittest.main()
| gpl-3.0 |
PatrickSteiner/IoT_Demo_Grafana | LogReceiver/src/main/java/com/redhat/demo/iotdemo/MyHelper.java | 1501 |
package com.redhat.demo.iotdemo;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.camel.Exchange;
import org.apache.camel.Handler;
public class MyHelper {
@Handler
public String enhanceMessage( String body, Exchange exchange ) {
String res = null;
res = getDeviceType(exchange) +
",deviceID="+getDeviceID(exchange)+
",deviceType="+getDeviceType(exchange)+
" value="+getPayload(body);
return res;
}
@Handler
public String getPayload(String body) {
return body.substring(0, body.indexOf(','));
}
@Handler
public String getDeviceType(Exchange exchange) {
String result=null;
Pattern pattern = Pattern.compile("(?<=\\/)(.*?)(?=\\/)");
Matcher matcher = pattern.matcher((String)exchange.getIn().getHeader("CamelMQTTSubscribeTopic"));
if (matcher.find())
{
result = matcher.group(0);
}
return result;
}
@Handler
public String getDeviceID(Exchange exchange) {
String result=null;
Pattern pattern = Pattern.compile("([^\\/]*)$");
Matcher matcher = pattern.matcher((String)exchange.getIn().getHeader("CamelMQTTSubscribeTopic"));
if (matcher.find())
{
result = matcher.group(0);
}
return result;
}
}
| gpl-3.0 |
nitro2010/moodle | mod/courseboard/version.php | 1278 | <?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/>.
/**
* Code fragment to define the version of courseboard
* This fragment is called by moodle_needs_upgrading() and /admin/index.php
*
* @author Franz Weidmann
* @package mod_courseboard
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2015120601; // The current module version (Date: YYYYMMDDXX).
$plugin->requires = 2015050500; // Requires this Moodle version.
$plugin->component = 'mod_courseboard';
$plugin->release = "1.01";
$plugin->maturity = MATURITY_STABLE;
| gpl-3.0 |
OpenEducationFoundation/OpenBoard | src/adaptors/UBExportWeb.cpp | 2505 | /*
* Copyright (C) 2013 Open Education Foundation
*
* Copyright (C) 2010-2013 Groupement d'Intérêt Public pour
* l'Education Numérique en Afrique (GIP ENA)
*
* This file is part of OpenBoard.
*
* OpenBoard 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, version 3 of the License,
* with a specific linking exception for the OpenSSL project's
* "OpenSSL" library (or with modified versions of it that use the
* same license as the "OpenSSL" library).
*
* OpenBoard 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 OpenBoard. If not, see <http://www.gnu.org/licenses/>.
*/
#include "UBExportWeb.h"
#include "frameworks/UBPlatformUtils.h"
#include "frameworks/UBFileSystemUtils.h"
#include "core/UBDocumentManager.h"
#include "core/UBApplication.h"
#include "document/UBDocumentProxy.h"
#include "globals/UBGlobals.h"
THIRD_PARTY_WARNINGS_DISABLE
#include "quazip.h"
#include "quazipfile.h"
THIRD_PARTY_WARNINGS_ENABLE
#include "core/memcheck.h"
UBExportWeb::UBExportWeb(QObject *parent)
: UBExportAdaptor(parent)
{
UBExportWeb::tr("Page"); // dummy slot for translation
}
UBExportWeb::~UBExportWeb()
{
// NOOP
}
void UBExportWeb::persist(UBDocumentProxy* pDocumentProxy)
{
if (!pDocumentProxy)
return;
QString dirName = askForDirName(pDocumentProxy, tr("Export as Web data"));
if (dirName.length() > 0)
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
UBApplication::showMessage(tr("Exporting document..."));
if(UBFileSystemUtils::copyDir(pDocumentProxy->persistencePath(), dirName))
{
QString htmlPath = dirName + "/index.html";
QFile html(":www/OpenBoard-web-player.html");
html.copy(htmlPath);
UBApplication::showMessage(tr("Export successful."));
QDesktopServices::openUrl(QUrl::fromLocalFile(htmlPath));
}
else
{
UBApplication::showMessage(tr("Export failed."));
}
QApplication::restoreOverrideCursor();
}
}
QString UBExportWeb::exportName()
{
return tr("Export to Web Browser");
}
| gpl-3.0 |
DreamblazeNet/SqlS | src/DreamblazeNet/SqlS/DatabaseConnection.php | 6167 | <?php
namespace DreamblazeNet\SqlS;
use PDO;
use PDOException;
abstract class DatabaseConnection {
/**
* @var \Psr\Log\LoggerInterface
*/
public $log;
/**
* The PDO connection object.
* @var mixed
*/
public $connection;
/**
* The last query run.
* @var string
*/
public $last_query;
/**
* The name of the protocol that is used.
* @var string
*/
public $protocol;
/**
* Default PDO options to set for each connection.
* @var array
*/
static $PDO_OPTIONS = array(
PDO::ATTR_CASE => PDO::CASE_LOWER,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_ORACLE_NULLS => PDO::NULL_NATURAL,
PDO::ATTR_STRINGIFY_FETCHES => false);
/**
* The quote character for stuff like column and field names.
* @var string
*/
static $QUOTE_CHARACTER = '`';
/**
* Default port.
* @var int
*/
static $DEFAULT_PORT = 0;
public function __construct(\DreamblazeNet\SqlS\DatabaseConfig $info, \Psr\Log\LoggerInterface $log) {
try {
$this->log = $log;
// unix sockets start with a /
if ($info->host[0] != '/') {
$host = "host=$info->host";
if (isset($info->port))
$host .= ";port=$info->port";
}
else
$host = "unix_socket=$info->host";
$this->connection = new PDO("$info->protocol:$host;dbname=$info->db", $info->user, $info->pass, static::$PDO_OPTIONS);
} catch (PDOException $e) {
$this->log->error($e->getMessage() . "\n" . $e->getTraceAsString() . "\n");
throw new DatabaseException("Can't connect to database {$info->db}", $e->getCode() , $e);
}
}
/**
* Retrieves column meta data for the specified table.
*
* @param string $table Name of a table
* @return array An array of {@link Column} objects.
*/
public function columns($table) {
$columns = array();
$sth = $this->query_column_info($table);
while (($row = $sth->fetch())) {
$c = $this->create_column($row);
$columns[$c->name] = $c;
}
return $columns;
}
public function columns_array($table) {
$fields = array();
$sth = $this->query_column_info($table);
while ($row = $sth->fetch()) {
if (isset($row['Field']))
$fields[] = $row['Field'];
}
return $fields;
}
/**
* Escapes quotes in a string.
*
* @param string $string The string to be quoted.
* @return string The string with any quotes in it properly escaped.
*/
public function escape($string) {
return $this->connection->quote($string);
}
/**
* Retrieve the insert id of the last model saved.
*
* @param string $sequence Optional name of a sequence to use
* @return int
*/
public function insert_id($sequence=null) {
return $this->connection->lastInsertId($sequence);
}
/**
* Execute a raw SQL query on the database.
*
* @param string $sql Raw SQL string to execute.
* @param array &$values Optional array of bind values
* @return \PDOStatement
*/
public function query($sql, $values=array()) {
$this->last_query = $sql;
$this->log->debug($sql . ' => ' . var_export($values,true));
try {
if (!($sth = $this->connection->prepare($sql))){
$error = $sth->errorInfo();
$this->log->error('PDO Prepare ERROR!' . ' SQL:' . $sql);
throw new \Exception($error[0], $this->connection->errorCode());
}
$sth->setFetchMode(PDO::FETCH_ASSOC);
if (!$sth->execute($values)){
$error = $sth->errorInfo();
$this->log->error(array('PDO Exec ERROR!', "SQL: " . $sql , "VALUES: " . var_export($values, true) ,'PDO: ' . $error[0]));
throw new DatabaseException("PDO Exec ERROR! " . $error[0], $sth->errorCode());
}
} catch (PDOException $e) {
$this->log->error($e->getMessage());
throw new DatabaseException("PDO Exec ERROR! " . $e->getCode(), 0 , $e);
}
return $sth;
}
/**
* Execute a query that returns maximum of one row with one field and return it.
*
* @param string $sql Raw SQL string to execute.
* @param array &$values Optional array of values to bind to the query.
* @return string
*/
public function query_and_fetch_one($sql, $values=array()) {
$sth = $this->query($sql, $values);
$row = $sth->fetch(PDO::FETCH_ASSOC);
return $row;
}
/**
* Execute a raw SQL query and fetch the results.
*
* @param string $sql Raw SQL string to execute.
* @param \Closure $handler Closure that will be passed the fetched results.
*/
public function query_and_fetch($sql, \Closure $handler, $values=array()) {
$sth = $this->query($sql, $values);
$result = array();
while (($row = $sth->fetch(PDO::FETCH_ASSOC))) {
$result[] = $handler($row);
}
return $result;
}
/**
* Returns all tables for the current database.
*
* @return array Array containing table names.
*/
public function tables() {
$tables = array();
$sth = $this->query_for_tables();
while (($row = $sth->fetch(PDO::FETCH_NUM)))
$tables[] = $row[0];
return $tables;
}
/**
* Quote a name like table names and field names.
*
* @param string $string String to quote.
* @return string
*/
public function quote_name($string) {
return $string[0] === static::$QUOTE_CHARACTER || $string[strlen($string) - 1] === static::$QUOTE_CHARACTER ?
$string : static::$QUOTE_CHARACTER . $string . static::$QUOTE_CHARACTER;
}
public abstract function set_timezone();
public abstract function set_encoding($charset);
}
| gpl-3.0 |
xiaolowe/srdz-supplier-api | srdz-supplier-api/src/main/java/cn/org/citycloud/core/BaseController.java | 861 | package cn.org.citycloud.core;
/**
* 控制器基类
*
* @author Allen
*
*/
public class BaseController {
/**
* 供应商用户Id
*/
private int userId;
/**
* 供应商用户名
*/
private String userName;
/**
* 供应商Id
*/
private int supplierId;
/**
* token
*/
private String accessToken;
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getSupplierId() {
return supplierId;
}
public void setSupplierId(int supplierId) {
this.supplierId = supplierId;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
| gpl-3.0 |
unitymakesus/myfriendteresa.com | plugins/gravityforms/includes/addon/class-gf-addon.php | 169661 | <?php
/**
* @package GFAddOn
* @author Rocketgenius
*/
if ( ! class_exists( 'GFForms' ) ) {
die();
}
/**
* Class GFAddOn
*
* Handles all tasks mostly common to any Gravity Forms Add-On, including third party ones.
*/
abstract class GFAddOn {
/**
* @var string Version number of the Add-On
*/
protected $_version;
/**
* @var string Gravity Forms minimum version requirement
*/
protected $_min_gravityforms_version;
/**
* @var string URL-friendly identifier used for form settings, add-on settings, text domain localization...
*/
protected $_slug;
/**
* @var string Relative path to the plugin from the plugins folder. Example "gravityforms/gravityforms.php"
*/
protected $_path;
/**
* @var string Full path the the plugin. Example: __FILE__
*/
protected $_full_path;
/**
* @var string URL to the Gravity Forms website. Example: 'http://www.gravityforms.com' OR affiliate link.
*/
protected $_url;
/**
* @var string Title of the plugin to be used on the settings page, form settings and plugins page. Example: 'Gravity Forms MailChimp Add-On'
*/
protected $_title;
/**
* @var string Short version of the plugin title to be used on menus and other places where a less verbose string is useful. Example: 'MailChimp'
*/
protected $_short_title;
/**
* @var array Members plugin integration. List of capabilities to add to roles.
*/
protected $_capabilities = array();
/**
* @var string The hook suffix for the app menu
*/
public $app_hook_suffix;
private $_saved_settings = array();
private $_previous_settings = array();
/**
* @var array Stores a copy of setting fields that failed validation; only populated after validate_settings() has been called.
*/
private $_setting_field_errors = array();
// ------------ Permissions -----------
/**
* @var string|array A string or an array of capabilities or roles that have access to the settings page
*/
protected $_capabilities_settings_page = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the form settings
*/
protected $_capabilities_form_settings = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the plugin page
*/
protected $_capabilities_plugin_page = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the app menu
*/
protected $_capabilities_app_menu = array();
/**
* @var string|array A string or an array of capabilities or roles that have access to the app settings page
*/
protected $_capabilities_app_settings = array();
/**
* @var string|array A string or an array of capabilities or roles that can uninstall the plugin
*/
protected $_capabilities_uninstall = array();
// ------------ RG Autoupgrade -----------
/**
* @var bool Used by Rocketgenius plugins to activate auto-upgrade.
* @ignore
*/
protected $_enable_rg_autoupgrade = false;
// ------------ Private -----------
private $_no_conflict_scripts = array();
private $_no_conflict_styles = array();
private $_preview_styles = array();
private $_print_styles = array();
private static $_registered_addons = array( 'active' => array(), 'inactive' => array() );
/**
* Class constructor which hooks the instance into the WordPress init action
*/
function __construct() {
add_action( 'init', array( $this, 'init' ) );
if ( $this->_enable_rg_autoupgrade ) {
require_once( 'class-gf-auto-upgrade.php' );
$is_gravityforms_supported = $this->is_gravityforms_supported( $this->_min_gravityforms_version );
new GFAutoUpgrade( $this->_slug, $this->_version, $this->_min_gravityforms_version, $this->_title, $this->_full_path, $this->_path, $this->_url, $is_gravityforms_supported );
}
$this->pre_init();
}
/**
* Registers an addon so that it gets initialized appropriately
*
* @param string $class - The class name
* @param string $overrides - Specify the class to replace/override
*/
public static function register( $class, $overrides = null ) {
//Ignore classes that have been marked as inactive
if ( in_array( $class, self::$_registered_addons['inactive'] ) ) {
return;
}
//Mark classes as active. Override existing active classes if they are supposed to be overridden
$index = array_search( $overrides, self::$_registered_addons['active'] );
if ( $index !== false ) {
self::$_registered_addons['active'][ $index ] = $class;
} else {
self::$_registered_addons['active'][] = $class;
}
//Mark overridden classes as inactive.
if ( ! empty( $overrides ) ) {
self::$_registered_addons['inactive'][] = $overrides;
}
}
/**
* Gets all active, registered Add-Ons.
*
* @since Unknown
* @access public
*
* @uses GFAddOn::$_registered_addons
*
* @return array Active, registered Add-Ons.
*/
public static function get_registered_addons() {
return self::$_registered_addons['active'];
}
/**
* Initializes all addons.
*/
public static function init_addons() {
//Removing duplicate add-ons
$active_addons = array_unique( self::$_registered_addons['active'] );
foreach ( $active_addons as $addon ) {
call_user_func( array( $addon, 'get_instance' ) );
}
}
/**
* Gets executed before all init functions. Override this function to perform initialization tasks that must be done prior to init
*/
public function pre_init() {
if ( $this->is_gravityforms_supported() ) {
//Entry meta
if ( $this->method_is_overridden( 'get_entry_meta' ) ) {
add_filter( 'gform_entry_meta', array( $this, 'get_entry_meta' ), 10, 2 );
}
}
}
/**
* Plugin starting point. Handles hooks and loading of language files.
*/
public function init() {
$this->load_text_domain();
add_filter( 'gform_logging_supported', array( $this, 'set_logging_supported' ) );
if ( RG_CURRENT_PAGE == 'admin-ajax.php' ) {
//If gravity forms is supported, initialize AJAX
if ( $this->is_gravityforms_supported() ) {
$this->init_ajax();
}
} elseif ( is_admin() ) {
$this->init_admin();
} else {
if ( $this->is_gravityforms_supported() ) {
$this->init_frontend();
}
}
}
/**
* Override this function to add initialization code (i.e. hooks) for the admin site (WP dashboard)
*/
public function init_admin() {
// enqueues admin scripts
add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_scripts' ), 10, 0 );
// message enforcing min version of Gravity Forms
if ( isset( $this->_min_gravityforms_version ) && RG_CURRENT_PAGE == 'plugins.php' && false === $this->_enable_rg_autoupgrade ) {
add_action( 'after_plugin_row_' . $this->_path, array( $this, 'plugin_row' ) );
}
// STOP HERE IF GRAVITY FORMS IS NOT SUPPORTED
if ( isset( $this->_min_gravityforms_version ) && ! $this->is_gravityforms_supported( $this->_min_gravityforms_version ) ) {
return;
}
$this->setup();
// Add form settings only when there are form settings fields configured or form_settings() method is implemented
if ( self::has_form_settings_page() ) {
$this->form_settings_init();
}
// Add plugin page when there is a plugin page configured or plugin_page() method is implemented
if ( self::has_plugin_page() ) {
$this->plugin_page_init();
}
// Add addon settings page only when there are addon settings fields configured or settings_page() method is implemented
if ( self::has_plugin_settings_page() ) {
if ( $this->current_user_can_any( $this->_capabilities_settings_page ) ) {
$this->plugin_settings_init();
}
}
// creates the top level app left menu
if ( self::has_app_menu() ) {
if ( $this->current_user_can_any( $this->_capabilities_app_menu ) ) {
add_action( 'admin_menu', array( $this, 'create_app_menu' ) );
}
}
// Members plugin integration
if ( self::has_members_plugin() ) {
add_filter( 'members_get_capabilities', array( $this, 'members_get_capabilities' ) );
}
// Results page
if ( $this->method_is_overridden( 'get_results_page_config' ) ) {
$results_page_config = $this->get_results_page_config();
$results_capabilities = rgar( $results_page_config, 'capabilities' );
if ( $results_page_config && $this->current_user_can_any( $results_capabilities ) ) {
$this->results_page_init( $results_page_config );
}
}
// Locking
if ( $this->method_is_overridden( 'get_locking_config' ) ) {
require_once( GFCommon::get_base_path() . '/includes/locking/class-gf-locking.php' );
require_once( 'class-gf-addon-locking.php' );
$config = $this->get_locking_config();
new GFAddonLocking( $config, $this );
}
// No conflict scripts
add_filter( 'gform_noconflict_scripts', array( $this, 'register_noconflict_scripts' ) );
add_filter( 'gform_noconflict_styles', array( $this, 'register_noconflict_styles' ) );
}
/**
* Override this function to add initialization code (i.e. hooks) for the public (customer facing) site
*/
public function init_frontend() {
$this->setup();
add_filter( 'gform_preview_styles', array( $this, 'enqueue_preview_styles' ), 10, 2 );
add_filter( 'gform_print_styles', array( $this, 'enqueue_print_styles' ), 10, 2 );
add_action( 'gform_enqueue_scripts', array( $this, 'enqueue_scripts' ), 10, 2 );
}
/**
* Override this function to add AJAX hooks or to add initialization code when an AJAX request is being performed
*/
public function init_ajax() {
if ( rgpost( 'view' ) == 'gf_results_' . $this->_slug ) {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
require_once( 'class-gf-results.php' );
$gf_results = new GFResults( $this->_slug, $this->get_results_page_config() );
add_action( 'wp_ajax_gresults_get_results_gf_results_' . $this->_slug, array( $gf_results, 'ajax_get_results' ) );
add_action( 'wp_ajax_gresults_get_more_results_gf_results_' . $this->_slug, array( $gf_results, 'ajax_get_more_results' ) );
} elseif ( $this->method_is_overridden( 'get_locking_config' ) ) {
require_once( GFCommon::get_base_path() . '/includes/locking/class-gf-locking.php' );
require_once( 'class-gf-addon-locking.php' );
$config = $this->get_locking_config();
new GFAddonLocking( $config, $this );
}
}
//-------------- Setup ---------------
/**
* Performs upgrade tasks when the version of the Add-On changes. To add additional upgrade tasks, override the upgrade() function, which will only get executed when the plugin version has changed.
*/
public function setup() {
//Upgrading add-on
$installed_version = get_option( 'gravityformsaddon_' . $this->_slug . '_version' );
//Making sure version has really changed. Gets around aggressive caching issue on some sites that cause setup to run multiple times.
if ( $installed_version != $this->_version ) {
$installed_version = GFForms::get_wp_option( 'gravityformsaddon_' . $this->_slug . '_version' );
}
//Upgrade if version has changed
if ( $installed_version != $this->_version ) {
$this->upgrade( $installed_version );
update_option( 'gravityformsaddon_' . $this->_slug . '_version', $this->_version );
}
}
/**
* Override this function to add to add database update scripts or any other code to be executed when the Add-On version changes
*/
public function upgrade( $previous_version ) {
return;
}
//-------------- Script enqueuing ---------------
/**
* Override this function to provide a list of styles to be enqueued.
* When overriding this function, be sure to call parent::styles() to ensure the base class scripts are enqueued.
* See scripts() for an example of the format expected to be returned.
*/
public function styles() {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
return array(
array(
'handle' => 'gaddon_form_settings_css',
'src' => GFAddOn::get_gfaddon_base_url() . "/css/gaddon_settings{$min}.css",
'version' => GFCommon::$version,
'enqueue' => array(
array( 'admin_page' => array( 'form_settings', 'plugin_settings', 'plugin_page', 'app_settings' ) ),
)
),
array(
'handle' => 'gaddon_results_css',
'src' => GFAddOn::get_gfaddon_base_url() . "/css/gaddon_results{$min}.css",
'version' => GFCommon::$version,
'enqueue' => array(
array( 'admin_page' => array( 'results' ) ),
)
),
);
}
/**
* Override this function to provide a list of scripts to be enqueued.
* When overriding this function, be sure to call parent::scripts() to ensure the base class scripts are enqueued.
* Following is an example of the array that is expected to be returned by this function:
*<pre>
* <code>
*
* array(
* array( "handle" => 'maskedinput',
* "src" => GFCommon::get_base_url() . '/js/jquery.maskedinput-1.3.min.js',
* "version" => GFCommon::$version,
* "deps" => array("jquery"),
* "in_footer" => false,
*
* //Determines where the script will be enqueued. The script will be enqueued if any of the conditions match
* "enqueue" => array(
* //admin_page - Specified one or more pages (known pages) where the script is supposed to be enqueued.
* //To enqueue scripts in the front end (public website), simply don't define this setting
* array("admin_page" => array("form_settings", 'plugin_settings') ),
*
* //tab - Specifies a form settings or plugin settings tab in which the script is supposed to be enqueued. If none is specified, the script will be enqueued in any of the form settings or plugin_settings page
* array("tab" => 'signature'),
*
* //query - Specifies a set of query string ($_GET) values. If all specified query string values match the current requested page, the script will be enqueued
* array("query" => 'page=gf_edit_forms&view=settings&id=_notempty_')
*
* //post - Specifies a set of post ($_POST) values. If all specified posted values match the current request, the script will be enqueued
* array("post" => 'posted_field=val')
*
* )
* ),
* array(
* "handle" => 'super_signature_script',
* "src" => $this->get_base_url() . '/super_signature/ss.js',
* "version" => $this->_version,
* "deps" => array("jquery"),
* "callback" => array($this, 'localize_scripts'),
* "strings" => array(
* // Accessible in JavaScript using the global variable "[script handle]_strings"
* "stringKey1" => __("The string", 'gravityforms'),
* "stringKey2" => __("Another string.", 'gravityforms')
* )
* "enqueue" => array(
* //field_types - Specifies one or more field types that requires this script. The script will only be enqueued if the current form has a field of any of the specified field types. Only applies when a current form is available.
* array("field_types" => array("signature"))
* )
* )
* );
*
* </code>
* </pre>
*/
public function scripts() {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
return array(
array(
'handle' => 'gform_form_admin',
'enqueue' => array( array( 'admin_page' => array( 'form_settings' ) ) )
),
array(
'handle' => 'gform_gravityforms',
'enqueue' => array( array( 'admin_page' => array( 'form_settings' ) ) )
),
array(
'handle' => 'google_charts',
'src' => 'https://www.google.com/jsapi',
'version' => GFCommon::$version,
'enqueue' => array(
array( 'admin_page' => array( 'results' ) ),
)
),
array(
'handle' => 'gaddon_results_js',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/gaddon_results{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery', 'sack', 'jquery-ui-resizable', 'gform_datepicker_init', 'google_charts', 'gform_field_filter' ),
'callback' => array( 'GFResults', 'localize_results_scripts' ),
'enqueue' => array(
array( 'admin_page' => array( 'results' ) ),
)
),
array(
'handle' => 'gaddon_repeater',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/repeater{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery' ),
'enqueue' => array(
array(
'admin_page' => array( 'form_settings' ),
),
),
),
array(
'handle' => 'gaddon_fieldmap_js',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/gaddon_fieldmap{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery', 'gaddon_repeater' ),
'enqueue' => array(
array( 'admin_page' => array( 'form_settings' ) ),
)
),
array(
'handle' => 'gaddon_selectcustom_js',
'src' => GFAddOn::get_gfaddon_base_url() . "/js/gaddon_selectcustom{$min}.js",
'version' => GFCommon::$version,
'deps' => array( 'jquery' ),
'enqueue' => array(
array( 'admin_page' => array( 'form_settings', 'plugin_settings' ) ),
)
),
);
}
/**
* Target of admin_enqueue_scripts and gform_enqueue_scripts hooks.
* Not intended to be overridden by child classes.
* In order to enqueue scripts and styles, override the scripts() and styles() functions
*
* @ignore
*/
public function enqueue_scripts( $form = '', $is_ajax = false ) {
if ( empty( $form ) ) {
$form = $this->get_current_form();
}
//Enqueueing scripts
$scripts = $this->scripts();
foreach ( $scripts as $script ) {
$src = isset( $script['src'] ) ? $script['src'] : false;
$deps = isset( $script['deps'] ) ? $script['deps'] : array();
$version = array_key_exists( 'version', $script ) ? $script['version'] : false;
$in_footer = isset( $script['in_footer'] ) ? $script['in_footer'] : false;
wp_register_script( $script['handle'], $src, $deps, $version, $in_footer );
if ( isset( $script['enqueue'] ) && $this->_can_enqueue_script( $script['enqueue'], $form, $is_ajax ) ) {
$this->add_no_conflict_scripts( array( $script['handle'] ) );
wp_enqueue_script( $script['handle'] );
if ( isset( $script['strings'] ) ) {
wp_localize_script( $script['handle'], $script['handle'] . '_strings', $script['strings'] );
}
if ( isset( $script['callback'] ) && is_callable( $script['callback'] ) ) {
$args = compact( 'form', 'is_ajax' );
call_user_func_array( $script['callback'], $args );
}
}
}
//Enqueueing styles
$styles = $this->styles();
foreach ( $styles as $style ) {
$src = isset( $style['src'] ) ? $style['src'] : false;
$deps = isset( $style['deps'] ) ? $style['deps'] : array();
$version = array_key_exists( 'version', $style ) ? $style['version'] : false;
$media = isset( $style['media'] ) ? $style['media'] : 'all';
wp_register_style( $style['handle'], $src, $deps, $version, $media );
if ( $this->_can_enqueue_script( $style['enqueue'], $form, $is_ajax ) ) {
$this->add_no_conflict_styles( array( $style['handle'] ) );
if ( $this->is_preview() ) {
$this->_preview_styles[] = $style['handle'];
} elseif ( $this->is_print() ) {
$this->_print_styles[] = $style['handle'];
} else {
wp_enqueue_style( $style['handle'] );
}
}
}
}
/**
* Target of gform_preview_styles. Enqueue styles to the preview page.
* Not intended to be overridden by child classes
*
* @ignore
*/
public function enqueue_preview_styles( $preview_styles, $form ) {
return array_merge( $preview_styles, $this->_preview_styles );
}
/**
* Target of gform_print_styles. Enqueue styles to the print entry page.
* Not intended to be overridden by child classes
*
* @ignore
*/
public function enqueue_print_styles( $print_styles, $form ) {
if ( false === $print_styles ) {
$print_styles = array();
}
$styles = $this->styles();
foreach ( $styles as $style ) {
if ( $this->_can_enqueue_script( $style['enqueue'], $form, false ) ) {
$this->add_no_conflict_styles( array( $style['handle'] ) );
$src = isset( $style['src'] ) ? $style['src'] : false;
$deps = isset( $style['deps'] ) ? $style['deps'] : array();
$version = isset( $style['version'] ) ? $style['version'] : false;
$media = isset( $style['media'] ) ? $style['media'] : 'all';
wp_register_style( $style['handle'], $src, $deps, $version, $media );
$print_styles[] = $style['handle'];
}
}
return array_merge( $print_styles, $this->_print_styles );
}
/**
* Adds scripts to the list of white-listed no conflict scripts.
*
* @param $scripts
*/
private function add_no_conflict_scripts( $scripts ) {
$this->_no_conflict_scripts = array_merge( $scripts, $this->_no_conflict_scripts );
}
/**
* Adds styles to the list of white-listed no conflict styles.
*
* @param $styles
*/
private function add_no_conflict_styles( $styles ) {
$this->_no_conflict_styles = array_merge( $styles, $this->_no_conflict_styles );
}
private function _can_enqueue_script( $enqueue_conditions, $form = array(), $is_ajax = false ) {
if ( empty( $enqueue_conditions ) ) {
return false;
}
foreach ( $enqueue_conditions as $condition ) {
if ( is_callable( $condition ) ) {
$callback_matches = call_user_func( $condition, $form, $is_ajax );
if ( $callback_matches ) {
return true;
}
} else {
$query_matches = isset( $condition['query'] ) ? $this->_request_condition_matches( $_GET, $condition['query'] ) : true;
$post_matches = isset( $condition['post'] ) ? $this->_request_condition_matches( $_POST, $condition['query'] ) : true;
$admin_page_matches = isset( $condition['admin_page'] ) ? $this->_page_condition_matches( $condition['admin_page'], rgar( $condition, 'tab' ) ) : true;
$field_type_matches = isset( $condition['field_types'] ) ? $this->_field_condition_matches( $condition['field_types'], $form ) : true;
if ( $query_matches && $post_matches && $admin_page_matches && $field_type_matches ) {
return true;
}
}
}
return false;
}
private function _request_condition_matches( $request, $query ) {
parse_str( $query, $query_array );
foreach ( $query_array as $key => $value ) {
switch ( $value ) {
case '_notempty_' :
if ( rgempty( $key, $request ) ) {
return false;
}
break;
case '_empty_' :
if ( ! rgempty( $key, $request ) ) {
return false;
}
break;
default :
if ( rgar( $request, $key ) != $value ) {
return false;
}
break;
}
}
return true;
}
private function _page_condition_matches( $pages, $tab ) {
if ( ! is_array( $pages ) ) {
$pages = array( $pages );
}
foreach ( $pages as $page ) {
switch ( $page ) {
case 'form_editor' :
if ( $this->is_form_editor() ) {
return true;
}
break;
case 'form_list' :
if ( $this->is_form_list() ) {
return true;
}
break;
case 'form_settings' :
if ( $this->is_form_settings( $tab ) ) {
return true;
}
break;
case 'plugin_settings' :
if ( $this->is_plugin_settings( $tab ) ) {
return true;
}
break;
case 'app_settings' :
if ( $this->is_app_settings( $tab ) ) {
return true;
}
break;
case 'plugin_page' :
if ( $this->is_plugin_page() ) {
return true;
}
break;
case 'entry_list' :
if ( $this->is_entry_list() ) {
return true;
}
break;
case 'entry_view' :
if ( $this->is_entry_view() ) {
return true;
}
break;
case 'entry_edit' :
if ( $this->is_entry_edit() ) {
return true;
}
break;
case 'results' :
if ( $this->is_results() ) {
return true;
}
break;
case 'customizer' :
if ( is_customize_preview() ) {
return true;
}
break;
}
}
return false;
}
private function _field_condition_matches( $field_types, $form ) {
if ( ! is_array( $field_types ) ) {
$field_types = array( $field_types );
}
$fields = GFAPI::get_fields_by_type( $form, $field_types );
if ( count( $fields ) > 0 ) {
return true;
}
return false;
}
/**
* Target for the gform_noconflict_scripts filter. Adds scripts to the list of white-listed no conflict scripts.
*
* Not intended to be overridden or called directed by Add-Ons.
*
* @ignore
*
* @param array $scripts Array of scripts to be white-listed
*
* @return array
*/
public function register_noconflict_scripts( $scripts ) {
//registering scripts with Gravity Forms so that they get enqueued when running in no-conflict mode
return array_merge( $scripts, $this->_no_conflict_scripts );
}
/**
* Target for the gform_noconflict_styles filter. Adds styles to the list of white-listed no conflict scripts.
*
* Not intended to be overridden or called directed by Add-Ons.
*
* @ignore
*
* @param array $styles Array of styles to be white-listed
*
* @return array
*/
public function register_noconflict_styles( $styles ) {
//registering styles with Gravity Forms so that they get enqueued when running in no-conflict mode
return array_merge( $styles, $this->_no_conflict_styles );
}
//-------------- Entry meta --------------------------------------
/**
* Override this method to activate and configure entry meta.
*
*
* @param array $entry_meta An array of entry meta already registered with the gform_entry_meta filter.
* @param int $form_id The form id
*
* @return array The filtered entry meta array.
*/
public function get_entry_meta( $entry_meta, $form_id ) {
return $entry_meta;
}
//-------------- Results page --------------------------------------
/**
* Returns the configuration for the results page. By default this is not activated.
* To activate the results page override this function and return an array with the configuration data.
*
* Example:
* public function get_results_page_config() {
* return array(
* "title" => 'Quiz Results',
* "capabilities" => array("gravityforms_quiz_results"),
* "callbacks" => array(
* "fields" => array($this, 'results_fields'),
* "calculation" => array($this, 'results_calculation'),
* "markup" => array($this, 'results_markup'),
* )
* );
* }
*
*/
public function get_results_page_config() {
return false;
}
/**
* Initializes the result page functionality. To activate result page functionality, override the get_results_page_config() function.
*
* @param $results_page_config - configuration returned by get_results_page_config()
*/
public function results_page_init( $results_page_config ) {
require_once( 'class-gf-results.php' );
if ( isset( $results_page_config['callbacks']['filters'] ) ) {
add_filter( 'gform_filters_pre_results', $results_page_config['callbacks']['filters'], 10, 2 );
}
if ( isset( $results_page_config['callbacks']['filter_ui'] ) ) {
add_filter( 'gform_filter_ui', $results_page_config['callbacks']['filter_ui'], 10, 5 );
}
$gf_results = new GFResults( $this->_slug, $results_page_config );
$gf_results->init();
}
//-------------- Logging integration --------------------------------------
public function set_logging_supported( $plugins ) {
$plugins[ $this->_slug ] = $this->_title;
return $plugins;
}
//-------------- Members plugin integration --------------------------------------
/**
* Checks whether the Members plugin is installed and activated.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*
* @return bool
*/
public function has_members_plugin() {
return function_exists( 'members_get_capabilities' );
}
/**
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*
* @param $caps
*
* @return array
*/
public function members_get_capabilities( $caps ) {
return array_merge( $caps, $this->_capabilities );
}
//-------------- Permissions: Capabilities and Roles ----------------------------
/**
* Checks whether the current user is assigned to a capability or role.
*
* @param string|array $caps An string or array of capabilities to check
*
* @return bool Returns true if the current user is assigned to any of the capabilities.
*/
public function current_user_can_any( $caps ) {
return GFCommon::current_user_can_any( $caps );
}
//------- Settings Helper Methods (Common to all settings pages) -------------------
/***
* Renders the UI of all settings page based on the specified configuration array $sections
*
* @param array $sections - Configuration array containing all fields to be rendered grouped into sections
*/
public function render_settings( $sections ) {
if ( ! $this->has_setting_field_type( 'save', $sections ) ) {
$sections = $this->add_default_save_button( $sections );
}
?>
<form id="gform-settings" action="" method="post">
<?php wp_nonce_field( $this->_slug . '_save_settings', '_' . $this->_slug . '_save_settings_nonce' ) ?>
<?php $this->settings( $sections ); ?>
</form>
<?php
}
/***
* Renders settings fields based on the specified configuration array $sections
*
* @param array $sections - Configuration array containing all fields to be rendered grouped into sections
*/
public function settings( $sections ) {
$is_first = true;
foreach ( $sections as $section ) {
if ( $this->setting_dependency_met( rgar( $section, 'dependency' ) ) ) {
$this->single_section( $section, $is_first );
}
$is_first = false;
}
}
/***
* Displays the UI for a field section
*
* @param array $section - The section to be displayed
* @param bool $is_first - true for the first section in the list, false for all others
*/
public function single_section( $section, $is_first = false ) {
extract(
wp_parse_args(
$section, array(
'title' => false,
'description' => false,
'id' => '',
'class' => false,
'style' => '',
'tooltip' => false,
'tooltip_class' => ''
)
)
);
$classes = array( 'gaddon-section' );
if ( $is_first ) {
$classes[] = 'gaddon-first-section';
}
if ( $class )
$classes[] = $class;
?>
<div
id="<?php echo $id; ?>"
class="<?php echo implode( ' ', $classes ); ?>"
style="<?php echo $style; ?>"
>
<?php if ( $title ): ?>
<h4 class="gaddon-section-title gf_settings_subgroup_title">
<?php echo $title; ?>
<?php if( $tooltip ): ?>
<?php gform_tooltip( $tooltip, $tooltip_class ); ?>
<?php endif; ?>
</h4>
<?php endif; ?>
<?php if ( $description ): ?>
<div class="gaddon-section-description"><?php echo $description; ?></div>
<?php endif; ?>
<table class="form-table gforms_form_settings">
<?php
foreach ( $section['fields'] as $field ) {
if ( ! $this->setting_dependency_met( rgar( $field, 'dependency' ) ) )
continue;
if ( is_callable( array( $this, "single_setting_row_{$field['type']}" ) ) ) {
call_user_func( array( $this, "single_setting_row_{$field['type']}" ), $field );
} else {
$this->single_setting_row( $field );
}
}
?>
</table>
</div>
<?php
}
/***
* Displays the UI for the field container row
*
* @param array $field - The field to be displayed
*/
public function single_setting_row( $field ) {
$display = rgar( $field, 'hidden' ) || rgar( $field, 'type' ) == 'hidden' ? 'style="display:none;"' : '';
?>
<tr id="gaddon-setting-row-<?php echo $field['name'] ?>" <?php echo $display; ?>>
<th>
<?php $this->single_setting_label( $field ); ?>
</th>
<td>
<?php $this->single_setting( $field ); ?>
</td>
</tr>
<?php
}
/**
* Displays the label for a field, including the tooltip and requirement indicator.
*/
public function single_setting_label( $field ) {
echo rgar( $field, 'label' );
if ( isset( $field['tooltip'] ) ) {
echo $this->maybe_get_tooltip( $field );
}
if ( rgar( $field, 'required' ) ) {
echo ' ' . $this->get_required_indicator( $field );
}
}
public function single_setting_row_save( $field ) {
?>
<tr>
<td colspan="2">
<?php $this->single_setting( $field ); ?>
</td>
</tr>
<?php
}
/***
* Calls the appropriate field function to handle rendering of each specific field type
*
* @param array $field - The field to be rendered
*/
public function single_setting( $field ) {
if ( is_callable( rgar( $field, 'callback' ) ) ) {
call_user_func( $field['callback'], $field );
} elseif ( is_callable( array( $this, "settings_{$field['type']}" ) ) ) {
call_user_func( array( $this, "settings_{$field['type']}" ), $field );
} else {
printf( esc_html__( "Field type '%s' has not been implemented", 'gravityforms' ), esc_html( $field['type'] ) );
}
}
/***
* Sets the current saved settings to a class variable so that it can be accessed by lower level functions in order to initialize inputs with the appropriate values
*
* @param array $settings : Settings to be saved
*/
public function set_settings( $settings ) {
$this->_saved_settings = $settings;
}
/***
* Sets the previous settings to a class variable so that it can be accessed by lower level functions providing support for
* verifying whether a value was changed before executing an action
*
* @param array $settings : Settings to be stored
*/
public function set_previous_settings( $settings ) {
$this->_previous_settings = $settings;
}
public function get_previous_settings() {
return $this->_previous_settings;
}
/***
* Gets settings from $_POST variable, returning a name/value collection of setting name and setting value
*/
public function get_posted_settings() {
global $_gaddon_posted_settings;
if ( isset( $_gaddon_posted_settings ) ) {
return $_gaddon_posted_settings;
}
$_gaddon_posted_settings = array();
if ( count( $_POST ) > 0 ) {
foreach ( $_POST as $key => $value ) {
if ( preg_match( '|_gaddon_setting_(.*)|', $key, $matches ) ) {
$_gaddon_posted_settings[ $matches[1] ] = self::maybe_decode_json( stripslashes_deep( $value ) );
}
}
}
return $_gaddon_posted_settings;
}
public static function maybe_decode_json( $value ) {
if ( self::is_json( $value ) ) {
return json_decode( $value, ARRAY_A );
}
return $value;
}
public static function is_json( $value ) {
if ( is_string( $value ) && in_array( substr( $value, 0, 1 ), array( '{', '[' ) ) && is_array( json_decode( $value, ARRAY_A ) ) ) {
return true;
}
return false;
}
/***
* Gets the "current" settings, which are settings from $_POST variables if this is a postback request, or the current saved settings for a get request.
*/
public function get_current_settings() {
//try getting settings from post
$settings = $this->get_posted_settings();
//if nothing has been posted, get current saved settings
if ( empty( $settings ) ) {
$settings = $this->_saved_settings;
}
return $settings;
}
/***
* Retrieves the setting for a specific field/input
*
* @param string $setting_name The field or input name
* @param string $default_value Optional. The default value
* @param bool|array $settings Optional. THe settings array
*
* @return string|array
*/
public function get_setting( $setting_name, $default_value = '', $settings = false ) {
if ( ! $settings ) {
$settings = $this->get_current_settings();
}
if ( false === $settings ) {
return $default_value;
}
if ( strpos( $setting_name, '[' ) !== false ) {
$path_parts = explode( '[', $setting_name );
foreach ( $path_parts as $part ) {
$part = trim( $part, ']' );
if ( $part != '0'){
if ( empty( $part ) ) {
return $settings;
}
}
if ( false === isset( $settings[ $part ] ) ) {
return $default_value;
}
$settings = rgar( $settings, $part );
}
$setting = $settings;
} else {
if ( false === isset( $settings[ $setting_name ] ) ) {
return $default_value;
}
$setting = $settings[ $setting_name ];
}
return $setting;
}
/***
* Determines if a dependent field has been populated.
*
* @param string $dependency - Field or input name of the "parent" field.
*
* @return bool - true if the "parent" field has been filled out and false if it has not.
*
*/
public function setting_dependency_met( $dependency ) {
// if no dependency, always return true
if ( ! $dependency ) {
return true;
}
//use a callback if one is specified in the configuration
if ( is_callable( $dependency ) ) {
return call_user_func( $dependency );
}
if ( is_array( $dependency ) ) {
//supports: 'dependency' => array("field" => 'myfield', 'values' => array("val1", 'val2'))
$dependency_field = $dependency['field'];
$dependency_value = $dependency['values'];
} else {
//supports: 'dependency' => 'myfield'
$dependency_field = $dependency;
$dependency_value = '_notempty_';
}
if ( ! is_array( $dependency_value ) ) {
$dependency_value = array( $dependency_value );
}
$current_value = $this->get_setting( $dependency_field );
foreach ( $dependency_value as $val ) {
if ( $current_value == $val ) {
return true;
}
if ( $val == '_notempty_' && ! rgblank( $current_value ) ) {
return true;
}
}
return false;
}
public function has_setting_field_type( $type, $fields ) {
if ( ! empty( $fields ) ) {
foreach ( $fields as &$section ) {
foreach ( $section['fields'] as $field ) {
if ( rgar( $field, 'type' ) == $type ) {
return true;
}
}
}
}
return false;
}
public function add_default_save_button( $sections ) {
$sections[ count( $sections ) - 1 ]['fields'][] = array( 'type' => 'save' );
return $sections;
}
public function get_save_success_message( $sections ) {
$save_button = $this->get_save_button( $sections );
return isset( $save_button['messages']['success'] ) ? $save_button['messages']['success'] : esc_html__( 'Settings updated', 'gravityforms' );
}
public function get_save_error_message( $sections ) {
$save_button = $this->get_save_button( $sections );
return isset( $save_button['messages']['error'] ) ? $save_button['messages']['error'] : esc_html__( 'There was an error while saving your settings', 'gravityforms' );
}
public function get_save_button( $sections ) {
$sections = array_values( $sections );
$fields = $sections[ count( $sections ) - 1 ]['fields'];
foreach ( $fields as $field ) {
if ( $field['type'] == 'save' )
return $field;
}
return false;
}
//------------- Field Types ------------------------------------------------------
/***
* Renders and initializes a text field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_text( $field, $echo = true ) {
$field['type'] = 'text'; //making sure type is set to text
$field['input_type'] = rgar( $field, 'input_type' ) ? rgar( $field, 'input_type' ) : 'text';
$attributes = $this->get_field_attributes( $field );
$default_value = rgar( $field, 'value' ) ? rgar( $field, 'value' ) : rgar( $field, 'default_value' );
$value = $this->get_setting( $field['name'], $default_value );
$html = '';
$html .= '<input
type="' . esc_attr( $field['input_type'] ) . '"
name="_gaddon_setting_' . esc_attr( $field['name'] ) . '"
value="' . esc_attr( htmlspecialchars( $value, ENT_QUOTES ) ) . '" ' .
implode( ' ', $attributes ) .
' />';
$html .= rgar( $field, 'after_input' );
$feedback_callback = rgar( $field, 'feedback_callback' );
if ( is_callable( $feedback_callback ) ) {
$is_valid = call_user_func_array( $feedback_callback, array( $value, $field ) );
$icon = '';
if ( $is_valid === true ) {
$icon = 'icon-check fa-check gf_valid'; // check icon
} elseif ( $is_valid === false ) {
$icon = 'icon-remove fa-times gf_invalid'; // x icon
}
if ( ! empty( $icon ) ) {
$html .= " <i class=\"fa {$icon}\"></i>";
}
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a textarea field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_textarea( $field, $echo = true ) {
$field['type'] = 'textarea'; //making sure type is set to textarea
$attributes = $this->get_field_attributes( $field );
$default_value = rgar( $field, 'value' ) ? rgar( $field, 'value' ) : rgar( $field, 'default_value' );
$value = $this->get_setting( $field['name'], $default_value );
$name = '' . esc_attr( $field['name'] );
$html = '';
if ( rgar( $field, 'use_editor' ) ) {
$html .= '<span class="mt-gaddon-editor mt-_gaddon_setting_'. $field['name'] .'"></span>';
ob_start();
wp_editor( $value, '_gaddon_setting_'. $field['name'], array( 'autop' => false, 'editor_class' => 'merge-tag-support mt-wp_editor mt-manual_position mt-position-right' ) );
$html .= ob_get_contents();
ob_end_clean();
} else {
$html .= '<textarea
name="_gaddon_setting_' . $name . '" ' .
implode( ' ', $attributes ) .
'>' .
esc_textarea( $value ) .
'</textarea>';
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a hidden field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_hidden( $field, $echo = true ) {
$field['type'] = 'hidden'; //making sure type is set to hidden
$attributes = $this->get_field_attributes( $field );
$default_value = rgar( $field, 'value' ) ? rgar( $field, 'value' ) : rgar( $field, 'default_value' );
$value = $this->get_setting( $field['name'], $default_value );
if ( is_array( $value ) ) {
$value = json_encode( $value );
}
$html = '<input
type="hidden"
name="_gaddon_setting_' . esc_attr( $field['name'] ) . '"
value=\'' . esc_attr( $value ) . '\' ' .
implode( ' ', $attributes ) .
' />';
if ( $echo ) {
echo $html;
}
return $html;
}
/***
* Renders and initializes a checkbox field or a collection of checkbox fields based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_checkbox( $field, $echo = true ) {
$field['type'] = 'checkbox'; //making sure type is set to checkbox
$field_attributes = $this->get_field_attributes( $field, array() );
$have_icon = $this->choices_have_icon( rgar( $field, 'choices' ) );
$horizontal = rgar( $field, 'horizontal' ) || $have_icon ? ' gaddon-setting-inline' : '';
$html = '';
$default_choice_attributes = array( 'onclick' => 'jQuery(this).siblings("input[type=hidden]").val(jQuery(this).prop("checked") ? 1 : 0);', 'onkeypress' => 'jQuery(this).siblings("input[type=hidden]").val(jQuery(this).prop("checked") ? 1 : 0);' );
$is_first_choice = true;
if ( is_array( $field['choices'] ) ) {
foreach ( $field['choices'] as $choice ) {
$choice['id'] = sanitize_title( $choice['name'] );
$choice_attributes = $this->get_choice_attributes( $choice, $field_attributes, $default_choice_attributes );
$value = $this->get_setting( $choice['name'], rgar( $choice, 'default_value' ) );
$tooltip = $this->maybe_get_tooltip( $choice );
//displaying error message after first checkbox item
$error_icon = '';
if ( $is_first_choice ){
$error_icon = $this->field_failed_validation( $field ) ? $this->get_error_icon( $field ) : '';
}
// Add icon to choice if choices have icon
if ( $have_icon ) {
$choice['icon'] = rgar( $choice, 'icon' ) ? $choice['icon'] : 'fa-cog';
}
$html .= $this->checkbox_item( $choice, $horizontal, $choice_attributes, $value, $tooltip, $error_icon );
$is_first_choice = false;
}
}
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Returns the markup for an individual checkbox item give the parameters
*
* @param $choice - Choice array with all configured properties
* @param $horizontal_class - CSS class to style checkbox items horizontally
* @param $attributes - String containing all the attributes for the input tag.
* @param $value - Currently selection (1 if field has been checked. 0 or null otherwise)
* @param $tooltip - String containing a tooltip for this checkbox item.
*
* @return string - The markup of an individual checkbox item
*/
public function checkbox_item( $choice, $horizontal_class, $attributes, $value, $tooltip, $error_icon='' ) {
$hidden_field_value = $value == '1' ? '1' : '0';
$icon_class = rgar( $choice, 'icon' ) ? ' gaddon-setting-choice-visual' : '';
$checkbox_item = '<div id="gaddon-setting-checkbox-choice-' . $choice['id'] . '" class="gaddon-setting-checkbox' . $horizontal_class . $icon_class . '">';
$checkbox_item .= '<input type=hidden name="_gaddon_setting_' . esc_attr( $choice['name'] ) . '" value="' . $hidden_field_value . '" />';
if ( is_callable( array( $this, "checkbox_input_{$choice['name']}" ) ) ) {
$markup = call_user_func( array( $this, "checkbox_input_{$choice['name']}" ), $choice, $attributes, $value, $tooltip );
} else {
$markup = $this->checkbox_input( $choice, $attributes, $value, $tooltip );
}
$checkbox_item .= $markup . $error_icon . '</div>';
return $checkbox_item;
}
/**
* Returns the markup for an individual checkbox input and its associated label
*
* @param $choice - Choice array with all configured properties
* @param $attributes - String containing all the attributes for the input tag.
* @param $value - Currently selection (1 if field has been checked. 0 or null otherwise)
* @param $tooltip - String containing a tooltip for this checkbox item.
*
* @return string - The markup of an individual checkbox input and its associated label
*/
public function checkbox_input( $choice, $attributes, $value, $tooltip ) {
$icon_tag = '';
if ( rgar( $choice, 'icon' ) ) {
/* Get the defined icon. */
$icon = rgar( $choice, 'icon' ) ? $choice['icon'] : 'fa-cog';
/* Set icon tag based on icon type. */
if ( filter_var( $icon, FILTER_VALIDATE_URL ) ) {
$icon_tag = '<img src="' . esc_attr( $icon ) .'" />';
} else {
$icon_tag = '<i class="fa ' . esc_attr( $icon ) .'"></i>';
}
$icon_tag .= '<br />';
}
$markup = '<input type = "checkbox" ' . implode( ' ', $attributes ) . ' ' . checked( $value, '1', false ) . ' />';
$markup .= '<label for="' . esc_attr( $choice['id'] ) . '"><span>' . $icon_tag . esc_html( $choice['label'] ) . $tooltip . '</span></label>';
return $markup;
}
/***
* Renders and initializes a radio field or a collection of radio fields based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string Returns the markup for the radio buttons
*
*/
public function settings_radio( $field, $echo = true ) {
$field['type'] = 'radio'; //making sure type is set to radio
$selected_value = $this->get_setting( $field['name'], rgar( $field, 'default_value' ) );
$field_attributes = $this->get_field_attributes( $field );
$have_icon = $this->choices_have_icon( rgar( $field, 'choices' ) );
$horizontal = rgar( $field, 'horizontal' ) || $have_icon ? ' gaddon-setting-inline' : '';
$html = '';
if ( is_array( $field['choices'] ) ) {
foreach ( $field['choices'] as $i => $choice ) {
if ( rgempty( 'id', $choice ) ) {
$choice['id'] = $field['name'] . $i;
}
$choice_attributes = $this->get_choice_attributes( $choice, $field_attributes );
$tooltip = $this->maybe_get_tooltip( $choice );
$radio_value = isset( $choice['value'] ) ? $choice['value'] : $choice['label'];
$checked = checked( $selected_value, $radio_value, false );
if ( $have_icon ) {
/* Get the defined icon. */
$icon = rgar( $choice, 'icon' ) ? $choice['icon'] : 'fa-cog';
/* Set icon tag based on icon type. */
if ( filter_var( $icon, FILTER_VALIDATE_URL ) ) {
$icon_tag = '<img src="' . esc_attr( $icon ) .'" />';
} else {
$icon_tag = '<i class="fa ' . esc_attr( $icon ) .'"></i>';
}
$html .= '<div id="gaddon-setting-radio-choice-' . $choice['id'] . '" class="gaddon-setting-radio gaddon-setting-choice-visual' . $horizontal . '">';
$html .= '<input type="radio" name="_gaddon_setting_' . esc_attr( $field['name'] ) . '" ' .
'value="' . $radio_value . '" ' . implode( ' ', $choice_attributes ) . ' ' . $checked . ' />';
$html .= '<label for="' . esc_attr( $choice['id'] ) . '">';
$html .= '<span>' . $icon_tag . '<br />' . esc_html( $choice['label'] ) . $tooltip . '</span>';
$html .= '</label>';
$html .= '</div>';
} else {
$html .= '<div id="gaddon-setting-radio-choice-' . $choice['id'] . '" class="gaddon-setting-radio' . $horizontal . '">';
$html .= '<label for="' . esc_attr( $choice['id'] ) . '">';
$html .= '<input type="radio" name="_gaddon_setting_' . esc_attr( $field['name'] ) . '" ' .
'value="' . $radio_value . '" ' . implode( ' ', $choice_attributes ) . ' ' . $checked . ' />';
$html .= '<span>' . esc_html( $choice['label'] ) . $tooltip . '</span>';
$html .= '</label>';
$html .= '</div>';
}
}
}
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Determines if any of the available settings choices have an icon.
*
* @access public
* @param array $choices (default: array())
* @return bool
*/
public function choices_have_icon( $choices = array() ) {
$have_icon = false;
foreach ( $choices as $choice ) {
if ( rgar( $choice, 'icon' ) ) {
$have_icon = true;
}
}
return $have_icon;
}
/***
* Renders and initializes a drop down field based on the $field array
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_select( $field, $echo = true ) {
$field['type'] = 'select'; // making sure type is set to select
$attributes = $this->get_field_attributes( $field );
$value = $this->get_setting( $field['name'], rgar( $field, 'default_value' ) );
$name = '' . esc_attr( $field['name'] );
$html = sprintf(
'<select name="%1$s" %2$s>%3$s</select>',
'_gaddon_setting_' . $name, implode( ' ', $attributes ), $this->get_select_options( $field['choices'], $value )
);
$html .= rgar( $field, 'after_select' );
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Renders and initializes a drop down field with a input field for custom input based on the $field array.
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_select_custom( $field, $echo = true ) {
/* Prepare select field */
$select_field = $field;
$select_field_value = $this->get_setting( $select_field['name'], rgar( $select_field, 'default_value' ) );
$select_field['onchange'] = '';
$select_field['class'] = ( isset( $select_field['class'] ) ) ? $select_field['class'] . 'gaddon-setting-select-custom' : 'gaddon-setting-select-custom';
/* Prepare input field */
$input_field = $field;
$input_field['name'] .= '_custom';
$input_field['style'] = 'width:200px;max-width:90%;';
$input_field_display = '';
/* Loop through select choices and make sure option for custom exists */
$has_gf_custom = false;
foreach ( $select_field['choices'] as $choice ) {
if ( rgar( $choice, 'name' ) == 'gf_custom' || rgar( $choice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
/* If choice has choices, check inside those choices. */
if ( rgar( $choice, 'choices' ) ) {
foreach ( $choice['choices'] as $subchoice ) {
if ( rgar( $subchoice, 'name' ) == 'gf_custom' || rgar( $subchoice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
}
}
}
if ( ! $has_gf_custom ) {
$select_field['choices'][] = array(
'label' => esc_html__( 'Add Custom', 'gravityforms' ) .' ' . $select_field['label'],
'value' => 'gf_custom'
);
}
/* If select value is "gf_custom", hide the select field and display the input field. */
if ( $select_field_value == 'gf_custom' || ( count( $select_field['choices'] ) == 1 && $select_field['choices'][0]['value'] == 'gf_custom' ) ) {
$select_field['style'] = 'display:none;';
} else {
$input_field_display = ' style="display:none;"';
}
/* Add select field */
$html = $this->settings_select( $select_field, false );
/* Add input field */
$html .= '<div class="gaddon-setting-select-custom-container"'. $input_field_display .'>';
$html .= count( $select_field['choices'] ) > 1 ? '<a href="#" class="select-custom-reset">Reset</a>' : '';
$html .= $this->settings_text( $input_field, false );
$html .= '</div>';
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Prepares an HTML string of options for a drop down field.
*
* @param array $choices - Array containing all the options for the drop down field
* @param string $selected_value - The value currently selected for the field
*
* @return string The HTML for the select options
*/
public function get_select_options( $choices, $selected_value ) {
$options = '';
foreach ( $choices as $choice ) {
if ( isset( $choice['choices'] ) ) {
$options .= sprintf( '<optgroup label="%1$s">%2$s</optgroup>', esc_attr( $choice['label'] ), $this->get_select_options( $choice['choices'], $selected_value ) );
} else {
if ( ! isset( $choice['value'] ) ) {
$choice['value'] = $choice['label'];
}
$options .= $this->get_select_option( $choice, $selected_value );
}
}
return $options;
}
/**
* Prepares an HTML string for a single drop down field option.
*
* @access protected
* @param array $choice - Array containing the settings for the drop down option
* @param string $selected_value - The value currently selected for the field
*
* @return string The HTML for the select choice
*/
public function get_select_option( $choice, $selected_value ) {
if ( is_array( $selected_value ) ) {
$selected = in_array( $choice['value'], $selected_value ) ? "selected='selected'" : '';
} else {
$selected = selected( $selected_value, $choice['value'], false );
}
return sprintf( '<option value="%1$s" %2$s>%3$s</option>', esc_attr( $choice['value'] ), $selected, $choice['label'] );
}
//------------- Field Map Field Type --------------------------
public function settings_field_map( $field, $echo = true ) {
$html = '';
$field_map = rgar( $field, 'field_map' );
if ( empty( $field_map ) ) {
return $html;
}
$form_id = rgget( 'id' );
$html .= '<table class="settings-field-map-table" cellspacing="0" cellpadding="0">' .
$this->field_map_table_header() .
'<tbody>';
foreach ( $field['field_map'] as $child_field ) {
if ( ! $this->setting_dependency_met( rgar( $child_field, 'dependency' ) ) ) {
continue;
}
$child_field['name'] = $this->get_mapped_field_name( $field, $child_field['name'] );
$tooltip = $this->maybe_get_tooltip( $child_field );
$required = rgar( $child_field, 'required' ) ? ' ' . $this->get_required_indicator( $child_field ) : '';
$html .= '
<tr>
<td>
<label for="' . $child_field['name'] . '">' . $child_field['label'] . $tooltip . $required . '</label>
</td>
<td>' .
$this->settings_field_map_select( $child_field, $form_id ) .
'</td>
</tr>';
}
$html .= '
</tbody>
</table>';
if ( $echo ) {
echo $html;
}
return $html;
}
public function field_map_table_header() {
return '<thead>
<tr>
<th>' . $this->field_map_title() . '</th>
<th>' . esc_html__( 'Form Field', 'gravityforms' ) . '</th>
</tr>
</thead>';
}
public function settings_field_map_select( $field, $form_id ) {
$field_type = rgempty( 'field_type', $field ) ? null : $field['field_type'];
$exclude_field_types = rgempty( 'exclude_field_types', $field ) ? null : $field['exclude_field_types'];
$field['choices'] = $this->get_field_map_choices( $form_id, $field_type, $exclude_field_types );
if ( empty( $field['choices'] ) || ( count( $field['choices'] ) == 1 && rgblank( $field['choices'][0]['value'] ) ) ) {
if ( ( ! is_array( $field_type ) && ! rgblank( $field_type ) ) || ( is_array( $field_type ) && count( $field_type ) == 1 ) ) {
$type = is_array( $field_type ) ? $field_type[0] : $field_type;
$type = ucfirst( GF_Fields::get( $type )->get_form_editor_field_title() );
return sprintf( __( 'Please add a %s field to your form.', 'gravityforms' ), $type );
}
}
// Set default value.
$field['default_value'] = $this->get_default_field_select_field( $field );
return $this->settings_select( $field, false );
}
public function field_map_title() {
return esc_html__( 'Field', 'gravityforms' );
}
public static function get_field_map_choices( $form_id, $field_type = null, $exclude_field_types = null ) {
$form = RGFormsModel::get_form_meta( $form_id );
$fields = array();
// Setup first choice
if ( rgblank( $field_type ) || ( is_array( $field_type ) && count( $field_type ) > 1 ) ) {
$first_choice_label = __( 'Select a Field', 'gravityforms' );
} else {
$type = is_array( $field_type ) ? $field_type[0] : $field_type;
$type = ucfirst( GF_Fields::get( $type )->get_form_editor_field_title() );
$first_choice_label = sprintf( __( 'Select a %s Field', 'gravityforms' ), $type );
}
$fields[] = array( 'value' => '', 'label' => $first_choice_label );
// if field types not restricted add the default fields and entry meta
if ( is_null( $field_type ) ) {
$fields[] = array( 'value' => 'id', 'label' => esc_html__( 'Entry ID', 'gravityforms' ) );
$fields[] = array( 'value' => 'date_created', 'label' => esc_html__( 'Entry Date', 'gravityforms' ) );
$fields[] = array( 'value' => 'ip', 'label' => esc_html__( 'User IP', 'gravityforms' ) );
$fields[] = array( 'value' => 'source_url', 'label' => esc_html__( 'Source Url', 'gravityforms' ) );
$fields[] = array( 'value' => 'form_title', 'label' => esc_html__( 'Form Title', 'gravityforms' ) );
$entry_meta = GFFormsModel::get_entry_meta( $form['id'] );
foreach ( $entry_meta as $meta_key => $meta ) {
$fields[] = array( 'value' => $meta_key, 'label' => rgars( $entry_meta, "{$meta_key}/label" ) );
}
}
// Populate form fields
if ( is_array( $form['fields'] ) ) {
foreach ( $form['fields'] as $field ) {
$input_type = $field->get_input_type();
$inputs = $field->get_entry_inputs();
$field_is_valid_type = ( empty( $field_type ) || ( is_array( $field_type ) && in_array( $input_type, $field_type ) ) || ( ! empty( $field_type ) && $input_type == $field_type ) );
if ( is_null( $exclude_field_types ) ) {
$exclude_field = false;
} elseif ( is_array( $exclude_field_types ) ) {
if ( in_array( $input_type, $exclude_field_types ) ) {
$exclude_field = true;
} else {
$exclude_field = false;
}
} else {
//not array, so should be single string
if ( $input_type == $exclude_field_types ) {
$exclude_field = true;
} else {
$exclude_field = false;
}
}
if ( is_array( $inputs ) && $field_is_valid_type && ! $exclude_field ) {
//If this is an address field, add full name to the list
if ( $input_type == 'address' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
//If this is a name field, add full name to the list
if ( $input_type == 'name' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
//If this is a checkbox field, add to the list
if ( $input_type == 'checkbox' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Selected', 'gravityforms' ) . ')'
);
}
foreach ( $inputs as $input ) {
$fields[] = array(
'value' => $input['id'],
'label' => GFCommon::get_label( $field, $input['id'] )
);
}
} elseif ( $input_type == 'list' && $field->enableColumns && $field_is_valid_type && ! $exclude_field ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
$col_index = 0;
foreach ( $field->choices as $column ) {
$fields[] = array(
'value' => $field->id . '.' . $col_index,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html( rgar( $column, 'text' ) ) . ')',
);
$col_index ++;
}
} elseif ( ! $field->displayOnly && $field_is_valid_type && ! $exclude_field ) {
$fields[] = array( 'value' => $field->id, 'label' => GFCommon::get_label( $field ) );
}
}
}
/**
* Filter the choices available in the field map drop down.
*
* @since 2.0.7.11
*
* @param array $fields The value and label properties for each choice.
* @param int $form_id The ID of the form currently being configured.
* @param null|array $field_type Null or the field types to be included in the drop down.
* @param null|array|string $exclude_field_types Null or the field type(s) to be excluded from the drop down.
*/
$fields = apply_filters( 'gform_addon_field_map_choices', $fields, $form_id, $field_type, $exclude_field_types );
$callable = array( get_called_class(), 'get_instance' );
if ( is_callable( $callable ) ) {
$addon = call_user_func( $callable );
$slug = $addon->get_slug();
$fields = apply_filters( "gform_{$slug}_field_map_choices", $fields, $form_id, $field_type, $exclude_field_types );
}
return $fields;
}
public function get_mapped_field_name( $parent_field, $field_name ) {
return "{$parent_field['name']}_{$field_name}";
}
public static function get_field_map_fields( $feed, $field_name ) {
$fields = array();
$prefix = "{$field_name}_";
foreach ( $feed['meta'] as $name => $value ) {
if ( strpos( $name, $prefix ) === 0 ) {
$name = str_replace( $prefix, '', $name );
$fields[ $name ] = $value;
}
}
return $fields;
}
public static function get_dynamic_field_map_fields( $feed, $field_name ) {
$fields = array();
$dynamic_fields = $feed['meta'][$field_name];
if ( ! empty( $dynamic_fields ) ) {
foreach ( $dynamic_fields as $dynamic_field ) {
$field_key = ( $dynamic_field['key'] == 'gf_custom' ) ? $dynamic_field['custom_key'] : $dynamic_field['key'];
$fields[$field_key] = $dynamic_field['value'];
}
}
return $fields;
}
//----------------------------------------------------------------
public function settings_dynamic_field_map( $field, $echo = true ) {
$html = '';
$value_field = $key_field = $custom_key_field = $field;
$form = $this->get_current_form();
/* Setup key field drop down */
$key_field['choices'] = ( isset( $field['field_map'] ) ) ? $field['field_map'] : null;
$key_field['name'] .= '_key';
$key_field['class'] = 'key key_{i}';
$key_field['style'] = 'width:200px;';
/* Setup custom key text field */
$custom_key_field['name'] .= '_custom_key_{i}';
$custom_key_field['class'] = 'custom_key custom_key_{i}';
$custom_key_field['style'] = 'width:200px;max-width:90%;';
$custom_key_field['value'] = '{custom_key}';
/* Setup value drop down */
$value_field['name'] .= '_custom_value';
$value_field['class'] = 'value value_{i}';
/* Remove unneeded values */
unset( $field['field_map'] );
unset( $value_field['field_map'] );
unset( $key_field['field_map'] );
unset( $custom_key_field['field_map'] );
//add on errors set when validation fails
if ( $this->field_failed_validation( $field ) ) {
$html .= $this->get_error_icon( $field );
}
/* Build key cell based on available field map choices */
if ( empty( $key_field['choices'] ) ) {
/* Set key field value to "gf_custom" so custom key is used. */
$key_field['value'] = 'gf_custom';
/* Build HTML string */
$key_field_html = '<td>' .
$this->settings_hidden( $key_field, false ) . '
<div class="custom-key-container">
' . $this->settings_text( $custom_key_field, false ) . '
</div>
</td>';
} else {
/* Ensure field map array has a custom key option. */
$has_gf_custom = false;
foreach ( $key_field['choices'] as $choice ) {
if ( rgar( $choice, 'name' ) == 'gf_custom' || rgar( $choice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
if ( rgar( $choice, 'choices' ) ) {
foreach ( $choice['choices'] as $subchoice ) {
if ( rgar( $subchoice, 'name' ) == 'gf_custom' || rgar( $subchoice, 'value' ) == 'gf_custom' ) {
$has_gf_custom = true;
}
}
}
}
if ( ! $has_gf_custom && ! rgar( $field, 'disable_custom' ) ) {
$key_field['choices'][] = array(
'label' => esc_html__( 'Add Custom Key', 'gravityforms' ),
'value' => 'gf_custom'
);
}
/* Build HTML string */
$key_field_html = '<th>' .
$this->settings_select( $key_field, false ) . '
<div class="custom-key-container">
<a href="#" class="custom-key-reset">Reset</a>' .
$this->settings_text( $custom_key_field, false ) . '
</div>
</th>';
}
$html .= '
<table class="settings-field-map-table" cellspacing="0" cellpadding="0">
<tbody class="repeater">
<tr>
'. $key_field_html .'
<td>' .
$this->settings_field_map_select( $value_field, $form['id'] ) . '
</td>
<td>
{buttons}
</td>
</tr>
</tbody>
</table>';
$html .= $this->settings_hidden( $field, false );
$limit = empty( $field['limit'] ) ? 0 : $field['limit'];
$html .= "
<script type=\"text/javascript\">
var dynamicFieldMap". esc_attr( $field['name'] ) ." = new gfieldmap({
'baseURL': '". GFCommon::get_base_url() ."',
'fieldId': '". esc_attr( $field['name'] ) ."',
'fieldName': '". $field['name'] ."',
'keyFieldName': '". $key_field['name'] ."',
'limit': '". $limit . "'
});
</script>";
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Renders and initializes a drop down field based on the $field array whose choices are populated by the form's fields.
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_field_select( $field, $echo = true ) {
$field = $this->prepare_field_select_field( $field );
$html = $this->settings_select( $field, false );
if ( $echo ) {
echo $html;
}
return $html;
}
public function prepare_field_select_field( $field ) {
$args = is_array( rgar( $field, 'args' ) ) ? rgar( $field, 'args' ) : array( rgar( $field, 'args' ) );
$args = wp_parse_args(
$args, array(
'append_choices' => array(),
'disable_first_choice' => false,
)
);
$field['choices'] = array();
if ( ! $args['disable_first_choice'] ) {
// Setup first choice
if ( empty( $args['input_types'] ) || ( is_array( $args['input_types'] ) && count( $args['input_types'] ) > 1 ) ) {
$first_choice_label = __( 'Select a Field', 'gravityforms' );
} else {
$type = is_array( $args['input_types'] ) ? $args['input_types'][0] : $args['input_types'];
$type = ucfirst( GF_Fields::get( $type )->get_form_editor_field_title() );
$first_choice_label = sprintf( __( 'Select a %s Field', 'gravityforms' ), $type );
}
$field['choices'][] = array( 'value' => '', 'label' => $first_choice_label );
}
$field['choices'] = array_merge( $field['choices'], $this->get_form_fields_as_choices( $this->get_current_form(), $args ) );
if ( ! empty( $args['append_choices'] ) ) {
$field['choices'] = array_merge( $field['choices'], $args['append_choices'] );
}
// Set default value.
$field['default_value'] = $this->get_default_field_select_field( $field );
return $field;
}
/**
* Returns the field to be selected by default for field select fields based on matching labels.
*
* @access public
* @param array $field - Field array containing the configuration options of this field
*
* @return string|null
*/
public function get_default_field_select_field( $field ) {
// If field's default value is not an array and not empty, return it.
if ( ! rgempty( 'default_value', $field ) && ! is_array( $field['default_value'] ) ) {
return $field['default_value'];
}
// Set default value if auto populate is not disabled.
if ( rgar( $field, 'auto_mapping' ) !== false ) {
$field_label = rgar( $field, 'label' );
// Initialize array to store auto-population choices.
$default_value_choices = array( $field_label );
// Define global aliases to help with the common case mappings.
$global_aliases = array(
__('First Name', 'gravityforms') => array( __( 'Name (First)', 'gravityforms' ) ),
__('Last Name', 'gravityforms') => array( __( 'Name (Last)', 'gravityforms' ) ),
__('Address', 'gravityforms') => array( __( 'Address (Street Address)', 'gravityforms' ) ),
__('Address 2', 'gravityforms') => array( __( 'Address (Address Line 2)', 'gravityforms' ) ),
__('City', 'gravityforms') => array( __( 'Address (City)', 'gravityforms' ) ),
__('State', 'gravityforms') => array( __( 'Address (State / Province)', 'gravityforms' ) ),
__('Zip', 'gravityforms') => array( __( 'Address (Zip / Postal Code)', 'gravityforms' ) ),
__('Country', 'gravityforms') => array( __( 'Address (Country)', 'gravityforms' ) ),
);
// If one or more global aliases are defined for this particular field label, merge them into auto-population choices.
if ( isset( $global_aliases[ $field_label ] ) ){
$default_value_choices = array_merge( $default_value_choices, $global_aliases[ $field_label ] );
}
// If field aliases are defined, merge them into auto-population choices.
if ( rgars( $field, 'default_value/aliases' ) ) {
$default_value_choices = array_merge( $default_value_choices, $field['default_value']['aliases'] );
}
// Convert all auto-population choices to lowercase.
$default_value_choices = array_map( 'strtolower', $default_value_choices );
// Loop through fields.
foreach ( $field['choices'] as $choice ) {
// If choice value is empty, skip it.
if ( rgblank( $choice['value'] ) ) {
continue;
}
// If lowercase field label matches a default value choice, set it to the default value.
if ( in_array( strtolower( $choice['label'] ), $default_value_choices ) ) {
return $choice['value'];
}
}
}
return null;
}
/**
* Retrieve an array of form fields formatted for select, radio and checkbox settings fields.
*
* @access public
* @param array $form - The form object
* @param array $args - Additional settings to check for (field and input types to include, callback for applicable input type)
*
* @return array The array of formatted form fields
*/
public function get_form_fields_as_choices( $form, $args = array() ) {
$fields = array();
if ( ! is_array( $form['fields'] ) ) {
return $fields;
}
$args = wp_parse_args(
$args, array(
'field_types' => array(),
'input_types' => array(),
'callback' => false
)
);
foreach ( $form['fields'] as $field ) {
$input_type = GFFormsModel::get_input_type( $field );
$is_applicable_input_type = empty( $args['input_types'] ) || in_array( $input_type, $args['input_types'] );
if ( is_callable( $args['callback'] ) ) {
$is_applicable_input_type = call_user_func( $args['callback'], $is_applicable_input_type, $field, $form );
}
if ( ! $is_applicable_input_type ) {
continue;
}
if ( ! empty( $args['property'] ) && ( ! isset( $field->$args['property'] ) || $field->$args['property'] != $args['property_value'] ) ) {
continue;
}
$inputs = $field->get_entry_inputs();
if ( is_array( $inputs ) ) {
// if this is an address field, add full name to the list
if ( $input_type == 'address' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
// if this is a name field, add full name to the list
if ( $input_type == 'name' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
}
// if this is a checkbox field, add to the list
if ( $input_type == 'checkbox' ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Selected', 'gravityforms' ) . ')'
);
}
foreach ( $inputs as $input ) {
$fields[] = array(
'value' => $input['id'],
'label' => GFCommon::get_label( $field, $input['id'] )
);
}
} elseif ( $input_type == 'list' && $field->enableColumns ) {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field ) . ' (' . esc_html__( 'Full', 'gravityforms' ) . ')'
);
$col_index = 0;
foreach ( $field->choices as $column ) {
$fields[] = array(
'value' => $field->id . '.' . $col_index,
'label' => GFCommon::get_label( $field ) . ' (' . rgar( $column, 'text' ) . ')',
);
$col_index ++;
}
} elseif ( ! $field->displayOnly ) {
$fields[] = array( 'value' => $field->id, 'label' => GFCommon::get_label( $field ) );
} else {
$fields[] = array(
'value' => $field->id,
'label' => GFCommon::get_label( $field )
);
}
}
return $fields;
}
/**
* Renders and initializes a checkbox field that displays a select field when checked based on the $field array.
*
* @access public
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML for the field
*/
public function settings_checkbox_and_select( $field, $echo = true ) {
$field = $this->prepare_settings_checkbox_and_select( $field );
$checkbox_field = $field['checkbox'];
$select_field = $field['select'];
$is_enabled = $this->get_setting( $checkbox_field['name'] );
// get markup
$html = sprintf(
'%s <span id="%s" class="%s">%s %s</span>',
$this->settings_checkbox( $checkbox_field, false ),
$select_field['name'] . 'Span',
$is_enabled ? '' : 'hidden',
$this->settings_select( $select_field, false ),
$this->maybe_get_tooltip( $select_field )
);
if ( $echo ) {
echo $html;
}
return $html;
}
public function prepare_settings_checkbox_and_select( $field ) {
// prepare checkbox
$checkbox_input = rgars( $field, 'checkbox' );
$checkbox_field = array(
'type' => 'checkbox',
'name' => $field['name'] . 'Enable',
'label' => esc_html__( 'Enable', 'gravityforms' ),
'horizontal' => true,
'value' => '1',
'choices' => false,
'tooltip' => false
);
$checkbox_field = wp_parse_args( $checkbox_input, $checkbox_field );
// prepare select
$select_input = rgars( $field, 'select' );
$select_field = array(
'name' => $field['name'] . 'Value',
'type' => 'select',
'class' => '',
'tooltip' => false
);
$select_field['class'] .= ' ' . $select_field['name'];
$select_field = wp_parse_args( $select_input, $select_field );
// a little more with the checkbox
if( empty( $checkbox_field['choices'] ) ) {
$checkbox_field['choices'] = array(
array(
'name' => $checkbox_field['name'],
'label' => $checkbox_field['label'],
'onchange' => sprintf( "( function( $, elem ) {
$( elem ).parents( 'td' ).css( 'position', 'relative' );
if( $( elem ).prop( 'checked' ) ) {
$( '%1\$s' ).fadeIn();
} else {
$( '%1\$s' ).fadeOut();
}
} )( jQuery, this );",
"#{$select_field['name']}Span" )
)
);
}
$field['select'] = $select_field;
$field['checkbox'] = $checkbox_field;
return $field;
}
/***
* Renders the save button for settings pages
*
* @param array $field - Field array containing the configuration options of this field
* @param bool $echo = true - true to echo the output to the screen, false to simply return the contents as a string
*
* @return string The HTML
*/
public function settings_save( $field, $echo = true ) {
$field['type'] = 'submit';
$field['name'] = 'gform-settings-save';
$field['class'] = 'button-primary gfbutton';
if ( ! rgar( $field, 'value' ) ) {
$field['value'] = esc_html__( 'Update Settings', 'gravityforms' );
}
$attributes = $this->get_field_attributes( $field );
$html = '<input
type="' . esc_attr( $field['type'] ) . '"
name="' . esc_attr( $field['name'] ) . '"
value="' . esc_attr( $field['value'] ) . '" ' . implode( ' ', $attributes ) . ' />';
if ( $echo ) {
echo $html;
}
return $html;
}
/**
* Parses the properties of the $field meta array and returns a set of HTML attributes to be added to the HTML element.
*
* @param array $field - current field meta to be parsed.
* @param array $default - default set of properties. Will be appended to the properties specified in the $field array
*
* @return array - resulting HTML attributes ready to be included in the HTML element.
*/
public function get_field_attributes( $field, $default = array() ) {
/**
* Each nonstandard property will be extracted from the $props array so it is not auto-output in the field HTML
*
* @param array $field The current field meta to be parsed
*/
$no_output_props = apply_filters(
'gaddon_no_output_field_properties',
array(
'default_value', 'label', 'choices', 'feedback_callback', 'checked', 'checkbox_label', 'value', 'type',
'validation_callback', 'required', 'hidden', 'tooltip', 'dependency', 'messages', 'name', 'args', 'exclude_field_types',
'field_type', 'after_input', 'input_type', 'icon', 'save_callback',
), $field
);
$default_props = array(
'class' => '', // will default to gaddon-setting
'default_value' => '', // default value that should be selected or entered for the field
);
// Property switch case
switch ( $field['type'] ) {
case 'select':
$default_props['choices'] = array();
break;
case 'checkbox':
$default_props['checked'] = false;
$default_props['checkbox_label'] = '';
$default_props['choices'] = array();
break;
case 'text':
default:
break;
}
$props = wp_parse_args( $field, $default_props );
$props['id'] = rgempty( 'id', $props ) ? rgar( $props, 'name' ) : rgar( $props, 'id' );
$props['class'] = trim( "{$props['class']} gaddon-setting gaddon-{$props['type']}" );
// extract no-output properties from $props array so they are not auto-output in the field HTML
foreach ( $no_output_props as $prop ) {
if ( isset( $props[ $prop ] ) ) {
${$prop} = $props[ $prop ];
unset( $props[ $prop ] );
}
}
//adding default attributes
foreach ( $default as $key => $value ) {
if ( isset( $props[ $key ] ) ) {
$props[ $key ] = $value . $props[ $key ];
} else {
$props[ $key ] = $value;
}
}
// get an array of property strings, example: name='myFieldName'
$prop_strings = array();
foreach ( $props as $prop => $value ) {
$prop_strings[ $prop ] = "{$prop}='" . esc_attr( $value ) . "'";
}
return $prop_strings;
}
/**
* Parses the properties of the $choice meta array and returns a set of HTML attributes to be added to the HTML element.
*
* @param array $choice - current choice meta to be parsed.
* @param array $field_attributes - current field's attributes.
*
* @return array - resulting HTML attributes ready to be included in the HTML element.
*/
public function get_choice_attributes( $choice, $field_attributes, $default_choice_attributes = array() ) {
$choice_attributes = $field_attributes;
foreach ( $choice as $prop => $val ) {
$no_output_choice_attributes = array(
'default_value', 'label', 'checked', 'value', 'type',
'validation_callback', 'required', 'tooltip',
);
if ( in_array( $prop, $no_output_choice_attributes ) || is_array( $val ) ) {
unset( $choice_attributes[ $prop ] );
} else {
$choice_attributes[ $prop ] = "{$prop}='" . esc_attr( $val ) . "'";
}
}
//Adding default attributes. Either creating a new attribute or pre-pending to an existing one.
foreach ( $default_choice_attributes as $default_attr_name => $default_attr_value ) {
if ( isset( $choice_attributes[ $default_attr_name ] ) ) {
$choice_attributes[ $default_attr_name ] = $this->prepend_attribute( $default_attr_name, $default_attr_value, $choice_attributes[ $default_attr_name ] );
}
else {
$choice_attributes[ $default_attr_name ] = "{$default_attr_name}='" . esc_attr( $default_attr_value ) . "'";
}
}
return $choice_attributes;
}
/***
* @param $name - The name of the attribute to be added
* @param $attribute - The attribute value to be added
* @param $current_attribute - The full string containing the current attribute value
* @return mixed - The new attribute string with the new value added to the beginning of the list
*/
public function prepend_attribute( $name, $attribute, $current_attribute ) {
return str_replace( "{$name}='", "{$name}='{$attribute}", $current_attribute );
}
/**
* Validates settings fields.
* Validates that all fields are valid. Fields can be invalid when they are blank and marked as required or if it fails a custom validation check.
* To specify a custom validation, use the 'validation_callback' field meta property and implement the validation function with the custom logic.
*
* @param $fields - A list of all fields from the field meta configuration
* @param $settings - A list of submitted settings values
*
* @return bool - Returns true if all fields have passed validation, and false otherwise.
*/
public function validate_settings( $fields, $settings ) {
foreach ( $fields as $section ) {
if ( ! $this->setting_dependency_met( rgar( $section, 'dependency' ) ) ) {
continue;
}
foreach ( $section['fields'] as $field ) {
if ( ! $this->setting_dependency_met( rgar( $field, 'dependency' ) ) ) {
continue;
}
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( is_callable( rgar( $field, 'validation_callback' ) ) ) {
call_user_func( rgar( $field, 'validation_callback' ), $field, $field_setting );
continue;
}
if ( is_callable( array( $this, 'validate_' . $field['type'] . '_settings' ) ) ) {
call_user_func( array( $this, 'validate_' . $field['type'] . '_settings' ), $field, $settings );
continue;
}
if ( rgar( $field, 'required' ) && rgblank( $field_setting ) ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
}
}
}
$field_errors = $this->get_field_errors();
$is_valid = empty( $field_errors );
return $is_valid;
}
public function validate_text_settings( $field, $settings ) {
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( rgar( $field, 'required' ) && rgblank( $field_setting ) ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
}
$field_setting_safe = sanitize_text_field( $field_setting );
if ( $field_setting !== $field_setting_safe ) {
$message = esc_html__( 'The text you have entered is not valid. For security reasons, some characters are not allowed. ', 'gravityforms' );
$script = sprintf( 'jQuery("input[name=\"_gaddon_setting_%s\"]").val(jQuery(this).data("safe"));', $field['name'] );
$double_encoded_safe_value = htmlspecialchars( htmlspecialchars( $field_setting_safe, ENT_QUOTES ), ENT_QUOTES );
$message .= sprintf( " <a href='javascript:void(0);' onclick='%s' data-safe='%s'>%s</a>", htmlspecialchars( $script, ENT_QUOTES ), $double_encoded_safe_value, esc_html__('Fix it', 'gravityforms' ) );
$this->set_field_error( $field, $message );
}
}
public function validate_textarea_settings( $field, $settings ) {
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( rgar( $field, 'required' ) && rgblank( $field_setting ) ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
}
$field_setting_safe = $this->maybe_wp_kses( $field_setting );
if ( $field_setting !== $field_setting_safe ) {
$message = esc_html__( 'The text you have entered is not valid. For security reasons, some characters are not allowed. ', 'gravityforms' );
$script = sprintf( 'jQuery("textarea[name=\"_gaddon_setting_%s\"]").val(jQuery(this).data("safe"));', $field['name'] );
$double_encoded_safe_value = htmlspecialchars( htmlspecialchars( $field_setting_safe, ENT_QUOTES ), ENT_QUOTES );
$message .= sprintf( " <a href='javascript:void(0);' onclick='%s' data-safe='%s'>%s</a>", htmlspecialchars( $script, ENT_QUOTES ), $double_encoded_safe_value, esc_html__('Fix it', 'gravityforms' ) );
$this->set_field_error( $field, $message );
}
}
public function validate_radio_settings( $field, $settings ) {
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( rgar( $field, 'required' ) && rgblank( $field_setting ) ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
return;
}
if ( rgblank( $field_setting ) ){
return; //Nothing is selected. Let it pass validation
}
foreach( $field['choices'] as $choice ) {
if ( $this->is_choice_valid( $choice, $field_setting ) ) {
return; // Choice is valid
}
}
$this->set_field_error( $field, esc_html__( 'Invalid value', 'gravityforms' ) );
}
public function validate_select_settings( $field, $settings ) {
$field_name = str_replace( '[]', '', $field['name'] );
$field_setting = rgar( $settings, $field_name );
$multiple = rgar( $field, 'multiple' ) == 'multiple';
$required = rgar( $field, 'required' );
if ( ! $multiple && $required && rgblank( $field_setting ) ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
return;
}
if ( rgblank( $field_setting ) ) {
return;
}
if ( $multiple ) {
$selected = 0;
foreach( $field['choices'] as $choice ) {
if ( isset( $choice['choices'] ) ) {
foreach( $choice['choices'] as $optgroup_choice ) {
if ( $this->is_choice_valid( $optgroup_choice, $field_setting ) ) {
$selected++;
}
}
} else {
if ( $this->is_choice_valid( $choice, $field_setting ) ) {
$selected++;
}
}
}
if ( $required && $selected == 0 ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
return;
}
if ( ! $required && $selected !== count( $field_setting ) ) {
$this->set_field_error( $field, esc_html__( 'Invalid value', 'gravityforms' ) );
}
} else {
foreach( $field['choices'] as $choice ) {
if ( isset( $choice['choices'] ) ) {
foreach( $choice['choices'] as $optgroup_choice ) {
if ( $this->is_choice_valid( $optgroup_choice, $field_setting ) ) {
return;
}
}
} else {
if ( $this->is_choice_valid( $choice, $field_setting ) ) {
return; // Choice is valid
}
}
}
$this->set_field_error( $field, esc_html__( 'Invalid value', 'gravityforms' ) );
}
}
public function validate_checkbox_settings( $field, $settings ) {
if ( ! is_array( rgar( $field, 'choices' ) ) ) {
return;
}
$selected = 0;
foreach ( $field['choices'] as $choice ) {
$value = $this->get_setting( $choice['name'], '', $settings );
if ( ! in_array( $value, array( '1', '0' ) ) ) {
$this->set_field_error( $field, esc_html__( 'Invalid value', 'gravityforms' ) );
return;
}
if ( $value === '1' ) {
$selected++;
}
}
if ( rgar( $field, 'required' ) && $selected < 1 ) {
$this->set_field_error( $field, rgar( $field, 'error_message' ) );
}
}
public function validate_select_custom_settings( $field, $settings ) {
if ( ! is_array( rgar( $field, 'choices' ) ) ) {
return;
}
$select_value = rgar( $settings, $field['name'] );
$custom_value = rgar( $settings, $field['name'] . '_custom' );
if ( rgar( $field, 'required' ) && rgblank( $select_value ) ) {
$this->set_field_error( $field );
return;
}
if ( rgar( $field, 'required' ) && $select_value == 'gf_custom' && rgblank( $custom_value ) ) {
$custom_field = $field;
$custom_field['name'] .= '_custom';
$this->set_field_error( $custom_field );
return;
}
if ( $select_value != 'gf_custom' ) {
foreach( $field['choices'] as $choice ) {
if ( isset( $choice['choices'] ) ) {
foreach ( $choice['choices'] as $optgroup_choice ) {
if ( $this->is_choice_valid( $optgroup_choice, $select_value ) ) {
return;
}
}
} else {
if ( $this->is_choice_valid( $choice, $select_value ) ) {
return;
}
}
}
$this->set_field_error( $field, esc_html__( 'Invalid value', 'gravityforms' ) );
}
}
public function validate_field_select_settings( $field, $settings ) {
$field = $this->prepare_field_select_field( $field );
$this->validate_select_settings( $field, $settings );
}
public function validate_field_map_settings( $field, $settings ) {
$field_map = rgar( $field, 'field_map' );
if ( empty( $field_map ) ) {
return;
}
foreach ( $field_map as $child_field ) {
if ( ! $this->setting_dependency_met( rgar( $child_field, 'dependency' ) ) ) {
continue;
}
$child_field['name'] = $this->get_mapped_field_name( $field, $child_field['name'] );
$setting_value = rgar( $settings, $child_field['name'] );
if ( rgar( $child_field, 'required' ) && rgblank( $setting_value ) ) {
$this->set_field_error( $child_field );
} elseif ( rgar( $child_field, 'validation_callback' ) && is_callable( rgar( $child_field, 'validation_callback' ) ) ) {
call_user_func( rgar( $child_field, 'validation_callback' ), $child_field, $field );
}
}
}
public function validate_checkbox_and_select_settings( $field, $settings ) {
$field = $this->prepare_settings_checkbox_and_select( $field );
$checkbox_field = $field['checkbox'];
$select_field = $field['select'];
$this->validate_checkbox_settings( $checkbox_field, $settings );
$this->validate_select_settings( $select_field, $settings );
}
/**
* Helper to determine if the current choice is a match for the submitted field value.
*
* @param array $choice The choice properties.
* @param string|array $value The submitted field value.
*
* @return bool
*/
public function is_choice_valid( $choice, $value ) {
$choice_value = isset( $choice['value'] ) ? $choice['value'] : $choice['label'];
return is_array( $value ) ? in_array( $choice_value, $value ) : $choice_value == $value;
}
/**
* Sets the validation error message
* Sets the error message to be displayed when a field fails validation.
* When implementing a custom validation callback function, use this function to specify the error message to be displayed.
*
* @param array $field - The current field meta
* @param string $error_message - The error message to be displayed
*/
public function set_field_error( $field, $error_message = '' ) {
// set default error message if none passed
if ( ! $error_message ) {
$error_message = esc_html__( 'This field is required.', 'gravityforms' );
}
$this->_setting_field_errors[ $field['name'] ] = $error_message;
}
/**
* Gets the validation errors for a field.
* Returns validation errors associated with the specified field or a list of all validation messages (if a field isn't specified)
*
* @param array|boolean $field - Optional. The field meta. When specified, errors for this field will be returned
*
* @return mixed - If a field is specified, a string containing the error message will be returned. Otherwise, an array of all errors will be returned
*/
public function get_field_errors( $field = false ) {
if ( ! $field ) {
return $this->_setting_field_errors;
}
return isset( $this->_setting_field_errors[ $field['name'] ] ) ? $this->_setting_field_errors[ $field['name'] ] : array();
}
/**
* Gets the invalid field icon
* Returns the markup for an alert icon to indicate and highlight invalid fields.
*
* @param array $field - The field meta.
*
* @return string - The full markup for the icon
*/
public function get_error_icon( $field ) {
$error = $this->get_field_errors( $field );
return '<span
class="gf_tooltip tooltip"
title="<h6>' . esc_html__( 'Validation Error', 'gravityforms' ) . '</h6>' . $error . '"
style="display:inline-block;position:relative;right:-3px;top:1px;font-size:14px;">
<i class="fa fa-exclamation-circle icon-exclamation-sign gf_invalid"></i>
</span>';
}
/**
* Returns the tooltip markup if a tooltip is configured for the supplied item (field/child field/choice).
*
* @param array $item The item properties.
*
* @return string
*/
public function maybe_get_tooltip( $item ) {
$html = '';
if ( isset( $item['tooltip'] ) ) {
$html = ' ' . gform_tooltip( $item['tooltip'], rgar( $item, 'tooltip_class' ), true );
}
return $html;
}
/**
* Gets the required indicator
* Gets the markup of the required indicator symbol to highlight fields that are required
*
* @param $field - The field meta.
*
* @return string - Returns markup of the required indicator symbol
*/
public function get_required_indicator( $field ) {
return '<span class="required">*</span>';
}
/**
* Checks if the specified field failed validation
*
* @param $field - The field meta to be checked
*
* @return bool|mixed - Returns a validation error string if the field has failed validation. Otherwise returns false
*/
public function field_failed_validation( $field ) {
$field_error = $this->get_field_errors( $field );
return ! empty( $field_error ) ? $field_error : false;
}
/**
* Filter settings fields.
* Runs through each field and applies the 'save_callback', if set, before saving the settings.
* To specify a custom save filter, use the 'save_callback' field meta property and implement the save filter function with the custom logic.
*
* @param $fields - A list of all fields from the field meta configuration
* @param $settings - A list of submitted settings values
*
* @return $settings - The updated settings values.
*/
public function filter_settings( $fields, $settings ) {
foreach ( $fields as $section ) {
if ( ! $this->setting_dependency_met( rgar( $section, 'dependency' ) ) ) {
continue;
}
foreach ( $section['fields'] as $field ) {
if ( ! $this->setting_dependency_met( rgar( $field, 'dependency' ) ) ) {
continue;
}
$field_setting = rgar( $settings, rgar( $field, 'name' ) );
if ( is_callable( rgar( $field, 'save_callback' ) ) ) {
$settings[ $field['name'] ] = call_user_func( rgar( $field, 'save_callback' ), $field, $field_setting );
continue;
}
}
}
return $settings;
}
public function add_field_before( $name, $fields, $settings ) {
return $this->add_field( $name, $fields, $settings, 'before' );
}
public function add_field_after( $name, $fields, $settings ) {
return $this->add_field( $name, $fields, $settings, 'after' );
}
public function add_field( $name, $fields, $settings, $pos ) {
if ( rgar( $fields, 'name' ) ) {
$fields = array( $fields );
}
$pos_mod = $pos == 'before' ? 0 : 1;
foreach ( $settings as &$section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
array_splice( $section['fields'], $i + $pos_mod, 0, $fields );
break 2;
}
}
}
return $settings;
}
public function remove_field( $name, $settings ) {
foreach ( $settings as &$section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
array_splice( $section['fields'], $i, 1 );
break 2;
}
}
}
return $settings;
}
public function replace_field( $name, $fields, $settings ) {
if ( rgar( $fields, 'name' ) ) {
$fields = array( $fields );
}
foreach ( $settings as &$section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
array_splice( $section['fields'], $i, 1, $fields );
break 2;
}
}
}
return $settings;
}
public function get_field( $name, $settings ) {
foreach ( $settings as $section ) {
for ( $i = 0; $i < count( $section['fields'] ); $i ++ ) {
if ( $section['fields'][ $i ]['name'] == $name ) {
return $section['fields'][ $i ];
}
}
}
return false;
}
public function build_choices( $key_value_pairs ) {
$choices = array();
if ( ! is_array( $key_value_pairs ) ) {
return $choices;
}
$first_key = key( $key_value_pairs );
$is_numeric = is_int( $first_key ) && $first_key === 0;
foreach ( $key_value_pairs as $value => $label ) {
if ( $is_numeric ) {
$value = $label;
}
$choices[] = array( 'value' => $value, 'label' => $label );
}
return $choices;
}
//-------------- Simple Condition ------------------------------------------------
/**
* Helper to create a simple conditional logic set of fields. It creates one row of conditional logic with Field/Operator/Value inputs.
*
* @param mixed $setting_name_root - The root name to be used for inputs. It will be used as a prefix to the inputs that make up the conditional logic fields.
*
* @return string The HTML
*/
public function simple_condition( $setting_name_root ) {
$conditional_fields = $this->get_conditional_logic_fields();
$value_input = esc_js( '_gaddon_setting_' . esc_attr( $setting_name_root ) . '_value' );
$object_type = esc_js( "simple_condition_{$setting_name_root}" );
$str = $this->settings_select( array(
'name' => "{$setting_name_root}_field_id",
'type' => 'select',
'choices' => $conditional_fields,
'class' => 'optin_select',
'onchange' => "jQuery('#" . esc_js( $setting_name_root ) . "_container').html(GetRuleValues('{$object_type}', 0, jQuery(this).val(), '', '{$value_input}'));"
), false );
$str .= $this->settings_select( array(
'name' => "{$setting_name_root}_operator",
'type' => 'select',
'onchange' => "SetRuleProperty('{$object_type}', 0, 'operator', jQuery(this).val()); jQuery('#" . esc_js( $setting_name_root ) . "_container').html(GetRuleValues('{$object_type}', 0, jQuery('#{$setting_name_root}_field_id').val(), '', '{$value_input}'));",
'choices' => array(
array(
'value' => 'is',
'label' => esc_html__( 'is', 'gravityforms' ),
),
array(
'value' => 'isnot',
'label' => esc_html__( 'is not', 'gravityforms' ),
),
array(
'value' => '>',
'label' => esc_html__( 'greater than', 'gravityforms' ),
),
array(
'value' => '<',
'label' => esc_html__( 'less than', 'gravityforms' ),
),
array(
'value' => 'contains',
'label' => esc_html__( 'contains', 'gravityforms' ),
),
array(
'value' => 'starts_with',
'label' => esc_html__( 'starts with', 'gravityforms' ),
),
array(
'value' => 'ends_with',
'label' => esc_html__( 'ends with', 'gravityforms' ),
),
),
), false );
$str .= sprintf( "<span id='%s_container'></span>", esc_attr( $setting_name_root ) );
$field_id = $this->get_setting( "{$setting_name_root}_field_id" );
$value = $this->get_setting( "{$setting_name_root}_value" );
$operator = $this->get_setting( "{$setting_name_root}_operator" );
if ( empty( $operator ) ) {
$operator = 'is';
}
$field_id_attribute = ! empty( $field_id ) ? $field_id : 'jQuery("#' . esc_attr( $setting_name_root ) . '_field_id").val()';
$str .= "<script type='text/javascript'>
var " . esc_attr( $setting_name_root ) . "_object = {'conditionalLogic':{'rules':[{'fieldId':'{$field_id}','operator':'{$operator}','value':'" . esc_attr( $value ) . "'}]}};
jQuery(document).ready(
function(){
gform.addFilter( 'gform_conditional_object', 'SimpleConditionObject' );
jQuery('#" . esc_attr( $setting_name_root ) . "_container').html(
GetRuleValues('{$object_type}', 0, {$field_id_attribute}, '" . esc_attr( $value ) . "', '_gaddon_setting_" . esc_attr( $setting_name_root ) . "_value'));
}
);
</script>";
return $str;
}
/**
* Override this to define the array of choices which should be used to populate the Simple Condition fields drop down.
*
* Each choice should have 'label' and 'value' properties.
*
* @return array
*/
public function get_conditional_logic_fields() {
return array();
}
/**
* Evaluate the rules defined for the Simple Condition field.
*
* @param string $setting_name_root The root name used as the prefix to the inputs that make up the Simple Condition field.
* @param array $form The form currently being processed.
* @param array $entry The entry currently being processed.
* @param array $feed The feed currently being processed or an empty array when the field is stored in the form settings.
*
* @return bool
*/
public function is_simple_condition_met( $setting_name_root, $form, $entry, $feed = array() ) {
$settings = empty( $feed ) ? $this->get_form_settings( $form ) : rgar( $feed, 'meta', array() );
$is_enabled = rgar( $settings, $setting_name_root . '_enabled' );
if ( ! $is_enabled ) {
// The setting is not enabled so we handle it as if the rules are met.
return true;
}
// Build the logic array to be used by Gravity Forms when evaluating the rules.
$logic = array(
'logicType' => 'all',
'rules' => array(
array(
'fieldId' => rgar( $settings, $setting_name_root . '_field_id' ),
'operator' => rgar( $settings, $setting_name_root . '_operator' ),
'value' => rgar( $settings, $setting_name_root . '_value' ),
),
)
);
return GFCommon::evaluate_conditional_logic( $logic, $form, $entry );
}
//-------------- Form settings ---------------------------------------------------
/**
* Initializes form settings page
* Hooks up the required scripts and actions for the Form Settings page
*/
public function form_settings_init() {
$view = rgget( 'view' );
$subview = rgget( 'subview' );
if ( $this->current_user_can_any( $this->_capabilities_form_settings ) ) {
add_action( 'gform_form_settings_menu', array( $this, 'add_form_settings_menu' ), 10, 2 );
}
if ( rgget( 'page' ) == 'gf_edit_forms' && $view == 'settings' && $subview == $this->_slug && $this->current_user_can_any( $this->_capabilities_form_settings ) ) {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
add_action( 'gform_form_settings_page_' . $this->_slug, array( $this, 'form_settings_page' ) );
}
}
/**
* Initializes plugin settings page
* Hooks up the required scripts and actions for the Plugin Settings page
*/
public function plugin_page_init() {
if ( $this->current_user_can_any( $this->_capabilities_plugin_page ) ) {
//creates the subnav left menu
add_filter( 'gform_addon_navigation', array( $this, 'create_plugin_page_menu' ) );
}
}
/**
* Creates plugin page menu item
* Target of gform_addon_navigation filter. Creates a menu item in the left nav, linking to the plugin page
*
* @param $menus - Current list of menu items
*
* @return array - Returns a new list of menu items
*/
public function create_plugin_page_menu( $menus ) {
$menus[] = array( 'name' => $this->_slug, 'label' => $this->get_short_title(), 'callback' => array( $this, 'plugin_page_container' ), 'permission' => $this->_capabilities_plugin_page );
return $menus;
}
/**
* Renders the form settings page.
*
* Not intended to be overridden or called directly by Add-Ons.
* Sets up the form settings page.
*
* @ignore
*/
public function form_settings_page() {
GFFormSettings::page_header( $this->_title );
?>
<div class="gform_panel gform_panel_form_settings" id="form_settings">
<?php
$form = $this->get_current_form();
$form_id = $form['id'];
$form = gf_apply_filters( array( 'gform_admin_pre_render', $form_id ), $form );
if ( $this->method_is_overridden( 'form_settings' ) ) {
//enables plugins to override settings page by implementing a form_settings() function
$this->form_settings( $form );
} else {
//saves form settings if save button was pressed
$this->maybe_save_form_settings( $form );
//reads current form settings
$settings = $this->get_form_settings( $form );
$this->set_settings( $settings );
//reading addon fields
$sections = $this->form_settings_fields( $form );
GFCommon::display_admin_message();
$page_title = $this->form_settings_page_title();
if ( empty( $page_title ) ) {
$page_title = rgar( $sections[0], 'title' );
//using first section title as page title, so disable section title
$sections[0]['title'] = false;
}
$icon = $this->form_settings_icon();
if ( empty( $icon ) ) {
$icon = '<i class="fa fa-cogs"></i>';
}
?>
<h3><span><?php echo $icon ?> <?php echo $page_title ?></span></h3>
<?php
//rendering settings based on fields and current settings
$this->render_settings( $sections );
}
?>
<script type="text/javascript">
var form = <?php echo json_encode( $this->get_current_form() ) ?>;
</script>
</div>
<?php
GFFormSettings::page_footer();
}
/***
* Saves form settings if the submit button was pressed
*
* @param array $form The form object
*
* @return null|true|false True on success, false on error, null on no action
*/
public function maybe_save_form_settings( $form ) {
if ( $this->is_save_postback() ) {
check_admin_referer( $this->_slug . '_save_settings', '_' . $this->_slug . '_save_settings_nonce' );
if ( ! $this->current_user_can_any( $this->_capabilities_form_settings ) ) {
GFCommon::add_error_message( esc_html__( "You don't have sufficient permissions to update the form settings.", 'gravityforms' ) );
return false;
}
// store a copy of the previous settings for cases where action would only happen if value has changed
$this->set_previous_settings( $this->get_form_settings( $form ) );
$settings = $this->get_posted_settings();
$sections = $this->form_settings_fields( $form );
$is_valid = $this->validate_settings( $sections, $settings );
$result = false;
if ( $is_valid ) {
$settings = $this->filter_settings( $sections, $settings );
$result = $this->save_form_settings( $form, $settings );
}
if ( $result ) {
GFCommon::add_message( $this->get_save_success_message( $sections ) );
} else {
GFCommon::add_error_message( $this->get_save_error_message( $sections ) );
}
return $result;
}
}
/***
* Saves form settings to form object
*
* @param array $form
* @param array $settings
*
* @return true|false True on success or false on error
*/
public function save_form_settings( $form, $settings ) {
$form[ $this->_slug ] = $settings;
$result = GFFormsModel::update_form_meta( $form['id'], $form );
return ! ( false === $result );
}
/**
* Checks whether the current Add-On has a form settings page.
*
* @return bool
*/
private function has_form_settings_page() {
return $this->method_is_overridden( 'form_settings_fields' ) || $this->method_is_overridden( 'form_settings' );
}
/**
* Custom form settings page
* Override this function to implement a complete custom form settings page.
* Before overriding this function, consider using the form_settings_fields() and specifying your field meta.
*/
public function form_settings( $form ) {
}
/**
* Custom form settings title
* Override this function to display a custom title on the Form Settings Page.
* By default, the first section in the configuration done in form_settings_fields() will be used as the page title.
* Use this function to override that behavior and add a custom page title.
*/
public function form_settings_page_title() {
return '';
}
/**
* Override this function to customize the form settings icon
*/
public function form_settings_icon() {
return '';
}
/**
* Checks whether the current Add-On has a plugin page.
*
* @return bool
*/
private function has_plugin_page() {
return $this->method_is_overridden( 'plugin_page' );
}
/**
* Override this function to create a custom plugin page
*/
public function plugin_page() {
}
/**
* Override this function to customize the plugin page icon
*/
public function plugin_page_icon() {
return '';
}
/**
* Override this function to customize the plugin page title
*/
public function plugin_page_title() {
return $this->_title;
}
/**
* Plugin page container
* Target of the plugin menu left nav icon. Displays the outer plugin page markup and calls plugin_page() to render the actual page.
* Override plugin_page() in order to provide a custom plugin page
*/
public function plugin_page_container() {
?>
<div class="wrap">
<?php
$icon = $this->plugin_page_icon();
if ( ! empty( $icon ) ) {
?>
<img alt="<?php echo $this->get_short_title() ?>" style="margin: 15px 7px 0pt 0pt; float: left;" src="<?php echo $icon ?>" />
<?php
}
?>
<h2 class="gf_admin_page_title"><?php echo $this->plugin_page_title() ?></h2>
<?php
$this->plugin_page();
?>
</div>
<?php
}
/**
* Checks whether the current Add-On has a top level app menu.
*
* @return bool
*/
public function has_app_menu() {
return $this->has_app_settings() || $this->method_is_overridden( 'get_app_menu_items' );
}
/**
* Creates a top level app menu. Adds the app settings page automatically if it's configured.
* Target of the WordPress admin_menu action.
* Not intended to be overridden or called directly by add-ons.
*/
public function create_app_menu() {
$has_full_access = current_user_can( 'gform_full_access' );
$min_cap = GFCommon::current_user_can_which( $this->_capabilities_app_menu );
if ( empty( $min_cap ) ) {
$min_cap = 'gform_full_access';
}
$menu_items = $this->get_app_menu_items();
$addon_menus = array();
/**
* Filters through addon menus (filter by addon slugs)
*
* @param array $addon_menus A modifiable array of admin addon menus
*/
$addon_menus = apply_filters( 'gform_addon_app_navigation_' . $this->_slug, $addon_menus );
$parent_menu = self::get_parent_menu( $menu_items, $addon_menus );
if ( empty( $parent_menu ) ) {
return;
}
// Add a top-level left nav
$callback = isset( $parent_menu['callback'] ) ? $parent_menu['callback'] : array( $this, 'app_tab_page' );
global $menu;
$number = 10;
$menu_position = '16.' . $number;
while ( isset( $menu[$menu_position] ) ) {
$number += 10;
$menu_position = '16.' . $number;
}
/**
* Modify the menu position of an add-on menu
*
* @param int $menu_position The Menu position of the add-on menu
*/
$menu_position = apply_filters( 'gform_app_menu_position_' . $this->_slug, $menu_position );
$this->app_hook_suffix = add_menu_page( $this->get_short_title(), $this->get_short_title(), $has_full_access ? 'gform_full_access' : $min_cap, $parent_menu['name'], $callback, $this->get_app_menu_icon(), $menu_position );
if ( method_exists( $this, 'load_screen_options' ) ) {
add_action( "load-$this->app_hook_suffix", array( $this, 'load_screen_options' ) );
}
// Adding submenu pages
foreach ( $menu_items as $menu_item ) {
$callback = isset( $menu_item['callback'] ) ? $menu_item['callback'] : array( $this, 'app_tab_page' );
add_submenu_page( $parent_menu['name'], $menu_item['label'], $menu_item['label'], $has_full_access || empty( $menu_item['permission'] ) ? 'gform_full_access' : $menu_item['permission'], $menu_item['name'], $callback );
}
if ( is_array( $addon_menus ) ) {
foreach ( $addon_menus as $addon_menu ) {
add_submenu_page( $parent_menu['name'], $addon_menu['label'], $addon_menu['label'], $has_full_access ? 'gform_full_access' : $addon_menu['permission'], $addon_menu['name'], $addon_menu['callback'] );
}
}
if ( $this->has_app_settings() ) {
add_submenu_page( $parent_menu['name'], esc_html__( 'Settings', 'gravityforms' ), esc_html__( 'Settings', 'gravityforms' ), $has_full_access ? 'gform_full_access' : $this->_capabilities_app_settings, $this->_slug . '_settings', array( $this, 'app_tab_page' ) );
}
}
/**
* Returns the parent menu item
*
* @param $menu_items
* @param $addon_menus
*
* @return array|bool The parent menu araray or false if none
*/
private function get_parent_menu( $menu_items, $addon_menus ) {
$parent = false;
if ( GFCommon::current_user_can_any( $this->_capabilities_app_menu ) ) {
foreach ( $menu_items as $menu_item ) {
if ( $this->current_user_can_any( $menu_item['permission'] ) ) {
$parent = $menu_item;
break;
}
}
} elseif ( is_array( $addon_menus ) && sizeof( $addon_menus ) > 0 ) {
foreach ( $addon_menus as $addon_menu ) {
if ( $this->current_user_can_any( $addon_menu['permission'] ) ) {
$parent = array( 'name' => $addon_menu['name'], 'callback' => $addon_menu['callback'] );
break;
}
}
} elseif ( $this->has_app_settings() && $this->current_user_can_any( $this->_capabilities_app_settings ) ) {
$parent = array( 'name' => $this->_slug . '_settings', 'callback' => array( $this, 'app_settings' ) );
}
return $parent;
}
/**
* Override this function to create a top level app menu.
*
* e.g.
* $menu_item['name'] = 'gravitycontacts';
* $menu_item['label'] = __("Contacts", 'gravitycontacts');
* $menu_item['permission'] = 'gravitycontacts_view_contacts';
* $menu_item['callback'] = array($this, 'app_menu');
*
* @return array The array of menu items
*/
public function get_app_menu_items() {
return array();
}
/**
* Override this function to specify a custom icon for the top level app menu.
* Accepts a dashicon class or a URL.
*
* @return string
*/
public function get_app_menu_icon() {
return '';
}
/**
* Override this function to load custom screen options.
*
* e.g.
* $screen = get_current_screen();
* if(!is_object($screen) || $screen->id != $this->app_hook_suffix)
* return;
*
* if($this->is_contact_list_page()){
* $args = array(
* 'label' => __('Contacts per page', 'gravitycontacts'),
* 'default' => 20,
* 'option' => 'gcontacts_per_page'
* );
* add_screen_option( 'per_page', $args );
*/
public function load_screen_options() {
}
/**
* Handles the rendering of app menu items that implement the tabs UI.
*
* Not intended to be overridden or called directly by add-ons.
*/
public function app_tab_page() {
$page = rgget( 'page' );
$current_tab = rgget( 'view' );
if ( $page == $this->_slug . '_settings' ) {
$tabs = $this->get_app_settings_tabs();
} else {
$menu_items = $this->get_app_menu_items();
$current_menu_item = false;
foreach ( $menu_items as $menu_item ) {
if ( $menu_item['name'] == $page ) {
$current_menu_item = $menu_item;
break;
}
}
if ( empty( $current_menu_item ) ) {
return;
}
if ( empty( $current_menu_item['tabs'] ) ) {
return;
}
$tabs = $current_menu_item['tabs'];
}
if ( empty( $current_tab ) ) {
foreach ( $tabs as $tab ) {
if ( ! isset( $tab['permission'] ) || $this->current_user_can_any( $tab['permission'] ) ) {
$current_tab = $tab['name'];
break;
}
}
}
if ( empty( $current_tab ) ) {
wp_die( esc_html__( "You don't have adequate permission to view this page", 'gravityforms' ) );
}
foreach ( $tabs as $tab ) {
if ( $tab['name'] == $current_tab && isset( $tab['callback'] ) && is_callable( $tab['callback'] ) ) {
if ( isset( $tab['permission'] ) && ! $this->current_user_can_any( $tab['permission'] ) ) {
wp_die( esc_html__( "You don't have adequate permission to view this page", 'gravityforms' ) );
}
$title = rgar( $tab,'title' );
if ( empty( $title ) ) {
$title = isset( $tab['label'] ) ? $tab['label'] : $tab['name'];
}
$this->app_tab_page_header( $tabs, $current_tab, $title, '' );
call_user_func( $tab['callback'] );
$this->app_tab_page_footer();
return;
}
}
$this->app_tab_page_header( $tabs, $current_tab, $current_tab, '' );
/**
* Fires when an addon page and tab is accessed.
*
* Typically used to render settings tab content.
*/
$action_hook = 'gform_addon_app_' . $page . '_' . str_replace( ' ', '_', $current_tab );
do_action( $action_hook );
$this->app_tab_page_footer();
}
/**
* Returns the form settings for the Add-On
*
* @param $form
*
* @return string
*/
public function get_form_settings( $form ) {
return rgar( $form, $this->_slug );
}
/**
* Add the form settings tab.
*
* Override this function to add the tab conditionally.
*
*
* @param $tabs
* @param $form_id
*
* @return array
*/
public function add_form_settings_menu( $tabs, $form_id ) {
$tabs[] = array( 'name' => $this->_slug, 'label' => $this->get_short_title(), 'query' => array( 'fid' => null ) );
return $tabs;
}
/**
* Override this function to specify the settings fields to be rendered on the form settings page
*/
public function form_settings_fields( $form ) {
// should return an array of sections, each section contains a title, description and an array of fields
return array();
}
//-------------- Plugin Settings ---------------------------------------------------
public function plugin_settings_init() {
$subview = rgget( 'subview' );
RGForms::add_settings_page(
array(
'name' => $this->_slug,
'tab_label' => $this->get_short_title(),
'title' => $this->plugin_settings_title(),
'handler' => array( $this, 'plugin_settings_page' ),
)
);
if ( rgget( 'page' ) == 'gf_settings' && $subview == $this->_slug && $this->current_user_can_any( $this->_capabilities_settings_page ) ) {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
}
add_filter( 'plugin_action_links', array( $this, 'plugin_settings_link' ), 10, 2 );
}
public function plugin_settings_link( $links, $file ) {
if ( $file != $this->_path ) {
return $links;
}
array_unshift( $links, '<a href="' . admin_url( 'admin.php' ) . '?page=gf_settings&subview=' . $this->_slug . '">' . esc_html__( 'Settings', 'gravityforms' ) . '</a>' );
return $links;
}
/**
* Plugin settings page
*/
public function plugin_settings_page() {
$icon = $this->plugin_settings_icon();
if ( empty( $icon ) ) {
$icon = '<i class="fa fa-cogs"></i>';
}
?>
<h3><span><?php echo $icon ?> <?php echo $this->plugin_settings_title() ?></span></h3>
<?php if ( $this->has_deprecated_elements() ) : ?>
<div class="push-alert-red" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php esc_html_e( 'This add-on needs to be updated. Please contact the developer.', 'gravityforms' ); ?>
</div>
<?php endif; ?>
<?php
if ( $this->method_is_overridden( 'plugin_settings' ) ) {
//enables plugins to override settings page by implementing a plugin_settings() function
$this->plugin_settings();
} elseif ( $this->maybe_uninstall() ) {
?>
<div class="push-alert-gold" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php printf( esc_html__( '%s has been successfully uninstalled. It can be re-activated from the %splugins page%s.', 'gravityforms'), $this->_title, "<a href='plugins.php'>", '</a>' ); ?>
</div>
<?php
} else {
//saves settings page if save button was pressed
$this->maybe_save_plugin_settings();
//reads main addon settings
$settings = $this->get_plugin_settings();
$this->set_settings( $settings );
//reading addon fields
$sections = $this->plugin_settings_fields();
GFCommon::display_admin_message();
//rendering settings based on fields and current settings
$this->render_settings( $sections, $settings );
//renders uninstall section
$this->render_uninstall();
}
}
public function plugin_settings_title() {
return sprintf( esc_html__( "%s Settings", "gravityforms" ), $this->get_short_title() );
}
public function plugin_settings_icon() {
return '';
}
/**
* Override this function to add a custom settings page.
*/
public function plugin_settings() {
}
/**
* Checks whether the current Add-On has a settings page.
*
* @return bool
*/
public function has_plugin_settings_page() {
return $this->method_is_overridden( 'plugin_settings_fields' ) || $this->method_is_overridden( 'plugin_settings_page' ) || $this->method_is_overridden( 'plugin_settings' );
}
/**
* Returns the currently saved plugin settings
* @return mixed
*/
public function get_plugin_settings() {
return get_option( 'gravityformsaddon_' . $this->_slug . '_settings' );
}
/**
* Get plugin setting
* Returns the plugin setting specified by the $setting_name parameter
*
* @param string $setting_name - Plugin setting to be returned
*
* @return mixed - Returns the specified plugin setting or null if the setting doesn't exist
*/
public function get_plugin_setting( $setting_name ) {
$settings = $this->get_plugin_settings();
return isset( $settings[ $setting_name ] ) ? $settings[ $setting_name ] : null;
}
/**
* Updates plugin settings with the provided settings
*
* @param array $settings - Plugin settings to be saved
*/
public function update_plugin_settings( $settings ) {
update_option( 'gravityformsaddon_' . $this->_slug . '_settings', $settings );
}
/**
* Saves the plugin settings if the submit button was pressed
*
*/
public function maybe_save_plugin_settings() {
if ( $this->is_save_postback() ) {
check_admin_referer( $this->_slug . '_save_settings', '_' . $this->_slug . '_save_settings_nonce' );
if ( ! $this->current_user_can_any( $this->_capabilities_settings_page ) ) {
GFCommon::add_error_message( esc_html__( "You don't have sufficient permissions to update the settings.", 'gravityforms' ) );
return false;
}
// store a copy of the previous settings for cases where action would only happen if value has changed
$this->set_previous_settings( $this->get_plugin_settings() );
$settings = $this->get_posted_settings();
$sections = $this->plugin_settings_fields();
$is_valid = $this->validate_settings( $sections, $settings );
if ( $is_valid ) {
$settings = $this->filter_settings( $sections, $settings );
$this->update_plugin_settings( $settings );
GFCommon::add_message( $this->get_save_success_message( $sections ) );
} else {
GFCommon::add_error_message( $this->get_save_error_message( $sections ) );
}
}
}
/**
* Override this function to specify the settings fields to be rendered on the plugin settings page
* @return array
*/
public function plugin_settings_fields() {
// should return an array of sections, each section contains a title, description and an array of fields
return array();
}
//-------------- App Settings ---------------------------------------------------
/**
* Returns the tabs for the settings app menu item
*
* Not intended to be overridden or called directly by add-ons.
*
* @return array|mixed|void
*/
public function get_app_settings_tabs() {
// Build left side options, always have app Settings first and Uninstall last, put add-ons in the middle
$setting_tabs = array( array( 'name' => 'settings', 'label' => esc_html__( 'Settings', 'gravityforms' ), 'callback' => array( $this, 'app_settings_tab' ) ) );
/**
* Filters the tabs within the settings menu.
*
* This filter is appended by the page slug. Ex: gform_addon_app_settings_menu_SLUG
*
* @param array $setting_tabs Contains the information on the settings tabs.
*/
$setting_tabs = apply_filters( 'gform_addon_app_settings_menu_' . $this->_slug, $setting_tabs );
if ( $this->current_user_can_any( $this->_capabilities_uninstall ) ) {
$setting_tabs[] = array( 'name' => 'uninstall', 'label' => esc_html__( 'Uninstall', 'gravityforms' ), 'callback' => array( $this, 'app_settings_uninstall_tab' ) );
}
ksort( $setting_tabs, SORT_NUMERIC );
return $setting_tabs;
}
/**
* Renders the app settings uninstall tab.
*
* Not intended to be overridden or called directly by add-ons.
*/
public function app_settings_uninstall_tab() {
if ( $this->maybe_uninstall() ) {
?>
<div class="push-alert-gold" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php printf( esc_html__( '%s has been successfully uninstalled. It can be re-activated from the %splugins page%s.', 'gravityforms' ), esc_html( $this->_title ), "<a href='plugins.php'>", '</a>' ); ?>
</div>
<?php
} else {
if ( $this->current_user_can_any( $this->_capabilities_uninstall ) && ( ! function_exists( 'is_multisite' ) || ! is_multisite() || is_super_admin() ) ) {
?>
<form action="" method="post">
<?php wp_nonce_field( 'uninstall', 'gf_addon_uninstall' ) ?>
<?php ?>
<h3>
<span><i class="fa fa-times"></i> <?php printf( esc_html__( 'Uninstall %s', 'gravityforms' ), $this->get_short_title() ); ?></span>
</h3>
<div class="delete-alert alert_red">
<h3>
<i class="fa fa-exclamation-triangle gf_invalid"></i> <?php esc_html_e( 'Warning', 'gravityforms' ); ?>
</h3>
<div class="gf_delete_notice">
<?php echo $this->uninstall_warning_message() ?>
</div>
<?php
$uninstall_button = '<input type="submit" name="uninstall" value="' . sprintf( esc_attr__( 'Uninstall %s', 'gravityforms' ), $this->get_short_title() ) . '" class="button" onclick="return confirm(\'' . esc_js( $this->uninstall_confirm_message() ) . '\');" onkeypress="return confirm(\'' . esc_js( $this->uninstall_confirm_message() ) . '\');"/>';
echo $uninstall_button;
?>
</div>
</form>
<?php
}
}
}
/**
* Renders the header for the tabs UI.
*
* @param $tabs
* @param $current_tab
* @param $title
* @param string $message
*/
public function app_tab_page_header( $tabs, $current_tab, $title, $message = '' ) {
$min = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG || isset( $_GET['gform_debug'] ) ? '' : '.min';
// register admin styles
wp_register_style( 'gform_admin', GFCommon::get_base_url() . "/css/admin{$min}.css" );
wp_print_styles( array( 'jquery-ui-styles', 'gform_admin' ) );
?>
<div class="wrap <?php echo GFCommon::get_browser_class() ?>">
<?php if ( $message ) { ?>
<div id="message" class="updated"><p><?php echo $message; ?></p></div>
<?php } ?>
<h2><?php echo esc_html( $title ) ?></h2>
<div id="gform_tab_group" class="gform_tab_group vertical_tabs">
<ul id="gform_tabs" class="gform_tabs">
<?php
foreach ( $tabs as $tab ) {
if ( isset( $tab['permission'] ) && ! $this->current_user_can_any( $tab['permission'] ) ) {
continue;
}
$label = isset( $tab['label'] ) ? $tab['label'] : $tab['name'];
?>
<li <?php echo urlencode( $current_tab ) == $tab['name'] ? "class='active'" : '' ?>>
<a href="<?php echo esc_url( add_query_arg( array( 'view' => $tab['name'] ) ) ); ?>"><?php echo esc_html( $label ) ?></a>
</li>
<?php
}
?>
</ul>
<div id="gform_tab_container" class="gform_tab_container">
<div class="gform_tab_content" id="tab_<?php echo $current_tab ?>">
<?php
}
/**
* Renders the footer for the tabs UI.
*
*/
public function app_tab_page_footer() {
?>
</div> <!-- / gform_tab_content -->
</div> <!-- / gform_tab_container -->
</div> <!-- / gform_tab_group -->
<br class="clear" style="clear: both;" />
</div> <!-- / wrap -->
<script type="text/javascript">
// JS fix for keep content contained on tabs with less content
jQuery(document).ready(function ($) {
$('#gform_tab_container').css('minHeight', jQuery('#gform_tabs').height() + 100);
});
</script>
<?php
}
public function app_settings_tab() {
require_once( GFCommon::get_base_path() . '/tooltips.php' );
$icon = $this->app_settings_icon();
if ( empty( $icon ) ) {
$icon = '<i class="fa fa-cogs"></i>';
}
?>
<h3><span><?php echo $icon ?> <?php echo $this->app_settings_title() ?></span></h3>
<?php
if ( $this->method_is_overridden( 'app_settings' ) ) {
//enables plugins to override settings page by implementing a plugin_settings() function
$this->app_settings();
} elseif ( $this->maybe_uninstall() ) {
?>
<div class="push-alert-gold" style="border-left: 1px solid #E6DB55; border-right: 1px solid #E6DB55;">
<?php printf( esc_html__( '%s has been successfully uninstalled. It can be re-activated from the %splugins page%s.', 'gravityforms' ), esc_html( $this->_title ), "<a href='plugins.php'>", '</a>' ); ?>
</div>
<?php
} else {
//saves settings page if save button was pressed
$this->maybe_save_app_settings();
//reads main addon settings
$settings = $this->get_app_settings();
$this->set_settings( $settings );
//reading addon fields
$sections = $this->app_settings_fields();
GFCommon::display_admin_message();
//rendering settings based on fields and current settings
$this->render_settings( $sections, $settings );
}
}
/**
* Override this function to specific a custom app settings title
*
* @return string
*/
public function app_settings_title() {
return sprintf( esc_html__( '%s Settings', 'gravityforms' ), $this->get_short_title() );
}
/**
* Override this function to specific a custom app settings icon
*
* @return string
*/
public function app_settings_icon() {
return '';
}
/**
* Checks whether the current Add-On has a settings page.
*
* @return bool
*/
public function has_app_settings() {
return $this->method_is_overridden( 'app_settings_fields' ) || $this->method_is_overridden( 'app_settings' );
}
/**
* Override this function to add a custom app settings page.
*/
public function app_settings() {
}
/**
* Returns the currently saved plugin settings
* @return mixed
*/
public function get_app_settings() {
return get_option( 'gravityformsaddon_' . $this->_slug . '_app_settings' );
}
/**
* Get app setting
* Returns the app setting specified by the $setting_name parameter
*
* @param string $setting_name - Plugin setting to be returned
*
* @return mixed - Returns the specified plugin setting or null if the setting doesn't exist
*/
public function get_app_setting( $setting_name ) {
$settings = $this->get_app_settings();
return isset( $settings[ $setting_name ] ) ? $settings[ $setting_name ] : null;
}
/**
* Updates app settings with the provided settings
*
* @param array $settings - App settings to be saved
*/
public function update_app_settings( $settings ) {
update_option( 'gravityformsaddon_' . $this->_slug . '_app_settings', $settings );
}
/**
* Saves the plugin settings if the submit button was pressed
*
*/
public function maybe_save_app_settings() {
if ( $this->is_save_postback() ) {
check_admin_referer( $this->_slug . '_save_settings', '_' . $this->_slug . '_save_settings_nonce' );
if ( ! $this->current_user_can_any( $this->_capabilities_app_settings ) ) {
GFCommon::add_error_message( esc_html__( "You don't have sufficient permissions to update the settings.", 'gravityforms' ) );
return false;
}
// store a copy of the previous settings for cases where action would only happen if value has changed
$this->set_previous_settings( $this->get_app_settings() );
$settings = $this->get_posted_settings();
$sections = $this->app_settings_fields();
$is_valid = $this->validate_settings( $sections, $settings );
if ( $is_valid ) {
$settings = $this->filter_settings( $sections, $settings );
$this->update_app_settings( $settings );
GFCommon::add_message( $this->get_save_success_message( $sections ) );
} else {
GFCommon::add_error_message( $this->get_save_error_message( $sections ) );
}
}
}
/**
* Override this function to specify the settings fields to be rendered on the plugin settings page
* @return array
*/
public function app_settings_fields() {
// should return an array of sections, each section contains a title, description and an array of fields
return array();
}
/**
* Returns an flattened array of field settings for the specified settings type ignoring sections.
*
* @param string $settings_type The settings type. e.g. 'plugin'
*
* @return array
*/
public function settings_fields_only( $settings_type = 'plugin' ) {
$fields = array();
if ( ! is_callable( array( $this, "{$settings_type}_settings_fields" ) ) ) {
return $fields;
}
$sections = call_user_func( array( $this, "{$settings_type}_settings_fields" ) );
foreach ( $sections as $section ) {
foreach ( $section['fields'] as $field ) {
$fields[] = $field;
}
}
return $fields;
}
//-------------- Uninstall ---------------
/**
* Override this function to customize the markup for the uninstall section on the plugin settings page
*/
public function render_uninstall() {
?>
<form action="" method="post">
<?php wp_nonce_field( 'uninstall', 'gf_addon_uninstall' ) ?>
<?php if ( $this->current_user_can_any( $this->_capabilities_uninstall ) ) { ?>
<div class="hr-divider"></div>
<h3><span><i class="fa fa-times"></i> <?php printf( esc_html__( 'Uninstall %s Add-On', 'gravityforms' ), $this->get_short_title() ) ?></span></h3>
<div class="delete-alert alert_red">
<h3><i class="fa fa-exclamation-triangle gf_invalid"></i> Warning</h3>
<div class="gf_delete_notice">
<?php echo $this->uninstall_warning_message() ?>
</div>
<input type="submit" name="uninstall" value="<?php esc_attr_e( 'Uninstall Add-On', 'gravityforms' ) ?>" class="button" onclick="return confirm('<?php echo esc_js( $this->uninstall_confirm_message() ); ?>');" onkeypress="return confirm('<?php echo esc_js( $this->uninstall_confirm_message() ); ?>');">
</div>
<?php
}
?>
</form>
<?php
}
public function uninstall_warning_message() {
return sprintf( esc_html__( '%sThis operation deletes ALL %s settings%s. If you continue, you will NOT be able to retrieve these settings.', 'gravityforms' ), '<strong>', esc_html( $this->get_short_title() ), '</strong>' );
}
public function uninstall_confirm_message() {
return sprintf( __( "Warning! ALL %s settings will be deleted. This cannot be undone. 'OK' to delete, 'Cancel' to stop", 'gravityforms' ), __( $this->get_short_title() ) );
}
/**
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*/
public function maybe_uninstall() {
if ( rgpost( 'uninstall' ) ) {
check_admin_referer( 'uninstall', 'gf_addon_uninstall' );
return $this->uninstall_addon();
}
return false;
}
/**
* Removes all settings and deactivates the Add-On.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*/
public function uninstall_addon() {
if ( ! $this->current_user_can_any( $this->_capabilities_uninstall ) ) {
die( esc_html__( "You don't have adequate permission to uninstall this add-on: " . $this->_title, 'gravityforms' ) );
}
$continue = $this->uninstall();
if ( false === $continue ) {
return false;
}
global $wpdb;
$lead_meta_table = GFFormsModel::get_lead_meta_table_name();
$forms = GFFormsModel::get_forms();
$all_form_ids = array();
// remove entry meta
foreach ( $forms as $form ) {
$all_form_ids[] = $form->id;
$entry_meta = $this->get_entry_meta( array(), $form->id );
if ( is_array( $entry_meta ) ) {
foreach ( array_keys( $entry_meta ) as $meta_key ) {
$sql = $wpdb->prepare( "DELETE from $lead_meta_table WHERE meta_key=%s", $meta_key );
$wpdb->query( $sql );
}
}
}
//remove form settings
if ( ! empty( $all_form_ids ) ) {
$form_metas = GFFormsModel::get_form_meta_by_id( $all_form_ids );
require_once( GFCommon::get_base_path() . '/form_detail.php' );
foreach ( $form_metas as $form_meta ) {
if ( isset( $form_meta[ $this->_slug ] ) ) {
unset( $form_meta[ $this->_slug ] );
$form_json = json_encode( $form_meta );
GFFormDetail::save_form_info( $form_meta['id'], addslashes( $form_json ) );
}
}
}
//removing options
delete_option( 'gravityformsaddon_' . $this->_slug . '_settings' );
delete_option( 'gravityformsaddon_' . $this->_slug . '_app_settings' );
delete_option( 'gravityformsaddon_' . $this->_slug . '_version' );
//Deactivating plugin
deactivate_plugins( $this->_path );
update_option( 'recently_activated', array( $this->_path => time() ) + (array) get_option( 'recently_activated' ) );
return true;
}
/**
* Called when the user chooses to uninstall the Add-On - after permissions have been checked and before removing
* all Add-On settings and Form settings.
*
* Override this method to perform additional functions such as dropping database tables.
*
*
* Return false to cancel the uninstall request.
*/
public function uninstall() {
return true;
}
//-------------- Enforce minimum GF version ---------------------------------------------------
/**
* Target for the after_plugin_row action hook. Checks whether the current version of Gravity Forms
* is supported and outputs a message just below the plugin info on the plugins page.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*/
public function plugin_row() {
if ( ! self::is_gravityforms_supported( $this->_min_gravityforms_version ) ) {
$message = $this->plugin_message();
self::display_plugin_message( $message, true );
}
}
/**
* Returns the message that will be displayed if the current version of Gravity Forms is not supported.
*
* Override this method to display a custom message.
*/
public function plugin_message() {
$message = sprintf( esc_html__( 'Gravity Forms %s is required. Activate it now or %spurchase it today!%s', 'gravityforms' ), $this->_min_gravityforms_version, "<a href='http://www.gravityforms.com'>", '</a>' );
return $message;
}
/**
* Formats and outs a message for the plugin row.
*
* Not intended to be overridden or called directly by Add-Ons.
*
* @ignore
*
* @param $message
* @param bool $is_error
*/
public static function display_plugin_message( $message, $is_error = false ) {
$style = $is_error ? 'style="background-color: #ffebe8;"' : '';
echo '</tr><tr class="plugin-update-tr"><td colspan="5" class="plugin-update"><div class="update-message" ' . $style . '>' . $message . '</div></td>';
}
//--------------- Logging -------------------------------------------------------------
/**
* Writes an error message to the Gravity Forms log. Requires the Gravity Forms logging Add-On.
*
* Not intended to be overridden by Add-Ons.
*
* @ignore
*/
public function log_error( $message ) {
if ( class_exists( 'GFLogging' ) ) {
GFLogging::include_logger();
GFLogging::log_message( $this->_slug, $message, KLogger::ERROR );
}
}
/**
* Writes an error message to the Gravity Forms log. Requires the Gravity Forms logging Add-On.
*
* Not intended to be overridden by Add-Ons.
*
* @ignore
*/
public function log_debug( $message ) {
if ( class_exists( 'GFLogging' ) ) {
GFLogging::include_logger();
GFLogging::log_message( $this->_slug, $message, KLogger::DEBUG );
}
}
//--------------- Locking ------------------------------------------------------------
/**
* Returns the configuration for locking
*
* e.g.
*
* array(
* "object_type" => 'contact',
* "capabilities" => array("gravityforms_contacts_edit_contacts"),
* "redirect_url" => admin_url("admin.php?page=gf_contacts"),
* "edit_url" => admin_url(sprintf("admin.php?page=gf_contacts&id=%d", $contact_id)),
* "strings" => $strings
* );
*
* Override this method to implement locking
*/
public function get_locking_config() {
return array();
}
/**
* Returns TRUE if the current page is the edit page. Otherwise, returns FALSE
*
* Override this method to implement locking on the edit page.
*/
public function is_locking_edit_page() {
return false;
}
/**
* Returns TRUE if the current page is the list page. Otherwise, returns FALSE
*
* Override this method to display locking info on the list page.
*/
public function is_locking_list_page() {
return false;
}
/**
* Returns TRUE if the current page is the view page. Otherwise, returns FALSE
*
* Override this method to display locking info on the view page.
*/
public function is_locking_view_page() {
return false;
}
/**
* Returns the ID of the object to be locked. E.g. Form ID
*
* Override this method to implement locking
*/
public function get_locking_object_id() {
return 0;
}
/**
* Outputs information about the user currently editing the specified object
*
* @param int $object_id The Object ID
* @param bool $echo Whether to echo
*
* @return string The markup for the lock info
*/
public function lock_info( $object_id, $echo = true ) {
$gf_locking = new GFAddonLocking( $this->get_locking_config(), $this );
$lock_info = $gf_locking->lock_info( $object_id, false );
if ( $echo ) {
echo $lock_info;
}
return $lock_info;
}
/**
* Outputs class for the row for the specified Object ID on the list page.
*
* @param int $object_id The object ID
* @param bool $echo Whether to echo
*
* @return string The markup for the class
*/
public function list_row_class( $object_id, $echo = true ) {
$gf_locking = new GFAddonLocking( $this->get_locking_config(), $this );
$class = $gf_locking->list_row_class( $object_id, false );
if ( $echo ) {
echo $class;
}
return $class;
}
/**
* Checked whether an object is locked
*
* @param int|mixed $object_id The object ID
*
* @return bool
*/
public function is_object_locked( $object_id ) {
$gf_locking = new GFAddonLocking( $this->get_locking_config(), $this );
return $gf_locking->is_locked( $object_id );
}
//------------- Field Value Retrieval -------------------------------------------------
/**
* Returns the value of the mapped field.
*
* @param string $setting_name
* @param array $form
* @param array $entry
* @param mixed $settings
*
* @return string
*/
public function get_mapped_field_value( $setting_name, $form, $entry, $settings = false ) {
$field_id = $this->get_setting( $setting_name, '', $settings );
return $this->get_field_value( $form, $entry, $field_id );
}
/**
* Returns the value of the selected field.
*
* @access private
*
* @param array $form
* @param array $entry
* @param string $field_id
*
* @return string field value
*/
public function get_field_value( $form, $entry, $field_id ) {
$field_value = '';
switch ( strtolower( $field_id ) ) {
case 'form_title':
$field_value = rgar( $form, 'title' );
break;
case 'date_created':
$date_created = rgar( $entry, strtolower( $field_id ) );
if ( empty( $date_created ) ) {
//the date created may not yet be populated if this function is called during the validation phase and the entry is not yet created
$field_value = gmdate( 'Y-m-d H:i:s' );
} else {
$field_value = $date_created;
}
break;
case 'ip':
case 'source_url':
case 'id':
$field_value = rgar( $entry, strtolower( $field_id ) );
break;
default:
$field = GFFormsModel::get_field( $form, $field_id );
if ( is_object( $field ) ) {
$is_integer = $field_id == intval( $field_id );
$input_type = $field->get_input_type();
if ( $is_integer && $input_type == 'address' ) {
$field_value = $this->get_full_address( $entry, $field_id );
} elseif ( $is_integer && $input_type == 'name' ) {
$field_value = $this->get_full_name( $entry, $field_id );
} elseif ( is_callable( array( $this, "get_{$input_type}_field_value" ) ) ) {
$field_value = call_user_func( array( $this, "get_{$input_type}_field_value" ), $entry, $field_id, $field );
} else {
$field_value = $field->get_value_export( $entry, $field_id );
}
} else {
$field_value = rgar( $entry, $field_id );
}
}
/**
* A generic filter allowing the field value to be overridden. Form and field id modifiers supported.
*
* @param string $field_value The value to be overridden.
* @param array $form The Form currently being processed.
* @param array $entry The Entry currently being processed.
* @param string $field_id The ID of the Field currently being processed.
* @param string $slug The add-on slug e.g. gravityformsactivecampaign.
*
* @since 1.9.15.12
*
* @return string
*/
$field_value = gf_apply_filters( array( 'gform_addon_field_value', $form['id'], $field_id ), $field_value, $form, $entry, $field_id, $this->_slug );
return $this->maybe_override_field_value( $field_value, $form, $entry, $field_id );
}
/**
* Enables use of the gform_SLUG_field_value filter to override the field value. Override this function to prevent the filter being used or to implement a custom filter.
*
* @param string $field_value
* @param array $form
* @param array $entry
* @param string $field_id
*
* @return string
*/
public function maybe_override_field_value( $field_value, $form, $entry, $field_id ) {
/* Get Add-On slug */
$slug = str_replace( 'gravityforms', '', $this->_slug );
return gf_apply_filters( array(
"gform_{$slug}_field_value",
$form['id'],
$field_id
), $field_value, $form, $entry, $field_id );
}
/**
* Returns the combined value of the specified Address field.
*
* @param array $entry
* @param string $field_id
*
* @return string
*/
public function get_full_address( $entry, $field_id ) {
return GF_Fields::get( 'address' )->get_value_export( $entry, $field_id );
}
/**
* Returns the combined value of the specified Name field.
*
* @param array $entry
* @param string $field_id
*
* @return string
*/
public function get_full_name( $entry, $field_id ) {
return GF_Fields::get( 'name' )->get_value_export( $entry, $field_id );
}
/**
* Returns the value of the specified List field.
*
* @param array $entry
* @param string $field_id
* @param object $field
*
* @return string
*/
public function get_list_field_value( $entry, $field_id, $field ) {
return $field->get_value_export( $entry, $field_id );
}
/**
* Returns the field ID of the first field of the desired type.
*
* @access public
* @param string $field_type
* @param int $subfield_id (default: null)
* @param int $form_id (default: null)
* @return string
*/
public function get_first_field_by_type( $field_type, $subfield_id = null, $form_id = null, $return_first_only = true ) {
/* Get the current form ID. */
if ( rgblank( $form_id ) ) {
$form_id = rgget( 'id' );
}
/* Get the form. */
$form = GFAPI::get_form( $form_id );
/* Get the request field type for the form. */
$fields = GFAPI::get_fields_by_type( $form, array( $field_type ) );
if ( count( $fields ) == 0 || ( count( $fields ) > 1 && $return_first_only ) ) {
return null;
} else {
if ( rgblank( $subfield_id ) ) {
return $fields[0]->id;
} else {
return $fields[0]->id . '.' . $subfield_id;
}
}
}
//--------------- Notes ------------------
/**
* Override this function to specify a custom avatar (i.e. the payment gateway logo) for entry notes created by the Add-On
* @return string - A fully qualified URL for the avatar
*/
public function note_avatar() {
return false;
}
public function notes_avatar( $avatar, $note ) {
if ( $note->user_name == $this->_short_title && empty( $note->user_id ) && $this->method_is_overridden( 'note_avatar', 'GFAddOn' ) ) {
$new_avatar = $this->note_avatar();
}
return empty( $new_avatar ) ? $avatar : "<img alt='{$this->_short_title}' src='{$new_avatar}' class='avatar avatar-48' height='48' width='48' />";
}
public function add_note( $entry_id, $note, $note_type = null ) {
$user_id = 0;
$user_name = $this->_short_title;
GFFormsModel::add_note( $entry_id, $user_id, $user_name, $note, $note_type );
}
//-------------- Helper functions ---------------------------------------------------
protected final function method_is_overridden( $method_name, $base_class = 'GFAddOn' ) {
$reflector = new ReflectionMethod( $this, $method_name );
$name = $reflector->getDeclaringClass()->getName();
return $name !== $base_class;
}
/**
* Returns the url of the root folder of the current Add-On.
*
* @param string $full_path Optional. The full path the the plugin file.
*
* @return string
*/
public function get_base_url( $full_path = '' ) {
if ( empty( $full_path ) ) {
$full_path = $this->_full_path;
}
return plugins_url( null, $full_path );
}
/**
* Returns the url of the Add-On Framework root folder.
*
* @return string
*/
final public static function get_gfaddon_base_url() {
return plugins_url( null, __FILE__ );
}
/**
* Returns the physical path of the Add-On Framework root folder.
*
* @return string
*/
final public static function get_gfaddon_base_path() {
return self::_get_base_path();
}
/**
* Returns the physical path of the plugins root folder.
*
* @param string $full_path
*
* @return string
*/
public function get_base_path( $full_path = '' ) {
if ( empty( $full_path ) ) {
$full_path = $this->_full_path;
}
$folder = basename( dirname( $full_path ) );
return WP_PLUGIN_DIR . '/' . $folder;
}
/**
* Returns the physical path of the Add-On Framework root folder
*
* @return string
*/
private static function _get_base_path() {
$folder = basename( dirname( __FILE__ ) );
return GFCommon::get_base_path() . '/includes/' . $folder;
}
/**
* Returns the URL of the Add-On Framework root folder
*
* @return string
*/
private static function _get_base_url() {
$folder = basename( dirname( __FILE__ ) );
return GFCommon::get_base_url() . '/includes/' . $folder;
}
/**
* Checks whether the Gravity Forms is installed.
*
* @return bool
*/
public function is_gravityforms_installed() {
return class_exists( 'GFForms' );
}
public function table_exists( $table_name ) {
global $wpdb;
$count = $wpdb->get_var( "SHOW TABLES LIKE '{$table_name}'" );
return ! empty( $count );
}
/**
* Checks whether the current version of Gravity Forms is supported
*
* @param $min_gravityforms_version
*
* @return bool|mixed
*/
public function is_gravityforms_supported( $min_gravityforms_version = '' ) {
if ( isset( $this->_min_gravityforms_version ) && empty( $min_gravityforms_version ) ) {
$min_gravityforms_version = $this->_min_gravityforms_version;
}
if ( empty( $min_gravityforms_version ) ) {
return true;
}
if ( class_exists( 'GFCommon' ) ) {
$is_correct_version = version_compare( GFCommon::$version, $min_gravityforms_version, '>=' );
return $is_correct_version;
} else {
return false;
}
}
/**
* Returns this plugin's short title. Used to display the plugin title in small areas such as tabs
*/
public function get_short_title() {
return isset( $this->_short_title ) ? $this->_short_title : $this->_title;
}
/**
* Returns the unescaped URL for the plugin settings tab associated with this plugin
*
*/
public function get_plugin_settings_url() {
return add_query_arg( array( 'page' => 'gf_settings', 'subview' => $this->_slug ), admin_url( 'admin.php' ) );
}
/**
* Returns the current form object based on the id query var. Otherwise returns false
*/
public function get_current_form() {
return rgempty( 'id', $_GET ) ? false : GFFormsModel::get_form_meta( rgget( 'id' ) );
}
/**
* Returns TRUE if the current request is a postback, otherwise returns FALSE
*/
public function is_postback() {
return is_array( $_POST ) && count( $_POST ) > 0;
}
/**
* Returns TRUE if the settings "Save" button was pressed
*/
public function is_save_postback() {
return ! rgempty( 'gform-settings-save' );
}
/**
* Returns TRUE if the current page is the form editor page. Otherwise, returns FALSE
*/
public function is_form_editor() {
if ( rgget( 'page' ) == 'gf_edit_forms' && ! rgempty( 'id', $_GET ) && rgempty( 'view', $_GET ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the form list page. Otherwise, returns FALSE
*/
public function is_form_list() {
if ( rgget( 'page' ) == 'gf_edit_forms' && rgempty( 'id', $_GET ) && rgempty( 'view', $_GET ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the form settings page, or a specific form settings tab (specified by the $tab parameter). Otherwise returns FALSE
*
* @param string $tab - Specifies a specific form setting page/tab
*
* @return bool
*/
public function is_form_settings( $tab = null ) {
$is_form_settings = rgget( 'page' ) == 'gf_edit_forms' && rgget( 'view' ) == 'settings';
$is_tab = $this->_tab_matches( $tab );
if ( $is_form_settings && $is_tab ) {
return true;
} else {
return false;
}
}
private function _tab_matches( $tabs ) {
if ( $tabs == null ) {
return true;
}
if ( ! is_array( $tabs ) ) {
$tabs = array( $tabs );
}
$current_tab = rgempty( 'subview', $_GET ) ? 'settings' : rgget( 'subview' );
foreach ( $tabs as $tab ) {
if ( strtolower( $tab ) == strtolower( $current_tab ) ) {
return true;
}
}
}
/**
* Returns TRUE if the current page is the plugin settings main page, or a specific plugin settings tab (specified by the $tab parameter). Otherwise returns FALSE
*
* @param string $tab - Specifies a specific plugin setting page/tab.
*
* @return bool
*/
public function is_plugin_settings( $tab = '' ) {
$is_plugin_settings = rgget( 'page' ) == 'gf_settings';
$is_tab = $this->_tab_matches( $tab );
if ( $is_plugin_settings && $is_tab ) {
return true;
} else {
return false;
}
}
/**
* Returns TRUE if the current page is the app settings main page, or a specific apps settings tab (specified by the $tab parameter). Otherwise returns FALSE
*
* @param string $tab - Specifies a specific app setting page/tab.
*
* @return bool
*/
public function is_app_settings( $tab = '' ) {
$is_app_settings = rgget( 'page' ) == $this->_slug . '_settings';
$is_tab = $this->_tab_matches( $tab );
if ( $is_app_settings && $is_tab ) {
return true;
} else {
return false;
}
}
/**
* Returns TRUE if the current page is the plugin page. Otherwise returns FALSE
* @return bool
*/
public function is_plugin_page() {
return strtolower( rgget( 'page' ) ) == strtolower( $this->_slug );
}
/**
* Returns TRUE if the current page is the entry view page. Otherwise, returns FALSE
* @return bool
*/
public function is_entry_view() {
if ( rgget( 'page' ) == 'gf_entries' && rgget( 'view' ) == 'entry' && ( ! isset( $_POST['screen_mode'] ) || rgpost( 'screen_mode' ) == 'view' ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the entry edit page. Otherwise, returns FALSE
* @return bool
*/
public function is_entry_edit() {
if ( rgget( 'page' ) == 'gf_entries' && rgget( 'view' ) == 'entry' && rgpost( 'screen_mode' ) == 'edit' ) {
return true;
}
return false;
}
public function is_entry_list() {
if ( rgget( 'page' ) == 'gf_entries' && ( rgget( 'view' ) == 'entries' || rgempty( 'view', $_GET ) ) ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the results page. Otherwise, returns FALSE
*/
public function is_results() {
if ( rgget( 'page' ) == 'gf_entries' && rgget( 'view' ) == 'gf_results_' . $this->_slug ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the print page. Otherwise, returns FALSE
*/
public function is_print() {
if ( rgget( 'gf_page' ) == 'print-entry' ) {
return true;
}
return false;
}
/**
* Returns TRUE if the current page is the preview page. Otherwise, returns FALSE
*/
public function is_preview() {
if ( rgget( 'gf_page' ) == 'preview' ) {
return true;
}
return false;
}
public function has_deprecated_elements() {
$deprecated = GFAddOn::get_all_deprecated_protected_methods( get_class( $this ) );
if ( ! empty( $deprecated ) ) {
return true;
}
return false;
}
public static function get_all_deprecated_protected_methods($add_on_class_name = ''){
$deprecated = array();
$deprecated = array_merge( $deprecated, self::get_deprecated_protected_methods_for_base_class( 'GFAddOn', $add_on_class_name )) ;
$deprecated = array_merge( $deprecated, self::get_deprecated_protected_methods_for_base_class( 'GFFeedAddOn', $add_on_class_name ) ) ;
$deprecated = array_merge( $deprecated, self::get_deprecated_protected_methods_for_base_class( 'GFPaymentAddOn', $add_on_class_name ) ) ;
return $deprecated;
}
public static function get_deprecated_protected_methods_for_base_class( $base_class_name, $add_on_class_name = '' ) {
$deprecated = array();
if ( ! class_exists( $base_class_name ) ) {
return $deprecated;
}
$base_class_names = array(
'GFAddOn',
'GFFeedAddOn',
'GFPaymentAddOn'
);
$base_class = new ReflectionClass( $base_class_name );
$classes = empty($add_on_class_name) ? get_declared_classes() : array( $add_on_class_name );
foreach ( $classes as $class ) {
if ( ! is_subclass_of( $class, $base_class_name ) || in_array( $class, $base_class_names ) ) {
continue;
}
$add_on_class = new ReflectionClass( $class );
$add_on_methods = $add_on_class->getMethods( ReflectionMethod::IS_PROTECTED );
foreach ( $add_on_methods as $method ) {
$method_name = $method->getName();
$base_has_method = $base_class->hasMethod( $method_name );
$is_declared_by_base_class = $base_has_method && $base_class->getMethod( $method_name )->getDeclaringClass()->getName() == $base_class_name;
$is_overridden = $method->getDeclaringClass()->getName() == $class;
if ( $is_declared_by_base_class && $is_overridden ) {
$deprecated[] = $class . '::' . $method_name;
}
}
}
return $deprecated;
}
public function maybe_wp_kses( $html, $allowed_html = 'post', $allowed_protocols = array() ) {
return GFCommon::maybe_wp_kses( $html, $allowed_html, $allowed_protocols );
}
/**
* Returns the slug for the add-on.
*
* @since 2.0
*/
public function get_slug() {
return $this->_slug;
}
/**
* Initializing translations.
*
* @since 2.0.7
*/
public function load_text_domain() {
GFCommon::load_gf_text_domain( $this->_slug, plugin_basename( dirname( $this->_full_path ) ) );
}
}
| gpl-3.0 |
aroog/code | ArchMetrics/src/edu/wayne/metrics/adb/ADBTriplet.java | 7189 | package edu.wayne.metrics.adb;
import java.io.IOException;
import java.io.Writer;
import java.util.HashSet;
import java.util.Set;
import oog.itf.IDomain;
import oog.itf.IObject;
/**
* Information about an OObject extracted into an <A,D,B> triplet
* NOTE: One IObject can generate many ADBTriplets.
* So DO NOT generate ADBTriplets from IObjects, then traverse the ADBTriplets.
* Always go back to and traverse IObjects. Generate an ADBTriplet as just an adapter to an IObject
*/
public class ADBTriplet {
private IObject objectA;
public ADBTriplet() {
}
public ADBTriplet(IObject childObject) {
if ( childObject == null )
throw new IllegalArgumentException("Null childObject not allowed");
objectA = childObject;
}
// TODO: Make sure this returns the generic type
private static String getType(IObject object) {
String fullType = "";
if (object != null) {
fullType = object.getC().getFullyQualifiedName();
}
return fullType;
}
/**
* Very inefficient implementation to get the short (unqualified type name)
* TODO: HIGH. Ideally, Type must also store the short name; it is not obvious to compute from the fully qualified typename,
* e.g. for java.util.ArrayList<java.lang.Object>
*/
private static String getShortType(IObject object) {
String fullName = "";
if (object != null) {
fullName = getType(object);
String shortName = org.eclipse.jdt.core.Signature.getSimpleName(fullName);
// TODO: Check what we got?
fullName = shortName;
}
return fullName;
}
private static String getInstanceName(IObject object) {
String instanceName = "";
if (object != null) {
instanceName = object.getInstanceDisplayName();
}
return instanceName;
}
public String getTypeA() {
return getType(this.objectA);
}
public String getShortTypeA() {
return getShortType(this.objectA);
}
public Set<String> getTypeBs() {
Set<String> typeB = new HashSet<String>();
for(IObject parentObject : getParentObjects() ) {
typeB.add ( getType(parentObject) );
}
return typeB;
}
public String getRawTypeA() {
return Util.getRawTypeName(getType(this.objectA));
}
// TODO: HIGH. XXX. Some of the callers may expect an unqualified domain
public String getDomainStringD() {
IDomain domainD = getDomainD();
String domain = "";
if (domainD != null ) {
domain = domainD.getD(); // TOMAR: TODO: HIGH. Make sure that D qualified?
}
return domain;
}
// NOTE: IDomain.getName() returns null.
// Return simple name, without qualifier of declaring class!
public String getRawDomainD() {
IDomain domainD = getDomainD();
String domainName = "";
if (domainD != null ) {
// NOTE: getD() returns just "d", not "C::d"
domainName = domainD.getD();
}
return domainName;
}
public String getDid() {
IDomain domainD = getDomainD();
String domainId = "";
if (domainD != null ) {
domainId = domainD.getD_id();
}
return domainId;
}
public Set<String> getRawTypeBs() {
Set<String> rawTypeB = new HashSet<String>();
for(IObject childObject : getObjectBs() ) {
rawTypeB.add(Util.getRawTypeName(getType(childObject)));
}
return rawTypeB;
}
public String getInstanceA() {
return getInstanceName(this.objectA);
}
@Override
public boolean equals(Object o) {
if (o == this) {
return true;
}
if (!(o instanceof ADBTriplet)) {
return false;
}
ADBTriplet other = (ADBTriplet) o;
// Two ADBTriplets are equal if they correspond to the same underlying IObject they adapt
return (objectA == other.objectA);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((objectA == null) ? 0 : objectA.hashCode());
return result;
}
// TODO: Have this be the toLongString.
// TODO: No need to show the Instance names. Not part of the <A,D,B> formal definition
// TODO: Use full types, rather than raw types.
@Override
public String toString() {
StringBuffer builder = new StringBuffer();
builder.append("<");
// Make less wordy
builder.append(getRawTypeA());
builder.append(",");
builder.append(getRawDomainD());
builder.append(",");
// TODO: HIGH. This does not work anymore: saving a set to a string.
builder.append(getRawTypeBs());
builder.append(">");
return builder.toString();
}
// DONE. No need to show the Instance names. Not part of the <A,D,B> formal definition.
// DONE. Show full types, rather than raw types.
public String toLongString() {
StringBuffer builder = new StringBuffer();
builder.append("<");
builder.append(getTypeA());
builder.append(",");
// NOTE: We purposely return the Raw domain. The fully qualified domain name is a bit hard to read.
builder.append(getRawDomainD());
builder.append(",");
// TODO: HIGH. This does not work anymore: saving a set to a string.
builder.append(getTypeBs());
builder.append(">");
return builder.toString();
}
// TODO: Maybe compute non qualified class names?
public String toShortString() {
StringBuffer builder = new StringBuffer();
builder.append("<");
builder.append(getRawTypeA());
builder.append(",");
builder.append(getRawDomainD());
builder.append(",");
// TODO: This does not work anymore...
builder.append(getRawTypeBs());
builder.append(">");
return builder.toString();
}
// TODO: Have this be the toLongString.
// TODO: No need to show the Instance names. Not part of the <A,D,B> formal definition
// TODO: Use full types, rather than raw types.
public String toObjectString() {
StringBuffer builder = new StringBuffer();
// TODO: Why use <> for O_id?
builder.append("<");
builder.append(objectA.getO_id());
builder.append(">");
return builder.toString();
}
public void writeTo(Writer writer) throws IOException {
// TODO: Why not use using toString()?
writer.append(",\"" + getTypeA() + "\"");
writer.append(",\"" + getRawDomainD() + "\"");
// TODO: This does not work anymore...
writer.append(",\"" + getTypeBs() + "\"");
}
public IObject getObject() {
return this.objectA;
}
public Set<? extends IObject> getParentObjects() {
return this.objectA.getParentObjects();
}
public static ADBTriplet getTripletFrom(IObject objectA) {
// TODO: We may need another class that has the following:
// A,D,B,Domain type.
// TripletGraphMetricItem tgmid = new TripleGraphMetricItem();
// For now lets just use Triplet itself.
if (objectA != null ) {
return new ADBTriplet(objectA);
}
else {
System.err.println("ADBTriplet: Encountered null IObject");
}
return null;
}
public IObject getObjectA() {
return objectA;
}
public Set<? extends IObject> getObjectBs() {
return objectA.getParentObjects();
}
public IDomain getDomainD() {
return objectA.getParent();
}
}
| gpl-3.0 |
svizion/MyClientBase-SB | application/modules_core/mcb_modules/controllers/mcb_modules.php | 3534 | <?php (defined('BASEPATH')) OR exit('No direct script access allowed');
/*
* Class handling MCB custom modules install/uninstall and core modules enable/disable
*/
class Mcb_Modules extends Admin_Controller {
function __construct() {
parent::__construct();
}
function index() {
redirect('mcb_modules/core');
}
function custom() {
$this->mdl_mcb_modules->refresh();
$data = array(
'modules' => $this->mdl_mcb_modules->custom_modules
);
$data['site_url'] = site_url($this->uri->uri_string());
$data['actions_panel'] = $this->plenty_parser->parse('actions_panel.tpl', $data, true, 'smarty', 'mcb_modules');
$this->load->view('custom', $data);
}
//DAM: lists core modules so that they can be enabled or disabled
public function core() {
$this->mdl_mcb_modules->refresh();
$data = array(
'modules' => $this->mdl_mcb_modules->core_modules
);
$data['site_url'] = site_url($this->uri->uri_string());
$data['actions_panel'] = $this->plenty_parser->parse('actions_panel.tpl', $data, true, 'smarty', 'mcb_modules');
$this->load->view('core', $data);
}
//DAM: it runs common code for several methods. Check below
private function getDbItem()
{
$module_path = $this->uri->segment(3);
$this->db->where('module_path', $module_path);
return $module_path;
}
//DAM checks in the database to see if the core module can be enabled/disabled
private function status_can_change()
{
$module_path = $this->uri->segment(3);
$this->mdl_mcb_modules->refresh();
$modules = $this->mdl_mcb_modules->core_modules;
if($modules[$module_path]->module_change_status != "1")
{
$this->session->set_flashdata('custom_error', $this->lang->line('module_cant_change_status'));
return false;
}
return true;
}
//DAM: enables a core module
public function enable() {
if (!$this->status_can_change()) {
redirect('mcb_modules/core');
}
$this->getDbItem();
$db_array = array(
'module_enabled' => 1
);
$this->db->update('mcb_modules', $db_array);
$this->session->set_flashdata('custom_success', $this->lang->line('module_successfully_enabled'));
redirect('mcb_modules/core');
}
//DAM: disables a core module
public function disable() {
if (!$this->status_can_change()) redirect('mcb_modules/core');
$this->getDbItem();
$db_array = array(
'module_enabled' => 0
);
$return = $this->db->update('mcb_modules', $db_array);
$this->session->set_flashdata('custom_success', $this->lang->line('module_successfully_disabled'));
redirect('mcb_modules/core');
}
public function install() {
$module_path = $this->getDbItem();
$this->load->module($module_path . '/setup');
$this->setup->install();
$db_array = array(
'module_enabled' => 1
);
$this->db->update('mcb_modules', $db_array);
redirect('mcb_modules');
}
/*
* DAM: uninstalls a custom module
*
* 1. Runs the setup/uninstall function of the custom module.
* 2. Changes the status of the module to disabled.
*
*/
public function uninstall() {
$module_path = $this->getDbItem();
$this->load->module($module_path . '/setup');
$this->setup->uninstall();
$this->db->delete('mcb_modules');
redirect('mcb_modules');
}
/*
* Runs the setup/upgrade function of the custom module.
*/
public function upgrade() {
$module_path = $this->getDbItem();
$this->load->module($module_path . '/setup');
$this->setup->upgrade();
redirect('mcb_modules');
}
}
?> | gpl-3.0 |
lowentropy/simpleX3D | src/Core/MetadataString.cc | 934 | /*
* Copyright 2009 Nathan Matthews <[email protected]>
*
* This file is part of SimpleX3D.
*
* SimpleX3D 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.
*
* SimpleX3D 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 SimpleX3D. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Core/MetadataString.h"
namespace X3D {
namespace Core {
void MetadataString::assignFromString(const string& str) {
value().clear();
value().add(str);
value.changed();
}
}}
| gpl-3.0 |
manojdjoshi/dnSpy | Extensions/dnSpy.Debugger/dnSpy.Debugger/Evaluation/UI/VariablesWindowVMOptions.cs | 3028 | /*
Copyright (C) 2014-2019 [email protected]
This file is part of dnSpy
dnSpy is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
dnSpy is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with dnSpy. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using dnSpy.Contracts.Debugger.Evaluation;
using dnSpy.Debugger.Evaluation.ViewModel;
namespace dnSpy.Debugger.Evaluation.UI {
readonly struct ValueNodesProviderResult {
public DbgValueNodeInfo[] Nodes { get; }
public bool RecreateAllNodes { get; }
public ValueNodesProviderResult(DbgValueNodeInfo[] nodes, bool recreateAllNodes) {
Nodes = nodes ?? throw new ArgumentNullException(nameof(nodes));
RecreateAllNodes = recreateAllNodes;
}
}
abstract class VariablesWindowValueNodesProvider {
public virtual event EventHandler NodesChanged { add { } remove { } }
public abstract ValueNodesProviderResult GetNodes(DbgEvaluationInfo evalInfo, DbgLanguage language, DbgEvaluationOptions options, DbgValueNodeEvaluationOptions nodeEvalOptions, DbgValueFormatterOptions nameFormatterOptions);
public virtual DbgValueNodeInfo[] GetDefaultNodes() => Array.Empty<DbgValueNodeInfo>();
/// <summary>
/// Called when the window gets shown or closed
/// </summary>
/// <param name="enable">true if window is shown, false if it's closed</param>
public virtual void Initialize(bool enable) { }
public virtual void OnIsDebuggingChanged(bool isDebugging) { }
/// <summary>
/// true if root nodes can be added/deleted (supported by watch window)
/// </summary>
public virtual bool CanAddRemoveExpressions => false;
public virtual void DeleteExpressions(string[] ids) => throw new NotSupportedException();
public virtual void ClearAllExpressions() => throw new NotSupportedException();
public virtual void EditExpression(string? id, string expression) => throw new NotSupportedException();
public virtual void AddExpressions(string[] expressions) => throw new NotSupportedException();
}
sealed class VariablesWindowVMOptions {
#pragma warning disable CS8618 // Non-nullable field is uninitialized.
public VariablesWindowValueNodesProvider VariablesWindowValueNodesProvider { get; set; }
public string WindowContentType { get; set; }
public string NameColumnName { get; set; }
public string ValueColumnName { get; set; }
public string TypeColumnName { get; set; }
#pragma warning restore CS8618 // Non-nullable field is uninitialized.
public VariablesWindowKind VariablesWindowKind { get; set; }
public Guid VariablesWindowGuid { get; set; }
}
}
| gpl-3.0 |
kaoz70/flexcms | flexcms/modules/admin/controllers/Admin.php | 5638 | <?php
/**
* Created by PhpStorm.
* User: Miguel
* Date: 08/01/14
* Time: 02:32 PM
*/
use App\Config;
use App\Category;
use App\Content;
use App\Utils;
use Cartalyst\Sentinel\Checkpoints\NotActivatedException;
use Cartalyst\Sentinel\Checkpoints\ThrottlingException;
use Cartalyst\Sentinel\Native\Facades\Sentinel;
class Admin extends AdminController {
private $site_config;
function __construct(){
parent::__construct();
$this->load->library('form_validation');
}
/**
* Initial check
*/
public function index()
{
try {
$user = Sentinel::getUser();
$this->site_config = Config::get();
$data['title'] = $this->site_config['site_name'];
$data['error'] = $this->session->flashdata('error');
//User is loged in and is administrator
if ($user && Sentinel::hasAccess(['admin'])) {
$this->renderAdmin();
}
//User is logged in but not admin
else if ($user && !Sentinel::hasAccess(['admin'])) {
$data['error'] = 'Usted no tiene los permisos necesarios para poder entrar a esta sección. <a href="'. base_url() .'">regresar el inicio</a>';
\App\View::blade(APPPATH . 'modules/admin/views/login', $data);
}
//Not loged in
else {
\App\View::blade(APPPATH . 'modules/admin/views/login', $data);
}
} catch (Exception $e) {
$data = [
"heading" => "Error",
"message" => $e->getMessage(),
];
\App\View::blade(APPPATH . 'views/errors/html/general', $data);
}
}
/**
* Shows the admin control panel
*/
private function renderAdmin()
{
$data['titulo'] = $this->site_config['site_name'] . " Control Panel";
$data['user'] = Sentinel::getUser();
$root = Category::find(1);
$root->descendants()->get();
$data['root_node'] = $root;
$data['visible'] = Content::getEditable(TRUE);
$data['menu'] = \App\Admin::getModules();
$data['assets_js'] = \App\Admin::getModuleAssets();
\App\View::blade(APPPATH . 'modules/admin/views/index', $data);
}
/**
* Logs the user out
*/
public function logout()
{
Sentinel::logout();
redirect('admin');
}
/**
* Checks if the user is logged in
*/
public function logged_in()
{
$data['return'] = Sentinel::check();
$this->load->view('admin/request/json', $data);
}
/**
* Gets the login form
*/
public function loginForm(){
$data['error'] = '';
$data['form_action'] = base_url('admin/validate');
$this->load->view('admin/login_form_view', $data);
}
/**
* Checks the user login
*/
public function validate(){
$this->form_validation->set_rules('username', 'Email', 'required');
$this->form_validation->set_rules('password', 'Contraseña', 'required');
$errors = $this->lang->line('login_unsuccessful');
try {
//Did not pass form validation
if (!$this->form_validation->run()) {
throw new InvalidArgumentException('invalid fields');
}
$credentials = [
"email" => $this->input->post("username"),
"password" => $this->input->post("password"),
];
if ($user = Sentinel::authenticate($credentials, true)) {
if(!Sentinel::hasAccess(['admin'])) {
throw new Exception("invalid access");
}
if ($this->input->is_ajax_request()) {
$data['return'] = [
'message' => 'Login success'
];
$this->load->view( 'admin/request/json', $data );
} else {
redirect( 'admin' );
}
}
} catch (NotActivatedException $e) {
$errors = $this->lang->line('account_not_active');
} catch (ThrottlingException $e) {
$delay = $e->getDelay();
$errors = $this->lang->lineParam('account_blocked', $delay);
} catch (InvalidArgumentException $e) {
$errors = $e->getMessage();
} catch (Exception $e) {
$errors = $e->getMessage();
}
$data['return'] = [
'error' => true,
'message' => $errors
];
$this->load->view( 'admin/request/json', $data );
}
public function notifyError()
{
$response = new \App\Response();
//Save a log of the error
log_message('error', json_encode($this->input->post()));
//Send an email
$mail = new \PHPMailer();
$mail->setFrom('[email protected]', 'FlexCMS');
$mail->addAddress('[email protected]', 'Miguel Suarez'); // Add a recipient
$mail->Subject = '[' . base_url() . '] Notificacion de error';
$mail->Body = $this->load->view('admin/email/notify_error_view', [
'data' => $this->input->post()
], true);
if($mail->send()) {
$response->setMessage('Notificacion enviada correctamente');
} else {
$response->setType('warning');
$response->setMessage('No se pudo enviar el email con los datos del error, pero se guardo un registro');
}
$this->load->view(static::RESPONSE_VIEW, [static::RESPONSE_VAR => $response]);
}
}
| gpl-3.0 |
ebrelsford/v2v | vacant_to_vibrant/groundtruth/forms.py | 425 | from django import forms
from livinglots_groundtruth.forms import GroundtruthRecordFormMixin
from .models import GroundtruthRecord
class GroundtruthRecordForm(GroundtruthRecordFormMixin, forms.ModelForm):
class Meta:
model = GroundtruthRecord
widgets = {
'content_type': forms.HiddenInput(),
'object_id': forms.HiddenInput(),
'use': forms.HiddenInput(),
}
| gpl-3.0 |
Madril/env | emacs.d/jde/java/src/jde/debugger/command/TraceThreads.java | 3511 | package jde.debugger.command;
import java.util.List;
import com.sun.jdi.ObjectReference;
import com.sun.jdi.ThreadReference;
import com.sun.jdi.request.EventRequestManager;
import com.sun.jdi.request.ThreadDeathRequest;
import com.sun.jdi.request.ThreadStartRequest;
import jde.debugger.Etc;
import jde.debugger.JDEException;
import jde.debugger.ObjectStore;
/**
* 'trace_threads' command.
* <p>
*
* <b>Syntax:</b>
* <pre>
* trace_threads <u>type</u> [threadID]
* [{@link Etc#getSuspendPolicyFromArgs(List) suspend-policy}]
* </pre>
*
* <b>Comments:</b>
* <ul>
* <li> <u>type</u> can be either "start" or "death"
* <li> If no threadID is specified, all the corresponding thread
* events are raised.
* </ul>
*
* <p>
* @see jde.debugger.EventHandler#threadStartEvent(ThreadStartEvent)
* @see jde.debugger.EventHandler#threadDeathEvent(ThreadDeathEvent)
*
* @author Paul Kinnucan
* @version $Revision: 1.2 $
*
* Copyright (c) 2000, 2001, 2003 Paul Kinnucan
*
*/
public class TraceThreads extends DebugProcessCommand {
/**
*
* @exception jde.debugger.JDEException <description>
*/
public void doCommand() throws JDEException {
if (m_args.size() < 2)
throw new JDEException("Insufficient arguments");
String type = m_args.remove(0).toString().toLowerCase();
if (!(type.equals("start") || type.equals("death")))
throw new JDEException("Invalid type");
List classFilters = Etc.getClassFiltersFromArgs(m_args);
List classExFilters = Etc.getClassExFiltersFromArgs(m_args);
EventRequestManager em = m_debugger.getVM().eventRequestManager();
Long requestID = null;
ObjectStore store = m_debugger.getStore();
if (type.equals("start")) {
ThreadStartRequest ter = em.createThreadStartRequest();
ter.setSuspendPolicy(Etc.getSuspendPolicyFromArgs(m_args));
if (m_args.size() > 0) {
Long threadID = Etc.safeGetLong(m_args.remove(0), "thread ID");
ObjectReference tRef = store.get(threadID);
if (tRef == null) {
throw new JDEException("No such thread exists");
} else if (!(tRef instanceof ThreadReference)) {
throw new JDEException("No such thread exists (anymore?)");
}
ter.addThreadFilter((ThreadReference)tRef);
}
requestID = m_debugger.addIdentifiableRequest(ter);
} else if (type.equals("death")) {
ThreadDeathRequest ter = em.createThreadDeathRequest();
ter.setSuspendPolicy(Etc.getSuspendPolicyFromArgs(m_args));
if (m_args.size() > 0) {
Long threadID = Etc.safeGetLong(m_args.remove(0), "thread ID");
ObjectReference tRef = store.get(threadID);
if (tRef == null) {
throw new JDEException("No such thread exists");
} else if (!(tRef instanceof ThreadReference)) {
throw new JDEException("No such thread exists (anymore?)");
}
ter.addThreadFilter((ThreadReference)tRef);
}
requestID = m_debugger.addIdentifiableRequest(ter);
}
m_debugger.signalCommandResult(m_cmdID, requestID.toString(), CMD_OK);
}
public Object clone() {return new TraceThreads();}
} // TraceThreads
/*
* $Log: TraceThreads.java,v $
* Revision 1.2 2003/01/15 05:56:26 paulk
* Add Petter Mahlen's changes.
*
* Revision 1.1 2001/03/24 13:35:26 paulk
* Initial revision.
*
*
*/
// End of TraceThreads.java
| gpl-3.0 |
Invertika/data | scripts/maps/ow-p0022-p0012-o0000.lua | 1404 | ----------------------------------------------------------------------------------
-- Map File --
-- --
-- In dieser Datei stehen die entsprechenden externen NPC's, Trigger und --
-- anderer Dinge. --
-- --
----------------------------------------------------------------------------------
-- Copyright 2010 The Invertika Development Team --
-- --
-- This file is part of Invertika. --
-- --
-- Invertika 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 any later version. --
----------------------------------------------------------------------------------
require "scripts/lua/npclib"
require "scripts/libs/warp"
atinit(function()
create_inter_map_warp_trigger(2436, 2486, 2434, 2384) --- Intermap warp
end)
| gpl-3.0 |
quintesse/java-webserv | src/main/java/org/codejive/websrv/config/HttpListenerConfig.java | 5940 | /*
* HttpListenerConfig.java
*
* Created on Aug 11, 2007, 7:17:04 PM
* Copyright Tako Schotanus
*
* This file is part of websrv.
*
* websrv 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.
*
* websrv 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.codejive.websrv.config;
import org.codejive.websrv.listener.HttpListener;
import org.codejive.websrv.servlet.Servlet;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* Builder class for HttpListener objects
* @author Tako Schotanus <tako AT codejive.org>
*/
public class HttpListenerConfig {
/**
* The address to bind the listener to
*/
private String address;
/**
* The port to bind the listener to
*/
private int port;
/**
* The timeout in milliseconds after which inactive connections
* will be closed (default = 10 seconds)
*/
private int keepAliveTimeout;
/**
* The maximum amount a requests that will be served over one
* connection before closing it. Setting it to -1 will allow
* an unlimited amount of requests (default = -1).
*/
private int keepAliveMaxRequests;
/**
* The servlet that will handle client requests
*/
private Servlet defaultServlet;
/**
* Constructs a new instance using "localhost" as the address
* and "0" as the port
*/
public HttpListenerConfig() {
this("localhost", 0);
}
/**
* Constructs a new instance using "localhost" as the address
* and the given port
* @param port The port to use for this instance
*/
public HttpListenerConfig(int port) {
this("localhost", port);
}
/**
* Constructs a new instance using the given address and port
* @param address The address to use for this instance
* @param port The port to use for this instance
*/
public HttpListenerConfig(String address, int port) {
this.address = address;
this.port = port;
keepAliveTimeout = 10000;
keepAliveMaxRequests = -1;
}
/**
* Returns the address that will be used to construct the listener
* @return The address to use for the listener
*/
public String getAddress() {
return address;
}
/**
* Sets the address that will be used to construct the listener
* @param address The address to use for the listener
*/
public void setAddress(String address) {
this.address = address;
}
/**
* Returns the configured address as an InetAddress object
* @return The address to use for the listener
* @throws java.net.UnknownHostException If the configured address
* cannot be resolved
*/
public InetAddress getInetAddress() throws UnknownHostException {
return InetAddress.getByName(address);
}
/**
* Returns the port that will be used to construct the listener
* @return The port to use for the listener
*/
public int getPort() {
return port;
}
/**
* Sets the port that will be used to construct the listener
* @param port The port to use for the listener
*/
public void setPort(int port) {
this.port = port;
}
/**
* Returns the default servlet that will be used to construct the listener
* @return The default servlet to use for the listener
*/
public Servlet getDefaultServlet() {
return defaultServlet;
}
/**
* Sets the default servlet that will be used to construct the listener
* @param servlet The default servlet to use for the listener
*/
public void setDefaultServlet(Servlet servlet) {
this.defaultServlet = servlet;
}
/**
* Returns the Keep-Alive time-out that will be used to construct the listener
* @return The Keep-Alive time-out to use for the listener
*/
public int getKeepAliveTimeout() {
return keepAliveTimeout;
}
/**
* Sets the Keep-Alive time-out that will be used to construct the listener
* @param keepAliveTimeout The Keep-Alive time-out to use for the listener
*/
public void setKeepAliveTimeout(int keepAliveTimeout) {
this.keepAliveTimeout = keepAliveTimeout;
}
/**
* Returns the maximum Keep-Alive requests that will be used to construct the listener
* @return The maximum number of requests to use for the listener
*/
public int getKeepAliveMaxRequests() {
return keepAliveMaxRequests;
}
/**
* Sets the maximum Keep-Alive requests that will be used to construct the listener
* @param keepAliveMaxRequests The maximum number of requests to use for the listener
*/
public void setKeepAliveMaxRequests(int keepAliveMaxRequests) {
this.keepAliveMaxRequests = keepAliveMaxRequests;
}
/**
* Constructs an HttpListener using the information previously stored
* in the object's attributes
* @return A properly configured HttpListener
* @throws org.codejive.websrv.config.ConfigurationException If the object
* could not be created
*/
public HttpListener buildListener() throws ConfigurationException {
if (address == null || address.length() == 0) {
throw new ConfigurationException("An address must be specified");
}
if (defaultServlet == null) {
throw new ConfigurationException("A default servlet must be specified");
}
try {
HttpListener listener = new HttpListener();
listener.setAddress(getInetAddress());
listener.setPort(port);
listener.setDefaultServlet(defaultServlet);
listener.setKeepAliveTimeout(keepAliveTimeout);
listener.setKeepAliveMaxRequests(keepAliveMaxRequests);
return listener;
} catch (UnknownHostException ex) {
throw new ConfigurationException(ex);
}
}
}
| gpl-3.0 |
idega/com.idega.block.ldap | src/java/com/idega/core/ldap/business/LDAPUserBusinessHomeImpl.java | 353 | package com.idega.core.ldap.business;
public class LDAPUserBusinessHomeImpl extends com.idega.business.IBOHomeImpl implements LDAPUserBusinessHome
{
protected Class getBeanInterfaceClass(){
return LDAPUserBusiness.class;
}
public LDAPUserBusiness create() throws javax.ejb.CreateException{
return (LDAPUserBusiness) super.createIBO();
}
} | gpl-3.0 |
jonaski/strawberry | src/widgets/favoritewidget.cpp | 2050 | /*
* Strawberry Music Player
* This file was part of Clementine.
* Copyright 2013, David Sansome <[email protected]>
*
* Strawberry 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.
*
* Strawberry 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 Strawberry. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "config.h"
#include <QtGlobal>
#include <QWidget>
#include <QSize>
#include <QStyle>
#include <QStylePainter>
#include <QPaintEvent>
#include <QMouseEvent>
#include "favoritewidget.h"
const int FavoriteWidget::kStarSize = 15;
FavoriteWidget::FavoriteWidget(const int tab_index, const bool favorite, QWidget *parent)
: QWidget(parent),
tab_index_(tab_index),
favorite_(favorite),
on_(":/icons/64x64/star.png"),
off_(":/icons/64x64/star-grey.png"),
rect_(0, 0, kStarSize, kStarSize) {}
void FavoriteWidget::SetFavorite(bool favorite) {
if (favorite_ != favorite) {
favorite_ = favorite;
update();
emit FavoriteStateChanged(tab_index_, favorite_);
}
}
QSize FavoriteWidget::sizeHint() const {
const int frame_width = 1 + style()->pixelMetric(QStyle::PM_DefaultFrameWidth);
return QSize(kStarSize + frame_width * 2, kStarSize + frame_width * 2);
}
void FavoriteWidget::paintEvent(QPaintEvent *e) {
Q_UNUSED(e);
QStylePainter p(this);
if (favorite_) {
p.drawPixmap(rect_, on_);
}
else {
p.drawPixmap(rect_, off_);
}
}
void FavoriteWidget::mouseReleaseEvent(QMouseEvent *e) {
Q_UNUSED(e);
favorite_ = !favorite_;
update();
emit FavoriteStateChanged(tab_index_, favorite_);
}
| gpl-3.0 |
vmon/demystegofier | src/features/__init__.py | 251 | #All features
__all__ = ["feature_average_request_interval", "feature_variance_request_interval", "feature_cycling_user_agent", "feature_html_to_image_ratio", "feature_request_depth", "feature_HTTP_response_code_rate", "feature_payload_size_average"]
| gpl-3.0 |
rarog/TranslationManagerForAndroidApps | module/Setup/src/Controller/SetupController.php | 18090 | <?php
/**
* Translation Manager for Android Apps
*
* PHP version 7
*
* @category PHP
* @package TranslationManagerForAndroidApps
* @author Andrej Sinicyn <[email protected]>
* @copyright 2017 Andrej Sinicyn
* @license https://www.gnu.org/licenses/gpl-3.0.html GNU General Public License version 3 or later
* @link https://github.com/rarog/TranslationManagerForAndroidApps
*/
namespace Setup\Controller;
use Setup\Helper\DatabaseHelper;
use Setup\Helper\FileHelper;
use Zend\Cache\Storage\Adapter\AbstractAdapter as CacheAdapter;
use Zend\Http\PhpEnvironment\Response;
use Zend\Math\Rand;
use Zend\ModuleManager\Listener\ListenerOptions;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Mvc\I18n\Translator;
use Zend\Session\Container as SessionContainer;
use Zend\Session\SessionManager;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;
use Zend\View\Renderer\PhpRenderer as Renderer;
use ZfcUser\Options\ModuleOptions as ZUModuleOptions;
use ZfcUser\Service\User as ZUUser;
class SetupController extends AbstractActionController
{
/**
* @var Translator
*/
private $translator;
/**
* @var SessionContainer
*/
private $container;
/**
* @var ListenerOptions
*/
private $listenerOptions;
/**
* @var Renderer
*/
private $renderer;
/**
* @var ZUUser
*/
private $zuUserService;
/**
* @var ZUModuleOptions
*/
private $zuModuleOptions;
/**
* @var DatabaseHelper
*/
private $databaseHelper;
/**
* @var SessionManager
*/
private $session;
/**
* @var CacheAdapter
*/
private $setupCache;
/**
* @var array
*/
private $availableLanguages;
/**
* @var \Zend\Config\Config
*/
private $setupConfig;
/**
* @var int
*/
private $lastStep;
/**
* Returns array with languages availabe during setup
*
* @return array
*/
private function getAvailableLanguages()
{
if (is_null($this->availableLanguages)) {
$this->availableLanguages = $this->getSetupConfig()->available_languages->toArray();
}
return $this->availableLanguages;
}
/**
* Returns config of Setup module
*
* @return \Zend\Config\Config
*/
private function getSetupConfig()
{
if (is_null($this->setupConfig)) {
$this->setupConfig = $this->configHelp('setup');
}
return $this->setupConfig;
}
/**
* Sets the translator language to the current internal variable content
*/
private function setCurrentLanguage()
{
if (! is_null($this->container->currentLanguage) &&
array_key_exists($this->container->currentLanguage, $this->getAvailableLanguages())) {
$this->translator
->setLocale($this->container->currentLanguage)
->setFallbackLocale(\Locale::getPrimaryLanguage($this->container->currentLanguage));
}
}
/**
* Get the current value of last step variable
*
* @return int
*/
private function getLastStep()
{
return (int) $this->container->lastStep;
}
/**
* Sets the current value of last step variable
*
* @param int $lastStep
*/
private function setLastStep(int $lastStep)
{
$this->container->lastStep = $lastStep;
}
/**
* Checks, if the the call to the controller is allowed
*
* @param int $currentStep
* @return \Zend\Http\Response
*/
private function checkSetupStep(int $currentStep)
{
$this->protectCompletedSetup();
$this->ensureThereCanBeOnlyOne();
$lastStep = $this->getLastStep();
if ($currentStep > $lastStep) {
$action = [];
if ($lastStep > 1) {
$action['action'] = 'step' . $lastStep;
}
return $this->redirect()->toRoute('setup', $action);
} else {
$dbHelper = $this->databaseHelper;
if (! $dbHelper->canConnect() && ($currentStep > 2)) {
return $this->redirect()->toRoute('setup', ['action' => 'step2']);
}
}
}
/**
* Adds Bootstrap disabled class to a form element
*
* @param \Zend\Form\Element $element
*/
private function disableFormElement(\Zend\Form\Element $element)
{
if ($element) {
$element->setAttribute('disabled', 'disabled');
}
}
/**
* Ensures that there is only one session working on the setup process
*
* @return void|\Zend\Http\Response
*/
private function ensureThereCanBeOnlyOne()
{
$sessionId = $this->session->getId();
$now = time();
if (! (
$this->setupCache->hasItem('highlanderSessionId')
&& ($this->setupCache->hasItem('highlanderLastSeen'))
)
) {
$this->setupCache->setItems([
'highlanderSessionId' => $sessionId,
'highlanderLastSeen' => $now,
]);
}
if ($this->setupCache->getItem('highlanderSessionId') !== $sessionId) {
// Lock out all other non-highlander people trying to access setup.
return $this->redirect()->toRoute('setup', ['action' => 'locked']);
}
// Refresh highlander session
$this->setupCache->setItems([
'highlanderSessionId' => $sessionId,
'highlanderLastSeen' => $now,
]);
return;
}
/**
* Redirects to login page, if setup is complete.
*
* @return \Zend\Http\Response
*/
private function protectCompletedSetup()
{
if ($this->databaseHelper->isSetupComplete()) {
return $this->redirect()->toRoute('zfcuser/login');
}
}
/**
* Generates error 403
*
* @return \Zend\Http\PhpEnvironment\Response
*/
private function throw403()
{
return $this->getResponse()->setStatusCode(Response::STATUS_CODE_403);
}
/**
* Constructor
*
* @param Translator $translator
* @param SessionContainer $container
* @param ListenerOptions $listenerOptions
* @param Renderer $renderer
* @param ZUUser $zuUserService
* @param ZUModuleOptions $zuModuleOptions
* @param DatabaseHelper $databaseHelper
* @param SessionManager $session;
* @param CacheAdapter $setupCache
*/
public function __construct(
Translator $translator,
SessionContainer $container,
ListenerOptions $listenerOptions,
Renderer $renderer,
ZUUser $zuUserService,
ZUModuleOptions $zuModuleOptions,
DatabaseHelper $databaseHelper,
SessionManager $session,
CacheAdapter $setupCache
) {
$this->translator = $translator;
$this->container = $container;
$this->listenerOptions = $listenerOptions;
$this->renderer = $renderer;
$this->zuUserService = $zuUserService;
$this->zuModuleOptions = $zuModuleOptions;
$this->databaseHelper = $databaseHelper;
$this->session = $session;
$this->setupCache = $setupCache;
}
/**
* Action for database connection test call via JSON
*/
public function databaseconnectiontestAction()
{
$this->protectCompletedSetup();
$request = $this->getRequest();
if ($request->isXmlHttpRequest()) {
$this->setCurrentLanguage();
if ($request->isPost() && ($postData = $request->getPost()->toArray())) {
$dbHelper = $this->databaseHelper;
$dbHelper->setDbConfigArray($postData);
if ($dbHelper->canConnect()) {
$type = 'success';
$message = $this->translator->translate('Database connection successfully established.');
} else {
$type = 'danger';
$message = $this->translator->translate('Database connection can\'t be established.');
}
} else {
$type = 'danger';
$message = $this->translator->translate('<strong>Error:</strong> Invalid POST data was provided.');
}
$viewModel = new ViewModel([
'type' => $type,
'message' => $message,
'canClose' => true,
]);
$viewModel->setTemplate('partial/alert.phtml')
->setTerminal(true);
$htmlOutput = $this->renderer->render($viewModel);
$jsonModel = new JsonModel([
'html' => $htmlOutput,
]);
$jsonModel->setTerminal(true);
return $jsonModel;
} else {
return $this->throw403();
}
}
/**
* Action for database connection test call via JSON
*/
public function databaseschemainstallationAction()
{
$this->protectCompletedSetup();
if ($this->getRequest()->isXmlHttpRequest()) {
$dbHelper = $this->databaseHelper;
$dbHelper->installSchema();
$nextEnabled = true;
$installSchemaEnabled = true;
// Disable buttons if needed.
if (! $dbHelper->isSchemaInstalled()) {
$nextEnabled = false;
}
// This code works properly only, because isSchemaInstalled() was called above.
if ($dbHelper->getLastStatus() != $dbHelper::DBNOTINSTALLEDORTABLENOTPRESENT) {
$installSchemaEnabled = false;
}
$jsonModel = new JsonModel([
'html' => $dbHelper->getLastMessage(),
'nextEnabled' => $nextEnabled,
'installSchemaEnabled' => $installSchemaEnabled,
]);
$jsonModel->setTerminal(true);
return $jsonModel;
} else {
return $this->throw403();
}
}
/**
* Action for step 1 - welcome screen and setup language selection
*/
public function indexAction()
{
$this->setCurrentLanguage();
$this->setLastStep(1);
$this->checkSetupStep(1);
$setupLanguage = new \Setup\Model\SetupLanguage([
'setup_language' => $this->translator->getLocale(),
]);
$formStep1 = new \Setup\Form\Step1Form();
$formStep1->get('setup_language')->setValueOptions($this->getAvailableLanguages());
$formStep1->bind($setupLanguage);
$request = $this->getRequest();
if ($request->isPost()) {
$formStep1->setInputFilter($setupLanguage->getInputFilter());
$formStep1->setData($request->getPost());
if ($formStep1->isValid() &&
array_key_exists($setupLanguage->SetupLanguage, $this->getAvailableLanguages())) {
$this->container->currentLanguage = $setupLanguage->SetupLanguage;
$this->setLastStep(2);
return $this->redirect()->toRoute('setup', ['action' => 'step2']);
}
}
return new ViewModel([
'formStep1' => $formStep1,
]);
}
/**
* Action for showing, that setup process is locked by another user
*
* @return \Zend\View\Model\ViewModel
*/
public function lockedAction()
{
$this->protectCompletedSetup();
return new ViewModel([]);
}
/**
* Action for step 2 - setup of the database connection
*/
public function step2Action()
{
$this->setCurrentLanguage();
$this->checkSetupStep(2);
$database = new \Setup\Model\Database(
($this->configHelp()->db) ? $this->configHelp()->db->toArray() : []
);
$security = ($this->configHelp()->security) ? $this->configHelp()->security->toArray() : '';
$masterKey = (is_array($security)) ? (string) $security['master_key'] : '';
if ($masterKey == '') {
$masterKey = Rand::getString(64);
}
$formStep2 = new \Setup\Form\Step2Form();
$formStep2->get('driver')->setValueOptions($this->getSetupConfig()->drivers->toArray());
$formStep2->bind($database);
$formStep2->get('master_key')->setValue($masterKey);
$request = $this->getRequest();
if ($request->isPost()) {
$formStep2->setInputFilter($database->getInputFilter());
$formStep2->setData($request->getPost());
if ($formStep2->isValid()) {
$security['master_key'] = $masterKey;
$config = [];
$config['db'] = $database->getArrayCopy();
$config['security'] = $security;
$fileHelper = new FileHelper();
// Replacing content of local.php config file
$fileHelper->replaceConfigInFile('config/autoload/local.php', $config);
// Replacing content of config cache if enabled
if ($this->listenerOptions->getConfigCacheEnabled() &&
file_exists($this->listenerOptions->getConfigCacheFile())) {
$fileHelper->replaceConfigInFile($this->listenerOptions->getConfigCacheFile(), $config);
}
$this->setLastStep(3);
return $this->redirect()->toRoute('setup', [
'action' => 'step3'
]);
}
}
return new ViewModel([
'formStep2' => $formStep2,
]);
}
/**
* Action for step 3 - setup of the database schema
*/
public function step3Action()
{
$this->setCurrentLanguage();
$this->checkSetupStep(3);
$dbHelper = $this->databaseHelper;
$dbHelper->isSchemaInstalled();
$databaseSchema = new \Setup\Model\DatabaseSchema([
'output' => $dbHelper->getLastMessage(),
]);
$formStep3 = new \Setup\Form\Step3Form();
$formStep3->bind($databaseSchema);
$request = $this->getRequest();
if ($request->isPost()) {
$this->setLastStep(4);
return $this->redirect()->toRoute('setup', ['action' => 'step4']);
}
// Disable buttons if needed.
if (! $dbHelper->isSchemaInstalled()) {
$this->disableFormElement($formStep3->get('next'));
}
// This code works properly only, because isSchemaInstalled() was called above.
if ($dbHelper->getLastStatus() != $dbHelper::DBNOTINSTALLEDORTABLENOTPRESENT) {
$this->disableFormElement($formStep3->get('install_schema'));
}
return new ViewModel([
'formStep3' => $formStep3,
]);
}
/**
* Action for step 4 - setup of the database schema
*/
public function step4Action()
{
$this->setCurrentLanguage();
$this->checkSetupStep(4);
$userExists = $this->databaseHelper
->isSetupComplete();
if ($userExists) {
$type = 'success';
$message = $this->translator->translate('A user is already in the database. This step will be skipped.');
} else {
$type = 'info';
$message = $this->translator->translate('Please create your user.');
}
$service = $this->zuUserService;
$userCreation = new \Setup\Model\UserCreation($this->zuModuleOptions);
$formStep4 = new \Setup\Form\Step4Form();
if (! $this->zuModuleOptions->getEnableUsername()) {
$formStep4->remove('username');
}
if (! $this->zuModuleOptions->getEnableDisplayName()) {
$formStep4->remove('display_name');
}
$formStep4->setHydrator(new \Zend\Hydrator\ClassMethods);
$formStep4->bind($userCreation);
$request = $this->getRequest();
if ($request->isPost()) {
if ($userExists) {
return $this->redirect()->toRoute('application', ['action' => 'index']);
} else {
$formStep4->setInputFilter($userCreation->getInputFilter());
$formStep4->setData($request->getPost());
if ($formStep4->isValid() && ($zuUser = $service->register($userCreation->getArrayCopy()))) {
// Workaround for ZfcUser with Pdo_Pgsql, where generatedValue remains empty.
$zuUser = $service->getUserMapper()->findByEmail($zuUser->getEmail());
$this->getEventManager()->trigger('userCreated', null, ['user' => $zuUser]);
$userExists = true;
$type = 'success';
$message = $this->translator->translate('The user has been sucessfully created.');
} else {
$type = 'danger';
$message = $this->translator->translate('The user couldn\'t be created. Please check the entries.');
}
}
}
$formElement = $userExists ? 'create_user' : 'next';
$this->disableFormElement($formStep4->get($formElement));
if ($userExists) {
$this->disableFormElement($formStep4->get('username'));
$this->disableFormElement($formStep4->get('email'));
$this->disableFormElement($formStep4->get('display_name'));
$this->disableFormElement($formStep4->get('password'));
$this->disableFormElement($formStep4->get('passwordVerify'));
}
$viewModel = new ViewModel([
'type' => $type,
'message' => $message,
'canClose' => false,
]);
$viewModel->setTemplate('partial/alert.phtml')
->setTerminal(true);
$infoArea = $this->renderer->render($viewModel);
return new ViewModel([
'infoArea' => $infoArea,
'formStep4' => $formStep4,
]);
}
}
| gpl-3.0 |
Mikescher/jClipCorn | src/main/de/jClipCorn/util/SimpleSerializableData.java | 7689 | package de.jClipCorn.util;
import de.jClipCorn.util.exceptions.XMLFormatException;
import de.jClipCorn.util.filesystem.FSPath;
import de.jClipCorn.util.stream.CCStreams;
import org.apache.commons.lang3.ArrayUtils;
import org.jdom2.Attribute;
import org.jdom2.DataConversionException;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
@SuppressWarnings("nls")
public class SimpleSerializableData {
private static final Decoder B64_DECODER = Base64.getDecoder();
private static final Encoder B64_ENCODER = Base64.getEncoder();
private final Map<String, SimpleSerializableData> children = new HashMap<>();
private final Map<String, String> dataString = new HashMap<>();
private final Map<String, Integer> dataInt = new HashMap<>();
private final Map<String, Long> dataLong = new HashMap<>();
private final Map<String, Boolean> dataBool = new HashMap<>();
private final Map<String, Byte[]> dataRaw = new HashMap<>();
private final boolean sortBeforeSerialize;
private SimpleSerializableData(boolean outputSorted) {
sortBeforeSerialize = outputSorted;
}
public String getStr(String id) {
return dataString.get(id);
}
public int getInt(String id) {
return dataInt.get(id);
}
public long getLong(String id) {
return dataLong.get(id);
}
public byte[] getRaw(String id) {
return ArrayUtils.toPrimitive(dataRaw.get(id));
}
public boolean getBool(String id) {
return dataBool.get(id);
}
public void set(String id, String val) {
dataString.put(id, val);
}
public void set(String id, int val) {
dataInt.put(id, val);
}
public void set(String id, long val) {
dataLong.put(id, val);
}
public void set(String id, boolean val) {
dataBool.put(id, val);
}
public void set(String id, byte[] val) {
dataRaw.put(id, ArrayUtils.toObject(val));
}
public boolean containsChild(String id) {
return children.containsKey(id);
}
public SimpleSerializableData getChild(String id) {
return children.get(id);
}
public SimpleSerializableData addChild(String id) {
SimpleSerializableData r = new SimpleSerializableData(sortBeforeSerialize);
children.put(id, r);
return r;
}
public void removeChild(String id) {
children.remove(id);
}
public static SimpleSerializableData createEmpty(boolean outputSorted) {
return new SimpleSerializableData(outputSorted);
}
public static SimpleSerializableData load(FSPath filename, boolean outputSorted) throws XMLFormatException {
try {
Document doc = new SAXBuilder().build(new StringReader(filename.readAsUTF8TextFile()));
Element root = doc.getRootElement();
if (! root.getName().equals("root")) throw new XMLFormatException("found unsupported element: <" + root.getName() + ">");
return deserialize(root, outputSorted);
} catch (Exception e) {
throw new XMLFormatException(e.getMessage(), e);
}
}
public void save(FSPath filepath) throws IOException {
Document xml = new Document(new Element("root"));
Element root = xml.getRootElement();
serialize(root);
XMLOutputter xout = new XMLOutputter();
xout.setFormat(Format.getPrettyFormat());
FileOutputStream ostream = null;
try {
ostream = new FileOutputStream(filepath.toString());
xout.output(xml, ostream);
} finally {
if (ostream != null) {
ostream.close();
}
}
}
private static SimpleSerializableData deserialize(Element el, boolean sbs) throws XMLFormatException, DataConversionException, NumberFormatException {
SimpleSerializableData r = new SimpleSerializableData(sbs);
for (Attribute attr : el.getAttributes()) {
if (attr.getName().equals("id")) {
// ignore
} else if (attr.getName().startsWith("str_")) {
r.dataString.put(attr.getName().substring(4), attr.getValue());
} else if (attr.getName().startsWith("int_")) {
r.dataInt.put(attr.getName().substring(4), attr.getIntValue());
} else if (attr.getName().startsWith("raw_")) {
r.dataRaw.put(attr.getName().substring(4), ArrayUtils.toObject(B64_DECODER.decode(attr.getValue())));
} else if (attr.getName().startsWith("bool_")) {
r.dataBool.put(attr.getName().substring(5), attr.getValue().equals("true"));
} else if (attr.getName().startsWith("long_")) {
r.dataLong.put(attr.getName().substring(5), attr.getLongValue());
} else {
throw new XMLFormatException("found unsupported attribute-type: " + attr.getName());
}
}
for (Element child : el.getChildren()) {
if (child.getName().equals("element"))
r.children.put(child.getAttributeValue("id"), deserialize(child, sbs));
else if (child.getName().equals("attr_str"))
r.dataString.put(child.getAttributeValue("name"), new String(B64_DECODER.decode(child.getText()), StandardCharsets.UTF_8));
else if (child.getName().equals("attr_int"))
r.dataInt.put(child.getAttributeValue("name"), Integer.parseInt(child.getText()));
else if (child.getName().equals("attr_bool"))
r.dataBool.put(child.getAttributeValue("name"), child.getText().equals("true"));
else if (child.getName().equals("attr_long"))
r.dataLong.put(child.getAttributeValue("name"), Long.parseLong(child.getText()));
else if (child.getName().equals("attr_raw"))
r.dataRaw.put(child.getAttributeValue("name"), ArrayUtils.toObject(B64_DECODER.decode(child.getText())));
else
throw new XMLFormatException("found unsupported element: <" + child.getName() + ">");
}
return r;
}
private void serialize(Element e) {
for (Entry<String, Integer> data : dataInt.entrySet()) {
e.setAttribute("int_"+data.getKey(), Integer.toString(data.getValue()));
}
for (Entry<String, Long> data : dataLong.entrySet()) {
e.setAttribute("long_"+data.getKey(), Long.toString(data.getValue()));
}
for (Entry<String, Boolean> data : dataBool.entrySet()) {
e.setAttribute("bool_"+data.getKey(), data.getValue() ? "true" : "false");
}
for (Entry<String, String> data : dataString.entrySet()) {
if (data.getValue().length() < 48) {
e.setAttribute("str_"+data.getKey(), data.getValue());
} else {
Element sub = new Element("attr_str");
sub.setText(B64_ENCODER.encodeToString(StandardCharsets.UTF_8.encode(data.getValue()).array()));
e.addContent(sub);
}
}
for (Entry<String, Byte[]> data : dataRaw.entrySet()) {
String dataValue = B64_ENCODER.encodeToString(ArrayUtils.toPrimitive(data.getValue()));
if (dataValue.length() < 32) {
e.setAttribute("raw_"+data.getKey(), dataValue);
} else {
Element sub = new Element("attr_raw");
sub.setText(dataValue);
e.addContent(sub);
}
}
if (sortBeforeSerialize) {
for (Entry<String, SimpleSerializableData> child : CCStreams.iterate(children.entrySet()).autosortByProperty(p -> p.getKey())) {
Element sub = new Element("element");
sub.setAttribute("id", child.getKey());
child.getValue().serialize(sub);
e.addContent(sub);
}
} else {
for (Entry<String, SimpleSerializableData> child : children.entrySet()) {
Element sub = new Element("element");
sub.setAttribute("id", child.getKey());
child.getValue().serialize(sub);
e.addContent(sub);
}
}
}
public Iterable<SimpleSerializableData> enumerateChildren() {
return children.values();
}
}
| gpl-3.0 |
dmnmsc/Unigram | Unigram/Unigram.Api/TL/TLUpdateWebPage.cs | 747 | // <auto-generated/>
using System;
namespace Telegram.Api.TL
{
public partial class TLUpdateWebPage : TLUpdateBase, ITLMultiPts
{
public TLWebPageBase WebPage { get; set; }
public Int32 Pts { get; set; }
public Int32 PtsCount { get; set; }
public TLUpdateWebPage() { }
public TLUpdateWebPage(TLBinaryReader from)
{
Read(from);
}
public override TLType TypeId { get { return TLType.UpdateWebPage; } }
public override void Read(TLBinaryReader from)
{
WebPage = TLFactory.Read<TLWebPageBase>(from);
Pts = from.ReadInt32();
PtsCount = from.ReadInt32();
}
public override void Write(TLBinaryWriter to)
{
to.Write(0x7F891213);
to.WriteObject(WebPage);
to.Write(Pts);
to.Write(PtsCount);
}
}
} | gpl-3.0 |
malikkirchner/knuth | src/vol_iv.hpp | 2953 | // clang-format disable
//**************************************************************************************//
// Copyright (C) 2014 Malik Kirchner "[email protected]" //
// //
// 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/>. //
// //
// Dieses Programm ist Freie Software: Sie können es unter den Bedingungen //
// der GNU General Public License, wie von der Free Software Foundation, //
// Version 3 der Lizenz oder (nach Ihrer Option) jeder späteren //
// veröffentlichten Version, weiterverbreiten und/oder modifizieren. //
// //
// Dieses Programm wird in der Hoffnung, dass es nützlich sein wird, aber //
// OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite //
// Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK. //
// Siehe die GNU General Public License für weitere Details. //
// //
// Sie sollten eine Kopie der GNU General Public License zusammen mit diesem //
// Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. //
// //
//**************************************************************************************//
// clang-format enable
/*!
* @file vol_iv.hpp
* @brief Includes all implementations of algorithms from volume IV.
*
* @author Malik Kirchner <[email protected]>
*/
#pragma once
| gpl-3.0 |
v3c70r/SLS | src/lib/calibration/Calibrator.hpp | 2320 | #pragma once
#include <core/ImageFileProcessor.h>
#include <string>
#include <condition_variable>
namespace SLS {
const int WINDOW_WIDTH = 1024;
const int WINDOW_HEIGHT = 768;
/*! Calibrator is a manual calibration tool to generate calibration
* configuration from checkerboard images. The calibration images must be in the
* form of **x.JPG** where x is a one digit number.
*/
class Calibrator {
/*! Show \p img with \p text on it. The window name is \p windowName
*
* \param img Image to overlay
* \param text to overlay
* \param window name
*/
static void showImgWithText_Block(const cv::Mat &img,
const std::string &text,
const std::string &windowName)
{
cv::Mat textImg;
cv::cvtColor(img, textImg, CV_GRAY2RGB);
cv::putText(textImg, text, cvPoint(20, 70), cv::FONT_HERSHEY_SIMPLEX,
3.0, cvScalar(0, 0, 255), 2, CV_AA);
cv::imshow(windowName, textImg);
textImg.release();
}
/**
*! Manually pick for extrenal corners of a image of checkerboard
*
* /param img Input image
* /return 4 external points
*/
static cv::vector<cv::Point2f> manualMarkCheckBoard(cv::Mat img);
/*! Extract corners in an image
*
* \param img Image to find corners in gray scale
* \param camCorners Output of image corners
* \param objCorners Output of object corners
* \param squareSize size of square
*
* \return
*/
static bool findCornersInCamImg(const cv::Mat &img,
cv::vector<cv::Point2f> &camCorners,
cv::vector<cv::Point3f> &objCorners,
cv::Size squareSize);
/*! Mark a white pixel on \p img image.
*/
static float markWhite(const cv::Mat &img);
public:
/*! Calibrate a camera
* \param cam A fileReader to load calibration checkerboards
* \param calibImgsDir Directory contains checkerboard
* \param calibFile Output calibration result
*/
static void Calibrate(ImageFileProcessor *cam, const std::string &calibImgsDir,
const std::string &calibFile);
};
} // namespace SLS
| gpl-3.0 |
exilium/pifarm-platform | app/scripts/services/AccountValidatorSvc.js | 458 | 'use strict';
angular.module('pifarmApp')
.factory('AccountValidatorSvc', ['Constants', function (Constants) {
var Validator = {};
/*
* Check if password is stronger than minimum length
* @param string password
* @return bool
*/
Validator.check_password_length = function (password) {
if( !password ) return false;
return password.length >= Constants.min_password_length;
};
return Validator;
}]); | gpl-3.0 |
FilippoLeon/ProjectPorcupine | Assets/Scripts/Controllers/BuildModeController.cs | 9471 | #region License
// ====================================================
// Project Porcupine Copyright(C) 2016 Team Porcupine
// This program comes with ABSOLUTELY NO WARRANTY; This is free software,
// and you are welcome to redistribute it under certain conditions; See
// file LICENSE, which is part of this source code package, for details.
// ====================================================
#endregion
using MoonSharp.Interpreter;
using UnityEngine;
public enum BuildMode
{
FLOOR,
FURNITURE,
DECONSTRUCT
}
public class BuildModeController
{
public BuildMode buildMode = BuildMode.FLOOR;
public string buildModeObjectType;
private MouseController mouseController;
private TileType buildModeTile = TileType.Floor;
// Use this for initialization
public void SetMouseController(MouseController currentMouseController)
{
mouseController = currentMouseController;
}
public bool IsObjectDraggable()
{
if (buildMode == BuildMode.FLOOR || buildMode == BuildMode.DECONSTRUCT)
{
// floors are draggable
return true;
}
Furniture proto = WorldController.Instance.world.furniturePrototypes[buildModeObjectType];
return proto.Width == 1 && proto.Height == 1;
}
public string GetFloorTile()
{
return buildModeTile.ToString();
}
public void SetModeBuildTile(TileType type)
{
buildMode = BuildMode.FLOOR;
buildModeTile = type;
mouseController.StartBuildMode();
}
public void SetMode_BuildFurniture(string objectType)
{
// Wall is not a Tile! Wall is an "Furniture" that exists on TOP of a tile.
buildMode = BuildMode.FURNITURE;
buildModeObjectType = objectType;
mouseController.StartBuildMode();
}
public void SetMode_Deconstruct()
{
buildMode = BuildMode.DECONSTRUCT;
mouseController.StartBuildMode();
}
public void DoPathfindingTest()
{
WorldController.Instance.world.SetupPathfindingExample();
}
public void DoBuild(Tile t)
{
if (buildMode == BuildMode.FURNITURE)
{
// Create the Furniture and assign it to the tile
// Can we build the furniture in the selected tile?
// Run the ValidPlacement function!
string furnitureType = buildModeObjectType;
if (
WorldController.Instance.world.IsFurniturePlacementValid(furnitureType, t) &&
DoesBuildJobOverlapExistingBuildJob(t, furnitureType) == false)
{
// This tile position is valid for this furniture
// Check if there is existing furniture in this tile. If so delete it.
// TODO Possibly return resources. Will the Deconstruct() method handle that? If so what will happen if resources drop ontop of new non-passable structure.
if (t.Furniture != null)
{
t.Furniture.Deconstruct();
}
// Create a job for it to be build
Job j;
if (WorldController.Instance.world.furnitureJobPrototypes.ContainsKey(furnitureType))
{
// Make a clone of the job prototype
j = WorldController.Instance.world.furnitureJobPrototypes[furnitureType].Clone();
// Assign the correct tile.
j.tile = t;
}
else
{
Debug.LogError("There is no furniture job prototype for '" + furnitureType + "'");
j = new Job(t, furnitureType, FurnitureActions.JobComplete_FurnitureBuilding, 0.1f, null, Job.JobPriority.High);
j.JobDescription = "job_build_" + furnitureType + "_desc";
}
j.furniturePrototype = WorldController.Instance.world.furniturePrototypes[furnitureType];
for (int x_off = t.X; x_off < (t.X + WorldController.Instance.world.furniturePrototypes[furnitureType].Width); x_off++)
{
for (int y_off = t.Y; y_off < (t.Y + WorldController.Instance.world.furniturePrototypes[furnitureType].Height); y_off++)
{
// FIXME: I don't like having to manually and explicitly set
// flags that preven conflicts. It's too easy to forget to set/clear them!
Tile offsetTile = WorldController.Instance.world.GetTileAt(x_off, y_off);
offsetTile.PendingBuildJob = j;
j.cbJobStopped += (theJob) =>
{
offsetTile.PendingBuildJob = null;
};
}
}
// Add the job to the queue
if (WorldController.Instance.devMode)
{
WorldController.Instance.world.PlaceFurniture(j.jobObjectType, j.tile);
}
else
{
WorldController.Instance.world.jobQueue.Enqueue(j);
}
}
}
else if (buildMode == BuildMode.FLOOR)
{
// We are in tile-changing mode.
////t.Type = buildModeTile;
TileType tileType = buildModeTile;
if (
t.Type != tileType &&
t.Furniture == null &&
t.PendingBuildJob == null &&
CanBuildTileTypeHere(t, tileType))
{
// This tile position is valid tile type
// Create a job for it to be build
Job j = TileType.GetConstructionJobPrototype(tileType);
j.tile = t;
// FIXME: I don't like having to manually and explicitly set
// flags that preven conflicts. It's too easy to forget to set/clear them!
t.PendingBuildJob = j;
j.cbJobStopped += (theJob) =>
{
theJob.tile.PendingBuildJob = null;
};
// Add the job to the queue
if (WorldController.Instance.devMode)
{
j.tile.Type = j.jobTileType;
}
else
{
WorldController.Instance.world.jobQueue.Enqueue(j);
}
}
}
else if (buildMode == BuildMode.DECONSTRUCT)
{
// TODO
if (t.Furniture != null)
{
// check if this is a WALL neighbouring a pressured and pressureless environ & if so bail
if (t.Furniture.HasTypeTag("Wall"))
{
Tile[] neighbors = t.GetNeighbours(); // diagOkay??
int pressuredNeighbors = 0;
int vacuumNeighbors = 0;
foreach (Tile neighbor in neighbors)
{
if (neighbor != null && neighbor.Room != null)
{
if ((neighbor.Room == World.current.GetOutsideRoom()) || MathUtilities.IsZero(neighbor.Room.GetTotalGasPressure()))
{
vacuumNeighbors++;
}
else
{
pressuredNeighbors++;
}
}
}
if (vacuumNeighbors > 0 && pressuredNeighbors > 0)
{
Debug.Log("Someone tried to deconstruct a wall between a pressurised room and vacuum!");
return;
}
}
t.Furniture.Deconstruct();
}
else if (t.PendingBuildJob != null)
{
t.PendingBuildJob.CancelJob();
}
}
else
{
Debug.LogError("UNIMPLEMENTED BUILD MODE");
}
}
public bool DoesBuildJobOverlapExistingBuildJob(Tile t, string furnitureType)
{
for (int x_off = t.X; x_off < (t.X + WorldController.Instance.world.furniturePrototypes[furnitureType].Width); x_off++)
{
for (int y_off = t.Y; y_off < (t.Y + WorldController.Instance.world.furniturePrototypes[furnitureType].Height); y_off++)
{
if (WorldController.Instance.world.GetTileAt(x_off, y_off).PendingBuildJob != null)
{
return true;
}
}
}
return false;
}
// Checks whether the given floor type is allowed to be built on the tile.
// TODO Export this kind of check to an XML/LUA file for easier modding of floor types.
private bool CanBuildTileTypeHere(Tile t, TileType tileType)
{
DynValue value = LuaUtilities.CallFunction(tileType.CanBuildHereLua, t);
if (value != null)
{
return value.Boolean;
}
else
{
Debug.ULogChannel("Lua", "Found no lua function " + tileType.CanBuildHereLua);
return false;
}
}
// Use this for initialization
private void Start()
{
}
}
| gpl-3.0 |
pajato/GameChat | app/src/main/java/com/pajato/android/gamechat/database/handler/ProfileGroupChangeHandler.java | 2680 | /*
* Copyright (C) 2016 Pajato Technologies LLC.
*
* This file is part of Pajato GameChat.
* GameChat 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.
* GameChat 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 GameChat. If not,
* see http://www.gnu.org/licenses
*/
package com.pajato.android.gamechat.database.handler;
import android.support.annotation.NonNull;
import android.util.Log;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.ValueEventListener;
import com.pajato.android.gamechat.chat.model.Group;
import com.pajato.android.gamechat.event.AppEventManager;
import com.pajato.android.gamechat.event.ChatListChangeEvent;
import com.pajato.android.gamechat.event.ProfileGroupChangeEvent;
/**
* Provide a class to handle changes to a room profile.
*
* @author Paul Michael Reilly
*/
public class ProfileGroupChangeHandler extends DatabaseEventHandler implements ValueEventListener {
// Private instance constants.
/** The logcat TAG. */
private final String TAG = ProfileGroupChangeHandler.class.getSimpleName();
// Public constructors.
/** Build a handler with the given name, path and key. */
public ProfileGroupChangeHandler(final String name, final String path, final String key) {
super(name, path, key);
}
/** Get the current generic profile. */
@Override public void onDataChange(@NonNull final DataSnapshot dataSnapshot) {
// Ensure that some data exists.
if (dataSnapshot.exists()) {
// There is data. Publish the group profile to the app.
Group group = dataSnapshot.getValue(Group.class);
AppEventManager.instance.post(new ProfileGroupChangeEvent(key, group));
AppEventManager.instance.post(new ChatListChangeEvent());
} else {
Log.e(TAG, "Invalid key. No value returned.");
}
}
/** Deal with a canceled event by logging it. */
@Override public void onCancelled(DatabaseError error) {
// Failed to read value
String message = String.format("Failed to read value at path: %s", path);
Log.w(TAG, message, error.toException());
}
}
| gpl-3.0 |
starlays/My-library | src/layout.php | 1524 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" type="text/css" href="style.css" />
<title><?php echo $active_page_title; ?></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<noscript>Aceasta pagina are nevoie de java pentru a beneficia de functionalitatea completa</noscript>
<div id="wrapper">
<div id="picture">
<a href="<?php ?>"><image src="images/my-library.png" title="My library" alt="My library logo"></a>
</div>
<div id="header">
<?php echo build_menu($active_page, $menu_items, 1, 'menu'); ?>
</div>
<div id="user-area">
<?php
echo build_menu($active_page, $menu_items, 2, 'menu');
echo build_greetings('greetings');
?>
</div>
<div id="books-wrapper">
<?php
if(check_file($menu_items[$active_page]['content_VL'],__MODULES__.$active_page.D_S)) {
include (__MODULES__.$active_page.D_S.$menu_items[$active_page]['content_VL']);
}
else {
echo sprintf('Error: %s page content is missing! Contact website administrator.', $active_page);
}
if(isset($errors)) {
foreach($errors as $error) {
echo sprintf('Error: %s', $error);
}
}
?>
</div>
</div>
<div id="footer">
here goes copyright info
</div>
</body>
</html>
| gpl-3.0 |
1412chen/potentialPack | Potential_CosineAngle.cpp | 991 | #include "Potential_CosineAngle.h"
#include "Math_Triangular.h"
#include <cmath>
using namespace Angle_Namespace;
Potential_CosineAngle::Potential_CosineAngle (
double k,
unsigned m,
double delta
) noexcept :
m_k( k ),
m_m( m ),
m_delta( delta )
{}
double
Potential_CosineAngle::ObjectiveFunction (
double cosTheta,
double /*rij*/,
double /*rik*/
) const noexcept
{
return m_k*(1.+CosNTheta_delta(m_m, cosTheta, m_delta));
}
_1stDerivative_t
Potential_CosineAngle::_1stDerivative (
double cosTheta,
double /*rij*/,
double /*rik*/
) const noexcept
{
_1stDerivative_t _1stDeri;
_1stDeri.fill(0.);
_1stDeri[DCosTheta] = m_k*_1stDCosNTheta_delta(m_m, cosTheta, m_delta);
return _1stDeri;
}
_2ndDerivative_t
Potential_CosineAngle::_2ndDerivative (
double cosTheta,
double /*rij*/,
double /*rik*/
) const noexcept
{
_2ndDerivative_t _2ndDeri;
_2ndDeri.fill(0.);
_2ndDeri[DCosTheta_DCosTheta] = m_k*_2ndDCosNTheta_delta(m_m, cosTheta, m_delta);
return _2ndDeri;
}
| gpl-3.0 |
mbeckersys/MavLogAnalyzer | src/mavplot.cpp | 32394 | /**
* @file mavplot.cpp
* @brief Custom plot widget based on Qwt.
* @author Martin Becker <[email protected]>
* @date 20.04.2014
This file is part of MavLogAnalyzer, Copyright 2014 by Martin Becker.
MavLogAnalyzer 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 <vector>
#include <sstream>
#include <QMessageBox>
#include <qwt_math.h>
#include <qwt_scale_engine.h>
#include <qwt_symbol.h>
#include <qwt_plot_grid.h>
#include <qwt_plot_marker.h>
#include <qwt_plot_curve.h>
#include <qwt_legend.h>
#include <qwt_text.h>
#include <qwt_color_map.h>
#include <qwt_scale_draw.h>
#include <qwt_scale_widget.h>
#include <QTime>
#include <qmath.h>
#include "mavplot.h"
#include "data_timeseries.h"
#include "data_event.h"
#include "dialogdatadetails.h"
using namespace std;
/**
* @brief labels at x axis as human-readable time
*/
class HumanReadableTime: public QwtScaleDraw {
public:
HumanReadableTime(): QwtScaleDraw() { }
// just override the label formatting
virtual QwtText label(double v_sec) const {
// isolate only hh:mm:ss:zzzz
unsigned long epoch_msec = round(v_sec*1000);
QDateTime qdt = QDateTime::fromMSecsSinceEpoch(epoch_msec);
QTime daytime(qdt.time());
return daytime.toString("hh:mm:ss.zzz");
}
};
QString MavPlot::getReadableTime(double timeval) const {
QwtText txt = axisScaleDraw(QwtPlot::xBottom)->label(timeval);
return QString(txt.text());
}
unsigned int MavPlot::exportCsv(const std::string&filename, bool /* onlyview -> ignored for now*/) {
unsigned int n_series = 0;
//std::ofstream fout(filename.c_str());
for (dataplotmap::iterator it_series = _series.begin(); it_series != _series.end(); ++it_series) {
const Data*const d = it_series->first;
if (d) {
d->export_csv(filename + "_" + d->get_name() + ".csv");
n_series++;
}
}
for (annotationsmap::iterator it_annot = _annotations.begin(); it_annot != _annotations.end(); ++it_annot) {
const Data*const d = it_annot->first;
if (d) {
d->export_csv(filename + "_" + d->get_name() + ".csv");
n_series++;
}
}
//fout.close();
return n_series;
}
void MavPlot::apply_print_colors(bool yes) {
if (yes && !_havePrintColors) {
const QColor printcol = QColor(0,0,0); // default color: black
/*******************
* ENABLE PRINT COLS
*******************/
// title
QwtText plottitle = title();
_col_title_screen = plottitle.color();
plottitle.setColor(printcol);
setTitle(plottitle);
// all legend entries ->
for (dataplotmap::iterator d = _series.begin(); d != _series.end(); ++d) {
QWT_ABSTRACT_SERIESITEM * s = d->second;
if (!s) continue;
if (d == _series.begin()) {
_col_legend_screen = s->title().color(); // save color of first legend text
}
// thicker lines for all
QwtPlotCurve * const q = dynamic_cast<QwtPlotCurve * const>(s);
if (q) {
QPen p = q->pen();
p.setWidth(PLOT_LINE_WIDTH);
p.setCosmetic(true);
q->setPen(p);
}
// text of legend -> black
QwtText title = s->title();
title.setColor(printcol);
s->setTitle(title);
}
// axes
_pal_axis_screen = axisWidget(QwtPlot::xBottom)->palette();
QPalette pal_print;
pal_print.setColor(QPalette::WindowText, printcol);
pal_print.setColor(QPalette::Text, printcol);
axisWidget(QwtPlot::xBottom)->setPalette(pal_print);
axisWidget(QwtPlot::yLeft)->setPalette(pal_print);
} else {
if (_havePrintColors) {
/*******************
* UNDO
*******************/
// title
QwtText plottitle = title();
plottitle.setColor(_col_title_screen);
setTitle(plottitle);
// all legend entries ->
for (dataplotmap::iterator d = _series.begin(); d != _series.end(); ++d) {
QWT_ABSTRACT_SERIESITEM * s = d->second;
if (!s) continue;
// thinner lines for all
QwtPlotCurve * const q = dynamic_cast<QwtPlotCurve * const>(s);
if (q) {
QPen p = q->pen();
p.setWidth(1);
p.setCosmetic(false);
q->setPen(p);
}
// restore legend text color
QwtText title = s->title();
title.setColor(_col_legend_screen);
s->setTitle(title);
}
// axes
axisWidget(QwtPlot::xBottom)->setPalette(_pal_axis_screen);
axisWidget(QwtPlot::yLeft)->setPalette(_pal_axis_screen);
}
}
_havePrintColors = yes;
}
void MavPlot::_updateDataBounds () {
bool first = true;
QRectF allrect;
for (dataplotmap::const_iterator s = _series.begin(); s != _series.end(); ++s) {
const QWT_ABSTRACT_SERIESITEM * const that = s->second;
// FIXME: now we can only do curves
const QwtPlotCurve * const q = dynamic_cast<const QwtPlotCurve * const>(that);
if (q) {
QRectF rect = q->boundingRect();
if (first) {
first=false;
allrect = rect;
} else {
#if (QT_VERSION > QT_VERSION_CHECK(5,0,0))
allrect = allrect.united(rect);
#else
allrect = allrect.unite(rect);
#endif
}
}
}
_databounds = allrect;
}
// for Qwt >= 6.1
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
void MavPlot::legendClickedNew(const QVariant& q, int /*i*/) {
//obtain QwtPlotItem and then delegate to legendClicked().
#if (QWT_VERSION < QWT_VERSION_CHECK(6,1,0))
return;
#else
QwtPlotItem*pi = infoToItem(q);
if (!pi) return;
legendClicked(pi);
#endif
}
#pragma GCC diagnostic pop
void MavPlot::legendClicked(QwtPlotItem*item) {
// see if it is seriesitem...only these react
QWT_ABSTRACT_SERIESITEM * si = dynamic_cast<QWT_ABSTRACT_SERIESITEM *>(item);
if (si) {
// look up the data behind it the series
/*
* FIXME: for now we do an exhaustive search for the key (Data), given the value (si)
* if it gets too slow one day, consider implementing a reverse map
*/
for (dataplotmap::const_iterator it = _series.begin(); it != _series.end(); ++it) {
if (it->second == si) {
const Data*const d = it->first;
QWT_ABSTRACT_SERIESITEM * const s = it->second;
// open up a dialog with details. this dialog also allows to delete data from plot.
DialogDataDetails*dialog = new DialogDataDetails(d, s, _model);
connect(dialog, SIGNAL(removeDataFromPlot(Data*const)), SLOT(onRemoveData(Data*const)));
dialog->show();
disconnect(this, SLOT(onRemoveData(Data*const)));
return;
}
}
}
// now it is an annotation
for (annotationsmap::const_iterator it = _annotations.begin(); it != _annotations.end(); ++it) {
if (it->second->front() == item) {
const Data*const d = it->first;
vector<QwtPlotItem*> *s = it->second;
// open up a dialog with details. this dialog also allows to delete data from plot.
DialogDataDetails*dialog = new DialogDataDetails(d, s, _model);
connect(dialog, SIGNAL(removeDataFromPlot(Data*const)), SLOT(onRemoveData(Data*const)));
dialog->show();
disconnect(this, SLOT(onRemoveData(Data*const)));
return;
}
}
qDebug() << "Weird...cannot find associated data for legend item";
return;
}
bool MavPlot::_removeData(const Data *const d) {
_model.model_remove(d);
#if 1
// look up whether data has series
dataplotmap::iterator it_series = _series.find(d);
if (it_series != _series.end()) {
// yes -> remove
QWT_ABSTRACT_SERIESITEM *s = dynamic_cast<QWT_ABSTRACT_SERIESITEM *>(it_series->second);
if (s) {
delete s; // that should do it
}
_series.erase(it_series); // erase Data from annotations list
return true;
}
#else
QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
if (s) {
delete s;
_series.erase(TODO); // missing iterator here
return true;
}
#endif
// look up whether data has annotations
annotationsmap::iterator it_annot = _annotations.find(d);
if (it_annot != _annotations.end()) {
// yes -> remove
std::vector<QwtPlotItem*>*v = dynamic_cast<std::vector<QwtPlotItem*>* >(it_annot->second);
if (v) {
// free all annotations in the vector...
for (std::vector<QwtPlotItem*>::iterator it_vect = v->begin(); it_vect != v->end(); ++it_vect) {
delete *it_vect;
}
delete v; // free vector itself
}
_annotations.erase(it_annot); // erase Data from annotations list
return true;
}
return false;
}
void MavPlot::onRemoveData(const Data *const d) {
bool removed = _removeData(d);
// conditionally update the internal data and replot
if (removed) {
_updateDataBounds();
replot();
}
}
MavPlot::MavPlot(QWidget *parent) : QwtPlot(parent), _havePrintColors(false) {
setAutoReplot(false);
setTitle("MAV System Data Plot");
setCanvasBackground(QColor(Qt::darkGray));
// legend
QwtLegend *legend = new QwtLegend;
insertLegend(legend, QwtPlot::BottomLegend);
#if (QWT_VERSION < QWT_VERSION_CHECK(6,1,0))
legend->setItemMode(QwtLegend::ClickableItem);
connect(this, SIGNAL(legendClicked(QwtPlotItem*)), SLOT(legendClicked(QwtPlotItem*)));
#else
legend->setDefaultItemMode(QwtLegendData::Clickable);
connect(legend, SIGNAL(clicked(const QVariant&, int)), SLOT(legendClickedNew(const QVariant&, int)));
#endif
// grid
QwtPlotGrid *grid = new QwtPlotGrid;
grid->enableXMin(true);
#if (QWT_VERSION < QWT_VERSION_CHECK(6,1,0))
grid->setMajPen(QPen(Qt::gray, 0, Qt::DotLine));
grid->setMinPen(QPen(QColor(0x8, 0x8, 0x8), 0 , Qt::DotLine));
#else
grid->setMajorPen(QPen(Qt::gray, 0, Qt::DotLine));
grid->setMinorPen(QPen(QColor(0x8, 0x8, 0x8), 0 , Qt::DotLine));
#endif
grid->attach(this);
// axes
//enableAxis(QwtPlot::yRight);
setAxisTitle(QwtPlot::xBottom, "time");
setAxisScaleDraw(QwtPlot::xBottom, new HumanReadableTime()); // no need to de-alloc or store, plot does it
// A-B markers
for (int i=0; i<2; i++) {
_user_markers[i].setLineStyle(QwtPlotMarker::VLine);
_user_markers[i].setLabelAlignment(Qt::AlignRight | Qt::AlignBottom);
_user_markers[i].setLinePen(QPen(QColor(255, 140, 0), 0, Qt::SolidLine));
_user_markers_visible[i] = false;
}
_user_markers[0].setLabel(QwtText("A"));
_user_markers[1].setLabel(QwtText("B"));
// data marker
_data_marker.setLineStyle(QwtPlotMarker::VLine);
_data_marker.setLinePen(QPen(QColor(255, 160, 47), 2, Qt::SolidLine));
_data_marker.setLabel(QwtText("data"));
_data_marker.setLabelAlignment(Qt::AlignTop | Qt::AlignRight);
_data_marker_visible = false;
_data_marker.setZ(9999); // higher value -> paint on top of everything else
setAutoReplot(true);
}
MavPlot::~MavPlot() {
// TODO: a lot of cleanup!!!
}
/**
* @brief function turning any data into double...it may fail.
*/
template <typename CT>
bool MavPlot::_convert2double(CT in, double &ret, double scale) {
ret = ((double) in)*scale;
return true;
}
QColor MavPlot::_suggestColor(unsigned int plotnumber) {
const QList<QColor> cols = QList<QColor>() << QColor(Qt::lightGray) << QColor(Qt::red) << QColor(Qt::green) << QColor(Qt::cyan) << QColor(Qt::yellow) << QColor(Qt::magenta);
unsigned index = plotnumber % cols.size();
return cols[index];
}
/**
* @brief MavPlot::_add_data_event
* @param generic plotting function for events
* @return ptr to plotseries if recognized data, else false
*/
template <typename ET>
std::vector<QwtPlotItem*>* MavPlot::_add_data_event(const DataEvent<ET> * data, unsigned int plotnumber /* used for colors etc */) {
vector <QwtPlotItem*> * markers = new vector <QwtPlotItem*>;
if (!markers) {
qDebug() << "Error allocating memory for an event series";
return NULL;
}
const vector<double> vt = data->get_time();
const vector<ET> vd = data->get_data();
// relative time -> absolute time
double t_datastart = data->get_epoch_datastart()/1E6;
for (unsigned int k=0; k<data->size(); k++) {
QwtPlotMarker * d_marker = new QwtPlotMarker();
if (!d_marker) {
qDebug() << "Error allocating memory for a marker";
continue;
}
d_marker->setLineStyle(QwtPlotMarker::VLine);
d_marker->setLabelAlignment(Qt::AlignRight | Qt::AlignBottom);
d_marker->setLinePen(QPen(_suggestColor(plotnumber), 0, Qt::DashDotLine));
//d_marker->setSymbol( new QwtSymbol(QwtSymbol::Diamond, QColor(Qt::yellow), QColor(Qt::green), QSize(7,7)));
d_marker->setValue(vt[k] + t_datastart, 0.0);
d_marker->setLabelOrientation(Qt::Vertical);
// try to set label from data
stringstream ss;
ss << vd[k];
QString label(ss.str().c_str()); // that relies on QString to be cool and do some clever conversion
d_marker->setLabel(QwtText(label));
// --
QwtPlotItem*item = dynamic_cast<QwtPlotItem*>(d_marker);
if (!item) {
delete d_marker;
return NULL;
}
markers->push_back(item);
d_marker->attach(this);
// add legend entry for first
if (markers->size()==1) {
d_marker->setTitle(QString::fromStdString(data->get_name()));
d_marker->setItemAttribute(QwtPlotItem::Legend);
}
}
return markers;
}
/**
* @brief MavPlot::_add_data_timeseries
* @param generic plotting functin for timeseries
* @return ptr to plotseries if recognized data, else false
*/
template <typename ST>
QWT_ABSTRACT_SERIESITEM * MavPlot::_add_data_timeseries(const DataTimeseries<ST> * data, unsigned int plotnumber /* used for colors etc */) {
/*
* so we have a timeseries of type ST. We need to "translate" it for the plot, and then add it.
* One problem is, that Qwt cannot plot double against float...so we need to "convert" every-
* thing to double here.
*/
QVector<double> xdata, ydata;
if (!data2xyvect(data, xdata, ydata)) {
return NULL;
}
QwtPlotCurve *curve = new QwtPlotCurve(QString().fromStdString(data->get_name()));
curve->setRenderHint(QwtPlotItem::RenderAntialiased);
curve->setPen(QPen(_suggestColor(plotnumber))); // FIXME: offer choices
curve->setLegendAttribute(QwtPlotCurve::LegendShowLine);
curve->setSamples(xdata, ydata); // makes a deep copy
curve->attach(this);
return dynamic_cast<QWT_ABSTRACT_SERIESITEM *>(curve);
}
std::vector<QwtPlotItem*>* MavPlot::_branch_datatype_annotation(const Data* data, unsigned int plotnumber /* used for colors etc */) {
const DataEvent<bool> * tseb = dynamic_cast<DataEvent<bool> const*>(data);
if (tseb) return _add_data_event<bool>(tseb, plotnumber);
const DataEvent<string> * tses = dynamic_cast<DataEvent<string> const*>(data);
if (tses) return _add_data_event<string>(tses, plotnumber);
// Add more here, if more data types
return NULL; // unrecognized data type
}
/**
* @brief MavPlot::_branch_datatype
* @param data
* @return ptr to plotseries if recognized data, else false
*/
// TODO: ugly stuff
QWT_ABSTRACT_SERIESITEM * MavPlot::_branch_datatype_series(const Data* data, unsigned int plotnumber /* used for colors etc */) {
const DataTimeseries<float> *const tsf = dynamic_cast<DataTimeseries<float> const*>(data);
if (tsf) return _add_data_timeseries<float>(tsf, plotnumber);
const DataTimeseries<double> * tsd = dynamic_cast<DataTimeseries<double> const*>(data);
if (tsd) return _add_data_timeseries<double>(tsd, plotnumber);
const DataTimeseries<unsigned int> * tsu = dynamic_cast<DataTimeseries<unsigned int> const*>(data);
if (tsu) return _add_data_timeseries<unsigned int>(tsu, plotnumber);
const DataTimeseries<int> * tsi = dynamic_cast<DataTimeseries<int> const*>(data);
if (tsi) return _add_data_timeseries<int>(tsi, plotnumber);
// Add more here, if more data types
return NULL; // unrecognized data type
}
// TODO: ugly stuff, same as _branch_datatype_series()
bool MavPlot::data2xyvect(const Data * data, QVector<double> & xdata, QVector<double> & ydata, double scale) {
const DataTimeseries<float> *const tsf = dynamic_cast<DataTimeseries<float> const*>(data);
if (tsf) return data2xyvect(tsf, xdata, ydata, scale);
const DataTimeseries<double> * tsd = dynamic_cast<DataTimeseries<double> const*>(data);
if (tsd) return data2xyvect(tsd, xdata, ydata, scale);
const DataTimeseries<unsigned int> * tsu = dynamic_cast<DataTimeseries<unsigned int> const*>(data);
if (tsu) return data2xyvect(tsu, xdata, ydata, scale);
const DataTimeseries<int> * tsi = dynamic_cast<DataTimeseries<int> const*>(data);
if (tsi) return data2xyvect(tsi, xdata, ydata, scale);
return false;
}
template <typename ST>
bool MavPlot::data2xyvect(const DataTimeseries<ST> * data, QVector<double> & xdata, QVector<double> & ydata, double scale) {
if (!data) return false;
xdata = QVector<double>::fromStdVector(data->get_time());
double t_datastart = data->get_epoch_datastart()/1E6;
for (QVector<double>::iterator it = xdata.begin(); it != xdata.end(); ++it ) {
// relative time -> absolute time
*it += t_datastart;
}
// data to double
for (typename vector<ST>::const_iterator it = data->get_data().begin(); it != data->get_data().end(); ++it) {
double ret;
if (!_convert2double(*it, ret, scale)) {
qDebug() << "ERROR: cannot convert given data type to double";
return false;
}
ydata.push_back(ret);
}
return true;
}
bool MavPlot::addData(const Data* data) {
// first check whether we already have it...
dataplotmap::iterator it = _series.find(data);
if (it != _series.end()) return true; // have it already
/* trick comes here. Data can be of different subtypes. First, find the type,
* then rewrite it for representation
*/
// try dynamic casts to find type, then branch
QWT_ABSTRACT_SERIESITEM *retS = _branch_datatype_series(data, _series.size());
if (retS) {
// remember the series
_series.insert(dataplotmap_pair(data, retS));
_model.model_append(data);
_updateDataBounds();
replot();
return true;
}
// was no seriesitem...try if it is an annotation.
std::vector<QwtPlotItem*>*retA = _branch_datatype_annotation(data, _annotations.size());
if (retA) {
// remember the series
_annotations.insert(annotationsmap_pair(data, retA));
_model.model_append(data);
// annotations do not influence data bounds
replot();
return true;
}
// now we really failed to recognize the type of the given data
return false;
}
void MavPlot::unset_markerData() {
_data_marker.detach();
_data_marker_visible = false;
replot();
updateStatusbar();
}
void MavPlot::rev_markerData(const Data *const d) {
if (!d || !_data_marker_visible) return;
const double markerx = _data_marker.xValue();
double markerx_next = markerx;
#if 0
/*******************
* SCAN IN Data
*******************/
#else
/*******************
* SCAN IN Plot
*******************/
// FIXME: heavy code clone from fwd_markerData()
QPointF xy;
QString value;
bool found = false;
// find out what it is, then scan for data
const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
if (s) {
// it's a series
const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
if (curve) {
for (unsigned int k=0; k<curve->dataSize(); k++) {
xy = curve->sample(k);
double x = xy.x();
if (x < markerx) {
found = true;
markerx_next = x;
value = QString::number(xy.y());
} else if (x > markerx) {
break;
}
}
}
}
// annotation
std::vector<QwtPlotItem*>*v = _get_annotations(d);
if (v && !found) {
// it's an annotation...we have to go through all of them
for (std::vector<QwtPlotItem*>::const_iterator it = v->begin(); it != v->end(); ++it) {
// only support marker annotations
const QwtPlotMarker * m = dynamic_cast<const QwtPlotMarker*>(*it);
if (m) {
// we only handle vertical markers
if (QwtPlotMarker::VLine == m->lineStyle()) {
xy = m->value();
double x = xy.x();
if (x < markerx) {
found = true;
markerx_next = x;
value = m->label().text();
} else if (x > markerx) {
break;
}
}
}
}
}
#endif
// set marker to found location
if (found) {
_data_marker_label = value;
_data_marker.setValue(markerx_next, 0);
replot();
}
updateStatusbar();
}
QWT_ABSTRACT_SERIESITEM *MavPlot::_get_series(const Data * const d) {
QWT_ABSTRACT_SERIESITEM *ret = NULL;
if (d) {
dataplotmap::iterator it_series = _series.find(d);
if (it_series != _series.end()) {
// data is series, get ptr
ret = dynamic_cast<QWT_ABSTRACT_SERIESITEM *>(it_series->second);
}
}
return ret;
}
std::vector<QwtPlotItem*>* MavPlot::_get_annotations(const Data * const d) {
std::vector<QwtPlotItem*>* ret = NULL;
if (d) {
annotationsmap::iterator it_annot = _annotations.find(d);
if (it_annot != _annotations.end()) {
// data is annotation
ret = dynamic_cast<std::vector<QwtPlotItem*>* >(it_annot->second);
}
}
return ret;
}
void MavPlot::setmin_markerData(const Data *const d) {
if (!d || !_data_marker_visible) return;
const double markerx = _data_marker.xValue();
double markerx_next = markerx;
#if 0
/*******************
* SCAN IN Data
*******************/
#else
/*******************
* SCAN IN Plot
*******************/
// FIXME: code clone from rev_markerData()
QPointF xy;
QString value;
bool found = false;
// find out what it is, then scan for data
const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
if (s) {
// it's a series
const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
if (curve) {
double minval = 0;
for (unsigned int k=0; k<curve->dataSize(); k++) {
QPointF xy = curve->sample(k);
if (k == 0 || (xy.y() < minval)) {
minval = xy.y();
markerx_next = xy.x();
found = true;
}
}
value = QString::number(minval);
}
}
#endif
// set marker to found location
if (found) {
_data_marker_label = value;
_data_marker.setValue(markerx_next, 0);
replot();
} else {
_data_marker_label = "";
}
updateStatusbar();
}
void MavPlot::setmax_markerData(const Data *const d) {
if (!d || !_data_marker_visible) return;
const double markerx = _data_marker.xValue();
double markerx_next = markerx;
#if 0
/*******************
* SCAN IN Data
*******************/
#else
/*******************
* SCAN IN Plot
*******************/
// FIXME: code clone from rev_markerData()
QPointF xy;
QString value;
bool found = false;
// find out what it is, then scan for data
const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
if (s) {
// it's a series
const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
if (curve) {
double maxval = 0;
for (unsigned int k=0; k<curve->dataSize(); k++) {
QPointF xy = curve->sample(k);
if (k == 0 || (xy.y() > maxval)) {
maxval = xy.y();
markerx_next = xy.x();
found = true;
}
}
value = QString::number(maxval);
}
}
#endif
// set marker to found location
if (found) {
_data_marker_label = value;
_data_marker.setValue(markerx_next, 0);
replot();
} else {
_data_marker_label = "";
}
updateStatusbar();
}
void MavPlot::fwd_markerData(const Data *const d) {
if (!d || !_data_marker_visible) return;
const double markerx = _data_marker.xValue();
double markerx_next = markerx;
#if 0
/*******************
* SCAN IN Data
*******************/
#else
/*******************
* SCAN IN Plot
*******************/
// FIXME: heavy code clone from rev_markerData()
QPointF xy;
QString value;
bool found = false;
// find out what it is, then scan for data
const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
if (s) {
// it's a series
const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
if (curve) {
for (unsigned int k=0; k<curve->dataSize(); k++) {
xy = curve->sample(k);
double x = xy.x();
if (x > markerx) {
found = true;
markerx_next = x;
value = QString::number(xy.y());
break;
}
}
}
}
// annotation
std::vector<QwtPlotItem*>*v = _get_annotations(d);
if (v && !found) {
// it's an annotation...we have to go through all of them
for (std::vector<QwtPlotItem*>::const_iterator it = v->begin(); it != v->end(); ++it) {
// only support marker annotations
const QwtPlotMarker * m = dynamic_cast<const QwtPlotMarker*>(*it);
if (m) {
// we only handle vertical markers
if (QwtPlotMarker::VLine == m->lineStyle()) {
xy = m->value();
double x = xy.x();
if (x > markerx) {
found = true;
markerx_next = x;
value = m->label().text();
break;
}
}
}
}
}
#endif
// set marker to found location
if (found) {
_data_marker_label = value;
_data_marker.setValue(markerx_next, 0);
replot();
}
updateStatusbar();
}
bool MavPlot::set_markerData(const Data *const d, unsigned long idx) {
if (!d ) return false;
if (idx >= d->size()) return false; // out of range
bool found = false;
double markerx = 0;
#if 0
/*******************
* SCAN IN Data
*******************/
#else
/*******************
* SCAN IN Plot
*******************/
// FIXME: heavy code clone from rev_markerData()
QPointF xy;
QString value;
// find out what it is, then scan for data
const QWT_ABSTRACT_SERIESITEM*s = _get_series(d);
if (s) {
// it's a series
const QwtPlotCurve *curve = dynamic_cast<const QwtPlotCurve *>(s);
if (curve) {
xy = curve->sample(idx);
markerx = xy.x();
value = QString::number(xy.y());
found = true;
}
}
// annotation
std::vector<QwtPlotItem*>*v = _get_annotations(d);
if (v && !found) {
// it's an annotation...we have to go through all of them
if (v->size() > idx) {
QwtPlotItem*tmp1 = (*v)[idx];
const QwtPlotMarker * m = dynamic_cast<const QwtPlotMarker*>(tmp1);
if (m) {
// we only handle vertical markers
if (QwtPlotMarker::VLine == m->lineStyle()) {
xy = m->value();
markerx = xy.x();
found = true;
value = m->label().text();
}
}
}
}
#endif
// set marker to found location
if (found) {
_data_marker_label = value;
_data_marker.setValue(markerx, 0);
if (!_data_marker_visible) {
_data_marker.attach(this);
_data_marker_visible = true;
}
replot();
}
updateStatusbar();
return found;
}
void MavPlot::set_markerData(double x) {
_data_marker.setValue(x, 0);
_data_marker.attach(this);
_data_marker_visible = true;
updateStatusbar();
replot();
}
void MavPlot::unset_markerA() {
_user_markers[0].detach();
_user_markers_visible[0] = false;
updateStatusbar();
replot();
}
void MavPlot::unset_markerB() {
_user_markers[1].detach();
_user_markers_visible[1] = false;
updateStatusbar();
replot();
}
void MavPlot::set_markerA(double x) {
_user_markers[0].setValue(x, 0);
_user_markers[0].attach(this);
_user_markers_visible[0] = true;
updateStatusbar();
replot();
}
void MavPlot::set_markerB(double x) {
_user_markers[1].setValue(x, 0);
_user_markers[1].attach(this);
_user_markers_visible[1] = true;
updateStatusbar();
replot();
}
void MavPlot::updateStatusbar(void) {
if (!_statusbar) return;
_statusbar->showMessage(verboseMarkers());
}
QString MavPlot::verboseMarkers() const {
QString desc;
if (_user_markers_visible[0]) {
desc += QString("A: ") + getReadableTime(_user_markers[0].value().x()) + " ";
}
if (_user_markers_visible[1]) {
desc += QString("B: ") + getReadableTime(_user_markers[1].value().x()) + " ";
}
if (_user_markers_visible[0] && _user_markers_visible[1]) {
desc += QString("difference B-A: %1").arg(_user_markers[1].value().x()-_user_markers[0].value().x()) + " ";
}
if (_data_marker_visible) {
desc += QString("data cursor at: ") + getReadableTime(_data_marker.value().x()) + ", value: " + _data_marker_label;
}
return desc;
}
void MavPlot::removeAllData() {
_model.model_clear();
// remove all series
for (dataplotmap::iterator it_series = _series.begin(); it_series != _series.end(); ++it_series) {
const Data*const d = it_series->first;
_removeData(d);
}
// remove all annotations
for (annotationsmap::iterator it_annot = _annotations.begin(); it_annot != _annotations.end(); ++it_annot) {
const Data*const d = it_annot->first;
_removeData(d);
}
_updateDataBounds();
replot();
}
| gpl-3.0 |
patrick246/tdesktop | Telegram/SourceFiles/media/view/media_clip_volume_controller.cpp | 3499 | /*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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.
It 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.
In addition, as a special exception, the copyright holders give permission
to link the code of portions of this program with the OpenSSL library.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014-2016 John Preston, https://desktop.telegram.org
*/
#include "stdafx.h"
#include "media/view/media_clip_volume_controller.h"
#include "styles/style_mediaview.h"
namespace Media {
namespace Clip {
VolumeController::VolumeController(QWidget *parent) : TWidget(parent) {
resize(st::mediaviewVolumeSize);
setCursor(style::cur_pointer);
setMouseTracking(true);
}
void VolumeController::setVolume(float64 volume) {
_volume = volume;
update();
}
void VolumeController::paintEvent(QPaintEvent *e) {
Painter p(this);
int32 top = st::mediaviewVolumeIconTop;
int32 left = (width() - st::mediaviewVolumeIcon.width()) / 2;
int32 mid = left + qRound(st::mediaviewVolumeIcon.width() * _volume);
int32 right = left + st::mediaviewVolumeIcon.width();
if (mid > left) {
auto over = _a_over.current(getms(), _over ? 1. : 0.);
p.setOpacity(over * st::mediaviewActiveOpacity + (1. - over) * st::mediaviewInactiveOpacity);
p.setClipRect(rtlrect(left, top, mid - left, st::mediaviewVolumeIcon.height(), width()));
st::mediaviewVolumeOnIcon.paint(p, QPoint(left, top), width());
}
if (right > mid) {
p.setClipRect(rtlrect(mid, top, right - mid, st::mediaviewVolumeIcon.height(), width()));
st::mediaviewVolumeIcon.paint(p, QPoint(left, top), width());
}
}
void VolumeController::mouseMoveEvent(QMouseEvent *e) {
if (_downCoord < 0) {
return;
}
int delta = e->pos().x() - _downCoord;
int left = (width() - st::mediaviewVolumeIcon.width()) / 2;
float64 startFrom = snap((_downCoord - left) / float64(st::mediaviewVolumeIcon.width()), 0., 1.);
float64 add = delta / float64(4 * st::mediaviewVolumeIcon.width());
auto newVolume = snap(startFrom + add, 0., 1.);
changeVolume(newVolume);
}
void VolumeController::mousePressEvent(QMouseEvent *e) {
_downCoord = snap(e->pos().x(), 0, width());
int left = (width() - st::mediaviewVolumeIcon.width()) / 2;
auto newVolume = snap((_downCoord - left) / float64(st::mediaviewVolumeIcon.width()), 0., 1.);
changeVolume(newVolume);
}
void VolumeController::changeVolume(float64 newVolume) {
if (newVolume != _volume) {
setVolume(newVolume);
emit volumeChanged(_volume);
}
}
void VolumeController::mouseReleaseEvent(QMouseEvent *e) {
_downCoord = -1;
}
void VolumeController::enterEvent(QEvent *e) {
setOver(true);
}
void VolumeController::leaveEvent(QEvent *e) {
setOver(false);
}
void VolumeController::setOver(bool over) {
if (_over == over) return;
_over = over;
auto from = _over ? 0. : 1., to = _over ? 1. : 0.;
START_ANIMATION(_a_over, func(this, &VolumeController::updateCallback), from, to, st::mediaviewOverDuration, anim::linear);
}
} // namespace Clip
} // namespace Media
| gpl-3.0 |
QiuShiqi/XiaoTian | Module/Form/ClientMainForm.java | 12703 | package Module.Form;
import javax.swing.*;
import javax.swing.plaf.basic.BasicListUI;
import java.awt.event.*;
import java.awt.*;
import java.util.Vector;
import java.util.HashMap;
import Module.*;
import Module.Base.*;
import Module.Data.*;
import Module.DirectUI.*;
import Module.User.*;
public class ClientMainForm extends BaseUI {
//数据
private HashMap<String, String> userPhotoList = new HashMap<String, String>(); //好友头像控件的容器
private DefaultListModel<String> userList = new DefaultListModel<String>(); //好友控件的容器
private Vector<Integer> userIDList = new Vector<Integer>(); //好友ID列表
private HashMap<Integer, Vector<RecordArray>> userRocordList = null; //聊天记录容
//控件
private JTextPane contentControl = new JTextPane();
private JScrollPane contentScrollControl = new JScrollPane(this.contentControl);
private JTextPane sendControl = new JTextPane();
private JScrollPane sendScrollControl = new JScrollPane(this.sendControl);
private SButtonControl submitControl = new SButtonControl(375, 425, 75, 23, "send-*.png"); //发送
private SButtonControl clearControl = new SButtonControl(290, 425, 75, 23, "clear-*.png"); //清空
private JList<String> userListControl = new JList<String>(userList);
private JScrollPane userListControlScrollControl = new JScrollPane(userListControl);
private SImageControl userPhotoControl = new SImageControl(460, 7, 60, 60, "photo.png");
private JLabel userNameControl = new JLabel("测试用户");
private SButtonControl searchButtonControl = new SButtonControl(465, 425, 75, 23, "search-*.png"); //查找
private SButtonControl aboutButtonControl = new SButtonControl(555, 425, 75, 23, "about2-*.png"); //关于
public ClientMainForm(int userID, String userName) {
//初始化客户端类
this.userModule = new Client(userID, userName);
this.pushRecord(); //聊天消息推送线程
this.pushFriend(); //好友请求推送线程
this.pushSystemType(); //消息推送推送线程
//窗体设置
this.setPosition(this, 640, 480);
this.initialize();
this.initializeUI(BaseModule.projectName, "client-main-title.png", "client-main-background.png");
this.titleControl.changeMinImages("title2-min-*.png");
this.titleControl.changeCloseImages("title2-close-*.png");
//获取数据库数据
HashMap<Integer, String> tmp = (HashMap<Integer, String>)userModule.listUser();
for(int index : tmp.keySet()){
this.userIDList.add(index); //记录好友id
this.userList.addElement(tmp.get(index));
this.userPhotoList.put(tmp.get(index), "photo.png");
}
this.userListControl.repaint();
//获取所有聊天记录
this.userRocordList = this.userModule.catchAllRecord();
//选中默认对话
if(this.userIDList.size() > 0){
this.userListControl.setSelectedIndex(0);
this.setTabShow(0);
}else{
this.submitControl.setEnabled(false);
}
}
private void initialize() {
//初始化控件
this.userlistControl();
this.usernameControl();
this.userPhotoControl();
this.contentControl();
this.sendControl();
this.submitControl();
this.clearControl();
this.searchButtonControl();
this.aboutButtonControl();
}
// 消息文本框
private void contentControl() {
this.contentControl.setEditable(false);
this.contentControl.setContentType("text/html");
this.contentControl.setBackground(new Color(253, 239, 243));
//new FixTextBug(contentControl);
this.setSize(contentScrollControl, 5, 0, 450, 300);
this.contentScrollControl.setBorder(null);
this.add(this.contentScrollControl);
}
// 发送文本框
private void sendControl() {
this.sendControl.setBackground(new Color(253, 239, 243));
//new FixTextBug(sendControl);
this.setSize(this.sendScrollControl, 5, 320, 450, 100);
this.sendScrollControl.setBorder(null);
this.add(this.sendScrollControl);
}
// 发送按钮
private void submitControl() {
this.add(this.submitControl);
this.submitControl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(submitControl.getEnabled()){
if(!sendControl.getText().equals("")){
int userID = indexToUserID();
userModule.sendMessage(userID, sendControl.getText());
sendControl.setText(""); //清空发送框
}
}
}
});
}
//清空按钮
private void clearControl() {
this.add(this.clearControl);
this.clearControl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
sendControl.setText("");
}
});
}
//好友列表
private void userlistControl(){
ListUI ui = new ListUI();
this.userListControl.setUI(ui);
this.userListControl.setCellRenderer(new JListRenderer());
this.userListControlScrollControl.setBorder(null);
this.userListControl.setBackground(new Color(253, 239, 243));
this.setSize(this.userListControlScrollControl, 456, 75, 183, 345);
this.add(this.userListControlScrollControl);
//控件事件
this.userListControl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
if(e.getButton() == MouseEvent.BUTTON1 && userIDList.size() > 0){
int index = userListControl.getSelectedIndex();
setTabShow(index); //切换tab
}
if(e.getButton() != MouseEvent.BUTTON1 && userIDList.size() > 0){
Object[] options = { "确定", "取消" };
int index = userListControl.getSelectedIndex();
String name = userListControl.getModel().getElementAt(index).toString();
int result = JOptionPane.showOptionDialog(null, "确定要将好友[" + name +"]移出列表吗?", "提示 - " + BaseModule.projectName, JOptionPane.YES_OPTION, 2, null, options, options[0]);
switch(result){
case 0: //确定
if(userModule.removeUser(indexToUserID())){
userRocordList.remove(indexToUserID());
userPhotoList.remove(name);
userList.removeElement(name);
userIDList.remove(index);
userListControl.repaint();
if(userIDList.size() > 0){
userListControl.setSelectedIndex(0);
setTabShow(0);
}else{
contentControl.setText("");
sendControl.setText("");
submitControl.setEnabled(false);
setTitle(BaseModule.projectName);
}
}else{
BaseModule.messageBox("遇到未知原因,请稍后再尝试!", -1);
}
break;
}
}
}
});
}
//好友列表控件重写
class JListRenderer extends DefaultListCellRenderer {
private Font font = new Font(Font.DIALOG, 0, 12);
public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
ListImageControl label = new ListImageControl(0, 0, 30, 30, "photo.png", value.toString());
if (isSelected) {
((ListUI)list.getUI()).setCellHeight(index, 46, 26);
label.changeSize(40, 40);
}else{
((ListUI)list.getUI()).setCellHeight(index, 26);
label.changeSize(20, 20);
}
return label;
}
}
class ListUI extends BasicListUI {
public ListUI() {
super();
cellHeights = new int[2];
}
public void setCellHeight(int index, int value, int defaultHeight) {
for (int i = 0; i < cellHeights.length; i++) {
cellHeights[i] = defaultHeight;
}
cellHeights[index] = value;
}
void setCellHeight(int index, int i) {
cellHeights[index] = i;
}
}
//用户信息
private void usernameControl(){
this.userNameControl.setText("<html><div style='color:white;'><b>" + this.userModule.getUserName() + "</b></div><html>");
this.setSize(this.userNameControl, 530, 0, 170, 25);
this.add(this.userNameControl);
}
//用户头像
private void userPhotoControl(){
this.add(this.userPhotoControl);
SImageControl box = new SImageControl(455, 0, 184, 75, "userContent.png");
this.add(box);
}
//tab处理
private void setTabShow(int index){
String name = this.userListControl.getModel().getElementAt(index).toString();
this.setTitle(BaseModule.projectName + " - 与" + name + "聊天中");
if(this.userRocordList != null){
String box = "";
int userID = this.userIDList.get(index);
Vector<RecordArray> recordArray = this.userRocordList.get(userID);
if(recordArray != null){
String source = null;
for(RecordArray record : recordArray){
if(record.source != this.userModule.getUserID()){
source = name;
}else{
source = this.userModule.getUserName();
}
box += "<div style='font-size:10px;font-family:宋体;'><div style='color:blue;padding-bottom:5px;'><span>" + source + "(</span><span style='color:#0072c1;text-decoration:underline;'>" + (10000 + record.source) + "</span><span>) " + record.time + "</span></div><div<div style='color:black;padding-bottom:5px;'>" + record.content + "</div></div>";
}
this.contentControl.setText(box);
this.contentControl.setCaretPosition(this.contentControl.getDocument().getLength());
}else{
BaseModule.messageBox("a", -1);
}
}
}
//由ID转变为索引
public int indexToUserID(){
int index = this.userListControl.getSelectedIndex();
return this.userIDList.get(index);
}
//由索引转变为ID
public int userIDToIndex(int userID){
for(int i = 0; i < this.userIDList.size(); i++){
if(this.userIDList.get(i) == userID){
return i;
}
}
return -1;
}
//搜索按钮
private void searchButtonControl(){
this.add(this.searchButtonControl);
//控件事件
this.searchButtonControl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
new SearchForm(userModule.getUserID(), userModule.getUserName());
}
});
}
protected void aboutButtonControl(){
this.add(this.aboutButtonControl);
//控件事件
this.aboutButtonControl.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
aboutForm();
}
});
}
protected void close(){
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
//添加聊天记录
/*
public void addRecord(int userID){
RecordArray tmp = this.client.catchRecord(userID);
this.userRocordList.get(userID).add(tmp);
this.setTabShow(this.userIDToIndex(userID));
}
*/
public void addRecord(int id){
RecordArray tmp = this.userModule.pushRecord(id);
if(tmp != null){
int index = tmp.source;
if(tmp.target != this.userModule.getUserID()){
index = tmp.target;
}
try{ //以防单向好友发送消息
this.userRocordList.get(index).add(tmp);
index = this.userIDToIndex(index);
this.userListControl.setSelectedIndex(index);
this.setTabShow(index);
}catch(Exception e){
}
}
this.pushRecord(); //递归调用
}
public void addFriend(int id){
String name = (String)this.userModule.pushFriend(id);
this.userIDList.add(id); //记录好友id
this.userList.addElement(name);
this.userPhotoList.put(name, "photo.png");
this.userRocordList.put(new Integer(id), new Vector<RecordArray>());
this.userListControl.repaint();
if(this.userIDList.size() > 0){
this.submitControl.setEnabled(true);
this.userListControl.setSelectedIndex(0);
this.setTabShow(0);
}
BaseModule.messageBox("新好友[" + name + "]已被添加到好友列表!", 1);
this.pushFriend(); //递归调用
}
public void systemType(int id){
String tmp = this.userModule.pushSystemType(id);
//逐出服务器
if(tmp.equals("offline")){
BaseModule.messageBox("目前使用的帐号被服务器强制下线!", -1);
System.exit(0);
}
BaseModule.messageBox(tmp, 1);
this.pushSystemType(); //递归调用
}
private void pushRecord(){
(new ServerPush(this.userModule, this, 1)).start();
}
private void pushFriend(){
(new ServerPush(this.userModule, this, 2)).start();
}
private void pushSystemType(){
(new ServerPush(this.userModule, this, 3)).start();
}
}
| gpl-3.0 |
dskleingeld/HomeAutomation | pi_Cpp/lamps/main.cpp | 338 | #include <iostream> //cout
#include "lamps.h"
int main(){
Lamps* lamps = new Lamps;
// lamps->off();
// lamps->on();
lamps->off(lmp::BATHROOM);
lamps->on(lmp::BATHROOM);
while(1){
lamps->off(lmp::BATHROOM);
lamps->on(lmp::BATHROOM);
}
//lamps.setState(lmp::KITCHEN, "{\"on\": true, \"bri\": 200, \"transitiontime\": 0}");
}
| gpl-3.0 |
hammock-dev/hammock | src/cz/krejciadam/hammock/FileIOManager.java | 61614 | /*
* Class handles most of I/O work with files
*/
package cz.krejciadam.hammock;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
/**
*
* @author Adam Krejci
*/
public class FileIOManager {
/**
* Loads a scoring matrix. Matrix uses standard amino acid ordering (defined
* in UniqueSequence). Input file must contain scoring matrix in BioJava
* format.
*
* @param matrixFilePath path to file with scoring matrix in BioJava format
* @return two dimensional array representing scoring matrix.
* @throws IOException
* @throws HammockException
*/
public static int[][] loadScoringMatrix(String matrixFilePath) throws IOException, HammockException {
int[][] scoringMatrix = new int[24][24];
try (BufferedReader reader = new BufferedReader(new FileReader(new File(matrixFilePath)))) {
String line;
int lineCounter = 0;
while ((line = reader.readLine()) != null) {
if (line.startsWith("\\s")) {
if (!(line.replaceAll("\\s+", "").equals(new String(UniqueSequence.getAminoAcidsAndSpecials())))) {
throw new FileFormatException("Error in scoring matrix file: " + matrixFilePath + ". Scoring"
+ "matrix should have exactly this order of rows/columns: " + new String(UniqueSequence.getAminoAcidsAndSpecials()));
}
}
if (!(line.startsWith("#") || line.startsWith(" ") || line.startsWith("\t"))) { //skip comments and AA header line
String[] splitLine = line.split("\\s+"); //split on any number of whitespace characters
if (splitLine.length != 25) {
throw new FileFormatException("Error in scoring matrix file: " + matrixFilePath + ". Scoring matrix "
+ "should always have 24 columns (plus 1 column describing AAs).");
}
for (int i = 1; i < splitLine.length; i++) { //from 1 - first is AA name.
scoringMatrix[lineCounter][i - 1] = Integer.parseInt(splitLine[i]);
}
lineCounter++;
if (lineCounter > 24) {
throw new FileFormatException("Error in scoring matrix file: " + matrixFilePath + ". Scoring matrix "
+ "should always have 24 rows (plus 1 column describing AAs).");
}
}
}
} catch (ArrayIndexOutOfBoundsException e) {
throw new FileFormatException("Error in scoring matrix file: " + matrixFilePath + ". Scoring matrix "
+ "should always have 24 rows (plus 1 column describing AAs).");
}
return scoringMatrix;
}
/**
* Loads frequency matrix of background frequencies for KLD calculation
*
* @param path A path to the matrix
* @return The frequency matrix
* @throws IOException
*/
public static Map<Character, Map<Character, Double>> loadFrequencyMatrix(String path) throws IOException {
Map<Character, Map<Character, Double>> result = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))) {
String line;
List<Character> aaList = new ArrayList<>();
int lineIndex = 0;
while ((line = reader.readLine()) != null) {
if (line.startsWith("#")) {
continue;
}
if (line.matches("^[A-Z]+.*")) { //start line
for (String s : line.split("\t")) {
aaList.add(s.charAt(0));
}
continue;
}
String[] numberSplit = line.split("\t");
Map<Character, Double> aaMap = new HashMap<>();
for (int i = 0; i < numberSplit.length; i++) {
aaMap.put(aaList.get(i), Double.parseDouble(numberSplit[i]));
}
result.put(aaList.get(lineIndex), aaMap);
lineIndex++;
}
} catch (IOException e) {
throw new IOException(e);
}
return (result);
}
/**
* Loads a matrix of empirical probabilities
*
* @param path
* @return
* @throws IOException
*/
public static Map<Double, Double> loadEmpiricalProbabs(String path) throws IOException {
Map<Double, Double> result = new HashMap<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))) {
String line;
while ((line = reader.readLine()) != null) {
String[] splitLine = line.split("\t");
Double score = Double.parseDouble(splitLine[0]);
Double probab = Double.parseDouble(splitLine[1]);
result.put(score, probab);
}
} catch (IOException e) {
throw new IOException(e);
}
return (result);
}
/**
* /**
* Loads a fasta file. Retains input order (of first occurrence of a
* seuquence) Each seuqence must have a header line starting with ">".
* Header may contain sequence label in format: ">any_text|count|label". To
* each sequence not having label in the header, default label "no_label" is
* assigned. Sequences in fasta file need not to be unique. Multi-line fasta
* files are not supported.
*
* @param fileName Path to file to be loaded
* @return List of UniqueSequence objects parsed in the input order (of
* first occurrence)
* @throws IOException
* @throws FileNotFoundException
* @throws FileFormatException
*/
public static List<UniqueSequence> loadUniqueSequencesFromFasta(String fileName) throws IOException, FileNotFoundException, FileFormatException {
Map<String, Map<String, Integer>> sequenceMap = new LinkedHashMap<>();
String line;
String sequence = "";
String label = null;
Integer count = null;
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
while ((line = reader.readLine()) != null) {
if (line.startsWith(">")) {
if (sequence.length() > 0) { //add the previous sequence
Map<String, Integer> labelsMap = updateLabelsMap(sequenceMap.get(sequence), label, count);
sequenceMap.put(sequence, labelsMap);
sequence = "";
}
String[] splitLine = line.trim().substring(1).split("\\|");
if (splitLine.length >= 2) {
count = Integer.decode(splitLine[1].trim());
if (count < 1) {
throw new FileFormatException("Error while loading input file. Fasta header defines sequence count lower than 1.");
}
} else {
count = 1;
}
if (splitLine.length >= 3) {
label = splitLine[2];
} else {
label = "no_label";
}
} else {
if (label == null || count == null) {
throw new FileFormatException("Error. Incorrect fasta format. Maybe header or sequence line missing?");
}
sequence = sequence.concat(line.trim());
}
}//Add the last sequence:
Map<String, Integer> labelsMap = updateLabelsMap(sequenceMap.get(sequence), label, count);
sequenceMap.put(sequence, labelsMap);
}
List<UniqueSequence> result = new ArrayList<>();
for(Map.Entry<String, Map<String, Integer>> entry : sequenceMap.entrySet()){
result.add(new UniqueSequence(entry.getKey(), entry.getValue()));
}
return (result);
}
private static Map<String, Integer> updateLabelsMap(Map<String, Integer> labelsMap, String label, int count) {
if (labelsMap == null) {
labelsMap = new HashMap<>();
labelsMap.put(label, count);
} else {
Integer oldCount = labelsMap.get(label);
if (oldCount == null) {
oldCount = 0;
}
labelsMap.put(label, oldCount + count);
}
return (labelsMap);
}
/**
* Loads UniqueSequence from a .csv table. Table must contain header
* specifying full list of labels.
*
* @param fileName
* @return
* @throws IOException
* @throws cz.krejciadam.hammock.FileFormatException if wrong amino acid letter is used
*/
public static List<UniqueSequence> loadUniqueSequencesFromTable(String fileName) throws IOException, FileFormatException {
List<UniqueSequence> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
String line = reader.readLine(); //header line
String[] headerLine = line.split(Hammock.CSV_SEPARATOR);
List<String> labels = new ArrayList<>();
for (int i = 1; i < headerLine.length; i++) {
labels.add(headerLine[i]);
}
while ((line = reader.readLine()) != null) {
List<String> splitLine = Arrays.asList(line.split(Hammock.CSV_SEPARATOR));
result.add(lineToUniqueSequence(splitLine.get(0), splitLine.subList(1, splitLine.size()), labels));
}
} catch (IOException e) {
throw new IOException(e);
}
return result;
}
private static UniqueSequence lineToUniqueSequence(String sequence, List<String> labelsLine, List<String> labels) throws FileFormatException {
Map<String, Integer> labelsMap = new HashMap<>();
for (int i = 0; i < labelsLine.size(); i++) {
int value = Integer.decode(labelsLine.get(i));
if (value != 0) {
labelsMap.put(labels.get(i), value);
}
}
return (new UniqueSequence(sequence, labelsMap));
}
/**
* For specified clusters, loads their alignments from a file, saves them as
* temporal files and marks the clusters as having MSAs. If some clusters
* are missing or different in size in the file, a FileFormatException is
* thrown.
*
* @param clusters Clusters whose alignments are to be loaded
* @param fileName Path to the file with saved clusters
* @return
* @throws FileFormatException
* @throws IOException
*/
public static List<Cluster> loadClusterAlignmentsFromFile(List<Cluster> clusters, String fileName) throws FileFormatException, IOException {
List<Cluster> result = new ArrayList<>();
Set<Integer> ids = new HashSet<>();
for (Cluster cl : clusters) {
ids.add(cl.getId());
}
List<Cluster> loadedClusters = loadClusterDetailsFromCsv(fileName, ids, false);
Map<Integer, Cluster> loadedClustersMap = new HashMap<>();
for (Cluster cl : loadedClusters) {
loadedClustersMap.put(cl.getId(), cl);
}
for (Cluster cl : clusters) {
if (cl.size() != loadedClustersMap.get(cl.getId()).size()) {
throw new IOException("Cluster " + cl.getId() + " has different size than the number of alignment lines in file " + fileName);
}
result.add(loadedClustersMap.get(cl.getId()));
}
return result;
}
/**
* Loads clusters from a .csv file. The file may or may not contain
* alignment column. Clusters will be loaded with or without alignments,
* accordingly.
*
* @param fileName A path to the clusters' csv file.
* @param loadAlignments Should alignments be loaded from the file?
* @return
* @throws FileFormatException
* @throws IOException
*/
public static List<Cluster> loadClustersFromCsv(String fileName, boolean loadAlignments) throws FileFormatException, IOException {
return (loadClusterDetailsFromCsv(fileName, null, loadAlignments));
}
private static List<Cluster> loadClusterDetailsFromCsv(String fileName, Set<Integer> alignmentsToGet, boolean loadAllAlignments) throws FileFormatException, IOException {
List<Cluster> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(fileName)))) {
List<String> header = new ArrayList<>(Arrays.asList(reader.readLine().split(Hammock.CSV_SEPARATOR)));
int alignmentIndex = header.indexOf("alignment");
if (alignmentIndex != -1) { //to correct the next index for removing this
header.remove(alignmentIndex);
}
int sumIndex = header.indexOf("sum");
if (sumIndex != -1) {
header.remove(sumIndex);
}
List<String> labels = header.subList(2, header.size()); //0: cluster_id, 1: sequence
Map<Integer, List<List<String>>> splitLineMap = new HashMap<>();
String line;
while ((line = reader.readLine()) != null) {
List<String> splitLine = new ArrayList<>(Arrays.asList(line.split(Hammock.CSV_SEPARATOR)));
int id = Integer.decode(splitLine.get(0));
List<List<String>> lineList = splitLineMap.get(id);
if (lineList == null) {
lineList = new ArrayList<>();
}
lineList.add(splitLine);
splitLineMap.put(id, lineList);
}
for (Map.Entry<Integer, List<List<String>>> entry : splitLineMap.entrySet()) {
int clusterId = entry.getKey();
List<UniqueSequence> sequences = new ArrayList<>();
StringBuilder alignments = new StringBuilder();
int seqIndex = 0;
for (List<String> splitLine : entry.getValue()) {
if (alignmentIndex != -1) {
String alignedSeq = splitLine.get(alignmentIndex);
if (!alignedSeq.equals("NA")) {
alignments.append(">").append(clusterId).append("_").append(seqIndex).append("\n").append(alignedSeq).append("\n");
}
splitLine.remove(alignmentIndex);
seqIndex++;
}
if (sumIndex != -1) {
splitLine.remove(sumIndex);
}
sequences.add(lineToUniqueSequence(splitLine.get(1), splitLine.subList(2, splitLine.size()), labels));
}
Cluster cl = new Cluster(sequences, clusterId);
if ((alignments.length() >= 1) && ((loadAllAlignments) || ((alignmentsToGet != null) && (alignmentsToGet.contains(clusterId))))) {
int alignmentLinesCount = (StringUtils.countMatches(alignments, "\n") / 2);
if (alignmentLinesCount == cl.getUniqueSize()) { //alignments with some aligned sequences 'NA' will not be used
FileIOManager.saveStringToFile(alignments.toString(), Settings.getInstance().getMsaDirectory() + clusterId + ".aln");
cl.setAsHasMSA();
}
}
result.add(cl);
}
} catch (NumberFormatException | NullPointerException e) {
throw new FileFormatException("Error in cluster file: "
+ fileName + " - wrong format. Original message: ", e);
}
return (result);
}
/**
* @see FileIOManager#saveClusterSequencesToCsvOrdered(Collection<Cluster>,
* String, List<String>, Collection<UniqueSequence>, Map<Cluster, String>)
*/
public static void saveClusterSequencesToCsvOrdered(Collection<Cluster> clusters, String filePath, List<String> labels, Collection<UniqueSequence> orderedSequences) throws IOException {
Map<Cluster, List<String>> alignmentsMap = getAlignmentsMap(clusters);
writeClusterSequencesToCsv(orderedSequences, clusters, filePath, labels, alignmentsMap);
}
/**
* Saves a .csv file containing one line per sequence for every cluster on
* input, retains the order defined by orderedSequences
*
* @param clusters Clusters to be saved
* @param filePath Path to resulting file
* @param labels List of labels. Only these labels and their appropriate
* counts will be saved in resulting file.
* @param orderedSequences Defines the order of the sequences in the file
* @param alignmentsMap An existing alignmentsMap, which will be re-formated
* for writing purposes
* @throws IOException
*/
public static void saveClusterSequencesToCsvOrdered(Collection<Cluster> clusters, String filePath, List<String> labels, Collection<UniqueSequence> orderedSequences, Map<Cluster, String> alignmentsMap) throws IOException {
Map<Cluster, List<String>> newAlignmentsMap = reformatAlignmentsMap(clusters, alignmentsMap);
writeClusterSequencesToCsv(orderedSequences, clusters, filePath, labels, newAlignmentsMap);
}
/**
* @see saveClusterSequencesToCsv(Collection<Cluster>, String, List<String>,
* Map<Cluster, String>)
*/
public static void saveClusterSequencesToCsv(Collection<Cluster> clusters, String filePath, List<String> labels) throws IOException {
List<Cluster> clusterSortedList = new ArrayList<>(clusters);
Collections.sort(clusterSortedList, Collections.reverseOrder());
List<UniqueSequence> sortedSequences = getSortedSequences(clusterSortedList);
Map<Cluster, List<String>> alignmentsMap = getAlignmentsMap(clusters);
writeClusterSequencesToCsv(sortedSequences, clusters, filePath, labels, alignmentsMap);
}
/**
* Saves a csv file containing one line per sequence for every cluster on
* input. The resulting file is ordered from the largest cluster to the
* smallest, within a cluster, sequences are ordered by size and
* alphabetically
*
* @param clusters Clusters to be saved
* @param filePath Path to resulting file
* @param labels List of labels. Only these labels and their appropriate
* counts will be saved in resulting file.
* @param alignmentsMap An existing alignment map which will be re-formated
* for writing purposes
* @throws IOException
*/
public static void saveClusterSequencesToCsv(Collection<Cluster> clusters, String filePath, List<String> labels, Map<Cluster, String> alignmentsMap) throws IOException {
List<Cluster> clusterSortedList = new ArrayList<>(clusters);
Collections.sort(clusterSortedList, Collections.reverseOrder());
List<UniqueSequence> sortedSequences = getSortedSequences(clusterSortedList);
Map<Cluster, List<String>> newAlignmentsMap = reformatAlignmentsMap(clusters, alignmentsMap);
writeClusterSequencesToCsv(sortedSequences, clusters, filePath, labels, newAlignmentsMap);
}
private static double empiricalProbab(double score, double minScore, double maxScore, Map<Double, Double> empiricalProbabs) {
if (score < minScore) {
return 1;
}
if (score > maxScore) {
return 0;
}
return (empiricalProbabs.get((double) Math.round(score * 10) / 10)); //one decimal place rounding
}
/**
* Saves the results of multiple HMMSearch runs to a csv file.
*
* @param hits The HMMSearch hits to be saved
* @param filePath Path to save the results into
* @param empiricalProbabsFile File containing empirical probabilities for
* this search
* @param clusterCount How many clusters are in the result
* @param sequenceCount How many sequences are in the result
* @throws IOException
*/
public static void saveHmmsearchHitsToCsv(Collection<HmmsearchSequenceHit> hits, String filePath, String empiricalProbabsFile, int clusterCount, int sequenceCount) throws IOException {
Map<Double, Double> empiricalProbabs = null;
double min = Double.MAX_VALUE;
double max = Double.MIN_VALUE;
if (empiricalProbabsFile != null) {
empiricalProbabs = FileIOManager.loadEmpiricalProbabs(empiricalProbabsFile);
for (Double score : empiricalProbabs.keySet()) {
if (score > max) {
max = score;
}
if (score < min) {
min = score;
}
}
}
List<HmmsearchSequenceHit> hitList = new ArrayList<>(hits);
Collections.sort(hitList, Collections.reverseOrder());
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("cluster_id" + Hammock.CSV_SEPARATOR
+ "main_sequence" + Hammock.CSV_SEPARATOR
+ "found_sequence" + Hammock.CSV_SEPARATOR
+ "score");
if (empiricalProbabs != null) {
writer.write(Hammock.CSV_SEPARATOR + "evalue_empirical");
}
writer.write("\n");
for (HmmsearchSequenceHit hit : hitList) {
writer.write(hit.getCluster().getId() + Hammock.CSV_SEPARATOR
+ hit.getCluster().getSequences().get(0).getSequenceString() + Hammock.CSV_SEPARATOR
+ hit.getSequence().getSequenceString() + Hammock.CSV_SEPARATOR
+ hit.getScore());
if (empiricalProbabs != null) {
writer.write(Hammock.CSV_SEPARATOR + empiricalProbab(hit.getScore(), min, max, empiricalProbabs) * clusterCount * sequenceCount);
}
writer.write("\n");
}
}
}
/**
* Saves the results of multiple HHAlign runs to a csv file in the form of
* an all vs. all matrix.
*
* @param hits The HHAlign hits to be saved
* @param clusters1 One set of compared clusters (matrix rows)
* @param clusters2 The other set of compared clusters (matrix columns)
* @param filePath A path to save the file to.
* @throws IOException
*/
public static void saveHHAlignHitsToCsv(Collection<HHalignHit> hits, Collection<Cluster> clusters1, Collection<Cluster> clusters2, String filePath) throws IOException {
Map<Integer, Map<Integer, Double>> scoreMatrix = new HashMap<>();
for (HHalignHit hit : hits) {
int lineId = hit.getSearchedCluster().getId();
int columnId = hit.getFoundCluster().getId();
Map<Integer, Double> matrixLine;
matrixLine = scoreMatrix.get(lineId);
if (matrixLine == null) {
matrixLine = new HashMap<>();
}
matrixLine.put(columnId, hit.getScore());
scoreMatrix.put(lineId, matrixLine);
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (Cluster cl2 : clusters2) {
writer.write(Hammock.CSV_SEPARATOR + cl2.getId());
}
for (Cluster cl1 : clusters1) {
writer.newLine();
writer.write("" + cl1.getId());
for (Cluster cl2 : clusters2) {
Double score = scoreMatrix.get(cl1.getId()).get(cl2.getId());
if (score == null) {
score = -1.0;
}
writer.write(Hammock.CSV_SEPARATOR + score);
}
}
}
}
private static List<UniqueSequence> getSortedSequences(List<Cluster> sortedClusters) {
List<UniqueSequence> sortedSequences = new ArrayList<>();
for (Cluster cl : sortedClusters) {
List<UniqueSequence> sequences = cl.getSequences();
Collections.sort(sequences, Collections.reverseOrder(new UniqueSequenceSizeAlphabeticComparator()));
sortedSequences.addAll(sequences);
}
return (sortedSequences);
}
private static Map<Cluster, List<String>> reformatAlignmentsMap(Collection<Cluster> clusters, Map<Cluster, String> alignmentsMap) {
Map<Cluster, List<String>> newAlignmentsMap = new HashMap<>();
for (Cluster cl : clusters) {
if (alignmentsMap.containsKey(cl)) {
List<String> alignmentLines = new ArrayList<>();
String[] split = alignmentsMap.get(cl).split("\n");
for (int i = 1; i < split.length; i += 2) { //odd lines only
alignmentLines.add(split[i]);
}
newAlignmentsMap.put(cl, alignmentLines);
}
}
return (newAlignmentsMap);
}
private static Map<Cluster, List<String>> getAlignmentsMap(Collection<Cluster> clusters) throws IOException {
Map<Cluster, List<String>> alignmentsMap = new HashMap<>();
for (Cluster cl : clusters) {
if (cl.hasMSA()) {
alignmentsMap.put(cl, FileIOManager.getAlignmentLines(cl));
}
}
return (alignmentsMap);
}
/**
* Saves a collection of unique sequences into a file
*
* @param sequences Sequences to be saved
* @param filePath File to write the sequences into
* @param labels A list of sequence labels. Defines the column order
* @throws IOException
*/
public static void saveUniqueSequencesToCsv(Collection<UniqueSequence> sequences, String filePath, List<String> labels) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("sequence");
for (String label : labels) {
writer.write(Hammock.CSV_SEPARATOR + label);
}
writer.newLine();
for (UniqueSequence seq : sequences) {
writer.write(seq.getSequenceString());
for (String label : labels) {
Integer count = seq.getLabelsMap().get(label);
if (count == null) {
count = 0;
}
writer.write(Hammock.CSV_SEPARATOR + count);
}
writer.newLine();
}
}
}
private static void writeClusterSequencesToCsv(Collection<UniqueSequence> sequences, Collection<Cluster> clusters, String filePath, List<String> labels, Map<Cluster, List<String>> clusterAlignments) throws IOException {
Map<String, String> msaMap = new HashMap<>();
Map<String, Cluster> sequenceClusterMap = new HashMap<>();
for (Cluster cl : clusters) {
for (UniqueSequence seq : cl.getSequences()) {
sequenceClusterMap.put(seq.getSequenceString(), cl);
}
if (clusterAlignments.containsKey(cl)) {
for (String msaLine : clusterAlignments.get(cl)) {
msaMap.put(msaLine.replace("-", ""), msaLine);
}
}
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("cluster_id" + Hammock.CSV_SEPARATOR + "sequence" + Hammock.CSV_SEPARATOR + "alignment" + Hammock.CSV_SEPARATOR + "sum");
for (String label : labels) {
writer.write(Hammock.CSV_SEPARATOR + label);
}
writer.newLine();
for (UniqueSequence seq : sequences) {
Cluster cluster = sequenceClusterMap.get(seq.getSequenceString());
if (cluster != null) {
writer.write(cluster.getId() + Hammock.CSV_SEPARATOR + seq.getSequenceString() + Hammock.CSV_SEPARATOR);
if (msaMap.containsKey(seq.getSequenceString())) {
writer.write(msaMap.get(seq.getSequenceString()) + Hammock.CSV_SEPARATOR);
} else {
writer.write("NA" + Hammock.CSV_SEPARATOR);
}
} else {
writer.write("NA" + Hammock.CSV_SEPARATOR + seq.getSequenceString() + Hammock.CSV_SEPARATOR + "NA" + Hammock.CSV_SEPARATOR);
}
writer.write("" + seq.size());
for (String label : labels) {
Integer count = seq.getLabelsMap().get(label);
if (count == null) {
count = 0;
}
writer.write(Hammock.CSV_SEPARATOR + count);
}
writer.newLine();
}
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Saves cluster overview to .csv file. Lines are sorted by cluster size
* from the largest.
*
* @param clusters Clusters to be saved
* @param filePath Path to a file write the clusters into
* @param labels A list of labels to use. Defines column order
* @throws IOException
*/
public static void SaveClustersToCsv(Collection<Cluster> clusters, String filePath, List<String> labels) throws IOException {
List<Cluster> sortedList = new ArrayList<>(clusters);
Collections.sort(sortedList, Collections.reverseOrder());
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write("cluster_id" + Hammock.CSV_SEPARATOR + "main_sequence" + Hammock.CSV_SEPARATOR + "sum");
for (String label : labels) {
writer.write(Hammock.CSV_SEPARATOR + label);
}
writer.newLine();
for (Cluster cl : sortedList) {
List<UniqueSequence> sequences = cl.getSequences();
Collections.sort(sequences, Collections.reverseOrder());
writer.write(cl.getId() + Hammock.CSV_SEPARATOR + sequences.get(0).getSequenceString() + Hammock.CSV_SEPARATOR + cl.size());
Map<String, Integer> clusterCountMap = getClusterLabelsMap(cl);
for (String label : labels) {
Integer count = clusterCountMap.get(label);
if (count == null) {
count = 0;
}
writer.write(Hammock.CSV_SEPARATOR + count);
}
writer.newLine();
}
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Returns labels count map of an entire cluster (sum of all sequences)
*
* @param cl
* @return
*/
private static Map<String, Integer> getClusterLabelsMap(Cluster cl) {
Map<String, Integer> res = new HashMap<>();
for (UniqueSequence seq : cl.getSequences()) {
for (Map.Entry<String, Integer> entry : seq.getLabelsMap().entrySet()) {
Integer current = res.get(entry.getKey());
if (current == null) {
current = 0;
}
current += entry.getValue();
// current += 1;
res.put(entry.getKey(), current);
}
}
return res;
}
/**
* Saves a file containing input statistics - information on sequences and
* their counts
*
* @param sequences
* @param labels Labels to be part of the file. Defines column order
* @param filePath
* @throws IOException
*/
public static void saveInputStatistics(Collection<UniqueSequence> sequences, List<String> labels, String filePath) throws IOException {
Map<String, Integer> totalMap = getTotalLabelCounts(sequences, labels);
Map<String, Integer> uniqueMap = getUniqueLabelCounts(sequences, labels);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (String label : labels) {
writer.write(Hammock.CSV_SEPARATOR + label);
}
writer.newLine();
writer.write("total_count");
for (String label : labels) {
writer.write(Hammock.CSV_SEPARATOR + totalMap.get(label));
}
writer.newLine();
writer.write("unique_count");
for (String label : labels) {
writer.write(Hammock.CSV_SEPARATOR + uniqueMap.get(label));
}
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Loads the alignments from a MSA file.
*
* @param path Path to the MSA file
* @return A list of strings, each member is one MSA string. Input order is
* retained.
* @throws IOException
*/
public static List<String> getAlignmentLines(String path) throws IOException {
List<String> result = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(path)))) {
String line;
while ((line = reader.readLine()) != null) {
line = reader.readLine(); //only even lines
result.add(line.trim());
}
} catch (IOException e) {
throw new IOException(e);
}
return result;
}
/**
* Loads temporal MSA file for a cluster and returns only lines containing
* alignment in form of a (multiline) string
*
* @param cl
* @return
* @throws IOException
*/
public static List<String> getAlignmentLines(Cluster cl) throws IOException {
List<String> list = new ArrayList<>(Arrays.asList(getAllAlignmentLines(cl)));
List<String> res = new ArrayList<>();
for (int i = 1; i < list.size(); i += 2) {
res.add(list.get(i));
}
return (res);
}
private static String[] getAllAlignmentLines(Cluster cl) throws IOException {
if (cl.getUniqueSize() > 1) {
return (fileAsString(Settings.getInstance().getMsaDirectory() + cl.getId() + ".aln").split("\n"));
} else {
return (cl.getFastaString().split("\n"));
}
}
/**
* Saves one or more clusters to one fasta File.
*
* @param clusters clusters to be saved
* @param filePath path to output .fasta file
* @throws IOException
*/
public static void saveClustersToFasta(Collection<Cluster> clusters, String filePath) throws IOException {
String toWrite = "";
for (Cluster cluster : clusters) {
toWrite = toWrite.concat(cluster.getFastaString());
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(toWrite);
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Saves one Cluster to a fasta file. No linebreaks are addeded. Cluster's
* sequences are saved in reversed natural order.
*
* @param cluster Cluster object to be saved
* @param filePath Path to a file Cluster objects will be saved to.
* @throws IOException
*/
public static void saveClusterToFasta(Cluster cluster, String filePath) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(cluster.getFastaString());
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Returns the first aligned sequence (including gaps) from a MSA in .aln
* format (aligned fasta)
*
* @param cl cluster to get the first aligned sequence for
* @return the first aligned sequence of a .aln MSA file
* @throws DataException
* @throws IOException
*/
public static String getFirstAlnSeq(Cluster cl) throws DataException, IOException {
if (!cl.hasMSA()) {
throw new DataException("Error, Can't return alignment line for a cluster without alignment.");
}
return getNthLine(Settings.getInstance().getMsaDirectory() + cl.getId() + ".aln", 1);
}
/**
* Returns the first line of a cluster's alignment in the A2m format.
*
* @param cl
* @return
* @throws DataException
* @throws IOException
*/
public static String getFirstA2mSeq(Cluster cl) throws DataException, IOException {
if (!cl.hasMSA()) {
throw new DataException("Error, Can't return alignment line for a cluster without alignment.");
}
return getNthLine(Settings.getInstance().getMsaDirectory() + cl.getId() + ".a2m", 1);
}
private static String getNthLine(String file, int skip) throws IOException {
String res = null;
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
for (int i = 0; i < skip; i++) {
reader.readLine();
}
res = reader.readLine();
} catch (IOException e) {
throw new IOException(e);
}
return res;
}
/**
* Merges MSA files for two clusters, adds any gap columns specified
*
* @param cl1 first cluster to be merged
* @param cl2 second cluster to be merged
* @param gaps1 gaps to be added into first cluster
* @param gaps2 gaps to be added into second cluster
* @param newId id of resulting cluster
* @throws IOException
*/
public static void mergeAlignedClusters(Cluster cl1, Cluster cl2, List<Integer> gaps1, List<Integer> gaps2, int newId) throws IOException {
String cl1String = insertGapsIntoAlignment(cl1, gaps1, newId, 1);
String cl2String = insertGapsIntoAlignment(cl2, gaps2, newId, cl1.getUniqueSize() + 1);
cl1String = cl1String.concat(cl2String);
saveStringToFile(cl1String, Settings.getInstance().getMsaDirectory() + newId + ".aln");
}
/**
* Reformats a MSA file. Adds gaps on positions specified by gapPositions
* parameter
*
* @param id cluster to which .aln MSA file to add gaps
* @param gapPositions list of position of new gaps
* @param newId id of resulting .aln file
* @param startingSequenceId first sequence will have this id, id will
* increade throughout the file
* @return String reprecenting whole MSA in .aln format
* @throws IOException
*/
private static String insertGapsIntoAlignment(Cluster cl, List<Integer> gapPositions, int newId, int startingSequenceId) throws IOException {
StringBuilder res = new StringBuilder();
int currentId = startingSequenceId;
String[] alnLines = getAllAlignmentLines(cl);
for (String line : alnLines) {
if (line.startsWith(">")) {
res.append(">").append(newId).append("_").append(currentId).append("\n");
currentId++;
} else {
StringBuilder lineBuilder = new StringBuilder(line);
for (int gapPosition : gapPositions) {
lineBuilder.insert(gapPosition, '-');
}
res.append(lineBuilder).append("\n");
}
}
return res.toString();
}
/**
* For every cluster, saves the path to its appropriate .hmm file in
* temporal files
*
* @param clusters
* @param filePath
* @throws IOException
*/
public static void saveClusterHHPaths(Collection<Cluster> clusters, String filePath) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (Cluster cl : clusters) {
writer.write(Settings.getInstance().getHhDirectory() + Settings.getInstance().getSeparatorChar() + cl.getId() + ".hhm");
writer.newLine();
}
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Writes a collection of sequences intoto a fasta file. Assigns a unique
* (unique only within this file) id to each sequences, this id will be
* written to fasta file. Returns a map where key is assigned unique id and
* value is UniqueSequence object with this unique id assigned. Does not
* save information on unique sequence's labels and label counts.
*
* Each Cluster's sequences are saved in reversed natural order.
*
* @param sequences UniqueSequence objects to be written to fasta file
* @param filePath path to a file UniqeSequence objects will be saved to
* @return A map mapping new unique id used in output fasta file to each
* UniqueSequence.
* @throws IOException
*/
public static Map<String, UniqueSequence> saveUniqueSequencesToFastaWithoutLabels(Collection<UniqueSequence> sequences, String filePath) throws IOException {
Map<String, UniqueSequence> idMap = new HashMap<>();
int id = 0;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (UniqueSequence sequence : sequences) {
id++;
writer.write(">" + id);
writer.newLine();
writer.write(sequence.getSequenceString());
writer.newLine();
idMap.put("" + id, sequence);
}
} catch (IOException e) {
throw new IOException(e);
}
return idMap;
}
/**
* Writes a fasta file containing the unique sequences on input. Label and
* count information will be retained in the fasta headers. Input order is
* retained.
*
* @param sequences Sequences to save
* @param filePath Path to a file to save the sequences into.
* @throws IOException
*/
public static void saveUniqueSequencesToFasta(Collection<UniqueSequence> sequences, String filePath) throws IOException {
int id = 0;
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
for (UniqueSequence seq : sequences) {
for (Map.Entry<String, Integer> entry : seq.getLabelsMap().entrySet()) {
writer.write(">" + id + "|" + entry.getValue() + "|" + entry.getKey());
writer.newLine();
writer.write(seq.getSequenceString());
writer.newLine();
id++;
}
}
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Saves a single UniqueSequence object into a fasta file (containing then
* just one record)
*
* @param sequence A UniqueSequence object to be saved
* @param filePath path to file to write to.
* @param id
* @throws IOException
*/
public static void saveUniqueSequenceToFastaWithoutLabels(UniqueSequence sequence, String filePath, String id) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(">" + id);
writer.newLine();
writer.write(sequence.getSequenceString());
writer.newLine();
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Renames all records in a fasta file so that seuqnce headers are in format
* >newId_n where n is sequence index (from top to bottom in file)
*
* @param filePath path to fasta file to be changed
* @param newId header prefix
* @throws IOException
*/
public static void renameFasta(String filePath, String newId) throws IOException {
String toWrite = "";
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
int i = 1;
while ((line = reader.readLine()) != null) { //odd line
toWrite = toWrite.concat(">" + newId + "_" + i + "\n");
i++;
toWrite = toWrite.concat(reader.readLine() + "\n"); //even line
}
} catch (IOException e) {
throw new IOException(e);
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(toWrite);
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Deletes all files in a specified folder
*
* @param folderName Path to folder in which all files will be deleted
*/
public static void deleteFolderContents(String folderName) {
File folder = new File(folderName);
File[] files = folder.listFiles();
if (files != null) { //some JVMs return null for empty dirs
for (File f : files) {
f.delete();
}
}
}
/**
* Returns absolute paths to all files in input folder
*
* @param folderName path to the folder of interest
* @return
*/
public static List<String> listFolderContents(String folderName) {
File[] contents = new File(folderName).listFiles();
List<String> res = new ArrayList<>();
for (File f : contents) {
res.add(f.getAbsolutePath());
}
return (res);
}
/**
* Loads a file and returns its contents as string
*
* @param filePath
* @return
* @throws IOException
*/
public static String fileAsString(String filePath) throws IOException {
StringBuilder result = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new FileReader(new File(filePath)))) {
String line;
while ((line = reader.readLine()) != null) {
result.append(line).append("\n");
}
return result.toString();
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Saves a string into a file
*
* @param toSave
* @param filePath
* @throws IOException
*/
public static void saveStringToFile(String toSave, String filePath) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
writer.write(toSave);
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Performs file copy
*
* @param source
* @param target
* @throws IOException
*/
public static void copyFile(String source, String target) throws IOException {
Path sourcePath = Paths.get(source);
Path targetPath = Paths.get(target);
Files.copy(sourcePath, targetPath, REPLACE_EXISTING);
}
/**
* For every label in a list, counts its occurrences in collection of
* UniqueSequence objects. Full (nonunique) counts are returned
*
* @param sequences
* @param labels
* @return
*/
private static Map<String, Integer> getTotalLabelCounts(Collection<UniqueSequence> sequences, List<String> labels) {
Map<String, Integer> result = new HashMap<>();
for (String label : labels) {
result.put(label, 0);
}
for (UniqueSequence sequence : sequences) {
for (Map.Entry<String, Integer> entry : sequence.getLabelsMap().entrySet()) {
if (result.containsKey(entry.getKey())) {
int count = result.get(entry.getKey());
count += entry.getValue();
result.put(entry.getKey(), count);
}
}
}
return result;
}
/**
* For every label in list, counts its occurrences in collection of
* UniqueSequence objects. Each UniqueSequence having any positive count
* associated with this label is counted as 1.
*
* @param sequences
* @param labels
* @return
*/
private static Map<String, Integer> getUniqueLabelCounts(Collection<UniqueSequence> sequences, List<String> labels) {
Map<String, Integer> result = new HashMap<>();
for (String label : labels) {
result.put(label, 0);
}
for (UniqueSequence sequence : sequences) {
for (Map.Entry<String, Integer> entry : sequence.getLabelsMap().entrySet()) {
if (result.containsKey(entry.getKey())) {
int count = result.get(entry.getKey());
count++;
result.put(entry.getKey(), count);
}
}
}
return result;
}
/**
* Checks whether msa in "path" has enough conserved states satisfying
* maximal gap proportion and minimal information content thresholds.
*
* @param alignmentLines clusters MSA
* @param minMatchStates
* @param minIc
* @param maxGapProportion
* @return
* @throws IOException
*/
public static boolean checkConservedStates(List<String> alignmentLines, int minMatchStates, double minIc, double maxGapProportion) throws IOException {
List<Boolean> matchStates = defineMatchStates(alignmentLines, maxGapProportion, minIc, true); //true ensures conserved positions, not all match states between them are counted
int count = 0;
for (boolean position : matchStates) {
if (position) {
count++;
}
}
return count >= minMatchStates;
}
/**
* Returns list of information content values - one value for each column of
* input alignment. Information contents are calculated based on
* equiprobable model - no amino acid composition adjustments are performed.
* Positions not having enough non-gap characters get information content of
* -1.
*
* @param alignmentLines clusters MSA
* @param maxGapProportion
* @return
* @throws IOException
*/
public static List<Double> getInformationContents(List<String> alignmentLines, Double maxGapProportion) throws IOException {
List<Map<Character, Integer>> positionLetterCounts = getPositionLetterCounts(alignmentLines);
List<Double> result = new ArrayList<>();
int seqCount = 0;
for (Integer count : positionLetterCounts.get(0).values()) {
seqCount += count;
}
for (Map<Character, Integer> positionCount : positionLetterCounts) {
if ((positionCount.get('-') == null) || (((positionCount.get('-') + 0.0) / seqCount) <= maxGapProportion)) {
result.add(getInformationContent(positionCount));
} else {
result.add(-1.0); //-1 for positions not having enough non-gap positions
}
}
return result;
}
/**
* Counts the occurrences of amino acids in each column of an MSA.
*
* @param alignmentLines A string containing a MSA.
* @return A list, each member is a map respective to the appropriate
* position in the MSA
* @throws IOException
*/
public static List<Map<Character, Integer>> getPositionLetterCounts(List<String> alignmentLines) throws IOException {
List<Map<Character, Integer>> positionLetterCounts = new ArrayList<>();
int lineLength = alignmentLines.get(0).trim().length();
for (char aa : alignmentLines.get(0).trim().toCharArray()) {
Map<Character, Integer> countMap = new HashMap<>();
countMap.put(aa, 1);
positionLetterCounts.add(countMap);
}
for (String line : alignmentLines.subList(1, alignmentLines.size())) {
char[] aas = line.trim().toCharArray();
for (int i = 0; i < lineLength; i++) {
Integer count = null;
try{
count = positionLetterCounts.get(i).get(aas[i]);
} catch(ArrayIndexOutOfBoundsException e){
System.out.println(line);
System.exit(1);
}
if (count == null) {
count = 0;
}
count++;
positionLetterCounts.get(i).put(aas[i], count);
}
}
return (positionLetterCounts);
}
/**
* On the basis of criteria provided, decides which columns of a MSA fulfill
* the criteria - maximal gap proportion and minimal information content and
* will be considered match states.
*
* @param alignmentLines The MSA to be evaluated
* @param maxGapProportion Maximal proportion of gap ('-' characters) in a
* column to be considered a match state.
* @param minIc Minimal information content of a MSA column to be considered
* a match state
* @param allowInnerGaps If true, a non-match state can lay between two
* match states Otherwise, all the positions between the leftmost and the
* rightmost match states are considered match states.
* @return
* @throws IOException
*/
public static List<Boolean> defineMatchStates(List<String> alignmentLines, double maxGapProportion, double minIc, boolean allowInnerGaps) throws IOException {
List<Double> informationContents = getInformationContents(alignmentLines, maxGapProportion);
List<Boolean> result = new ArrayList<>();
if (allowInnerGaps) {
for (Double ic : informationContents) {
if (ic >= minIc) {
result.add(true);
} else {
result.add(false);
}
}
} else {
int minPosition = informationContents.size() + 1;
int maxPosition = -1;
for (int i = 0; i < informationContents.size(); i++) {
if (informationContents.get(i) >= minIc) {
if (i < minPosition) {
minPosition = i;
}
if (i > maxPosition) {
maxPosition = i;
}
}
}
for (int i = 0; i < informationContents.size(); i++) {
if ((i >= minPosition) && (i <= maxPosition)) {
result.add(Boolean.TRUE);
} else {
result.add(Boolean.FALSE);
}
}
}
return result;
}
/**
* Transforms MSA in aln format to a2m format. Match columns (upper case)
* are selected based on Global properties in Hammock. Saves the a2m file to
* the temporal folder.
*
* @param cluster
* @throws IOException
* @throws InterruptedException
*/
public static void alnToA2M(Cluster cluster) throws IOException, InterruptedException, DataException {
alnToA2M(Settings.getInstance().getMsaDirectory() + cluster.getId() + ".aln", Settings.getInstance().getMsaDirectory() + cluster.getId() + ".a2m", Hammock.maxGapProportion, Hammock.minIc, Hammock.innerGapsAllowed);
}
private static void alnToA2M(String inFile, String outFile, Double maxGapProportion, double minIc, boolean allowInnerGaps) throws IOException, DataException {
List<Boolean> matchStates = defineMatchStates(getAlignmentLines(inFile), maxGapProportion, minIc, allowInnerGaps);
try (BufferedReader reader = new BufferedReader(new FileReader(inFile)); BufferedWriter writer = new BufferedWriter(new FileWriter(outFile))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.startsWith(">")) {
writer.write(line + "\n");
line = reader.readLine();
}
if (line.length() != matchStates.size()) {
throw new DataException("Error. Wrong length of match state vector.");
}
StringBuilder newLine = new StringBuilder();
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == '-') {
if (matchStates.get(i)) {
newLine.append("-");
} else {
newLine.append(".");
}
} else {
if (matchStates.get(i)) {
newLine.append(Character.toUpperCase(line.charAt(i)));
} else {
newLine.append(Character.toLowerCase(line.charAt(i)));
}
}
}
writer.write(newLine.toString() + "\n");
}
} catch (IOException e) {
throw new IOException(e);
}
}
/**
* Gets the length of the first line of a file
*
* @param inFile
* @return
* @throws IOException
*/
public static int getAlnLength(String inFile) throws IOException {
String line;
try (BufferedReader reader = new BufferedReader(new FileReader(inFile))) {
reader.readLine();
line = reader.readLine(); //second line
} catch (IOException e) {
throw new IOException(e);
}
return line.length();
}
/**
* Checks whether alignment in inFile is longer or equal to maxLength
*
* @param alignmentLines clusters MSA
* @param maxLength
* @return
* @throws IOException
*/
public static boolean checkAlnLength(List<String> alignmentLines, int maxLength) throws IOException {
return (alignmentLines.get(0).length() <= maxLength);
}
/**
* Checks the number of inner gaps in the first and last lines of a msa
*
* @param alignmentLines
* @param maxGaps
* @return
*/
public static boolean checkBothInnerGaps(List<String> alignmentLines, int maxGaps) {
return ((countInnerGaps(alignmentLines.get(0)) <= maxGaps) && (countInnerGaps(alignmentLines.get(alignmentLines.size() - 1)) <= maxGaps));
}
private static int countInnerGaps(String line) {
List<Integer> gapBlocks = new ArrayList<>();
int currentBlock = 0;
for (char aa : line.toCharArray()) {
if (aa == '-') {
currentBlock++;
}
if (aa != '-' && currentBlock > 0) {
gapBlocks.add(currentBlock);
currentBlock = 0;
} //trailing gap block is never added
}
if ((line.toCharArray()[0]) == '-') { //starts with gaps
gapBlocks = gapBlocks.subList(1, gapBlocks.size());
}
int sum = 0;
for (int block : gapBlocks) {
sum += block;
}
return sum;
}
/**
* Calculates information content of one column in MSA. No amino acid
* composition adjustments are performed.
*
* @param countMap
* @return
*/
private static double getInformationContent(Map<Character, Integer> countMap) {
int size = 0;
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
if (entry.getKey() != '-') {
size += entry.getValue();
}
}
List<Double> probabs = new ArrayList<>();
for (Map.Entry<Character, Integer> entry : countMap.entrySet()) {
if (entry.getKey() != '-') {
probabs.add((entry.getValue() + 0.0) / size);
}
}
double enthropy = 0.0;
for (double probab : probabs) {
enthropy += probab * (Math.log(probab) / Math.log(2)); //log base 2
}
return (-(Math.log(0.05) / Math.log(2)) + enthropy);
}
/**
* Returns list of all UniqueSequence objects contained in a collection of
* clusters
*
* @param clusters
* @return
*/
public static List<UniqueSequence> getAllSequences(Collection<Cluster> clusters) {
List<UniqueSequence> result = new ArrayList<>();
for (Cluster cl : clusters) {
result.addAll(cl.getSequences());
}
return result;
}
}
/**
* Makes it possible to sort map according to values. Returns TOTAL ordering, so
* it DOES NOT respect equals(). (it is not possible to respect equals in this
* case - it would lead to key deletions)
*
* @author Adam Krejci
*/
class ValueComparator implements Comparator<String> {
Map<String, Integer> base;
public ValueComparator(Map<String, Integer> base) {
this.base = base;
}
@Override
public int compare(String a, String b) {
if (base.get(a) >= base.get(b)) {
return -1;
} else {
return 1;
}
}
}
| gpl-3.0 |
ericvader/cs3219r | src/main/java/sg/edu/nus/comp/cs3219r/ListenerServlet.java | 553 | package sg.edu.nus.comp.cs3219r;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class ListenerServlet implements ServletContextListener {
public static ServletContext context;
@Override
public void contextInitialized(ServletContextEvent sce) {
context = sce.getServletContext();
Utils.setWebapp(true);
Utils.init();
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
context = null;
}
} | gpl-3.0 |
wp-plugins/e-mailing-service | admin/send_user.php | 19705 | <div id="wrapper">
<header id="page-header">
<div class="wrapper">
<?php
if ( is_plugin_active( 'admin-hosting/admin-hosting.php' ) ) {
include(AH_PATH . '/include/entete.php');
} else {
include(smPATH . '/include/entete.php');
}
extract($_POST);
extract($_GET);
?>
</div>
</header>
</div>
<div id="page-subheader">
<div class="wrapper">
<h2>
<?php _e("Envoyer votre newsletter","e-mailing-service");?>
</h2>
</div>
</div>
<section id="content">
<div class="wrapper"> <section class="columns">
<?php echo "<p>".__("Programmer l'heure et la date d'envoi de votre newsletter","e-mailing-service")."</p>";?>
<hr />
<div class="grid_8">
<?php
if(isset($_POST["action"])){
if($_POST["action"] == "envoi"){
if($user_role !='administrator'){
if(ah_service_actif($user_login) == 'server'){
$infossmtp = $wpdb->get_results("SELECT * FROM `".AH_table_server_list."` WHERE login='".$user_login."' AND (status='Actif' OR status='ok' OR status='cancel') LIMIT 1");
foreach ( $infossmtp as $infossmtps )
{
if($infossmtps->version == 'load'){ $port = 27; } else { $port = 25; }
if(get_user_meta( $user_id, 'sm_host',true) == ''){
add_user_meta( $user_id, 'sm_sender',''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_from', ''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_host', ''.$infossmtps->mx.'.'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_port', $port,true);
add_user_meta( $user_id, 'sm_authentification', 'oui',true);
add_user_meta( $user_id, 'sm_username', ''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_pass', $infossmtps->pass_email_redirection,true);
} else {
update_user_meta( $user_id, 'sm_sender',''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_from', ''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_host', ''.$infossmtps->mx.'.'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_port', $port);
update_user_meta( $user_id, 'sm_authentification', 'oui');
update_user_meta( $user_id, 'sm_username', ''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_pass', $infossmtps->pass_email_redirection);
}
}
}
///// offre smtp
elseif(ah_service_actif($user_login) == 'smtp'){
$nb_total_a_envoyes = nb_destinataire($liste);
$nb_envoi_mois = sm_nb_envois_mois($user_login);
$infossmtp = $wpdb->get_results("SELECT * FROM `".AH_table_service_list."` WHERE login='".$user_login."' and categorie='service-smtp' and (status='ok' OR status='Actif' OR status='cancel') LIMIT 1");
foreach ( $infossmtp as $infossmtps )
{
$port=25;
if(ah_limit_month($reference) < $nb_total_envoyes){
if(get_user_meta( $user_id, 'sm_host',true) == ''){
add_user_meta( $user_id, 'sm_sender',''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_from', ''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_host', ''.$infossmtps->mx.'.'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_port', $port, true);
add_user_meta( $user_id, 'sm_authentification', 'oui',true);
add_user_meta( $user_id, 'sm_username', ''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_pass', $infossmtps->pass_email_redirection,true);
} else {
update_user_meta( $user_id, 'sm_sender',''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_from', ''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_host', ''.$infossmtps->mx.'.'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_port', $port);
update_user_meta( $user_id, 'sm_authentification', 'oui');
update_user_meta( $user_id, 'sm_username', ''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_pass', $infossmtps->pass_email_redirection);
}
} else {
echo "<h2>".__("Vous etes arrive au bout de votre quota , vous ne pouvez plus envoyer avant le mois suivant","e-mailing-service")." : ".$nb_credit_necessaire." ".__("credits necessaires","admin-hosting")."</h2>";
form_add_credit();
exit();
}
}
}
//// offre marketing
elseif(ah_service_actif($user_login) == 'marketing'){
$nb_total_a_envoyes = nb_destinataire($liste);
$nb_envoi_mois = sm_nb_envois_mois($user_login);
$infossmtp = $wpdb->get_results("SELECT * FROM `".AH_table_service_list."` WHERE login='".$user_login."' and categorie='service-smtp' and (status='ok' OR status='Actif' OR status='cancel') LIMIT 1");
foreach ( $infossmtp as $infossmtps )
{
$port=25;
if(ah_limit_month($reference) < $nb_total_envoyes){
if(get_user_meta( $user_id, 'sm_host',true) == ''){
add_user_meta( $user_id, 'sm_sender',''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_from', ''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_host', ''.$infossmtps->mx.'.'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_port', $port, true);
add_user_meta( $user_id, 'sm_authentification', 'oui',true);
add_user_meta( $user_id, 'sm_username', ''.$infossmtps->email.'@'.$infossmtps->domaine.'',true);
add_user_meta( $user_id, 'sm_pass', $infossmtps->pass_email_redirection,true);
} else {
update_user_meta( $user_id, 'sm_sender',''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_from', ''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_host', ''.$infossmtps->mx.'.'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_port', $port);
update_user_meta( $user_id, 'sm_authentification', 'oui');
update_user_meta( $user_id, 'sm_username', ''.$infossmtps->email.'@'.$infossmtps->domaine.'');
update_user_meta( $user_id, 'sm_pass', $infossmtps->pass_email_redirection);
}
} else {
echo "<h2>".__("Vous etes arrive au bout de votre quota , vous ne pouvez plus envoyer avant le mois suivant","e-mailing-service")." : ".$nb_credit_necessaire." ".__("credits necessaires","admin-hosting")."</h2>";
form_add_credit();
exit();
}
}
}
////// offre par credit
else {
$nb_total_envoyes = nb_destinataire($liste);
$nb_credit = get_option('ah_tarif_credit') * $nb_total_envoyes;
if(ah_credit($user_login) < $nb_credit){
$nb_mail_possible =ah_credit($user_login) / get_option('ah_tarif_credit');
$nb_credit_necessaire = get_option('ah_tarif_credit') * $nb_total_envoyes;
echo "<h2>".__("Votre solde de credit n'est pas suffisant pour envoyer un mailing, vous devez crediter votre compte","e-mailing-service")." : ".$nb_credit_necessaire." ".__("credits necessaires","admin-hosting")."</h2>";
form_add_credit();
exit();
}
}
}
if($_FILES['file']['name'] !=''){
$uploaddir = smPOST;
$uploadfile = $uploaddir . date('Ymshis') . basename($_FILES['file']['name']);
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$attachments = ''.$uploadfile.'';
} else {
_e("Probleme avec la piece jointe contacter le support","e-mailing-service");
exit();
}
} else {
$attachments ='';
}
if(get_user_meta( $user_id, 'sm_sender',true) == ''){
add_user_meta( $user_id, 'sm_sender',get_option('sm_email_exp'),true);
}
update_user_meta( $user_id, 'sm_fromname',$fromname);
update_user_meta( $user_id, 'sm_from', $fromname);
update_user_meta( $user_id, 'sm_reply',$reply_to);
$wpdb->insert("".$wpdb->prefix."sm_historique_envoi", array(
'id_newsletter' => $campagne,
'id_liste' => $liste,
'pause' => $pause,
'status' => 'En attente',
'type' => 'newsletter',
'track1' => $track1,
'track2' => $track2,
'date_envoi' => $date_envoi,
'mode' => $mode,
'login' => $user_login,
'attachments' => $attachments,
'user_id' => $user_id,
'fromname' => $fromname,
'reply_to' => $reply_to,
));
$hie = $wpdb->insert_id;
if(is_plugin_active('admin-hosting/admin-hosting.php') ) {
if(ah_service_actif($user_login) == 'null'){
$wpdb->insert(AH_table_financial_credit, array(
'membre_login' => $user_login,
'credit' => - $nb_credit,
'type' => __('solde','admin-hosting'),
'information' => ''.__('Debit campagne numero','admin-hosting').' : '.$hie.''
));
}
}
if(get_user_meta( $user_id, 'sm_host',true) == ''){
add_user_meta( $user_id, 'sm_host',get_option('sm_smtp_server_1'),true);
add_user_meta( $user_id, 'sm_sender',get_option('sm_smtp_sender_1'),true);
add_user_meta( $user_id, 'sm_port', get_option('sm_smtp_port_1'),true);
add_user_meta( $user_id, 'sm_authentification', get_option('sm_smtp_authentification_1'),true);
add_user_meta( $user_id, 'sm_username', get_option('sm_smtp_login_1'),true);
add_user_meta( $user_id, 'sm_pass',get_option('sm_smtp_pass_1'),true);
}
_e("Votre mailing va bientot demarrer","e-mailing-service");
echo '<meta http-equiv="refresh" content="1; url=admin.php?page=e-mailing-service/admin/live_user.php">';
}
elseif($action == "envoi_choix_auto"){
list($ID,$POSTTYPE)=explode("|",$campagne);
$wpdb->insert("".$wpdb->prefix."sm_historique_envoi", array(
'id_newsletter' => $ID,
'id_liste' => $liste,
'pause' => $pause,
'status' => 'En attente',
'type' => $POSTTYPE,
'track1' => $track1,
'track2' => $track2,
'date_envoi' => $date_envoi,
'serveur' => $serveur,
'mode' => $mode,
));
$hie = $wpdb->insert_id;
_e("Votre mailing va bientot demarrer","e-mailing-service");
echo '<meta http-equiv="refresh" content="1; url=admin.php?page=e-mailing-service/admin/live_user.php">';
}
elseif($action == "envoi_choix"){
$wpdb->insert("".$wpdb->prefix."sm_historique_envoi", array(
'id_newsletter' => $campagne,
'id_liste' => $liste,
'pause' => $pause,
'status' => 'En attente',
'type' => 'newsletter',
'track1' => $track1,
'track2' => $track2,
'date_envoi' => $date_envoi,
'serveur' => $serveur,
'mode' => $mode,
));
$hie = $wpdb->insert_id;
_e("Votre mailing va bientot demarrer","e-mailing-service");
echo '<meta http-equiv="refresh" content="1; url=admin.php?page=e-mailing-service/admin/live_user.php">';
}
elseif($action == "envoi_article"){
list($ID,$POSTTYPE)=explode("|",$campagne);
$wpdb->insert("".$wpdb->prefix."sm_historique_envoi", array(
'id_newsletter' => $ID,
'id_liste' => $liste,
'pause' => $pause,
'status' => 'En attente',
'type' => $POSTTYPE,
'track1' => $track1,
'track2' => $track2,
'date_envoi' => $date_envoi,
'mode' => $mode,
'login' => $user_login,
'attachments' => '',
'user_id' => $user_id,
));
$hie = $wpdb->insert_id;
_e("Votre mailing va bientot demarrer","e-mailing-service");
echo '<meta http-equiv="refresh" content="1; url=admin.php?page=e-mailing-service/admin/live_user.php">';
}
} else {
if($user_role == 'administrator'){
echo '<div class="message info">';
echo "<br><h1>".__("Envoyer un article ou une page avec un serveur au choix","e-mailing-service")."</h1>";
echo '<form action="admin.php?page=e-mailing-service/admin/send_user.php" method="post" target="_parent">
<input type="hidden" name="action" value="envoi_article" />';
echo '<table width="500">';
echo "<tr><td><blockquote><b>".__("Choisir une liste","e-mailing-service")."</b></blockquote></td>
<td><blockquote><select name=\"liste\">";
$listes = $wpdb->get_results("SELECT * FROM `".$table_liste."` WHERE login ='".$user_login."'");
foreach ( $listes as $liste )
{
echo "<option value=\"".$liste->id."|".$liste->liste_bd."\" selected=\"selected\">".$liste->liste_nom."</option>";
}
echo "</select></blockquote></td></tr>
<tr>
<td><blockquote><b>".__("Choisir une campagne","e-mailing-service")."</b></blockquote></td>
<td><blockquote><select name=\"campagne\">";
$news = $wpdb->get_results("SELECT ID,post_title,post_type FROM `".$wpdb->prefix."posts` WHERE (post_type='post' OR post_type='page') AND post_status ='publish' ORDER BY ID ASC");
foreach ( $news as $new )
{
echo "<option value=\"".$new->ID."|".$new->post_type."\" selected=\"selected\">".substr($new->post_title,0,70)."</option>";
}
echo "</select></blockquote></td></tr>
<td><blockquote><b>".__("Choisir la date","e-mailing-service")."</b></blockquote></td>
<td><input name=\"date_envoi\" type=\"text\" value=\"".date('Y-m-d H:i:s')."\" /></td>
</tr>
<tr>
<td><blockquote><b><a href=\"#\" title=\"".__("exemple pause 1s = 1 mail par seconde = 84 600 mails par jours, pause 10 s = 8 460 mails par jours )","e-mailing-service")."\">".__("Temps de pause","e-mailing-service")."</a></b></blockquote></td>
<td><input name=\"pause\" type=\"text\" value=\"10\" size=\"4\"/> s </td>
</tr>
<tr>
<td><blockquote><b><a href=\"#\" title=\"".__("Permet de suivre vos liens dans les statistiques pour separer vos theme par exemple rencontre, commerce, ...","e-mailing-service")."\">".__("Tracking 1","e-mailing-service")."</a></b></blockquote></td>
<td><input name=\"track1\" type=\"text\" value=\"\" size=\"10\"/></td>
</tr>
<tr>
<td><blockquote><b><a href=\"#\" title=\"".__("Permet de suivre vos liens dans les statistiques pour separer vos clients ou autres)","e-mailing-service")."\">".__("Tracking 2","e-mailing-service")."</a></b></blockquote></td>
<td><input name=\"track2\" type=\"text\" value=\"\" size=\"10\"/></td>
</tr>
<tr>
<td><blockquote><b><a href=\"#\" title=\"".__("Permet de suivre vos liens dans les statistiques pour separer vos clients ou autres)","e-mailing-service")."\">".__("Tracking 2","e-mailing-service")."</a></b></blockquote></td>
<td><blockquote><select name=\"mode\">";
echo "<option value=\"text/html\" selected=\"selected\">html</option>";
echo "<option value=\"text/plain\">text</option>";
echo "</select></blockquote></td>
</tr>
<tr>
<td><input name=\"envoyer\" type=\"submit\" class=\"button button-blue\" value=\"".__("envoyer","e-mailing-service")."\"/></td>
<td></td>
</tr></tbody></table></form>";
echo "</div>";
}
if(is_plugin_active('admin-hosting/admin-hosting.php') ) {
if(ah_service_actif($user_login) !='server' && $user_role != 'administrator'){
$all_meta_for_user = get_user_meta( $user_id );
echo '<div class="message warning">';
echo '<h1>'.ah_credit($user_login).' '.get_option('ah_curency1').'</h1>';
$nb_mail_possible =ah_credit($user_login) / get_option('ah_tarif_credit');
echo '<p>'.__("Vous pouvez envoyer","e-mailing-service").' '.$nb_mail_possible.' '.__("emails","e-mailing-service").' '.__("avec votre solde","e-mailing-service").'</p>';
echo '</div>';
if(ah_credit($user_login) < 1) {
echo "<h2>".__("Votre solde de credit n'est pas suffisant pour envoyer un mailing, vous devez crediter votre compte","e-mailing-service")."</h2>";
echo "<h2><a href=\"".get_site_url()."/".$all_meta_for_user['lang'][0]."/email/email-marketing/\">".__("ou choisisir un forfait","e-mailing-service")."</a></h2>";
form_add_credit();
exit();
}
}
}
echo '<div class="message success">';
echo "<br><h1>".__("Envoyer votre newsletter","e-mailing-service")."</h1>";
echo "<p>".__("Votre newsletter partira quelques minutes apres la validation du formulaire si vous ne changer pas la date et l'heure d'envoi","e-mailing-service")."</p>";
echo '<form action="admin.php?page=e-mailing-service/admin/send_user.php" method="post" target="_parent" enctype="multipart/form-data">
<input type="hidden" name="action" value="envoi" />';
echo '<table width="500">
<thead>';
echo "
<tr><td width=\"50%\"><blockquote><b>".__("Choisir une liste","e-mailing-service")."</b></blockquote></td>
<td width=\"200\"><select name=\"liste\">";
$n=0;
$listes = $wpdb->get_results("SELECT * FROM `".$table_liste."` where login='".$user_login."' ORDER BY id DESC");
foreach ( $listes as $liste )
{
if($n == 0){ $select = "selected=\"selected\""; } else { $select = ""; }
echo "<option value=\"".$liste->id."|".$liste->liste_bd."\" ".$select.">".$liste->liste_nom." </option>";
$n++;
}
$listes = $wpdb->get_results("SELECT * FROM `".$table_liste."` where type='location'");
foreach ( $listes as $liste )
{
echo '<option value="'.$liste->id.'|'.$liste->liste_bd.'">'.__('location','e-mailing-service').' : '.$liste->liste_nom.' '.$liste->tarif.' '.__('credit','e-mailing-service').' / email</option>';
}
echo "</select></td>
</tr>
<tr><td><blockquote><b>".__("Choisir une campagne","e-mailing-service")."</b></blockquote></td><td><select name=\"campagne\">";
$n=0;
if(isset($newsletter)){
$news = $wpdb->get_results("SELECT ID,post_title FROM `".$wpdb->prefix."posts` WHERE post_author='".$user_id."' AND ID ='".$newsletter."' ORDER BY ID DESC");
} else {
$news = $wpdb->get_results("SELECT ID,post_title FROM `".$wpdb->prefix."posts` WHERE post_author='".$user_id."' AND post_type='newsletter' AND post_status ='publish' ORDER BY ID DESC");
}
foreach ( $news as $new )
{
if($n == 0){ $select = "selected=\"selected\""; } else { $select = ""; }
echo "<option value=\"".$new->ID."\" ".$select.">".substr($new->post_title,0,70)."</option>";
$n++;
}
echo "</select></td></tr>
<tr>
<td width=\"200\"><blockquote><b>".__("Choisir la date","e-mailing-service")."</b></blockquote></td><td><input name=\"date_envoi\" type=\"text\" value=\"".date('Y-m-d H:i:s')."\" /></td></tr>
<tr><td><blockquote><b>".__("From Name","e-mailing-service")."</b></blockquote></td><td>
<input name=\"reply_to\" type=\"text\" value=\"".get_user_meta( $user_id, 'sm_reply',true)."\" /></td></tr>
<tr><td><blockquote><b>".__("Reply TO","e-mailing-service")."</b></blockquote></td><td>
<input name=\"fromname\" type=\"text\" value=\"".get_user_meta( $user_id, 'sm_fromname',true)."\" /></td></tr>
<tr><td><blockquote><b><a href=\"#\" title=\"".__("exemple pause 1s = 1 mail par seconde = 84 600 mails par jours, pause 10 s = 8 460 mails par jours )","e-mailing-service")."\">".__("Temps de pause")."</a></b></blockquote></td>
<td><input name=\"pause\" type=\"text\" value=\"10\" size=\"4\"/> s </td></tr>
<tr><td><blockquote><b><a href=\"#\" title=\"".__("Permet de suivre vos liens dans les statistiques pour separer vos theme par exemple rencontre, commerce, ...","e-mailing-service")."\">".__("Tracking 1","e-mailing-service")."</a></b></blockquote></td>
<td><input name=\"track1\" type=\"text\" value=\"\" size=\"10\"/></td>
</tr>
<tr><td><blockquote><b><a href=\"#\" title=\"".__("Permet de suivre vos liens dans les statistiques pour separer vos clients ou autres)","e-mailing-service")."\">".__("Tracking 2","e-mailing-service")."</a></b></blockquote></td>
<td><input name=\"track2\" type=\"text\" value=\"\" size=\"10\"/></td>
</tr>
<tr><td><blockquote><b>".__("Format","e-mailing-service")."</b></blockquote></td><td>
<select name=\"mode\">";
echo "<option value=\"text/html\" selected=\"selected\">html</option>";
echo "<option value=\"text/plain\">text</option>";
echo '</select></td></tr>
<tr><td><blockquote><b>'.__("Piece jointe","e-mailing-service").'</b></blockquote></td><td><input name="file" type="file"/></td></tr>
';
echo "</thead></table><br>
<input name=\"envoyer\" type=\"submit\" class=\"button button-green\" value=\"".__("envoyer","e-mailing-service")."\"/></td></form><br>
";
echo "</div>";
}
?></div></section></div></section> | gpl-3.0 |
hartwigmedical/hmftools | serve/src/main/java/com/hartwig/hmftools/serve/sources/iclusion/tools/IclusionExtractorTestApp.java | 4887 | package com.hartwig.hmftools.serve.sources.iclusion.tools;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import com.hartwig.hmftools.common.drivercatalog.panel.DriverGene;
import com.hartwig.hmftools.common.drivercatalog.panel.DriverGeneFile;
import com.hartwig.hmftools.common.ensemblcache.EnsemblDataCache;
import com.hartwig.hmftools.common.fusion.KnownFusionCache;
import com.hartwig.hmftools.common.genome.refgenome.RefGenomeVersion;
import com.hartwig.hmftools.common.serve.Knowledgebase;
import com.hartwig.hmftools.iclusion.classification.IclusionClassificationConfig;
import com.hartwig.hmftools.iclusion.datamodel.IclusionTrial;
import com.hartwig.hmftools.serve.ServeConfig;
import com.hartwig.hmftools.serve.ServeLocalConfigProvider;
import com.hartwig.hmftools.serve.curation.DoidLookup;
import com.hartwig.hmftools.serve.curation.DoidLookupFactory;
import com.hartwig.hmftools.serve.extraction.ExtractionResult;
import com.hartwig.hmftools.serve.extraction.ExtractionResultWriter;
import com.hartwig.hmftools.serve.extraction.hotspot.ProteinResolverFactory;
import com.hartwig.hmftools.serve.refgenome.EnsemblDataCacheLoader;
import com.hartwig.hmftools.serve.refgenome.ImmutableRefGenomeResource;
import com.hartwig.hmftools.serve.refgenome.RefGenomeResource;
import com.hartwig.hmftools.serve.sources.iclusion.IclusionExtractor;
import com.hartwig.hmftools.serve.sources.iclusion.IclusionExtractorFactory;
import com.hartwig.hmftools.serve.sources.iclusion.IclusionReader;
import com.hartwig.hmftools.serve.sources.iclusion.IclusionUtil;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.Configurator;
import org.jetbrains.annotations.NotNull;
import htsjdk.samtools.reference.IndexedFastaSequenceFile;
public class IclusionExtractorTestApp {
private static final Logger LOGGER = LogManager.getLogger(IclusionExtractorTestApp.class);
public static void main(String[] args) throws IOException {
Configurator.setRootLevel(Level.INFO);
ServeConfig config = ServeLocalConfigProvider.create();
Path outputPath = new File(config.outputDir()).toPath();
if (!Files.exists(outputPath)) {
LOGGER.info("Creating {} directory for writing SERVE output", outputPath.toString());
Files.createDirectory(outputPath);
}
DoidLookup doidLookup = DoidLookupFactory.buildFromMappingTsv(config.missingDoidsMappingTsv());
RefGenomeResource refGenomeResource = buildRefGenomeResource(config);
IclusionExtractor extractor =
IclusionExtractorFactory.buildIclusionExtractor(IclusionClassificationConfig.build(), refGenomeResource, doidLookup);
List<IclusionTrial> trials = IclusionReader.readAndCurate(config.iClusionTrialTsv(), config.iClusionFilterTsv());
ExtractionResult result = extractor.extract(trials);
IclusionUtil.printIclusionResult(result);
String iclusionMutationTsv = config.outputDir() + File.separator + "IclusionEventClassification.tsv";
IclusionUtil.writeIclusionMutationTypes(iclusionMutationTsv, trials);
new ExtractionResultWriter(config.outputDir(), Knowledgebase.ICLUSION.refGenomeVersion(), refGenomeResource.refSequence()).write(
result);
}
@NotNull
private static RefGenomeResource buildRefGenomeResource(@NotNull ServeConfig config) throws IOException {
LOGGER.info("Reading driver genes from {}", config.driverGene37Tsv());
List<DriverGene> driverGenes = DriverGeneFile.read(config.driverGene37Tsv());
LOGGER.info(" Read {} driver genes", driverGenes.size());
LOGGER.info("Reading known fusions from {}", config.knownFusion37File());
KnownFusionCache fusionCache = new KnownFusionCache();
if (!fusionCache.loadFile(config.knownFusion37File())) {
throw new IOException("Could not load known fusion cache from " + config.knownFusion37File());
}
LOGGER.info(" Read {} known fusions", fusionCache.getData().size());
LOGGER.info(" Reading ensembl data cache from {}", config.ensemblDataDir37());
EnsemblDataCache ensemblDataCache = EnsemblDataCacheLoader.load(config.ensemblDataDir37(), RefGenomeVersion.V37);
LOGGER.info(" Loaded ensembl data cache from {}", ensemblDataCache);
return ImmutableRefGenomeResource.builder()
.refSequence(new IndexedFastaSequenceFile(new File(config.refGenome37FastaFile())))
.driverGenes(driverGenes)
.knownFusionCache(fusionCache)
.ensemblDataCache(ensemblDataCache)
.proteinResolver(ProteinResolverFactory.dummy())
.build();
}
}
| gpl-3.0 |
XSZHOU/negf-reference | src/flens/fem/fem.cc | 7755 | #include <cmath>
#include <fem/fem.h>
#include <set>
#include <sstream>
namespace flens {
//------------------------------------------------------------------------------
typedef std::pair<int,int> NodePair;
bool
operator<(const NodePair &p1, const NodePair &p2)
{
if (p1.first<p2.first) {
return true;
}
if ((p1.first==p2.first) || (p1.second<p2.second)) {
return true;
}
return false;
}
NodePair
makeNodePair(int n1, int n2)
{
return (n1<n2) ? NodePair(n1, n2) : NodePair(n2,n1);
}
//------------------------------------------------------------------------------
Mesh::Mesh(const char *nodesFile, const char *trianglesFile)
{
std::ifstream inNodes(nodesFile), inTriangles(trianglesFile);
int _numNodes, _numTriangles;
inNodes >> _numNodes;
_nodes.resize(_numNodes, 2);
for (int i=1; i<=numNodes(); ++i) {
inNodes >> _nodes(i,1) >> _nodes(i,2);
}
inTriangles >> _numTriangles;
_triangles.resize(_numTriangles, 3);
for (int i=1; i<=numTriangles(); ++i) {
inTriangles >> _triangles(i,1) >> _triangles(i,2) >> _triangles(i,3);
}
_nu.resize(_numNodes);
_eta.resize(_numNodes);
// -------------------------------------------------------------------------
typedef std::map<NodePair,int> EdgeCount;
EdgeCount edgeCount;
for (int i=1; i<=numTriangles(); ++i) {
Triangle t = triangle(i);
for (int i=1; i<=3; ++i) {
NodePair e = makeNodePair(t(i), t((i<3) ? i+1 : 1));
++edgeCount[e];
}
}
// create set of boundary nodes
std::set<int> bn;
typedef EdgeCount::const_iterator EdgeCountIt;
for (EdgeCountIt it=edgeCount.begin(); it!=edgeCount.end(); ++it) {
if (it->second==1) {
bn.insert(it->first.first);
bn.insert(it->first.second);
}
}
// boundary nodes have indices nu(M+1),...,nu(N)
// where M = number of inner nodes, N = number of nodes
int counter = numNodes();
for (std::set<int>::const_iterator it=bn.begin(); it!=bn.end(); ++it) {
_nu(counter) = *it;
_eta(*it) = counter--;
}
_numInteriorNodes = counter;
// innern nodes have indices nu(1),...,nu(M)
counter = 1;
for (int i=1; i<=numNodes(); ++i) {
if (_eta(i)==0) {
_nu(counter) = i;
_eta(i) = counter++;
}
}
}
int
Mesh::numTriangles() const
{
return _triangles.numRows();
}
const Mesh::Triangle
Mesh::triangle(int index) const
{
return _triangles(index,_);
}
int
Mesh::numNodes() const
{
return _nodes.numRows();
}
Mesh::Node
Mesh::node(int index) const
{
return _nodes(index,_);
}
int
Mesh::numInteriorNodes() const
{
return _numInteriorNodes;
}
int
Mesh::nu(int index) const
{
return _nu(index);
}
int
Mesh::eta(int index) const
{
return _eta(index);
}
//------------------------------------------------------------------------------
double
det(const DenseVector<Array<double> > &a, const DenseVector<Array<double> > &b)
{
return a(1)*b(2) - a(2)*b(1);
}
double
dot(const DenseVector<Array<double> > &a, const DenseVector<Array<double> > &b)
{
return a(1)*b(1) + a(2)*b(2);
}
//------------------------------------------------------------------------------
extern "C" {
void
pardiso_(int *pt, int *maxfct, int *mnum, int *mtype, int *phase,
int *n, double *a, int *ia, int *ja, int *perm, int *nrhs,
int *iparm, int *msglvl, double *b, double *sol, int *error);
}
template <typename E1, typename E2>
void
pardiso(DenseVector<E1> &x,
SparseSymmetricMatrix<CRS<double> > &A, DenseVector<E2> &b)
{
int pt[2*64*10];
memset(pt, 0, 2*sizeof(int)*64*10);
int maxfct = 1;
int mnum = 1;
int mtype = 2;
int phase = 13;
int n = A.numRows();
double *a = A.engine().values().data();
int *ia = A.engine().rows().data();
int *ja = A.engine().columns().data();
int perm[n];
int nrhs = 1;
int iparm[64];
iparm[0] = 0;
iparm[2] = 1;
int msglvl = 1;
double *y = b.data();
double *sol = x.data();
int error;
pardiso_(pt, &maxfct, &mnum, &mtype, &phase, &n, a, ia, ja, perm, &nrhs,
iparm, &msglvl, y, sol, &error);
}
//------------------------------------------------------------------------------
FEM::FEM(const char *nodesFile, const char *trianglesFile,
const Func &_f, const Func &_g)
: mesh(nodesFile, trianglesFile), f(_f), g(_g),
u(mesh.numNodes()), b(mesh.numInteriorNodes()),
A(mesh.numInteriorNodes(), mesh.numInteriorNodes()),
Am(3,3), bm(3), S(3, DGeMatrix(3,3))
{
for (int i=mesh.numInteriorNodes()+1; i<=mesh.numNodes(); ++i) {
u(i) = g(mesh.node(mesh.nu(i)));
}
S[0] = 0.5, -0.5, 0,
-0.5, 0.5, 0,
0, 0, 0;
S[1] = 1, -0.5, -0.5,
-0.5, 0, 0.5,
-0.5, 0.5, 0;
S[2] = 0.5, 0, -0.5,
0, 0, 0,
-0.5, 0, 0.5;
}
void
FEM::assemble()
{
int M = mesh.numInteriorNodes();
for (int m=1; m<=mesh.numTriangles(); ++m) {
Triangle t = mesh.triangle(m);
compute_Am_bm(t);
for (int r=1; r<=3; ++r) {
int k=mesh.eta(t(r));
if (k<=M) {
b(k) += bm(r);
}
for (int s=r; s<=3; ++s) {
int l=mesh.eta(t(s));
if ((k>M) && (l>M)) {
continue;
}
if ((k<=M) && (l<=M)) {
A(k,l) += Am(r,s);
} else {
int k_ = std::min(k,l);
int l_ = std::max(k,l);
b(k_) -= Am(r,s)*u(l_);
}
}
}
}
A.finalize();
}
void
FEM::compute_Am_bm(const Triangle &t)
{
const Node &a1 = mesh.node(t(1)),
&a2 = mesh.node(t(2)),
&a3 = mesh.node(t(3));
/*
DenseVector<Array<double> > b1 = a2-a1,
b2 = a3-a1;
*/
DenseVector<Array<double> > b1(2), b2(2);
b1 = a2(1) - a1(1), a2(2) - a1(2);
b2 = a3(1) - a1(1), a3(2) - a1(2);
double absDetB = std::abs(det(b1,b2));
double gamma[3];
gamma[0] = dot(b2, b2)/absDetB,
gamma[1] = -dot(b1, b2)/absDetB,
gamma[2] = dot(b1, b1)/absDetB;
for (int i=1; i<=3; ++i) {
for (int j=i; j<=3; ++j) {
Am(i,j) = gamma[0]*S[0](i,j)
+gamma[1]*S[1](i,j)
+gamma[2]*S[2](i,j);
}
}
bm(1) = f(a1)*absDetB/6;
bm(2) = f(a2)*absDetB/6;
bm(3) = f(a3)*absDetB/6;
}
void
FEM::solve()
{
std::cerr << "install pardiso or write your own solver :-)" << std::endl;
/*
int M = mesh.numInteriorNodes();
DenseVector<ArrayView<double> > u_ = u(_(1,M));
pardiso(u_, A, b);
*/
}
void
FEM::writeSolution(const char *filename)
{
std::ostringstream pointsFile, facesFile;
pointsFile << filename << ".points";
facesFile << filename << ".faces";
std::ofstream pointsOut(pointsFile.str().c_str());
std::ofstream facesOut(facesFile.str().c_str());
pointsOut << mesh.numNodes() << std::endl;
for (int i=1; i<=mesh.numNodes(); ++i) {
Node node = mesh.node(i);
pointsOut << node(1) << " " << node(2) << " ";
pointsOut << u(mesh.eta(i)) << " 0" << std::endl;
}
facesOut << mesh.numTriangles() << std::endl;
for (int i=1; i<=mesh.numTriangles(); ++i) {
Triangle t = mesh.triangle(i);
facesOut << "3 " << t(1) << " " << t(2) << " " << t(3) << " ";
facesOut << "0 0 0 0" << std::endl;
}
}
} // namespace flens
| gpl-3.0 |
SeqWare/queryengine | seqware-queryengine-backend/src/main/java/com/github/seqware/queryengine/kernel/SeqWareQueryLanguageLexerWrapper.java | 1556 | /*
* Copyright (C) 2012 SeqWare
*
* 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.github.seqware.queryengine.kernel;
import com.github.seqware.queryengine.kernel.output.SeqWareQueryLanguageLexer;
import org.antlr.runtime.CharStream;
import org.antlr.runtime.RecognitionException;
import org.antlr.runtime.RecognizerSharedState;
/**
* <p>SeqWareQueryLanguageLexerWrapper class.</p>
*
* @author dyuen
* @version $Id: $Id
*/
public class SeqWareQueryLanguageLexerWrapper extends SeqWareQueryLanguageLexer {
/**
* <p>Constructor for SeqWareQueryLanguageLexerWrapper.</p>
*
* @param input a {@link org.antlr.runtime.CharStream} object.
*/
public SeqWareQueryLanguageLexerWrapper(CharStream input) {
super(input, new RecognizerSharedState());
}
/** {@inheritDoc} */
@Override
public void reportError(RecognitionException e) {
throw new IllegalArgumentException(e);
}
}
| gpl-3.0 |
lgulyas/MEME | Plugins/BeanShell/ai/aitia/meme/scripting/bshcmds/geti.java | 1356 | /*******************************************************************************
* Copyright (C) 2006-2013 AITIA International, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package ai.aitia.meme.scripting.bshcmds;
import bsh.CallStack;
import bsh.Interpreter;
import ai.aitia.meme.viewmanager.ParameterSet.Category;
/**
* Implements the <code>geti(String name)</code> command for BeanShell.
*/
public class geti
{
//-------------------------------------------------------------------------
public static Object invoke(Interpreter interp, CallStack callstack, String name) throws Exception
{
return get.doIt("geti", Category.INPUT, interp, name);
}
}
| gpl-3.0 |
Nithanaroy/ngn-events-rating | app/controllers/static_pages_controller.rb | 347 | class StaticPagesController < ApplicationController
def welcome
@coming_up = Event.order(from: :desc).limit(5) # First event in the Jumbotron
@coming_up = @coming_up.where('created_at > ?', Time.now) if Rails.env.production? # in dev show everything
@recently_added = Event.order(created_at: :desc).limit(4)
end
def about
end
end
| gpl-3.0 |
dmitry-vlasov/mdl | src/mdl/auxiliary/config/mdl_auxiliary_config_Mining.cpp | 8774 | /*****************************************************************************/
/* Project name: mdl - mathematics development language */
/* File name: mdl_auxiliary_config_Mining.cpp */
/* Description: Mining :: class for mdl source mining */
/* 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
namespace mdl {
namespace auxiliary {
namespace config {
/****************************
* Public members
****************************/
// lookup position
inline bool
Mining :: lookupDefinition() {
return lookupOptions_[LOOKUP_DEFINITION]->getValue();
}
inline bool
Mining :: lookupLocation() {
return lookupOptions_[LOOKUP_LOCATION]->getValue();
}
inline bool
Mining :: lookup() {
return (lookupDefinition() || lookupLocation());
}
// mining options
inline container :: Bit
Mining :: getMiningOptions() {
return miningOptions_;
}
inline Mining :: MiningMode_
Mining :: getMiningMode() {
return miningMode_;
}
inline bool
Mining :: mine() {
return (miningMode_ != MINE_NOTHING);
}
// parse only definitions
inline bool
Mining :: shallowParsing() {
return (mine() || lookup());
}
// parse only current file
inline bool
Mining :: localParsing() {
return (miningMode_ == MINE_OUTLINE);
}
template<class S>
void
Mining :: showUsageMessage (S& os, const List& groupList)
{
if (groupList.contains (optionGroupName_)) {
os << optionGroupName_ << ':' << chars :: NEW_LINE;
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
lookupOptions_ [i]->showUsageMessage (os);
}
os << chars :: NEW_LINE;
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
mineModes_ [i]->showUsageMessage (os);
}
os << chars :: NEW_LINE;
for (int i = 0; i < MINE_OPTIONS_NUM; ++ i) {
mineOptions_ [i]->showUsageMessage (os);
}
os << chars :: NEW_LINE;
}
}
template<class S>
void
Mining :: showOptionValues (S& os, const List& groupList)
{
if (groupList.contains (optionGroupName_)) {
os << optionGroupName_ << ':' << chars :: NEW_LINE;
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
lookupOptions_ [i]->showOptionValues (os);
}
os << chars :: NEW_LINE;
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
mineModes_ [i]->showOptionValues (os);
}
os << chars :: NEW_LINE;
for (int i = 0; i < MINE_OPTIONS_NUM; ++ i) {
mineOptions_ [i]->showOptionValues (os);
}
os << chars :: NEW_LINE;
}
}
template<class S>
inline void
Mining :: showGroupName (S& os) {
os << "\t" << optionGroupName_ << chars :: NEW_LINE;
}
/****************************
* Protected members
****************************/
bool
Mining :: proceedStringOption (const char* opt, const int argCount, const char* argValues[], int& i)
{
for (int j = 0; j < LOOKUP_OPTIONS_NUM; ++ j) {
if (lookupOptions_[j]->proceedStringOption (opt, argCount, argValues, i)) {
return true;
}
}
for (int j = 0; j < MINE_MODE_NUM; ++ j) {
if (mineModes_[j]->proceedStringOption (opt, argCount, argValues, i)) {
miningMode_ = static_cast<MiningMode_>(j);
return true;
}
}
for (int j = 0; j < MINE_OPTIONS_NUM; ++ j) {
if (mineOptions_[j]->proceedStringOption (opt, argCount, argValues, i)) {
miningOptions_.setValue (j);
if (mineOptions_ [MINE_ALL]->getValue()) {
for (int k = 0; k < MINE_OPTIONS_NUM; ++ k) {
mineOptions_ [k]->value() = true;
miningOptions_.setValue (k);
}
}
return true;
}
}
return false;
}
bool
Mining :: proceedOneCharOption (const char* opt, const int argCount, const char* argValues[], int& i) {
return false;
}
bool
Mining :: isCorrect()
{
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
if (!lookupOptions_ [i]->isCorrect()) {
return false;
}
}
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
if (!mineModes_ [i]->isCorrect()) {
return false;
}
}
for (int i = 0; i < MINE_OPTIONS_NUM; ++ i) {
if (!mineOptions_ [i]->isCorrect()) {
return false;
}
}
return true;
}
inline bool
Mining :: isConsistent()
{
bool someIsChecked = false;
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
if (lookupOptions_ [i]->getValue()) {
if (!someIsChecked) {
someIsChecked = true;
} else {
std :: cout << "two different actions are chosen." << std :: endl;
return false;
}
}
}
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
if (mineModes_ [i]->getValue()) {
if (!someIsChecked) {
someIsChecked = true;
} else {
std :: cout << "two different actions are chosen." << std :: endl;
return false;
}
}
}
return true;
}
inline bool
Mining :: someActionIsChosen()
{
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
if (lookupOptions_ [i]->getValue()) {
return true;
}
}
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
if (mineModes_ [i]->getValue()) {
return true;
}
}
return false;
}
inline void
Mining :: init ()
{
lookupOptions_ [LOOKUP_DEFINITION] = new option :: Bool (false, "lookup-definition", "find the definition of an object and put in into std :: cout.");
lookupOptions_ [LOOKUP_LOCATION] = new option :: Bool (false, "lookup-location", "find the location of an object and put in into std :: cout.");
mineModes_ [MINE_OUTLINE] = new option :: Bool (false, "mine-outline", "mine outline and put as XML in into std :: cout.");
mineModes_ [MINE_TYPE_SYSTEM] = new option :: Bool (false, "mine-type-system", "mine type system and put as XML in into std :: cou.t");
mineModes_ [MINE_STRUCTURE] = new option :: Bool (false, "mine-structure", "mine global structure and put as XML in into std :: cout.");
mineOptions_ [MINE_IMPORTS] = new option :: Bool (false, "mine-imports", "imports are considered.");
mineOptions_ [MINE_CONSTANTS] = new option :: Bool (false, "mine-constants", "constants are considered.");
mineOptions_ [MINE_AXIOMS] = new option :: Bool (false, "mine-axioms", "axioms are considered.");
mineOptions_ [MINE_DEFINITIONS] = new option :: Bool (false, "mine-definitions", "definitions are considered.");
mineOptions_ [MINE_RULES] = new option :: Bool (false, "mine-rules", "rules are considered.");
mineOptions_ [MINE_TYPES] = new option :: Bool (false, "mine-types", "types are considered.");
mineOptions_ [MINE_THEORIES] = new option :: Bool (false, "mine-theories", "theories are considered.");
mineOptions_ [MINE_THEOREMS] = new option :: Bool (false, "mine-theorems", "theorems are considered.");
mineOptions_ [MINE_PROBLEMS] = new option :: Bool (false, "mine-problems", "problems are considered.");
mineOptions_ [MINE_ALL] = new option :: Bool (false, "mine-all", "all kinds of objects are considered");
}
inline void
Mining :: release()
{
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
if (lookupOptions_ [i] != NULL) {
delete lookupOptions_ [i];
lookupOptions_ [i] = NULL;
}
}
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
if (mineModes_ [i] != NULL) {
delete mineModes_ [i];
mineModes_ [i] = NULL;
}
}
for (int i = 0; i < MINE_OPTIONS_NUM; ++ i) {
if (mineOptions_ [i] != NULL) {
delete mineOptions_ [i];
mineOptions_ [i] = NULL;
}
}
}
inline Size_t
Mining :: getVolume()
{
Size_t volume = 0;
for (int i = 0; i < LOOKUP_OPTIONS_NUM; ++ i) {
volume += object :: Object :: getAggregateVolume (lookupOptions_ [i]);
}
for (int i = 0; i < MINE_OPTIONS_NUM; ++ i) {
volume += object :: Object :: getAggregateVolume (mineOptions_ [i]);
}
for (int i = 0; i < MINE_MODE_NUM; ++ i) {
volume += object :: Object :: getAggregateVolume (mineModes_ [i]);
}
return volume;
}
/*************************************
* Private static attributes
*************************************/
container :: Bit Mining :: miningOptions_;
Mining :: MiningMode_ Mining :: miningMode_ = Mining :: DEFAULT_MINING;
option :: Bool* Mining :: lookupOptions_ [LOOKUP_OPTIONS_NUM];
option :: Bool* Mining :: mineModes_ [MINE_MODE_NUM];
option :: Bool* Mining :: mineOptions_ [MINE_OPTIONS_NUM];
const char* Mining :: optionGroupName_ = "mining";
}
}
}
| gpl-3.0 |
ThilinaPeiris/Training-Tracker | TrainingTracker-SourceCode/signin.cpp | 2064 | #include "signin.h"
#include "ui_signin.h"
SignIn::SignIn(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::SignIn)
{
ui->setupUi(this);
statusBar()->setStyleSheet("background: rgb(52, 152, 219);");
}
SignIn::~SignIn()
{
delete ui;
}
void SignIn::on_PushButton_SignIn_clicked()
{
path = QDir::currentPath() + "\\TrainingTracker.sqlite";
m_db = QSqlDatabase::addDatabase("QSQLITE");
m_db.setDatabaseName(path);
QString username = ui->LineEdit_UserName->text();
QString password = ui->LineEdit_Password->text();
if (!m_db.open())
{
//qDebug() << "Error: connection with database fail";
//Error Handle
}
else
{
//qDebug() << "Database: connection ok";
QSqlQuery qry;
if(qry.exec("select * from users where name='" + username + "' and password='" + password +"'"))
{
int count = 0;
while(qry.next())
{
count++;
}
if(count == 1)
{
m_db.close();
m_db = QSqlDatabase();
m_db.removeDatabase(QSqlDatabase::defaultConnection);
this->hide();
MainWindow mainwindow;
mainwindow.setModal(true);
mainwindow.exec();
}else
{
//username and password doesn't match.
statusBar()->showMessage("Invalid Username or Password! Try Again!");
}
}
}
// if(QString::compare(username, "Bhagy") == 0 && QString::compare(password, "123") == 0)
// {
// this->hide();
// MainWindow mainwindow;
// mainwindow.setModal(true);
// mainwindow.exec();
// }else
// {
// statusBar()->showMessage("Invalid Username or Password! Try Again!");
// }
}
void SignIn::on_pushButton_SignUp_clicked()
{
this->hide();
SignUp signup;
signup.setModal(true);
signup.exec();
}
| gpl-3.0 |
ouyangyu/fdmoodle | lib/yuilib/3.13.0/widget-parent/widget-parent.js | 26293 | /*
YUI 3.13.0 (build 508226d)
Copyright 2013 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('widget-parent', function (Y, NAME) {
/**
* Extension enabling a Widget to be a parent of another Widget.
*
* @module widget-parent
*/
var Lang = Y.Lang,
RENDERED = "rendered",
BOUNDING_BOX = "boundingBox";
/**
* Widget extension providing functionality enabling a Widget to be a
* parent of another Widget.
*
* <p>In addition to the set of attributes supported by WidgetParent, the constructor
* configuration object can also contain a <code>children</code> which can be used
* to add child widgets to the parent during construction. The <code>children</code>
* property is an array of either child widget instances or child widget configuration
* objects, and is sugar for the <a href="#method_add">add</a> method. See the
* <a href="#method_add">add</a> for details on the structure of the child widget
* configuration object.
* @class WidgetParent
* @constructor
* @uses ArrayList
* @param {Object} config User configuration object.
*/
function Parent(config) {
/**
* Fires when a Widget is add as a child. The event object will have a
* 'child' property that returns a reference to the child Widget, as well
* as an 'index' property that returns a reference to the index specified
* when the add() method was called.
* <p>
* Subscribers to the "on" moment of this event, will be notified
* before a child is added.
* </p>
* <p>
* Subscribers to the "after" moment of this event, will be notified
* after a child is added.
* </p>
*
* @event addChild
* @preventable _defAddChildFn
* @param {EventFacade} e The Event Facade
*/
this.publish("addChild", {
defaultTargetOnly: true,
defaultFn: this._defAddChildFn
});
/**
* Fires when a child Widget is removed. The event object will have a
* 'child' property that returns a reference to the child Widget, as well
* as an 'index' property that returns a reference child's ordinal position.
* <p>
* Subscribers to the "on" moment of this event, will be notified
* before a child is removed.
* </p>
* <p>
* Subscribers to the "after" moment of this event, will be notified
* after a child is removed.
* </p>
*
* @event removeChild
* @preventable _defRemoveChildFn
* @param {EventFacade} e The Event Facade
*/
this.publish("removeChild", {
defaultTargetOnly: true,
defaultFn: this._defRemoveChildFn
});
this._items = [];
var children,
handle;
if (config && config.children) {
children = config.children;
handle = this.after("initializedChange", function (e) {
this._add(children);
handle.detach();
});
}
// Widget method overlap
Y.after(this._renderChildren, this, "renderUI");
Y.after(this._bindUIParent, this, "bindUI");
this.after("selectionChange", this._afterSelectionChange);
this.after("selectedChange", this._afterParentSelectedChange);
this.after("activeDescendantChange", this._afterActiveDescendantChange);
this._hDestroyChild = this.after("*:destroy", this._afterDestroyChild);
this.after("*:focusedChange", this._updateActiveDescendant);
}
Parent.ATTRS = {
/**
* @attribute defaultChildType
* @type {String|Object}
*
* @description String representing the default type of the children
* managed by this Widget. Can also supply default type as a constructor
* reference.
*/
defaultChildType: {
setter: function (val) {
var returnVal = Y.Attribute.INVALID_VALUE,
FnConstructor = Lang.isString(val) ? Y[val] : val;
if (Lang.isFunction(FnConstructor)) {
returnVal = FnConstructor;
}
return returnVal;
}
},
/**
* @attribute activeDescendant
* @type Widget
* @readOnly
*
* @description Returns the Widget's currently focused descendant Widget.
*/
activeDescendant: {
readOnly: true
},
/**
* @attribute multiple
* @type Boolean
* @default false
* @writeOnce
*
* @description Boolean indicating if multiple children can be selected at
* once. Whether or not multiple selection is enabled is always delegated
* to the value of the <code>multiple</code> attribute of the root widget
* in the object hierarchy.
*/
multiple: {
value: false,
validator: Lang.isBoolean,
writeOnce: true,
getter: function (value) {
var root = this.get("root");
return (root && root != this) ? root.get("multiple") : value;
}
},
/**
* @attribute selection
* @type {ArrayList|Widget}
* @readOnly
*
* @description Returns the currently selected child Widget. If the
* <code>mulitple</code> attribte is set to <code>true</code> will
* return an Y.ArrayList instance containing the currently selected
* children. If no children are selected, will return null.
*/
selection: {
readOnly: true,
setter: "_setSelection",
getter: function (value) {
var selection = Lang.isArray(value) ?
(new Y.ArrayList(value)) : value;
return selection;
}
},
selected: {
setter: function (value) {
// Enforces selection behavior on for parent Widgets. Parent's
// selected attribute can be set to the following:
// 0 - Not selected
// 1 - Fully selected (all children are selected). In order for
// all children to be selected, multiple selection must be
// enabled. Therefore, you cannot set the "selected" attribute
// on a parent Widget to 1 unless multiple selection is enabled.
// 2 - Partially selected, meaning one ore more (but not all)
// children are selected.
var returnVal = value;
if (value === 1 && !this.get("multiple")) {
returnVal = Y.Attribute.INVALID_VALUE;
}
return returnVal;
}
}
};
Parent.prototype = {
/**
* The destructor implementation for Parent widgets. Destroys all children.
* @method destructor
*/
destructor: function() {
this._destroyChildren();
},
/**
* Destroy event listener for each child Widget, responsible for removing
* the destroyed child Widget from the parent's internal array of children
* (_items property).
*
* @method _afterDestroyChild
* @protected
* @param {EventFacade} event The event facade for the attribute change.
*/
_afterDestroyChild: function (event) {
var child = event.target;
if (child.get("parent") == this) {
child.remove();
}
},
/**
* Attribute change listener for the <code>selection</code>
* attribute, responsible for setting the value of the
* parent's <code>selected</code> attribute.
*
* @method _afterSelectionChange
* @protected
* @param {EventFacade} event The event facade for the attribute change.
*/
_afterSelectionChange: function (event) {
if (event.target == this && event.src != this) {
var selection = event.newVal,
selectedVal = 0; // Not selected
if (selection) {
selectedVal = 2; // Assume partially selected, confirm otherwise
if (Y.instanceOf(selection, Y.ArrayList) &&
(selection.size() === this.size())) {
selectedVal = 1; // Fully selected
}
}
this.set("selected", selectedVal, { src: this });
}
},
/**
* Attribute change listener for the <code>activeDescendant</code>
* attribute, responsible for setting the value of the
* parent's <code>activeDescendant</code> attribute.
*
* @method _afterActiveDescendantChange
* @protected
* @param {EventFacade} event The event facade for the attribute change.
*/
_afterActiveDescendantChange: function (event) {
var parent = this.get("parent");
if (parent) {
parent._set("activeDescendant", event.newVal);
}
},
/**
* Attribute change listener for the <code>selected</code>
* attribute, responsible for syncing the selected state of all children to
* match that of their parent Widget.
*
*
* @method _afterParentSelectedChange
* @protected
* @param {EventFacade} event The event facade for the attribute change.
*/
_afterParentSelectedChange: function (event) {
var value = event.newVal;
if (this == event.target && event.src != this &&
(value === 0 || value === 1)) {
this.each(function (child) {
// Specify the source of this change as the parent so that
// value of the parent's "selection" attribute isn't
// recalculated
child.set("selected", value, { src: this });
}, this);
}
},
/**
* Default setter for <code>selection</code> attribute changes.
*
* @method _setSelection
* @protected
* @param child {Widget|Array} Widget or Array of Widget instances.
* @return {Widget|Array} Widget or Array of Widget instances.
*/
_setSelection: function (child) {
var selection = null,
selected;
if (this.get("multiple") && !this.isEmpty()) {
selected = [];
this.each(function (v) {
if (v.get("selected") > 0) {
selected.push(v);
}
});
if (selected.length > 0) {
selection = selected;
}
}
else {
if (child.get("selected") > 0) {
selection = child;
}
}
return selection;
},
/**
* Attribute change listener for the <code>selected</code>
* attribute of child Widgets, responsible for setting the value of the
* parent's <code>selection</code> attribute.
*
* @method _updateSelection
* @protected
* @param {EventFacade} event The event facade for the attribute change.
*/
_updateSelection: function (event) {
var child = event.target,
selection;
if (child.get("parent") == this) {
if (event.src != "_updateSelection") {
selection = this.get("selection");
if (!this.get("multiple") && selection && event.newVal > 0) {
// Deselect the previously selected child.
// Set src equal to the current context to prevent
// unnecessary re-calculation of the selection.
selection.set("selected", 0, { src: "_updateSelection" });
}
this._set("selection", child);
}
if (event.src == this) {
this._set("selection", child, { src: this });
}
}
},
/**
* Attribute change listener for the <code>focused</code>
* attribute of child Widgets, responsible for setting the value of the
* parent's <code>activeDescendant</code> attribute.
*
* @method _updateActiveDescendant
* @protected
* @param {EventFacade} event The event facade for the attribute change.
*/
_updateActiveDescendant: function (event) {
var activeDescendant = (event.newVal === true) ? event.target : null;
this._set("activeDescendant", activeDescendant);
},
/**
* Creates an instance of a child Widget using the specified configuration.
* By default Widget instances will be created of the type specified
* by the <code>defaultChildType</code> attribute. Types can be explicitly
* defined via the <code>childType</code> property of the configuration object
* literal. The use of the <code>type</code> property has been deprecated, but
* will still be used as a fallback, if <code>childType</code> is not defined,
* for backwards compatibility.
*
* @method _createChild
* @protected
* @param config {Object} Object literal representing the configuration
* used to create an instance of a Widget.
*/
_createChild: function (config) {
var defaultType = this.get("defaultChildType"),
altType = config.childType || config.type,
child,
Fn,
FnConstructor;
if (altType) {
Fn = Lang.isString(altType) ? Y[altType] : altType;
}
if (Lang.isFunction(Fn)) {
FnConstructor = Fn;
} else if (defaultType) {
// defaultType is normalized to a function in it's setter
FnConstructor = defaultType;
}
if (FnConstructor) {
child = new FnConstructor(config);
} else {
Y.error("Could not create a child instance because its constructor is either undefined or invalid.");
}
return child;
},
/**
* Default addChild handler
*
* @method _defAddChildFn
* @protected
* @param event {EventFacade} The Event object
* @param child {Widget} The Widget instance, or configuration
* object for the Widget to be added as a child.
* @param index {Number} Number representing the position at
* which the child will be inserted.
*/
_defAddChildFn: function (event) {
var child = event.child,
index = event.index,
children = this._items;
if (child.get("parent")) {
child.remove();
}
if (Lang.isNumber(index)) {
children.splice(index, 0, child);
}
else {
children.push(child);
}
child._set("parent", this);
child.addTarget(this);
// Update index in case it got normalized after addition
// (e.g. user passed in 10, and there are only 3 items, the actual index would be 3. We don't want to pass 10 around in the event facade).
event.index = child.get("index");
// TO DO: Remove in favor of using event bubbling
child.after("selectedChange", Y.bind(this._updateSelection, this));
},
/**
* Default removeChild handler
*
* @method _defRemoveChildFn
* @protected
* @param event {EventFacade} The Event object
* @param child {Widget} The Widget instance to be removed.
* @param index {Number} Number representing the index of the Widget to
* be removed.
*/
_defRemoveChildFn: function (event) {
var child = event.child,
index = event.index,
children = this._items;
if (child.get("focused")) {
child.blur(); // focused is readOnly, so use the public i/f to unset it
}
if (child.get("selected")) {
child.set("selected", 0);
}
children.splice(index, 1);
child.removeTarget(this);
child._oldParent = child.get("parent");
child._set("parent", null);
},
/**
* @method _add
* @protected
* @param child {Widget|Object} The Widget instance, or configuration
* object for the Widget to be added as a child.
* @param child {Array} Array of Widget instances, or configuration
* objects for the Widgets to be added as a children.
* @param index {Number} (Optional.) Number representing the position at
* which the child should be inserted.
* @description Adds a Widget as a child. If the specified Widget already
* has a parent it will be removed from its current parent before
* being added as a child.
* @return {Widget|Array} Successfully added Widget or Array containing the
* successfully added Widget instance(s). If no children where added, will
* will return undefined.
*/
_add: function (child, index) {
var children,
oChild,
returnVal;
if (Lang.isArray(child)) {
children = [];
Y.each(child, function (v, k) {
oChild = this._add(v, (index + k));
if (oChild) {
children.push(oChild);
}
}, this);
if (children.length > 0) {
returnVal = children;
}
}
else {
if (Y.instanceOf(child, Y.Widget)) {
oChild = child;
}
else {
oChild = this._createChild(child);
}
if (oChild && this.fire("addChild", { child: oChild, index: index })) {
returnVal = oChild;
}
}
return returnVal;
},
/**
* @method add
* @param child {Widget|Object} The Widget instance, or configuration
* object for the Widget to be added as a child. The configuration object
* for the child can include a <code>childType</code> property, which is either
* a constructor function or a string which names a constructor function on the
* Y instance (e.g. "Tab" would refer to Y.Tab) (<code>childType</code> used to be
* named <code>type</code>, support for which has been deprecated, but is still
* maintained for backward compatibility. <code>childType</code> takes precedence
* over <code>type</code> if both are defined.
* @param child {Array} Array of Widget instances, or configuration
* objects for the Widgets to be added as a children.
* @param index {Number} (Optional.) Number representing the position at
* which the child should be inserted.
* @description Adds a Widget as a child. If the specified Widget already
* has a parent it will be removed from its current parent before
* being added as a child.
* @return {ArrayList} Y.ArrayList containing the successfully added
* Widget instance(s). If no children where added, will return an empty
* Y.ArrayList instance.
*/
add: function () {
var added = this._add.apply(this, arguments),
children = added ? (Lang.isArray(added) ? added : [added]) : [];
return (new Y.ArrayList(children));
},
/**
* @method remove
* @param index {Number} (Optional.) Number representing the index of the
* child to be removed.
* @description Removes the Widget from its parent. Optionally, can remove
* a child by specifying its index.
* @return {Widget} Widget instance that was successfully removed, otherwise
* undefined.
*/
remove: function (index) {
var child = this._items[index],
returnVal;
if (child && this.fire("removeChild", { child: child, index: index })) {
returnVal = child;
}
return returnVal;
},
/**
* @method removeAll
* @description Removes all of the children from the Widget.
* @return {ArrayList} Y.ArrayList instance containing Widgets that were
* successfully removed. If no children where removed, will return an empty
* Y.ArrayList instance.
*/
removeAll: function () {
var removed = [],
child;
Y.each(this._items.concat(), function () {
child = this.remove(0);
if (child) {
removed.push(child);
}
}, this);
return (new Y.ArrayList(removed));
},
/**
* Selects the child at the given index (zero-based).
*
* @method selectChild
* @param {Number} i the index of the child to be selected
*/
selectChild: function(i) {
this.item(i).set('selected', 1);
},
/**
* Selects all children.
*
* @method selectAll
*/
selectAll: function () {
this.set("selected", 1);
},
/**
* Deselects all children.
*
* @method deselectAll
*/
deselectAll: function () {
this.set("selected", 0);
},
/**
* Updates the UI in response to a child being added.
*
* @method _uiAddChild
* @protected
* @param child {Widget} The child Widget instance to render.
* @param parentNode {Object} The Node under which the
* child Widget is to be rendered.
*/
_uiAddChild: function (child, parentNode) {
child.render(parentNode);
// TODO: Ideally this should be in Child's render UI.
var childBB = child.get("boundingBox"),
siblingBB,
nextSibling = child.next(false),
prevSibling;
// Insert or Append to last child.
// Avoiding index, and using the current sibling
// state (which should be accurate), means we don't have
// to worry about decorator elements which may be added
// to the _childContainer node.
if (nextSibling && nextSibling.get(RENDERED)) {
siblingBB = nextSibling.get(BOUNDING_BOX);
siblingBB.insert(childBB, "before");
} else {
prevSibling = child.previous(false);
if (prevSibling && prevSibling.get(RENDERED)) {
siblingBB = prevSibling.get(BOUNDING_BOX);
siblingBB.insert(childBB, "after");
} else if (!parentNode.contains(childBB)) {
// Based on pull request from andreas-karlsson
// https://github.com/yui/yui3/pull/25#issuecomment-2103536
// Account for case where a child was rendered independently of the
// parent-child framework, to a node outside of the parentNode,
// and there are no siblings.
parentNode.appendChild(childBB);
}
}
},
/**
* Updates the UI in response to a child being removed.
*
* @method _uiRemoveChild
* @protected
* @param child {Widget} The child Widget instance to render.
*/
_uiRemoveChild: function (child) {
child.get("boundingBox").remove();
},
_afterAddChild: function (event) {
var child = event.child;
if (child.get("parent") == this) {
this._uiAddChild(child, this._childrenContainer);
}
},
_afterRemoveChild: function (event) {
var child = event.child;
if (child._oldParent == this) {
this._uiRemoveChild(child);
}
},
/**
* Sets up DOM and CustomEvent listeners for the parent widget.
* <p>
* This method in invoked after bindUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
*
* @method _bindUIParent
* @protected
*/
_bindUIParent: function () {
this.after("addChild", this._afterAddChild);
this.after("removeChild", this._afterRemoveChild);
},
/**
* Renders all child Widgets for the parent.
* <p>
* This method in invoked after renderUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
* @method _renderChildren
* @protected
*/
_renderChildren: function () {
/**
* <p>By default WidgetParent will render it's children to the parent's content box.</p>
*
* <p>If the children need to be rendered somewhere else, the _childrenContainer property
* can be set to the Node which the children should be rendered to. This property should be
* set before the _renderChildren method is invoked, ideally in your renderUI method,
* as soon as you create the element to be rendered to.</p>
*
* @protected
* @property _childrenContainer
* @value The content box
* @type Node
*/
var renderTo = this._childrenContainer || this.get("contentBox");
this._childrenContainer = renderTo;
this.each(function (child) {
child.render(renderTo);
});
},
/**
* Destroys all child Widgets for the parent.
* <p>
* This method is invoked before the destructor is invoked for the Widget
* class using YUI's aop infrastructure.
* </p>
* @method _destroyChildren
* @protected
*/
_destroyChildren: function () {
// Detach the handler responsible for removing children in
// response to destroying them since:
// 1) It is unnecessary/inefficient at this point since we are doing
// a batch destroy of all children.
// 2) Removing each child will affect our ability to iterate the
// children since the size of _items will be changing as we
// iterate.
this._hDestroyChild.detach();
// Need to clone the _items array since
this.each(function (child) {
child.destroy();
});
}
};
Y.augment(Parent, Y.ArrayList);
Y.WidgetParent = Parent;
}, '3.13.0', {"requires": ["arraylist", "base-build", "widget"]});
| gpl-3.0 |
hotstepper13/alexa-gira-bridge | src/main/java/com/hotstepper13/alexa/gira/Trigger.java | 6485 | /*******************************************************************************
* Copyright (C) 2017 Frank Mueller
*
* 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.hotstepper13.alexa.gira;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hotstepper13.alexa.GiraBridge;
import com.hotstepper13.alexa.gira.beans.Appliance;
import com.hotstepper13.alexa.gira.beans.HomeserverResponse;
import com.hotstepper13.alexa.gira.beans.HueStateChange;
public class Trigger {
private final static Logger log = LoggerFactory.getLogger(Trigger.class);
private static List<Appliance> appliances;
private static Homeserver homeserver;
public Trigger(List<Appliance> appliances) {
Trigger.appliances = appliances;
homeserver = new Homeserver(GiraBridge.config.getHomeserver());
}
public boolean pull(int id, HueStateChange state) {
log.info("Trigger pulled for id " + id + ": " + state.toString());
Appliance appliance = appliances.get(id - 1);
String action = "";
String circuitBreaker = "doNotHandle";
double value = 666.0;
double maxValue = 255.0;
int percMultiplier = 100;
String actionId = "";
// id = 0 == update Discovery
// getBri != 0 == setPercentage
// bri_inc > 0 == incrementPercentage
// bri_inc < 0 == decrementPercentage
// getBri = 0 && state = on == turn on
// getBri = 0 && state = off == turn off
if (id == Trigger.appliances.size()) {
log.warn("Request for not available id");
return true;
} else if (!state.isOn() && state.getBri() == 0 && state.getBri_inc() == 0) {
// turn off
if (appliance.getActions().contains(Appliance.Actions.turnOff)) {
log.info("Sending TurnOffRequest to " + appliance.getFriendlyName());
action = "TurnOffRequest";
value = 0.0;
actionId = getActionIdForAppliance(appliance);
} else if (!appliance.getActions().contains(Appliance.Actions.turnOff)
&& appliance.getActions().contains(Appliance.Actions.turnOn)) {
log.info("TurnOff Requested but TurnOff is not defined for appliance " + appliance.getFriendlyName()
+ " overwriting to TurnOn which is defined for this appliance");
action = "TurnOnRequest";
value = 1.0;
actionId = getActionIdForAppliance(appliance);
} else {
log.error("TurnOff was requested but neither TurnOff nor TurnOn is a valid action for appliance "
+ appliance.getFriendlyName());
action = circuitBreaker;
}
} else if (state.isOn() && state.getBri() == 0 && state.getBri_inc() == 0) {
// turn on
if (appliance.getActions().contains(Appliance.Actions.turnOn)) {
log.info("Sending TurnOnRequest to " + appliance.getFriendlyName());
action = "TurnOnRequest";
value = 1.0;
actionId = getActionIdForAppliance(appliance);
} else if (!appliance.getActions().contains(Appliance.Actions.turnOn)
&& appliance.getActions().contains(Appliance.Actions.turnOff)) {
log.info("TurnOn Requested but TurnOn is not defined for appliance " + appliance.getFriendlyName()
+ " overwriting to TurnOff which is defined for this appliance");
action = "TurnOffRequest";
value = 0.0;
actionId = getActionIdForAppliance(appliance);
} else {
log.error("TurnOn was requested but neither TurnOn nor TurnOff is a valid action for appliance "
+ appliance.getFriendlyName());
action = circuitBreaker;
}
} else if (state.getBri() > 0 && state.getBri_inc() == 0) {
// set perc
if (appliance.getActions().contains(Appliance.Actions.setPercentage)) {
action = "SetPercentageRequest";
value = round(new Double((state.getBri() / maxValue) * percMultiplier).doubleValue(), 1);
actionId = appliance.getIdPercentage();
log.info("Sending SetPercentageRequest with value " + value + " to appliance " + appliance.getFriendlyName());
} else {
log.error("SetPercentage was requested but SetPercentation id not a valid action for appliance "
+ appliance.getFriendlyName());
action = circuitBreaker;
}
} else if (state.getBri() == 0 && state.getBri_inc() > 0) {
// inc perc
log.info("IncrementPercentatge requested but not yet implemented!");
} else if (state.getBri() == 0 && state.getBri_inc() < 0) {
// dec perc
log.info("DecrementPercentatge requested but not yet implemented!");
} else {
log.error("Cannot determine needed action. State: " + state.toString());
}
if (action.equals(circuitBreaker) || actionId.equals("")) {
return false;
} else {
return requestGiraChange(actionId, action, value);
}
}
public boolean requestGiraChange(String groupaddress, String action, double value) {
log.info("Received statechange for " + groupaddress + " with action " + action + " to value " + value);
boolean result = false;
HomeserverResponse response = homeserver.setDoubleValueForKey(groupaddress, value);
log.debug("Homeserver response was " + response.getCode());
if(response.getCode() == 0 ) {
result = true;
}
return result;
}
private static String getActionIdForAppliance(Appliance appliance) {
if(appliance.getIdSwitch() != null) {
return appliance.getIdSwitch();
} else if (appliance.getIdTrigger() != null) {
return appliance.getIdTrigger();
} else {
log.error("Cannot determin the right group address for appliance " + appliance.getFriendlyName());
return "";
}
}
public static void updateAppliances() {
log.info("Update Appliances in Trigger");
Trigger.appliances = GiraBridge.discovery.appliances;
}
public static double round(double value, int places) {
if (places < 0)
throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
}
| gpl-3.0 |
KWARC/mwetoolkit | bin/libs/filetype/ft_csv.py | 4547 | #!/usr/bin/python
# -*- coding:UTF-8 -*-
################################################################################
#
# Copyright 2010-2015 Carlos Ramisch, Vitor De Araujo, Silvio Ricardo Cordeiro,
# Sandra Castellanos
#
# ft_csv.py is part of mwetoolkit
#
# mwetoolkit 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.
#
# mwetoolkit 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 mwetoolkit. If not, see <http://www.gnu.org/licenses/>.
#
################################################################################
"""
This module provides classes to manipulate files that are encoded in the
"CSV" filetype, which is useful when exporting data to Office spreadsheet and
related formats
You should use the methods in package `filetype` instead.
"""
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from . import _common as common
################################################################################
class CSVInfo(common.FiletypeInfo):
description = "Tab-separated CSV filetype format, one field per column"
filetype_ext = "CSV"
comment_prefix = "#"
escape_pairs = [("$", "${dollar}"), ("/", "${slash}"),
(" ", "${space}"), (";", "${semicolon}"),
("\t", "${tab}"), ("\n", "${newline}"),
("#", "${hash}")]
def operations(self):
return common.FiletypeOperations(CSVChecker, None, CSVPrinter)
INFO = CSVInfo()
r"""Singleton instance of CSVInfo."""
class CSVChecker(common.AbstractChecker):
r"""Checks whether input is in CSV format."""
filetype_info = INFO
def matches_header(self, strict):
return not strict
class CSVPrinter(common.AbstractPrinter):
filetype_info = INFO
valid_categories = ["candidates"]
def __init__(self, category, sep="\t", surfaces=False, lemmapos=False, **kwargs):
super(CSVPrinter, self).__init__(category, **kwargs)
self.sep = sep
self.surfaces = surfaces
self.lemmapos = lemmapos
def handle_meta(self, meta, info={}):
"""When the `Meta` header is read, this function generates a
corresponding header for the CSV file. The header includes name of the
fields, including fixed elements like the candidate n-gram and POS
sequence, as well as variable elements like TPClasses and feature names
@param meta: The `Meta` header that is being read from the file.
@param info: Any extra information as a dictionary
"""
headers = ["id", "ngram", "pos"]
headers.extend(self.escape(cs.name) for cs in meta.corpus_sizes)
headers.extend(["occurs", "sources"])
headers.extend(self.escape(cs.name) for cs in meta.meta_tpclasses)
headers.extend(self.escape(cs.name) for cs in meta.meta_feats)
self.add_string(self.sep.join(headers), "\n")
def handle_candidate(self, candidate, info={}):
"""
For each `Candidate`,
@param entity: `Candidate` being read from the file
"""
values = [str(candidate.id_number)]
ngram_list = map(lambda x:
"%s/%s" % (self.escape(x.lemma), self.escape(x.pos))
if self.lemmapos else
self.escape(x.surface)
if self.surfaces or common.WILDCARD == x.lemma
else self.escape(x.lemma),
candidate)
values.append(" ".join(ngram_list))
values.append("" if self.lemmapos else " ".join(map(lambda x: x.pos, candidate)))
values.extend(str(freq.value) for freq in candidate.freqs)
values.extend(str(tpclass.value) for tpclass in candidate.tpclasses)
values.append(";".join(map(lambda x:" ".join(map(lambda y:y.surface,x)),candidate.occurs)))
values.append(";".join(map(lambda o:";".join(map(str,o.sources)),candidate.occurs)))
values.extend(str(feat.value) for feat in candidate.features)
self.add_string(self.sep.join(values), "\n")
| gpl-3.0 |
Kicer86/mdadm-qt | src/raid_info_tests.cpp | 2429 |
#include <gmock/gmock.h>
#include "mdadm_controller.hpp"
using testing::_;
using testing::NiceMock;
class RaidInfoOperatorTest: public ::testing::TestWithParam<std::pair<RaidInfo, RaidInfo>>
{
};
TEST_P(RaidInfoOperatorTest, operatorLess)
{
const auto& raids = GetParam();
EXPECT_EQ( true, raids.first < raids.second ); // 1st < 2nd
EXPECT_EQ( false, raids.second < raids.first ); // 2nd !< 1st
}
class RaidComponentInfoOperatorTest:
public testing::TestWithParam<std::pair<RaidComponentInfo, RaidComponentInfo>>
{
};
TEST_P(RaidComponentInfoOperatorTest, operatorLess)
{
const auto& components = GetParam();
EXPECT_EQ( true, components.first < components.second ); // 1st < 2nd
EXPECT_EQ( false, components.second < components.first ); // 2nd !< 1st
}
namespace
{
const RaidComponentInfo dev1("dev1", RaidComponentInfo::Type::Normal, 128);
const RaidComponentInfo dev2("dev2", RaidComponentInfo::Type::Normal, 129);
const RaidComponentInfo dev3("dev2", RaidComponentInfo::Type::Spare, 130);
const RaidComponentInfo dev4("dev2", RaidComponentInfo::Type::Normal, 131);
const RaidComponentInfo dev5("dev5", RaidComponentInfo::Type::Normal, 132);
const RaidComponentInfo dev6("dev6", RaidComponentInfo::Type::Normal, 133);
const RaidComponentInfo dev7("dev7", RaidComponentInfo::Type::Normal, 134);
const RaidComponentInfo dev8("dev8", RaidComponentInfo::Type::Normal, 135);
const RaidInfo raid1(nullptr, RaidId("md1"));
const RaidInfo raid2(nullptr, RaidId("md2"));
const RaidInfo raid3(nullptr, RaidId("md3"));
const RaidInfo raid4(nullptr, RaidId("md0"));
}
INSTANTIATE_TEST_CASE_P(RaidsSet,
RaidInfoOperatorTest,
::testing::Values(
std::make_pair(raid1, raid2),
std::make_pair(raid1, raid3),
std::make_pair(raid4, raid3)
)
);
INSTANTIATE_TEST_CASE_P(RaidComponentsSet,
RaidComponentInfoOperatorTest,
::testing::Values(
std::make_pair(dev1, dev2), // different device
std::make_pair(dev2, dev3), // defferent type
std::make_pair(dev2, dev4) // different descriptor
)
);
| gpl-3.0 |
embryonic/poetry | proofreader/urls.py | 222 | from django.conf.urls import url
from . import views
app_name = 'proofreader'
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^poetry/(?P<pk>\d+)?$', views.proofread_poetry, name='poetry'),
] | gpl-3.0 |
projectestac/alexandria | html/langpacks/sv/atto_fontcolor.php | 1328 | <?php
// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
/**
* Strings for component 'atto_fontcolor', language 'sv', version '3.11'.
*
* @package atto_fontcolor
* @category string
* @copyright 1999 Martin Dougiamas and contributors
* @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$string['color_black'] = 'Svart';
$string['color_blue'] = 'Blå';
$string['color_green'] = 'Grön';
$string['color_red'] = 'Röd';
$string['color_white'] = 'Vit';
$string['color_yellow'] = 'Gul';
$string['pluginname'] = 'Teckenfärg';
$string['privacy:metadata'] = 'Pluginmodulen atto_fontcolor lagrar ingen personinformation.';
| gpl-3.0 |
ralit/OfutonReading | src/org/ralit/ofutonreading/TickerView.java | 6234 | package org.ralit.ofutonreading;
import java.util.LinkedList;
import android.animation.Animator;
import android.animation.TimeInterpolator;
import android.animation.Animator.AnimatorListener;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
/**
* ViewGroupの作成は以下のページが参考になりました。
* http://ga29.blog.fc2.com/blog-entry-7.html
*/
public class TickerView extends FrameLayout implements AnimatorListener {
private LinkedList<ImageView> mTickerList = new LinkedList<ImageView>();
private LinkedList<ObjectAnimator> mAnimatorList = new LinkedList<ObjectAnimator>();
private Context context;
private BookManager mBook;
private float mRH;
private float mRW;
private int mTickerWidth;
private int mTickerHeight;
private long mDuration;
private Handler handler = new Handler();
private Bitmap bmp;
private LineEndListener lineEndListener;
// private static final long durationBase = 530;
private static final long durationBase = 550;
// private long durationMultiplied = 530;
private long durationMultiplied = 550;
// private float marginRatio = 0.4f;
public TickerView(Context context, BookManager bookManager, LineEndListener _lineEndListener, float w, float h) {
super(context);
this.context = context;
mBook = bookManager;
lineEndListener = _lineEndListener;
mRW = w;
mRH = h;
setBackgroundColor(Color.DKGRAY);
}
// @Override
// protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// super.onSizeChanged(w, h, oldw, oldh);
// mRH = h;
// mRW = w;
// final int count = getChildCount();
// for (int i = 0; i < count; i++) {
// View view = getChildAt(i);
// android.view.ViewGroup.LayoutParams params = view.getLayoutParams();
// params.width = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
// params.height = android.view.ViewGroup.LayoutParams.MATCH_PARENT;
// view.setLayoutParams(params);
// }
// }
public void destroy() {
if( mAnimatorList.size() > 0 ) {
for (ObjectAnimator anim : mAnimatorList) {
anim.removeAllListeners();
anim.cancel();
}
}
removeAllViews();
mTickerList = null;
mAnimatorList = null;
mTickerList = new LinkedList<ImageView>();
mAnimatorList = new LinkedList<ObjectAnimator>();
}
public void setImage(Bitmap _bmp, float marginRatio) {
if (_bmp != null) {
bmp = _bmp;
}
ImageView ticker = new ImageView(context);
mTickerList.add(ticker);
Word layout = mBook.getPageLayout().get(mBook.getCurLine());
// 速度調節
if (layout.getHeightRatio() > 0) {
durationMultiplied = (long)(durationBase * layout.getHeightRatio());
} else {
durationMultiplied = (long)(durationBase * 1.4);
}
// 速度調節
int mLineW = layout.getRight() - layout.getLeft();
int mLineH = layout.getBottom() - layout.getTop();
int margin = (int)((layout.getBottom() - layout.getTop()) * marginRatio);
Bitmap scaledBitmap = Bitmap.createBitmap(
bmp,
Math.max(layout.getLeft() - margin, 0),
Math.max(layout.getTop() - margin, 0),
Math.min(mLineW + 2*margin, bmp.getWidth() - Math.max(layout.getLeft() - margin, 0) - 1),
Math.min(mLineH + 2*margin, bmp.getHeight() - Math.max(layout.getTop() - margin, 0) - 1));
ticker.setImageBitmap(scaledBitmap);
mLineW = scaledBitmap.getWidth();
mLineH = scaledBitmap.getHeight();
float mTextZoom = ((float)mRH / 2f) / ((float)mLineH * ((float)mRW / (float)mLineW));
ticker.setScaleX(mTextZoom);
ticker.setScaleY(mTextZoom);
mTickerHeight = (int) (mRH / 2); // 修正
mTickerWidth = (int) (mLineW * ((float)mTickerHeight/(float)mLineH)); // 修正
ticker.setX(mTickerWidth/2 + mRW/2);
ViewGroup parent = (ViewGroup)mTickerList.getFirst().getParent();
if ( parent != null ) {
parent.removeView(mTickerList.getFirst());
}
handler.post(new Runnable() {
@Override
public void run() {
addView(mTickerList.getFirst());
animation();
}
});
}
public void animation() {
mDuration = durationMultiplied;
ObjectAnimator move = ObjectAnimator.ofFloat(mTickerList.getFirst(), "x", -mTickerWidth/2 + mRW/2);
mAnimatorList.add(move);
if (mTickerWidth > mTickerHeight) {
mDuration *= ((float)mTickerWidth / (float)mTickerHeight);
} else {
mDuration *= ((float)mTickerHeight / (float)mTickerWidth);
}
Fun.log("mDuration:"+mDuration);
move.setDuration(mDuration);
move.addListener(this);
move.setInterpolator(new LinearInterpolator());
mBook.setCurLine(mBook.getCurLine());
mAnimatorList.getFirst().start();
}
@Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationEnd(Animator animation) {
Fun.log("onAnimationEnd");
mAnimatorList.pollFirst();
ObjectAnimator finish = ObjectAnimator.ofFloat(mTickerList.pollFirst(), "x", -mTickerWidth/2 + mRW/2, -mTickerWidth/2 - mRW/2);
finish.setDuration((long)(durationMultiplied * ((2 * mRW)/mRH)));
// finish.setInterpolator(new LinearInterpolator());
finish.start();
if (mBook.getPageLayout().size() - 1 < mBook.getCurLine() + 1) {
lineEndListener.onPageEnd();
} else {
mBook.setCurLine(mBook.getCurLine() + 1);
setImage(null, mBook.getMarginRatio());
lineEndListener.onLineEnd();
}
}
@Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
@Override
public void onAnimationStart(Animator animation) {
}
public void nextLine() {
mAnimatorList.getFirst().end();
}
public void previousLine() {
if(mBook.getCurLine() == 0) {
Toast.makeText(context, context.getString(R.string.ofuton_first_line), Toast.LENGTH_SHORT).show();
return;
}
mBook.setCurLine(mBook.getCurLine() - 2);
mAnimatorList.getFirst().end();
}
}
| gpl-3.0 |
EnricoBeltramo/ArduDebug | PC interface/Project/ArduDebug/GraphDisplay/GraphLib/PlotterGraphTypes.cs | 7264 | using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.ComponentModel;
using System.Drawing;
/* Copyright (c) 2008-2014 DI Zimmermann Stephan ([email protected])
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
namespace GraphLib
{
public struct cPoint
{
public float x;
public float y;
}
public class DataSource
{
public delegate String OnDrawXAxisLabelEvent(DataSource src, int idx);
public delegate String OnDrawYAxisLabelEvent(DataSource src, float value);
public OnDrawXAxisLabelEvent OnRenderXAxisLabel = null;
public OnDrawYAxisLabelEvent OnRenderYAxisLabel = null;
private cPoint[] samples = null;
private int length = 0;
private String name = String.Empty;
private int downSample = 1;
private Color color = Color.Black;
public float VisibleDataRange_X = 0;
public float DY = 0;
public float YD0 = -200;
public float YD1 = 200;
public float Cur_YD0 = -200;
public float Cur_YD1 = 200;
public float grid_distance_y = 200; // grid distance in units ( draw a horizontal line every 200 units )
public float off_Y = 0;
public float grid_off_y = 0;
public bool yFlip = true;
public bool Active = true;
private bool YAutoScaleGraph = false;
private bool XAutoScaleGraph = false;
public float XAutoScaleOffset = 100;
public float CurGraphHeight = 1.0f;
public float CurGraphWidth = 1.0f;
public bool AutoScaleY
{
get
{
return YAutoScaleGraph;
}
set
{
YAutoScaleGraph = value;
}
}
public bool AutoScaleX
{
get
{
return XAutoScaleGraph;
}
set
{
XAutoScaleGraph = value;
}
}
public cPoint[] Samples
{
get
{
return samples;
}
set
{
samples = value;
length = samples.Length;
}
}
public float XMin
{
get
{
float x_min = float.MaxValue;
if (samples.Length > 0)
{
foreach (cPoint p in samples)
{
if (p.x < x_min) x_min=p.x;
}
}
return x_min;
}
}
public float XMax
{
get
{
float x_max = float.MinValue;
if (samples.Length > 0)
{
foreach (cPoint p in samples)
{
if (p.x > x_max) x_max = p.x;
}
}
return x_max;
}
}
public float YMin
{
get
{
float y_min = float.MaxValue;
if (samples.Length > 0)
{
foreach (cPoint p in samples)
{
if (p.y < y_min) y_min = p.y;
}
}
return y_min;
}
}
public float YMax
{
get
{
float y_max = float.MinValue;
if (samples.Length > 0)
{
foreach (cPoint p in samples)
{
if (p.y > y_max) y_max = p.y;
}
}
return y_max;
}
}
public void SetDisplayRangeY(float y_start, float y_end)
{
YD0 = y_start;
YD1 = y_end;
}
public void SetGridDistanceY( float grid_dist_y_units)
{
grid_distance_y = grid_dist_y_units;
}
public void SetGridOriginY( float off_y)
{
grid_off_y = off_y;
}
[Category("Properties")] // Take this out, and you will soon have problems with serialization;
[DefaultValue(typeof(string), "")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public String Name
{
get { return name; }
set { name = value; }
}
[Category("Properties")] // Take this out, and you will soon have problems with serialization;
[DefaultValue(typeof(Color), "")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public Color GraphColor
{
get { return color; }
set { color = value; }
}
[Category("Properties")] // Take this out, and you will soon have problems with serialization;
[DefaultValue(typeof(int), "0")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public int Length
{
get { return length; }
set
{
length = value;
if (length != 0)
{
samples = new cPoint[length];
}
else
{
// length is 0
if (samples != null)
{
samples = null;
}
}
}
}
[Category("Properties")] // Take this out, and you will soon have problems with serialization;
[DefaultValue(typeof(int), "1")]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
public int Downsampling
{
get { return downSample; }
set { downSample = value; }
}
}
}
| gpl-3.0 |
TGAC/miso-lims | core/src/test/java/uk/ac/bbsrc/tgac/miso/core/data/ExperimentTest.java | 2550 | package uk.ac.bbsrc.tgac.miso.core.data;
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import uk.ac.bbsrc.tgac.miso.core.data.impl.kit.KitDescriptor;
import uk.ac.bbsrc.tgac.miso.core.data.type.KitType;
public class ExperimentTest {
private Experiment ae;
@Before
public void setUp() throws Exception {
ae = new Experiment();
}
@Test
public final void testGetKitsByKitType() {
final Collection<Kit> expectedLibraryKits = getNMockKits(3, KitType.LIBRARY);
final Collection<Kit> expectedSequencingKits = getNMockKits(2, KitType.SEQUENCING);
final Collection<Kit> expectedClusteringKits = getNMockKits(5, KitType.CLUSTERING);
final Collection<Kit> expectedMultiplexingKits = getNMockKits(6, KitType.MULTIPLEXING);
final Collection<Kit> libraryKits = ae.getKitsByKitType(KitType.LIBRARY);
final Collection<Kit> sequencingKits = ae.getKitsByKitType(KitType.SEQUENCING);
final Collection<Kit> clusteringKits = ae.getKitsByKitType(KitType.CLUSTERING);
final Collection<Kit> multiplexingKits = ae.getKitsByKitType(KitType.MULTIPLEXING);
assertKitListEqual(expectedLibraryKits, libraryKits);
assertKitListEqual(expectedSequencingKits, sequencingKits);
assertKitListEqual(expectedClusteringKits, clusteringKits);
assertKitListEqual(expectedMultiplexingKits, multiplexingKits);
}
// Utility methods.
private static final void assertKitListEqual(Collection<Kit> expected, Collection<Kit> actual) {
assertEquals(expected.size(), actual.size());
int found = 0;
for (final Kit eKit : expected) {
for (final Kit aKit : actual) {
if (eKit.getName().equals(aKit.getName())) {
found++;
break;
}
}
}
assertEquals(found, actual.size());
}
private final List<Kit> getNMockKits(int n, KitType kitType) {
final List<Kit> rtn = new ArrayList<>();
for (int i = 0; i < n; i++) {
final Kit k = Mockito.mock(Kit.class);
setUpKit(k, kitType, "" + kitType + i);
rtn.add(k);
}
return rtn;
}
private final void setUpKit(Kit kit, KitType type, String identifier) {
final KitDescriptor kitDescriptor = new KitDescriptor();
kitDescriptor.setKitType(type);
when(kit.getKitDescriptor()).thenReturn(kitDescriptor);
when(kit.getName()).thenReturn(identifier);
ae.addKit(kit);
}
}
| gpl-3.0 |
idega/platform2 | src/is/idega/idegaweb/golf/block/image/data/ImageCatagoryAttributes.java | 485 | package is.idega.idegaweb.golf.block.image.data;
public interface ImageCatagoryAttributes extends com.idega.data.IDOLegacyEntity
{
public java.lang.String getAttributeName();
public java.lang.String getAttributeValue();
public int getImageCatagoryId();
public java.lang.String getName();
public void setAttributeName(java.lang.String p0);
public void setAttributeValue(java.lang.String p0);
public void setImageCatagoryId(int p0);
public void setName(java.lang.String p0);
}
| gpl-3.0 |
dismine/Valentina_git | src/test/TranslationsTest/tst_tstranslation.cpp | 7234 | /************************************************************************
**
** @file tst_tstranslation.cpp
** @author Roman Telezhynskyi <dismine(at)gmail.com>
** @date 13 12, 2015
**
** @brief
** @copyright
** This source code is part of the Valentina project, a pattern making
** program, whose allow create and modeling patterns of clothing.
** Copyright (C) 2015 Valentina project
** <https://bitbucket.org/dismine/valentina> All Rights Reserved.
**
** Valentina 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.
**
** Valentina 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 Valentina. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include "tst_tstranslation.h"
#include "../vmisc/def.h"
#include <QDomDocument>
#include <QtTest>
Q_DECLARE_METATYPE(QDomElement) // Need for testing
//---------------------------------------------------------------------------------------------------------------------
TST_TSTranslation::TST_TSTranslation(QObject *parent)
: TST_AbstractTranslation(parent)
{}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::CheckEnglishLocalization_data()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QString>("translation");
const QString fileName = QStringLiteral("valentina_en_US.ts");
const QDomNodeList messages = LoadTSFile(fileName);
if (messages.isEmpty())
{
QFAIL("Can't begin test.");
}
for (qint32 i = 0, num = messages.size(); i < num; ++i)
{
const QDomElement message = messages.at(i).toElement();
if (message.isNull() == false)
{
const QString source = message.firstChildElement(TagSource).text();
if (source.isEmpty())
{
continue;
}
const QDomElement translationTag = message.firstChildElement(TagTranslation);
if (translationTag.hasAttribute(AttrType))
{
const QString attrVal = translationTag.attribute(AttrType);
if (attrVal == AttrValVanished || attrVal == AttrValUnfinished || attrVal == AttrValObsolete)
{
continue;
}
}
const QString translation = translationTag.text();
if (translation.isEmpty())
{
continue;
}
const QString message = QString("File '%1'. Check modification source message '%2'.").arg(fileName, source);
QTest::newRow(qUtf8Printable(message)) << source << translation;
}
else
{
const QString message = QString("Message %1 is null.").arg(i);
QFAIL(qUtf8Printable(message));
}
}
}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::CheckEnglishLocalization()
{
QFETCH(QString, source);
QFETCH(QString, translation);
QCOMPARE(source, translation);
}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::CheckEmptyToolButton_data()
{
PrepareOriginalStrings();
}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::CheckEmptyToolButton()
{
QFETCH(QString, source);
QFETCH(QDomElement, message);
if (source == QLatin1String("..."))
{
const QDomElement translationTag = message.firstChildElement(TagTranslation);
if (translationTag.hasAttribute(AttrType))
{
const QString attrVal = translationTag.attribute(AttrType);
if (attrVal == AttrValVanished || attrVal == AttrValObsolete)
{
return;
}
}
const QDomNode context = message.parentNode();
if (context.isNull())
{
QFAIL("Can't get context.");
}
const QString contextName = context.firstChildElement(TagName).text();
const QString error = QString("Found '...' in context '%1'").arg(contextName);
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::CheckEllipsis_data()
{
PrepareOriginalStrings();
}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::CheckEllipsis()
{
QFETCH(QString, source);
QFETCH(QDomElement, message);
if (source.endsWith("..."))
{
const QDomElement translationTag = message.firstChildElement(TagTranslation);
if (translationTag.hasAttribute(AttrType))
{
const QString attrVal = translationTag.attribute(AttrType);
if (attrVal == AttrValVanished || attrVal == AttrValObsolete)
{
return;
}
}
const QDomNode context = message.parentNode();
if (context.isNull())
{
QFAIL("Can't get context.");
}
const QString contextName = context.firstChildElement(TagName).text();
const QString error = QString("String '%1' ends with '...' in context '%2'. Repalce it with '…'.")
.arg(source, contextName);
QFAIL(qUtf8Printable(error));
}
}
//---------------------------------------------------------------------------------------------------------------------
void TST_TSTranslation::PrepareOriginalStrings()
{
QTest::addColumn<QString>("source");
QTest::addColumn<QDomElement>("message");
const QString fileName = QStringLiteral("valentina.ts");
const QDomNodeList messages = LoadTSFile(fileName);
if (messages.isEmpty())
{
QFAIL("Can't begin test.");
}
for (qint32 i = 0, num = messages.size(); i < num; ++i)
{
const QDomElement message = messages.at(i).toElement();
if (message.isNull() == false)
{
const QString source = message.firstChildElement(TagSource).text();
if (source.isEmpty())
{
continue;
}
const QString tag = QString("File '%1'. Check modification source message '%2'.").arg(fileName, source);
QTest::newRow(qUtf8Printable(tag)) << source << message;
}
else
{
const QString message = QString("Message %1 is null.").arg(i);
QFAIL(qUtf8Printable(message));
}
}
}
| gpl-3.0 |
noobavss/nooba-plugin-bgsubtractor | BgsubtractorPlugin/package_bgs/dp/DPAdaptiveMedianBGS.cpp | 2500 | #include "DPAdaptiveMedianBGS.h"
DPAdaptiveMedianBGS::DPAdaptiveMedianBGS() : firstTime(true), frameNumber(0), showOutput(true), threshold(40), samplingRate(7), learningFrames(30)
{
std::cout << "DPAdaptiveMedianBGS()" << std::endl;
}
DPAdaptiveMedianBGS::~DPAdaptiveMedianBGS()
{
std::cout << "~DPAdaptiveMedianBGS()" << std::endl;
}
void DPAdaptiveMedianBGS::process(const cv::Mat &img_input, cv::Mat &img_output)
{
if(img_input.empty())
return;
loadConfig();
if(firstTime)
saveConfig();
frame = new IplImage(img_input);
if(firstTime)
frame_data.ReleaseMemory(false);
frame_data = frame;
if(firstTime)
{
int width = img_input.size().width;
int height = img_input.size().height;
lowThresholdMask = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
lowThresholdMask.Ptr()->origin = IPL_ORIGIN_BL;
highThresholdMask = cvCreateImage(cvSize(width, height), IPL_DEPTH_8U, 1);
highThresholdMask.Ptr()->origin = IPL_ORIGIN_BL;
params.SetFrameSize(width, height);
params.LowThreshold() = threshold;
params.HighThreshold() = 2*params.LowThreshold(); // Note: high threshold is used by post-processing
params.SamplingRate() = samplingRate;
params.LearningFrames() = learningFrames;
bgs.Initalize(params);
bgs.InitModel(frame_data);
}
bgs.Subtract(frameNumber, frame_data, lowThresholdMask, highThresholdMask);
lowThresholdMask.Clear();
bgs.Update(frameNumber, frame_data, lowThresholdMask);
cv::Mat foreground(highThresholdMask.Ptr());
if(showOutput)
cv::imshow("Adaptive Median (McFarlane&Schofield)", foreground);
foreground.copyTo(img_output);
delete frame;
firstTime = false;
frameNumber++;
}
void DPAdaptiveMedianBGS::saveConfig()
{
CvFileStorage* fs = cvOpenFileStorage("./config/DPAdaptiveMedianBGS.xml", 0, CV_STORAGE_WRITE);
cvWriteInt(fs, "threshold", threshold);
cvWriteInt(fs, "samplingRate", samplingRate);
cvWriteInt(fs, "learningFrames", learningFrames);
cvWriteInt(fs, "showOutput", showOutput);
cvReleaseFileStorage(&fs);
}
void DPAdaptiveMedianBGS::loadConfig()
{
CvFileStorage* fs = cvOpenFileStorage("./config/DPAdaptiveMedianBGS.xml", 0, CV_STORAGE_READ);
threshold = cvReadIntByName(fs, 0, "threshold", 40);
samplingRate = cvReadIntByName(fs, 0, "samplingRate", 7);
learningFrames = cvReadIntByName(fs, 0, "learningFrames", 30);
showOutput = cvReadIntByName(fs, 0, "showOutput", true);
cvReleaseFileStorage(&fs);
} | gpl-3.0 |
RtcNbClient/RtcNbClient | RtcNbClientPlans/RtcNbClientPlansFacade/src/main/java/pl/edu/amu/wmi/kino/rtc/client/api/plans/items/RtcPlanItemType.java | 949 | /*
* Copyright (C) 2009-2011 RtcNbClient Team (http://rtcnbclient.wmi.amu.edu.pl/)
*
* This file is part of RtcNbClient.
*
* RtcNbClient 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.
*
* RtcNbClient 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 RtcNbClient. If not, see <http://www.gnu.org/licenses/>.
*/
package pl.edu.amu.wmi.kino.rtc.client.api.plans.items;
/**
*
* @author Patryk Żywica
*/
public enum RtcPlanItemType {
EXECUTABLE,
ABSENCE,
NON_EXECUTABLE;
}
| gpl-3.0 |
zeburon/sailfish-batterylog | translations/harbour-batterylog-de.ts | 7767 | <?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.1" language="de">
<context>
<name>AboutPage</name>
<message>
<source>Battery Log</source>
<translation>Battery Log</translation>
</message>
<message>
<source>Version %1</source>
<translation>Version %1</translation>
</message>
<message>
<source>Copyright © 2015 Lukas Fraser</source>
<translation>Copyright © 2015 Lukas Fraser</translation>
</message>
<message>
<source>This program is open source software licensed under the terms of the GNU General Public License.</source>
<translation>Dieses Programm ist Open Source Software und steht unter der GNU General Public License.</translation>
</message>
<message>
<source>You can find the source code at the</source>
<translation>Der Quelltext befindet sich auf der</translation>
</message>
<message>
<source>GitHub Project Page</source>
<translation>GitHub Projektseite</translation>
</message>
<message>
<source>Inspired by SailfishOS application Hunger Meter created by Michal Hrušecký.</source>
<translation>Inspiriert durch die Applikation Hunger Meter geschrieben von Michal Hrušecký.</translation>
</message>
</context>
<context>
<name>ColorChooserDialog</name>
<message>
<source>Red</source>
<translation>Rot</translation>
</message>
<message>
<source>Green</source>
<translation>Grün</translation>
</message>
<message>
<source>Blue</source>
<translation>Blau</translation>
</message>
<message>
<source>Alpha</source>
<translation>Alpha</translation>
</message>
</context>
<context>
<name>Event</name>
<message>
<source>Charging</source>
<translation>Laden</translation>
</message>
<message>
<source>Discharging</source>
<translation>Entladen</translation>
</message>
<message>
<source>Full</source>
<translation>Voll</translation>
</message>
</context>
<context>
<name>EventPage</name>
<message>
<source>Event Log</source>
<translation>Protokoll</translation>
</message>
</context>
<context>
<name>Graph</name>
<message>
<source>Malfunction Detected</source>
<translation>Störung erkannt</translation>
</message>
</context>
<context>
<name>MainCover</name>
<message>
<source>Until full</source>
<translation>Bis voll</translation>
</message>
<message>
<source>Time left</source>
<translation>Restdauer</translation>
</message>
<message>
<source>Remaining</source>
<translation>Verbleibend</translation>
</message>
<message>
<source>Average</source>
<translation>Durchschnitt</translation>
</message>
</context>
<context>
<name>MainPage</name>
<message>
<source>About Battery Log</source>
<translation>Über Battery Log</translation>
</message>
<message>
<source>Battery Log</source>
<translation>Battery Log</translation>
</message>
<message>
<source>until full</source>
<translation>bis voll</translation>
</message>
<message>
<source>until empty</source>
<translation>bis leer</translation>
</message>
<message>
<source>Current</source>
<translation>Stromstärke</translation>
</message>
<message>
<source>Voltage</source>
<translation>Spannung</translation>
</message>
<message>
<source>when unplugged now</source>
<translation>wenn jetzt ausgesteckt</translation>
</message>
<message>
<source>when fully charged</source>
<translation>wenn voll geladen</translation>
</message>
<message>
<source>Energy</source>
<translation>Energie</translation>
</message>
<message>
<source>Health</source>
<translation>Zustand</translation>
</message>
<message>
<source>on</source>
<translation>ein</translation>
</message>
<message>
<source>discharging</source>
<translation>entladen</translation>
</message>
<message>
<source>charging</source>
<translation>laden</translation>
</message>
<message>
<source>more data required</source>
<translation>benötige mehr Daten</translation>
</message>
<message>
<source>standby</source>
<translation>Standby</translation>
</message>
<message>
<source>fully charged</source>
<translation>vollständig aufgeladen</translation>
</message>
<message>
<source>Settings</source>
<translation>Einstellungen</translation>
</message>
<message>
<source>calculating...</source>
<translation>berechne...</translation>
</message>
<message>
<source>Displaying %1 day(s)</source>
<translation>Zeige %1 Tag(e)</translation>
</message>
<message>
<source>Starting now</source>
<translation>Beginne ab jetzt</translation>
</message>
<message>
<source>Starting %1 day(s) ago</source>
<translation>Beginne vor %1 Tag(en)</translation>
</message>
</context>
<context>
<name>SettingsPage</name>
<message>
<source>Settings</source>
<translation>Einstellungen</translation>
</message>
<message>
<source>Storage period</source>
<translation>Aufzeichnungszeitraum</translation>
</message>
<message>
<source> days</source>
<translation> Tage</translation>
</message>
<message>
<source>Reset Colors</source>
<translation>Farben zurücksetzen</translation>
</message>
<message>
<source>%1 events of %2 days stored</source>
<translation>%1 Einträge aus %2 Tagen gespeichert</translation>
</message>
<message>
<source>Charging + on</source>
<translation>Laden + eingeschaltet</translation>
</message>
<message>
<source>Charging + standby</source>
<translation>Laden + Standby</translation>
</message>
<message>
<source>Discharging + on</source>
<translation>Entladen + eingeschaltet</translation>
</message>
<message>
<source>Discharging + standby</source>
<translation>Entladen + Standby</translation>
</message>
<message>
<source>Line Colors</source>
<translation>Linienfarben</translation>
</message>
<message>
<source>Deleting %1 days</source>
<translation>Lösche %1 Tage</translation>
</message>
<message>
<source>Clearing logs</source>
<translation>Lösche Einträge</translation>
</message>
<message>
<source>Clear logs</source>
<translation>Einträge löschen</translation>
</message>
<message>
<source>Storage</source>
<translation>Speicher</translation>
</message>
</context>
<context>
<name>timeformat</name>
<message>
<source>%1 minute(s)</source>
<translation>%1 Minute(n)</translation>
</message>
<message>
<source>%1 hour(s)</source>
<translation>%1 Stunde(n)</translation>
</message>
<message>
<source> and </source>
<translation> und </translation>
</message>
<message>
<source>%1 day(s)</source>
<translation>%1 Tag(e)</translation>
</message>
<message>
<source>%1:%2</source>
<translation>%1:%2</translation>
</message>
</context>
</TS>
| gpl-3.0 |
odotopen/PixelDungeonLegend | src/com/watabou/pixeldungeon/actors/buffs/Buff.java | 3749 | /*
* 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.pixeldungeon.actors.buffs;
import com.watabou.pixeldungeon.Dungeon;
import com.watabou.pixeldungeon.actors.Actor;
import com.watabou.pixeldungeon.actors.Char;
import com.watabou.pixeldungeon.actors.hero.Hero;
import com.watabou.pixeldungeon.actors.mobs.Thief;
import com.watabou.pixeldungeon.items.Item;
import com.watabou.pixeldungeon.ui.BuffIndicator;
import com.watabou.pixeldungeon.utils.GLog;
public class Buff extends Actor {
public Char target;
interface itemAction{
public Item act(Item srcItem);
public String actionText(Item srcItem);
public void carrierFx();
}
public boolean attachTo( Char target ) {
if (target.immunities().contains( getClass() )) {
return false;
}
this.target = target;
target.add( this );
return true;
}
public void detach() {
target.remove( this );
}
@Override
public boolean act() {
deactivate();
return true;
}
public int icon() {
return BuffIndicator.NONE;
}
public static<T extends Buff> T affect( Char target, Class<T> buffClass ) {
T buff = target.buff( buffClass );
if (buff != null) {
return buff;
} else {
try {
buff = buffClass.newInstance();
buff.attachTo( target );
return buff;
} catch (Exception e) {
return null;
}
}
}
public static<T extends FlavourBuff> T affect( Char target, Class<T> buffClass, float duration ) {
T buff = affect( target, buffClass );
buff.spend( duration );
return buff;
}
public static<T extends FlavourBuff> T prolong( Char target, Class<T> buffClass, float duration ) {
T buff = affect( target, buffClass );
buff.postpone( duration );
return buff;
}
public static void detach( Buff buff ) {
if (buff != null) {
buff.detach();
}
}
public static void detach( Char target, Class<? extends Buff> cl ) {
detach( target.buff( cl ) );
}
private void collectOrDropItem(Item item){
if(!item.collect( ((Hero)target).belongings.backpack )){
Dungeon.level.drop(item, target.pos).sprite.drop();
}
}
protected void applyToCarriedItems(itemAction action ){
if (target instanceof Hero) {
Item item = ((Hero)target).belongings.randomUnequipped();
if(item == null){
return;
}
Item srcItem = item.detach(((Hero)target).belongings.backpack);
item = action.act(srcItem);
if(item == srcItem){ //item unaffected by buff
collectOrDropItem(item);
return;
}
String actionText = null;
if(item == null){
actionText = action.actionText(srcItem);
action.carrierFx();
}
else{
if(!srcItem.equals(item)){
actionText = action.actionText(srcItem);
collectOrDropItem(item);
action.carrierFx();
}
}
if(actionText != null){
GLog.w(actionText);
}
} else if (target instanceof Thief){
if (((Thief)target).item == null)
{
return;
}
((Thief)target).item = action.act(((Thief)target).item);
action.carrierFx();
//target.sprite.emitter().burst( ElmoParticle.FACTORY, 6 );
}
}
}
| gpl-3.0 |
xposure/zSprite_Old | Source/Framework/zSprite.Sandbox/Terasology/utilities/procedural/SimplexNoise.java | 18857 | /*
* Copyright 2013 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.utilities.procedural;
import org.terasology.utilities.random.FastRandom;
/**
* A speed-improved simplex noise algorithm for Simplex noise in 2D, 3D and 4D.
*
* Based on example code by Stefan Gustavson ([email protected]).
* Optimisations by Peter Eastman ([email protected]).
* Better rank ordering method by Stefan Gustavson in 2012.
*
* This could be speeded up even further, but it's useful as it is.
*
* Version 2012-03-09
*
* This code was placed in the public domain by its original author,
* Stefan Gustavson. You may use it as you see fit, but
* attribution is appreciated.
*
* See http://staffwww.itn.liu.se/~stegu/
*
* msteiger: Introduced seed value
*/
public class SimplexNoise implements Noise2D, Noise3D {
private static Grad[] grad3 = {
new Grad(1, 1, 0), new Grad(-1, 1, 0), new Grad(1, -1, 0), new Grad(-1, -1, 0),
new Grad(1, 0, 1), new Grad(-1, 0, 1), new Grad(1, 0, -1), new Grad(-1, 0, -1),
new Grad(0, 1, 1), new Grad(0, -1, 1), new Grad(0, 1, -1), new Grad(0, -1, -1)};
private static Grad[] grad4 = {
new Grad(0, 1, 1, 1), new Grad(0, 1, 1, -1), new Grad(0, 1, -1, 1), new Grad(0, 1, -1, -1),
new Grad(0, -1, 1, 1), new Grad(0, -1, 1, -1), new Grad(0, -1, -1, 1), new Grad(0, -1, -1, -1),
new Grad(1, 0, 1, 1), new Grad(1, 0, 1, -1), new Grad(1, 0, -1, 1), new Grad(1, 0, -1, -1),
new Grad(-1, 0, 1, 1), new Grad(-1, 0, 1, -1), new Grad(-1, 0, -1, 1), new Grad(-1, 0, -1, -1),
new Grad(1, 1, 0, 1), new Grad(1, 1, 0, -1), new Grad(1, -1, 0, 1), new Grad(1, -1, 0, -1),
new Grad(-1, 1, 0, 1), new Grad(-1, 1, 0, -1), new Grad(-1, -1, 0, 1), new Grad(-1, -1, 0, -1),
new Grad(1, 1, 1, 0), new Grad(1, 1, -1, 0), new Grad(1, -1, 1, 0), new Grad(1, -1, -1, 0),
new Grad(-1, 1, 1, 0), new Grad(-1, 1, -1, 0), new Grad(-1, -1, 1, 0), new Grad(-1, -1, -1, 0)};
// Skewing and unskewing factors for 2, 3, and 4 dimensions
private static final double F2 = 0.5 * (Math.sqrt(3.0) - 1.0);
private static final double G2 = (3.0 - Math.sqrt(3.0)) / 6.0;
private static final double F3 = 1.0 / 3.0;
private static final double G3 = 1.0 / 6.0;
private static final double F4 = (Math.sqrt(5.0) - 1.0) / 4.0;
private static final double G4 = (5.0 - Math.sqrt(5.0)) / 20.0;
private final short[] perm = new short[512];
private final short[] permMod12 = new short[512];
/**
* Initialize permutations with a given seed
* @param seed a seed value used for permutation shuffling
*/
public SimplexNoise(int seed) {
FastRandom rand = new FastRandom(seed);
short[] p = new short[256];
// Initialize with all values [0..255]
for (short i = 0; i < 256; i++) {
p[i] = i;
}
// Shuffle the array
for (int i = 0; i < 256; i++) {
int j = rand.nextInt(256);
short swap = p[i];
p[i] = p[j];
p[j] = swap;
}
for (int i = 0; i < 512; i++) {
perm[i] = p[i & 255];
permMod12[i] = (short) (perm[i] % 12);
}
}
// This method is a *lot* faster than using (int)Math.floor(x)
private static int fastfloor(double x) {
int xi = (int) x;
return x < xi ? xi - 1 : xi;
}
private static double dot(Grad g, double x, double y) {
return g.x * x + g.y * y;
}
private static double dot(Grad g, double x, double y, double z) {
return g.x * x + g.y * y + g.z * z;
}
private static double dot(Grad g, double x, double y, double z, double w) {
return g.x * x + g.y * y + g.z * z + g.w * w;
}
/**
* 2D simplex noise
* @param xin the x input coordinate
* @param yin the y input coordinate
* @return a noise value in the interval [-1,1]
*/
@Override
public double noise(double xin, double yin) {
double n0;
double n1;
double n2; // Noise contributions from the three corners
// Skew the input space to determine which simplex cell we're in
double s = (xin + yin) * F2; // Hairy factor for 2D
int i = fastfloor(xin + s);
int j = fastfloor(yin + s);
double t = (i + j) * G2;
double xo0 = i - t; // Unskew the cell origin back to (x,y) space
double yo0 = j - t;
double x0 = xin - xo0; // The x,y distances from the cell origin
double y0 = yin - yo0;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
int i1; // Offsets for second (middle) corner of simplex in (i,j) coords
int j1;
if (x0 > y0) { // lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1 = 1;
j1 = 0;
} else { // upper triangle, YX order: (0,0)->(0,1)->(1,1)
i1 = 0;
j1 = 1;
}
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
double x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
double y1 = y0 - j1 + G2;
double x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords
double y2 = y0 - 1.0 + 2.0 * G2;
// Work out the hashed gradient indices of the three simplex corners
int ii = i & 255;
int jj = j & 255;
int gi0 = permMod12[ii + perm[jj]];
int gi1 = permMod12[ii + i1 + perm[jj + j1]];
int gi2 = permMod12[ii + 1 + perm[jj + 1]];
// Calculate the contribution from the three corners
double t0 = 0.5 - x0 * x0 - y0 * y0;
if (t0 < 0) {
n0 = 0.0;
} else {
t0 *= t0;
n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient
}
double t1 = 0.5 - x1 * x1 - y1 * y1;
if (t1 < 0) {
n1 = 0.0;
} else {
t1 *= t1;
n1 = t1 * t1 * dot(grad3[gi1], x1, y1);
}
double t2 = 0.5 - x2 * x2 - y2 * y2;
if (t2 < 0) {
n2 = 0.0;
} else {
t2 *= t2;
n2 = t2 * t2 * dot(grad3[gi2], x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70.0 * (n0 + n1 + n2);
}
/**
* 3D simplex noise
* @param xin the x input coordinate
* @param yin the y input coordinate
* @param zin the z input coordinate
* @return a noise value in the interval [-1,1]
*/
@Override
public double noise(double xin, double yin, double zin) {
double n0;
double n1;
double n2;
double n3; // Noise contributions from the four corners
// Skew the input space to determine which simplex cell we're in
double s = (xin + yin + zin) * F3; // Very nice and simple skew factor for 3D
int i = fastfloor(xin + s);
int j = fastfloor(yin + s);
int k = fastfloor(zin + s);
double t = (i + j + k) * G3;
double xo0 = i - t; // Unskew the cell origin back to (x,y,z) space
double yo0 = j - t;
double zo0 = k - t;
double x0 = xin - xo0; // The x,y,z distances from the cell origin
double y0 = yin - yo0;
double z0 = zin - zo0;
// For the 3D case, the simplex shape is a slightly irregular tetrahedron.
// Determine which simplex we are in.
int i1;
int j1;
int k1; // Offsets for second corner of simplex in (i,j,k) coords
int i2;
int j2;
int k2; // Offsets for third corner of simplex in (i,j,k) coords
if (x0 >= y0) {
if (y0 >= z0) { // X Y Z order
i1 = 1;
j1 = 0;
k1 = 0;
i2 = 1;
j2 = 1;
k2 = 0;
} else if (x0 >= z0) { // X Z Y order
i1 = 1;
j1 = 0;
k1 = 0;
i2 = 1;
j2 = 0;
k2 = 1;
} else { // Z X Y order
i1 = 0;
j1 = 0;
k1 = 1;
i2 = 1;
j2 = 0;
k2 = 1;
}
} else { // x0<y0
if (y0 < z0) { // Z Y X order
i1 = 0;
j1 = 0;
k1 = 1;
i2 = 0;
j2 = 1;
k2 = 1;
} else if (x0 < z0) { // Y Z X order
i1 = 0;
j1 = 1;
k1 = 0;
i2 = 0;
j2 = 1;
k2 = 1;
} else { // Y X Z order
i1 = 0;
j1 = 1;
k1 = 0;
i2 = 1;
j2 = 1;
k2 = 0;
}
}
// A step of (1,0,0) in (i,j,k) means a step of (1-c,-c,-c) in (x,y,z),
// a step of (0,1,0) in (i,j,k) means a step of (-c,1-c,-c) in (x,y,z), and
// a step of (0,0,1) in (i,j,k) means a step of (-c,-c,1-c) in (x,y,z), where
// c = 1/6.
double x1 = x0 - i1 + G3; // Offsets for second corner in (x,y,z) coords
double y1 = y0 - j1 + G3;
double z1 = z0 - k1 + G3;
double x2 = x0 - i2 + 2.0 * G3; // Offsets for third corner in (x,y,z) coords
double y2 = y0 - j2 + 2.0 * G3;
double z2 = z0 - k2 + 2.0 * G3;
double x3 = x0 - 1.0 + 3.0 * G3; // Offsets for last corner in (x,y,z) coords
double y3 = y0 - 1.0 + 3.0 * G3;
double z3 = z0 - 1.0 + 3.0 * G3;
// Work out the hashed gradient indices of the four simplex corners
int ii = i & 255;
int jj = j & 255;
int kk = k & 255;
int gi0 = permMod12[ii + perm[jj + perm[kk]]];
int gi1 = permMod12[ii + i1 + perm[jj + j1 + perm[kk + k1]]];
int gi2 = permMod12[ii + i2 + perm[jj + j2 + perm[kk + k2]]];
int gi3 = permMod12[ii + 1 + perm[jj + 1 + perm[kk + 1]]];
// Calculate the contribution from the four corners
double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
if (t0 < 0) {
n0 = 0.0;
} else {
t0 *= t0;
n0 = t0 * t0 * dot(grad3[gi0], x0, y0, z0);
}
double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
if (t1 < 0) {
n1 = 0.0;
} else {
t1 *= t1;
n1 = t1 * t1 * dot(grad3[gi1], x1, y1, z1);
}
double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
if (t2 < 0) {
n2 = 0.0;
} else {
t2 *= t2;
n2 = t2 * t2 * dot(grad3[gi2], x2, y2, z2);
}
double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
if (t3 < 0) {
n3 = 0.0;
} else {
t3 *= t3;
n3 = t3 * t3 * dot(grad3[gi3], x3, y3, z3);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to stay just inside [-1,1]
return 32.0 * (n0 + n1 + n2 + n3);
}
/**
* 4D simplex noise, better simplex rank ordering method 2012-03-09
* @param xin the x input coordinate
* @param yin the y input coordinate
* @param zin the z input coordinate
* @return a noise value in the interval [-1,1]
*/
public double noise(double xin, double yin, double zin, double win) {
double n0;
double n1;
double n2;
double n3;
double n4; // Noise contributions from the five corners
// Skew the (x,y,z,w) space to determine which cell of 24 simplices we're in
double s = (xin + yin + zin + win) * F4; // Factor for 4D skewing
int i = fastfloor(xin + s);
int j = fastfloor(yin + s);
int k = fastfloor(zin + s);
int l = fastfloor(win + s);
double t = (i + j + k + l) * G4; // Factor for 4D unskewing
double xo0 = i - t; // Unskew the cell origin back to (x,y,z,w) space
double yo0 = j - t;
double zo0 = k - t;
double wo0 = l - t;
double x0 = xin - xo0; // The x,y,z,w distances from the cell origin
double y0 = yin - yo0;
double z0 = zin - zo0;
double w0 = win - wo0;
// For the 4D case, the simplex is a 4D shape I won't even try to describe.
// To find out which of the 24 possible simplices we're in, we need to
// determine the magnitude ordering of x0, y0, z0 and w0.
// Six pair-wise comparisons are performed between each possible pair
// of the four coordinates, and the results are used to rank the numbers.
int rankx = 0;
int ranky = 0;
int rankz = 0;
int rankw = 0;
if (x0 > y0) {
rankx++;
} else {
ranky++;
}
if (x0 > z0) {
rankx++;
} else {
rankz++;
}
if (x0 > w0) {
rankx++;
} else {
rankw++;
}
if (y0 > z0) {
ranky++;
} else {
rankz++;
}
if (y0 > w0) {
ranky++;
} else {
rankw++;
}
if (z0 > w0) {
rankz++;
} else {
rankw++;
}
int i1;
int j1;
int k1;
int l1; // The integer offsets for the second simplex corner
int i2;
int j2;
int k2;
int l2; // The integer offsets for the third simplex corner
int i3;
int j3;
int k3;
int l3; // The integer offsets for the fourth simplex corner
// simplex[c] is a 4-vector with the numbers 0, 1, 2 and 3 in some order.
// Many values of c will never occur, since e.g. x>y>z>w makes x<z, y<w and x<w
// impossible. Only the 24 indices which have non-zero entries make any sense.
// We use a thresholding to set the coordinates in turn from the largest magnitude.
// Rank 3 denotes the largest coordinate.
i1 = rankx >= 3 ? 1 : 0;
j1 = ranky >= 3 ? 1 : 0;
k1 = rankz >= 3 ? 1 : 0;
l1 = rankw >= 3 ? 1 : 0;
// Rank 2 denotes the second largest coordinate.
i2 = rankx >= 2 ? 1 : 0;
j2 = ranky >= 2 ? 1 : 0;
k2 = rankz >= 2 ? 1 : 0;
l2 = rankw >= 2 ? 1 : 0;
// Rank 1 denotes the second smallest coordinate.
i3 = rankx >= 1 ? 1 : 0;
j3 = ranky >= 1 ? 1 : 0;
k3 = rankz >= 1 ? 1 : 0;
l3 = rankw >= 1 ? 1 : 0;
// The fifth corner has all coordinate offsets = 1, so no need to compute that.
double x1 = x0 - i1 + G4; // Offsets for second corner in (x,y,z,w) coords
double y1 = y0 - j1 + G4;
double z1 = z0 - k1 + G4;
double w1 = w0 - l1 + G4;
double x2 = x0 - i2 + 2.0 * G4; // Offsets for third corner in (x,y,z,w) coords
double y2 = y0 - j2 + 2.0 * G4;
double z2 = z0 - k2 + 2.0 * G4;
double w2 = w0 - l2 + 2.0 * G4;
double x3 = x0 - i3 + 3.0 * G4; // Offsets for fourth corner in (x,y,z,w) coords
double y3 = y0 - j3 + 3.0 * G4;
double z3 = z0 - k3 + 3.0 * G4;
double w3 = w0 - l3 + 3.0 * G4;
double x4 = x0 - 1.0 + 4.0 * G4; // Offsets for last corner in (x,y,z,w) coords
double y4 = y0 - 1.0 + 4.0 * G4;
double z4 = z0 - 1.0 + 4.0 * G4;
double w4 = w0 - 1.0 + 4.0 * G4;
// Work out the hashed gradient indices of the five simplex corners
int ii = i & 255;
int jj = j & 255;
int kk = k & 255;
int ll = l & 255;
int gi0 = perm[ii + perm[jj + perm[kk + perm[ll]]]] % 32;
int gi1 = perm[ii + i1 + perm[jj + j1 + perm[kk + k1 + perm[ll + l1]]]] % 32;
int gi2 = perm[ii + i2 + perm[jj + j2 + perm[kk + k2 + perm[ll + l2]]]] % 32;
int gi3 = perm[ii + i3 + perm[jj + j3 + perm[kk + k3 + perm[ll + l3]]]] % 32;
int gi4 = perm[ii + 1 + perm[jj + 1 + perm[kk + 1 + perm[ll + 1]]]] % 32;
// Calculate the contribution from the five corners
double t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0;
if (t0 < 0) {
n0 = 0.0;
} else {
t0 *= t0;
n0 = t0 * t0 * dot(grad4[gi0], x0, y0, z0, w0);
}
double t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1;
if (t1 < 0) {
n1 = 0.0;
} else {
t1 *= t1;
n1 = t1 * t1 * dot(grad4[gi1], x1, y1, z1, w1);
}
double t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2;
if (t2 < 0) {
n2 = 0.0;
} else {
t2 *= t2;
n2 = t2 * t2 * dot(grad4[gi2], x2, y2, z2, w2);
}
double t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3;
if (t3 < 0) {
n3 = 0.0;
} else {
t3 *= t3;
n3 = t3 * t3 * dot(grad4[gi3], x3, y3, z3, w3);
}
double t4 = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4;
if (t4 < 0) {
n4 = 0.0;
} else {
t4 *= t4;
n4 = t4 * t4 * dot(grad4[gi4], x4, y4, z4, w4);
}
// Sum up and scale the result to cover the range [-1,1]
return 27.0 * (n0 + n1 + n2 + n3 + n4);
}
// Inner class to speed up gradient computations
// (array access is a lot slower than member access)
private static class Grad {
double x;
double y;
double z;
double w;
Grad(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
Grad(double x, double y, double z, double w) {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
}
}
| gpl-3.0 |
pt12lol/opeNotes | opeNotes/rhythmicValue.py | 2629 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from functools import total_ordering
@total_ordering
class RhythmicValue(object):
"""Represents class of music rhythmic values.
Attrs:
value (int): describing part of whole note (should be positive integer
power of 2)
dots (int): describing extension of base rhythmic value (each dot
extend half of last extension value)
"""
__slots__ = ['value', 'dots']
def __init__(self, value=None, dots=None):
"""Creates instance of RhythmicValue by value and number of dots.
Args:
value (int): part of whole note (should be positive integer
power of 2) (default: 4)
dots (int): number of extending dots (should be positive integer
value) (default: 0)
"""
if value is None:
value = 4
if dots is None:
dots = 0
self.value = value
self.dots = dots
def __repr__(self):
"""Returns string describing rhythmic value in LilyPond notation.
Returns:
string describing rhythmic value in LilyPond notation
"""
return str(self.value) + ''.join(['.' for _ in range(self.dots)])
def __str__(self):
"""Returns string describing rhythmic value in LilyPond notation.
Returns:
string describing rhythmic value in LilyPond notation
"""
return self.__repr__()
def __eq__(self, other):
"""Checks whether two rhythmic values are the same.
Args:
other (RhythmicValue): rhythmic value to compare with self
Returns:
result of equality of self pair of value and dots number with other
pair of vaue and dots number
"""
return (self.value, self.dots) == (other.value, other.dots)
def __ne__(self, other):
"""Checks whether two rhythmic values aren't the same.
Args:
other (RhythmicValue): rhythmic value to compare with self
Returns:
result of non-equality of self pair of value and dots number with
other pair of vaue and dots number
"""
return not self.__eq__(other)
def __lt__(self, other):
"""Compares two rhythmic values each other.
Args:
other (RhythmicValue): rhythmic value to compare with self
Returns:
result of comparison of length of last two rhythmic values
"""
return self.value > other.value if self.value != other.value \
else self.dots < other.dots
| gpl-3.0 |
fenwick67/bumbler | lib/hydrate-posts.js | 2508 | /*
take a post and hydrate it
*/
var marked = require('marked');
var mime = require('mime-types');
var plugins = require('./plugins');
var parseFrontMatter = require("yaml-front-matter").loadFront;
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: true,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false
});
module.exports = function(j){
j.permalink = '/post/'+j.id+'.html';
// split tags by commas
if (j.tags && typeof j.tags == 'string'){
j.tags = j.tags.split(/,\s*/g);
}else if (!j.tags){
j.tags = [];
}
j.assets = j.assets || [];
// create widgets for assets
j.assets.forEach(asset=>{
var type = asset.type;
if (type == 'image'){
asset.widget = `<img class="asset" src="${asset.href}"></img>`
}else if (type == 'audio'){
asset.widget = `<audio class="asset" controls src="${asset.href}"></audio>`
}else if (type = "video"){
asset.widget = `<video class="asset" controls src="${asset.href}"></video>`
}else{
asset.widget = `<span class="asset" Link to attachment: <a href="${asset.href}">${asset.href}</a></span>`
}
// add mimetype
asset.mimetype = mime.lookup(asset.href) || 'application/octet-stream';
// check to see if asset is already inline in the post body
if (j.caption.indexOf(asset.href) > -1){
asset.inline = true;
}else{
asset.inline = false;
}
});
j.englishDate = isoDateToEnglish(j.date);
var sourceData = j.caption || '';
// now remove front matter if there is any
try{
var frontMatter = parseFrontMatter(sourceData);
var postMarkdown = frontMatter.__content || '';
}catch(e){
console.warn('error parsing front matter:');
console.warn(e,e.trace)
var frontMatter = {};
var postMarkdown = sourceData;
}
delete frontMatter.__content;
j.markdown = postMarkdown;
j.frontMatter = frontMatter;
j.caption = marked(postMarkdown);
// alias the html data
j.rawHtml = j.caption;
j.content = j.caption;
return j;
}
function isoDateToEnglish(d){
var d = d;
if (typeof d != 'string'){
d = d.toISOString();
}
var dt = d.split(/[t\-]/ig);
var months = [ "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" ];
return months[Number(dt[1])-1] +' '+dt[2]+ ', '+dt[0];
}
| gpl-3.0 |
desci/tg-cryptoforexbot | plugins/coinmarketcap/valid.py | 3053 | # vim:fileencoding=utf-8
## Tests for available coinmarketcap parameters (assuming our json files are updated)
import json
from cryptoforexbot import texts
class valid():
def __init__(self):
pass
def crypto(self, string):
try:
valid_cryptos = json.load(open('plugins/coinmarketcap/cryptos.json'))
for crypto in valid_cryptos:
for symbol in valid_cryptos[crypto]['symbols']:
if string.lower() == symbol.lower():
return (True, (valid_cryptos[crypto]['coinmarketcap_id'], valid_cryptos[crypto]['name']), 'Found valid crypto: %s' % (valid_cryptos[crypto]['name']))
return (False, texts.err_valid[0], 'Did not found crypto: %s' % (string))
except Exception as e:
return (False, False, 'DEBUG %s%sexception: %s' % (self, '\n', e))
def convert(self, string):
try:
valid_converts = json.load(open('plugins/coinmarketcap/converts.json'))
for convert in valid_converts:
for symbol in valid_converts[convert]['symbols']:
if string.lower() == symbol.lower():
return (True, (valid_converts[convert]['coinmarketcap_id'], valid_converts[convert]['name']), 'Found valid convert: %s' % (valid_converts[convert]['name']))
return (False, texts.err_valid[0], 'Did not found convert: %s' % (string))
except Exception as e:
return (False, False, 'DEBUG %s%sexception: %s' % (self, '\n', e))
def coin(self, string):
try:
valid_convert = self.convert(string)
if valid_convert[0]:
return ('fiat', valid_convert[1], valid_convert[2])
else:
valid_crypto = self.crypto(string)
if valid_crypto[0]:
return ('crypto', valid_crypto[1], '\n'.join([valid_convert[2], valid_crypto[2]]))
elif valid_crypto[1]:
return (False, valid_crypto[1], valid_crypto[2])
elif valid_crypto[2]:
return (False, False, '\n'.join([valid_convert[2], valid_crypto[2]]))
else:
return (False, False, False)
except Exception as e:
return (False, False, 'DEBUG %s%sexception: %s' % (self, '\n', e))
class fake_valid():
def __init__(self):
pass
def crypto(self, string):
return (True, (string, string), 'Did not validate, sent True value')
def convert(self, string):
return (True, (string, string), 'Did not validate, sent True value')
def coin(self, string):
try:
valid_convert = self.convert(string)
if valid_convert[0]:
return ('fiat', valid_convert[1], valid_convert[2])
else:
valid_crypto = self.crypto(string)
if valid_crypto[0]:
return ('crypto', valid_crypto[1], '\n'.join([valid_convert[2], valid_crypto[2]]))
elif valid_crypto[1]:
return (False, valid_crypto[1], valid_crypto[2])
elif valid_crypto[2]:
return (False, False, '\n'.join([valid_convert[2], valid_crypto[2]]))
else:
return (False, False, False)
except Exception as e:
return (False, False, 'DEBUG %s%sexception: %s' % (self, '\n', e))
| gpl-3.0 |
iTXTech/Daedalus | app/src/main/java/org/itxtech/daedalus/util/Logger.java | 2607 | package org.itxtech.daedalus.util;
import android.util.Log;
import org.itxtech.daedalus.Daedalus;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Daedalus Project
*
* @author iTX Technologies
* @link https://itxtech.org
* <p>
* 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.
*/
public class Logger {
private static StringBuffer buffer = null;
public static void init() {
if (buffer != null) {
buffer.setLength(0);
} else {
buffer = new StringBuffer();
}
}
public static void shutdown() {
buffer = null;
}
public static String getLog() {
return buffer.toString();
}
public static void error(String message) {
send("[ERROR] " + message);
}
public static void warning(String message) {
send("[WARNING] " + message);
}
public static void info(String message) {
send("[INFO] " + message);
}
public static void debug(String message) {
send("[DEBUG] " + message);
}
public static void logException(Throwable e) {
error(getExceptionMessage(e));
}
public static String getExceptionMessage(Throwable e) {
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
e.printStackTrace(printWriter);
return stringWriter.toString();
}
private static int getLogSizeLimit() {
return Integer.parseInt(Daedalus.getPrefs().getString("settings_log_size", "10000"));
}
private static boolean checkBufferSize() {
int limit = getLogSizeLimit();
if (limit == 0) {//DISABLED!
return false;
}
if (limit == -1) {//N0 limit
return true;
}
if (buffer.length() > limit) {//LET's clean it up!
buffer.setLength(limit);
}
return true;
}
private static void send(String message) {
try {
if (checkBufferSize()) {
String fileDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ").format(new Date());
buffer.insert(0, "\n").insert(0, message).insert(0, fileDateFormat);
}
Log.d("Daedalus", message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
| gpl-3.0 |
mconf/mconf-mobile | bbb-android-core/jni/iva/common/compatibility/common.cpp | 27382 | extern "C" {
#include <libavcodec/avcodec.h>
};
#define _WINSOCKAPI_ /* Prevent inclusion of winsock.h in windows.h */
#include <windows.h>
#include <Commdlg.h>
#include <shlobj.h>
#include <iostream>
using namespace std;
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include <sys/types.h>
#include "error.h"
#include "errorDefs.h"
#include "common_compatibility.h"
#include "common_sock.h"
#include "common_leaks.h"
#ifdef _MSC_VER
#include <winsock2.h>
#else
#include <sys/socket.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <errno.h>
#endif
#include "../Folders.h"
common_context_t commonCtx;
int common_init()
{
struct tm today;
time_t t;
char strtime[100];
//char logpath[250];
int ret;
bzero(strtime, 100);
//bzero(logpath, 250);
pthread_mutex_init(&commonCtx.logMutex, NULL);
error_init();
IvaString logpath;
logpath = Folders::getLogFolder();
// tenta criar o diretório do log
#ifdef _MSC_VER
if (CreateDirectory(logpath.toWchar(), NULL) == 0) {
int error = GetLastError();
if (error != ERROR_ALREADY_EXISTS) { // já existe, não é erro
error_s(AT, E_ERROR, "Não foi possível criar arquivo o diretório log (%s)",
COMMON_LOG_DIRECTORY);
return E_ERROR;
}
}
#else
if (mkdir((char *)logpath.c_str(), NULL) == 0) {
if (errno != EEXIST) { // já existe, não é erro
error_s(AT, E_ERROR, "Não foi possível criar arquivo o diretório log (%s)",
COMMON_LOG_DIRECTORY);
return E_ERROR;
}
}
#endif
// nome do log padrão depende da data de hoje
time(&t);
localtime_s(&today, &t);
//strftime(strtime, 100, "log-%d.%m.%y-%Hh%M.txt", today); // usa a hora do dia tbm
strftime(strtime, 100, "log-%d.%m.%y.txt", &today); // usa só o dia
// abre o arquivo de log padrão
pthread_mutex_lock(&commonCtx.logMutex);
commonCtx.logFile = common_log_openFile(strtime);
// imprime data e o texto no arquivo de log
if (commonCtx.logFile) {
time(&t);
localtime_s(&today, &t);
strftime(strtime, 50, "%d/%m/%Y %H:%M.%S", &today);
fprintf(commonCtx.logFile, "\n+-------------------------------------------------------------+\n");
fprintf(commonCtx.logFile, "| Nova sessao [%s] |\n", strtime);
fprintf(commonCtx.logFile, "+-------------------------------------------------------------+\n");
fflush(commonCtx.logFile);
ret = E_OK;
} else {
ret = E_ERROR;
}
pthread_mutex_unlock(&commonCtx.logMutex);
return ret;
}
int common_end()
{
struct tm today;
time_t t;
char strtime[50];
// finaliza arquivo de lpg
if (commonCtx.logFile) {
// imprime data e o texto no arquivo de log
time(&t);
localtime_s(&today, &t);
strftime(strtime, 50, "%d/%m/%Y %H:%M.%S", &today);
pthread_mutex_lock(&commonCtx.logMutex);
fprintf(commonCtx.logFile,
"+-------------------------------------------------------------+\n");
fprintf(commonCtx.logFile,
"| Fim da sessao [%s] |\n", strtime);
fprintf(commonCtx.logFile,
"+-------------------------------------------------------------+\n\n");
fflush(commonCtx.logFile);
fclose(commonCtx.logFile); // fecha o arquivo
pthread_mutex_unlock(&commonCtx.logMutex);
}
error_end();
pthread_mutex_destroy(&commonCtx.logMutex);
return E_OK;
}
/********************************************************************/
#ifdef _MSC_VER
void bzero(char * s, int n)
{
memset(s, '\0', n);
}
#endif
void common_nullFunc(char *fmt, ...)
{
; // não deve fazer NADA
}
unsigned int getTimestamp(void)
{
#ifdef _MSC_VER
LARGE_INTEGER ts,freq;
unsigned int timestamp = 0;
// Query for the timestamp
QueryPerformanceCounter(&ts);
// se o hardware instalado suporta "high-resolution performance counter"
// o valor de freq é diferente de zero
QueryPerformanceFrequency(&freq);
/*
// não usa em alta-resolução
if(freq.QuadPart == 0)
{
// no caso do hardware nao suportar o mecanismo convencional,
// usa-se a funcao gettimeofday versao windows
FILETIME ft;
unsigned int tmpres = 0;
GetSystemTimeAsFileTime(&ft);
timestamp |= ft.dwLowDateTime;
timestamp /= 10000;
}
else*/
timestamp = (unsigned int) ((ts.QuadPart * 1000) / ((double) freq.QuadPart));
#else
/// \todo Código não testado
struct timespec ts;
unsigned int timestamp = 0;
clock_gettime(CLOCK_MONOTONIC,&ts);
timestamp = ts.tv_sec*1000 + ts.tv_nsec/1000000;
#endif
return timestamp;
}
wchar_t *charToWchar(char *str)
{
wchar_t *wcStr;
int length;
length = (int)strlen(str)+1;
wcStr = (wchar_t *)malloc(sizeof(wchar_t)*length);
mbstowcs(wcStr, str, length);
return wcStr;
}
char *wcharToChar(wchar_t *str)
{
char *cStr;
int length;
length = (int)wcslen(str)+1;
cStr = (char *)malloc(sizeof(char)*length);
wcstombs(cStr, str, length);
return cStr;
}
/// \todo ver se é necessária mesmo e remover
void die(int line, const char *function, const char *fmt,...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, fmt);
vsprintf(buffer,fmt,args);
va_end(args);
fprintf(stderr,"%d %s: %s\n",line, function, buffer);
#ifdef DEBUG
getchar();
#endif
common_log(buffer);
common_log("FINISH BY ERROR\n\n");
exit(EXIT_FAILURE);
}
#ifdef _MSC_VER
BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved )
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 );
if(WSAStartup( wVersionRequested, &wsaData)!=0){
return false;
}
return true;
}
#endif
/************************************************************************************
* Logs e printfs
************************************************************************************/
void common_log_internal(FILE * file, const char *fmt, ...)
{
va_list args;
time_t t;
struct tm today;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
char strtime[50];
// se não criou o arquivo de log, sai fora
if (!file) {
return;
}
va_start(args, fmt);
vsprintf(buffer,fmt,args);
va_end(args);
// pega a data atual
time(&t);
localtime_s(&today, &t);
strftime(strtime, 50, "%d/%m/%Y %H:%M.%S", &today);
// imprime data e o texto no arquivo de log
fprintf(file, "[%s] %s\n", strtime, buffer);
fflush(file);
}
void common_log(const char *fmt, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, fmt);
vsprintf(buffer, fmt, args);
va_end(args);
if (commonCtx.logMutex) {
pthread_mutex_lock(&commonCtx.logMutex);
}
common_log_internal(commonCtx.logFile, "%s", buffer);
if (commonCtx.logMutex) {
pthread_mutex_unlock(&commonCtx.logMutex);
}
}
void common_log_at(char *location, const char *fmt, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, fmt);
vsprintf(buffer, fmt, args);
va_end(args);
common_log("[%s]: %s", location, buffer);
}
void common_logprintf(const char *description, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, description);
vsprintf(buffer, description, args);
va_end(args);
common_log("%s", buffer);
#ifdef _CONSOLE
common_printf("%s\n", buffer);
#endif
}
void common_logprintf_at(char *location, const char *description, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
char *locAux;
va_start(args, description);
vsprintf(buffer, description, args);
va_end(args);
locAux = common_parseAtStr(location);
common_logprintf("[%s]: %s", locAux, buffer);
if (locAux) {
free(locAux);
}
}
void common_printf_at(char *location, const char *description, ...)
{
#ifdef _CONSOLE
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, description);
vsprintf(buffer, description, args);
va_end(args);
common_printf("[%s]: %s", location, buffer);
#endif
}
void common_flog(FILE * file, const char *fmt, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, fmt);
vsprintf(buffer, fmt, args);
va_end(args);
common_log_internal(file, "%s", buffer);
}
void common_flog_at(FILE * file, char *location, const char *fmt, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, fmt);
vsprintf(buffer, fmt, args);
va_end(args);
common_log_internal(file, "[%s]: %s", location, buffer);
}
void common_flogprintf(FILE * file, const char *description, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
va_start(args, description);
vsprintf(buffer, description, args);
va_end(args);
common_log_internal(file, "%s", buffer);
#ifdef _CONSOLE
common_printf("%s\n", buffer);
#endif
}
void common_flogprintf_at(FILE * file, char *location, const char *description, ...)
{
va_list args;
char buffer[COMMON_LOG_MAX_LINE_SIZE];
char *locAux;
va_start(args, description);
vsprintf(buffer, description, args);
va_end(args);
locAux = common_parseAtStr(location);
common_log_internal(file, "[%s]: %s", locAux, buffer);
if (locAux) {
free(locAux);
}
}
int common_log_closeFile(FILE * file)
{
if (file) {
return fclose(file);
} else {
return E_NULL_PARAMETER;
}
}
FILE * common_log_openFile(char *filename)
{
//char logpath[255];
FILE * file;
string logpath;
logpath = Folders::getLogFolder();
logpath += filename;
// tenta criar o arquivo de log
if ((file = fopen(logpath.c_str(), "a")) == NULL) {
error_s(AT, E_ERROR, "Não foi possível abrir arquivo de log (%s)", filename);
}
return file;
}
int common_log_getDefaultName(char *name, int namesize)
{
struct tm today;
time_t t;
if (!name) {
return E_NULL_PARAMETER;
}
// nome do log padrão depende da data de hoje
bzero(name, namesize);
time(&t);
localtime_s(&today, &t);
strftime(name, namesize, "log-%d.%m.%y", &today); // usa só o dia, sem hora
return E_OK;
}
/************************************************************************************
* sleeps
************************************************************************************/
void common_sleep(int msec)
{
struct timeval tv;
fd_set readfds;
SOCKET s=0;
if (msec <= 0) return;
tv.tv_sec = (long)(msec / 1000);
tv.tv_usec = (long)((msec % 1000) * 1000);
common_sock_startup();
s = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
FD_ZERO(&readfds);
FD_SET(s,&readfds);
// Usa a função select para manter o processo parado.
select((int)s, &readfds, NULL, NULL, &tv);
#ifdef _MSC_VER
closesocket(s);
#else
close(s);
#endif
}
void common_usleep(int usec)
{
struct timeval tv;
fd_set readfds;
SOCKET s=0;
if (usec <= 0) return;
tv.tv_sec = (long)(usec / 1000000);
tv.tv_usec = (long)((usec % 1000000) * 1000000);
common_sock_startup();
s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
FD_ZERO(&readfds);
FD_SET(s,&readfds);
// Usa a função select para manter o processo parado.
select((int)s, &readfds, NULL, NULL, &tv);
#ifdef _MSC_VER
closesocket(s);
#else
close(s);
#endif
}
/************************************************************************************
* outras...
************************************************************************************/
int common_iToChar(char **str, uint32_t value)
{
int valueSize;
if (!str) {
return E_NULL_PARAMETER;
}
if (value == 0) {
valueSize = 2; // texto será "0\0"
} else {
valueSize = sizeof(char)*((int)floor(log10((float)value))+2);
}
*str = (char *)malloc(valueSize);
_itoa(value, *str, 10);
return E_OK;
}
int common_validateIPv4(char *ip, uint8_t multicast)
{
char aux[15];
int ipNumb, j, k = 0, count = 0;
int firstIpNumb = 0;
// valida o tamanho máximo de um ip
int i = (int) strlen(ip);
//printf("i=%d\n",i);
if (i > 15) {
return E_ERROR;
}
while (count < 4) {
// acha o próximo ponto
i = (int) strcspn(ip + k, ".");
//printf("i=%d\n",i);
if (i > 3 || i == 0) { // mais de 3 dígitos ou 0 dígitos em um número
//printf("i > 3 || i == 0\n");
return E_ERROR;
}
// busca o número e coloca em aux
bzero(aux, i+1);
strncpy_s(aux, i+1, ip + k, i);
for(j = 0; j < i; j++) {
//printf("aux = %s\n",aux);
if (!isdigit(aux[j])) { // algo que não é um dígito
//printf("!isdigit(aux[j]): %d\n",aux[j]);
return E_ERROR;
}
}
ipNumb = atoi(aux);
// primeiro número do IP
if (count == 0) {
// aceita intervalo 1..239
if (ipNumb < 1 || ipNumb > 239) {
return E_ERROR;
// se multicast, só aceita intervalo 224..239
} else if (multicast && ipNumb < 224) {
return E_ERROR;
}
firstIpNumb = ipNumb;
// último número do IP
} else if (count == 3) {
// só maiores que 0
if(ipNumb < 0) {
return E_ERROR;
// se o primeiro número é 239, só aceita que 239.x.x.254
} else if (firstIpNumb == 239 && ipNumb > 254) {
return E_ERROR;
// se multicast, só aceita intervalo 1..254
} else if (multicast && ipNumb < 1) {
return E_ERROR;
}
else if ( ipNumb > 255) {
return E_ERROR;
}
} else {
// números intermediários entre 0..255
if(ipNumb < 0 || ipNumb > 255){
return E_ERROR;
}
}
k = k + i + 1;
count++;
if(count == 4) {
if(ip[k-1] != '\0') {
return E_ERROR;
}
}
}
return E_OK;
}
int common_getDB(int level)
{
switch(level) {
case 0: return VU_db30;
case 1: return VU_db33;
case 2: return VU_db36;
case 3: return VU_db39;
case 4: return VU_db42;
case 5: return VU_db45;
case 6: return VU_db48;
case 7: return VU_db51;
case 8: return VU_db54;
case 9: return VU_db57;
case 10: return VU_db60;
case 11: return VU_db63;
case 12: return VU_db66;
case 13: return VU_db69;
case 14: return VU_db72;
case 15: return VU_db75;
case 16: return VU_db78;
case 17: return VU_db81;
case 18: return VU_db84;
case 19: return VU_db87;
case 20: return VU_db90;
case 21: return VU_db93;
default:
common_logprintf("Nível inválido");
return VU_db93;
}
}
int common_getVULevel(double amp)
{
int level;
if (amp < VU_db30) level = 0;
else if (amp < VU_db33) level = 1;
else if (amp < VU_db36) level = 2;
else if (amp < VU_db39) level = 3;
else if (amp < VU_db42) level = 4;
else if (amp < VU_db45) level = 5;
else if (amp < VU_db48) level = 6;
else if (amp < VU_db51) level = 7;
else if (amp < VU_db54) level = 8;
else if (amp < VU_db57) level = 9;
else if (amp < VU_db60) level = 10;
else if (amp < VU_db63) level = 11;
else if (amp < VU_db66) level = 12;
else if (amp < VU_db69) level = 13;
else if (amp < VU_db72) level = 14;
else if (amp < VU_db75) level = 15;
else if (amp < VU_db78) level = 16;
else if (amp < VU_db81) level = 17;
else if (amp < VU_db84) level = 18;
else if (amp < VU_db87) level = 19;
else if (amp < VU_db90) level = 20;
else level = 21;
return level;
}
int common_rect_init(common_rect_t *rect)
{
if (!rect) {
return E_NULL_PARAMETER;
}
rect->x = 0;
rect->y = 0;
rect->w = 0;
rect->h = 0;
return E_OK;
}
int common_rect_copy(common_rect_t *dst, common_rect_t *src)
{
if (!dst || !src) {
return E_NULL_PARAMETER;
}
dst->x = src->x;
dst->y = src->y;
dst->w = src->w;
dst->h = src->h;
return E_OK;
}
int common_color_init(common_color_t *col)
{
if (!col) {
return E_NULL_PARAMETER;
}
col->r = 0;
col->g = 0;
col->b = 0;
col->unused = 0;
col->alpha = 255;
return E_OK;
}
int common_color_toInt(common_color_t *col)
{
int ret = 0;
if (!col) {
error_s(AT, E_NULL_PARAMETER, E_MSG_NULL_PARAMETER, "col");
return E_NULL_PARAMETER;
}
ret += col->alpha * 0x1000000;
ret += col->r * 0x10000;
ret += col->g * 0x100;
ret += col->b;
return ret;
}
/*
int common_color_fromInt(common_color_t *col, int value)
{
col->alpha = floor(value/0x1000000);
}*/
// créditos:
// http://devpinoy.org/blogs/cvega/archive/2006/06/19/xtoi-hex-to-integer-c-function.aspx
uint32_t common_xtoi(const char* xs)
{
size_t szlen = strlen(xs);
int i, xv, fact;
uint32_t result;
if (szlen > 0) {
// limita em 32 bits
if (szlen > 8) {
return 0;
}
result = 0;
fact = 1;
// varre todos caracteres de trás pra frente
for (i = (int)szlen-1; i >= 0; i--) {
if (isxdigit(*(xs+i))) {
if (*(xs+i)>=97) {
xv = ( *(xs+i) - 97) + 10;
} else if ( *(xs+i) >= 65) {
xv = (*(xs+i) - 65) + 10; // letras maiúsculas (A - F)
} else {
xv = *(xs+i) - 48; // digitos normais (0 - 9)
}
result += (xv * fact);
fact *= 16;
} else { // não é um dígito hexa válido
return 0;
}
}
}
return result;
}
int common_strtrim(char *str)
{
bool_t emptyChar = true;
int firstValid, lastValid;
int len;
int newLen;
if (!str) {
error_s(AT, E_NULL_PARAMETER, E_MSG_NULL_PARAMETER, "str");
return E_NULL_PARAMETER;
}
len = (int)strlen(str);
if (len == 0) {
//error_s(AT, E_STRING_EMPTY, E_MSG_STRING_EMPTY, "str");
return E_STRING_EMPTY;
}
// acha o primeiro caractere usável
firstValid = 0;
do {
emptyChar = isspace((unsigned char)str[firstValid]);
firstValid++;
} while (emptyChar && firstValid < len);
firstValid--;
if (emptyChar) { // nada usável na string, deixa ela limpa
bzero(str, len+1);
return E_OK;
}
// acha o último caractere usável
lastValid = len-1;
do {
emptyChar = isspace((unsigned char)str[lastValid]);
lastValid--;
} while (emptyChar && firstValid >= 0);
lastValid++;
// newLen = tamanho da palavra válida
newLen = lastValid-firstValid+1;
if (firstValid > 0) { // corta caracteres do início
strncpy(str, str+firstValid, newLen);
}
bzero(str+newLen, len-newLen); // corta caracteres do fim
return E_OK;
}
void common_strrep(char *str, char oldchar, char newchar)
{
int i;
for (i = 0; i < strlen(str); i++) {
if (str[i] == oldchar) {
str[i] = newchar;
}
}
}
char * common_parseAtStr(const char * location)
{
char * slashPt;
char * ret;
int i;
int strStart;
int retLen;
// recebe uma string como: "d:\iva\trunk\common\common_test\error_test.cpp:test():18"
// e quebra ela para: "common_test\error_test.cpp:test():18"
// procura a última normal
slashPt = strrchr((char *)location, '\\');
if (!slashPt) {
slashPt = strrchr((char *)location, '/');
}
if (!slashPt) {
return NULL; ///\todo melhorar. poderia alocar a própria 'location' inteira
} else {
// acha a próxima barra (de trás pra frente) pra incluir nome da lib junto na string
strStart = 0;
for (i = (int)(slashPt-location)-1; i >= 0; i--) {
if (location[i] == '\\' || location[i] == '/') {
strStart = i+1;
break;
}
}
// calcula tamanho da nova string e aloca memória
retLen = (int)strlen(location) - strStart + 1; // incluindo \0
ret = (char *)malloc(sizeof(char) * retLen);
if (!ret) {
error_s(AT, E_INSUFFICIENT_MEMORY, E_MSG_INSUFFICIENT_MEMORY2, retLen);
return NULL;
}
// copia pra nova string
sprintf_s(ret, retLen, "%s\0", location+strStart);
return ret;
}
}
char * common_formatChatMsg(const char *msg, const char *user)
{
int lenMsg, lenUser, lenNew;
time_t timeNow;
struct tm * timeInfo;
char timeMsg[8]; /// \todo fazer macro pro 8
char *newMsg;
if (!msg || !user) {
error_s(AT, E_NULL_PARAMETER, E_MSG_NULL_PARAMETER, "msg | user");
return NULL;
}
// busca a hora atual
time(&timeNow);
timeInfo = localtime(&timeNow);
strftime(timeMsg, 8, "%H:%M", timeInfo);
// tamanho das strs para calcular tamanho da str final
lenMsg = strlen(msg);
lenUser = strlen(user);
lenNew = lenMsg + lenUser + 8 + 6; // 6 devido à formatação feita abaixo
newMsg = (char *)malloc(sizeof(char) * lenNew);
if (!newMsg) {
error_s(AT, E_INSUFFICIENT_MEMORY, E_MSG_INSUFFICIENT_MEMORY2, lenNew);
return NULL;
}
bzero(newMsg, lenNew);
sprintf(newMsg, "(%s) %s: %s", timeMsg, user, msg);
return newMsg;
}
char * common_formatChatSystemMsg(char *msg, char *user)
{
int lenMsg, lenNew;
time_t timeNow;
struct tm * timeInfo;
char timeMsg[8]; /// \todo fazer macro pro 8
char *newMsg;
if (!msg) {
error_s(AT, E_NULL_PARAMETER, E_MSG_NULL_PARAMETER, "msg");
return NULL;
}
// busca a hora atual
time(&timeNow);
timeInfo = localtime(&timeNow);
strftime(timeMsg, 8, "%H:%M", timeInfo);
// tamanho das strs para calcular tamanho da str final
lenMsg = strlen(msg);
lenNew = lenMsg + 8 + 5; // 6 devido à formatação feita abaixo
newMsg = (char *)malloc(sizeof(char) * lenNew);
if (!newMsg) {
error_s(AT, E_INSUFFICIENT_MEMORY, E_MSG_INSUFFICIENT_MEMORY2, lenNew);
return NULL;
}
bzero(newMsg, lenNew);
sprintf(newMsg, "[%s: %s]", timeMsg, msg);
return newMsg;
}
/* Facilidade de portar para o Linux */
#ifndef _MSC_VER
void _itoa(int value, char * string, int radix)
{
sprintf(string,"%d",value);
}
char * strncpy_s(char *strDest, int numberOfElements, const char *strSource, unsigned count)
{
return strncpy(strDest,strSource,count);
}
int WSAGetLastError()
{
return errno;
}
#endif
int common_openSaveDialog(string * filename, list<pair<string,string>> filter, string extension)
{
int wfiltersize = 2; // dois \0 finais
string sfilter = "";
for (list<pair<string,string>>::iterator i = filter.begin(); i != filter.end(); i++) {
wfiltersize += (int) (*i).first.size() + 1;
sfilter += (*i).first;
sfilter += '\0';
wfiltersize += (int) (*i).second.size() + 1;
sfilter += (*i).second;
sfilter += '\0';
}
sfilter += '\0';
WCHAR * wfilter = new WCHAR[wfiltersize];
ZeroMemory(wfilter,wfiltersize);
WCHAR wextension[sizeof(extension)+1];
ZeroMemory(wextension,sizeof(extension)+1);
int buffersize;
buffersize = MultiByteToWideChar(CP_ACP, 0, sfilter.c_str(), wfiltersize-1, wfilter, wfiltersize);
buffersize = MultiByteToWideChar(CP_ACP, 0, extension.c_str(), (int) extension.size(), wextension, (int) extension.size()+1);
WCHAR wfilename[MAX_PATH];
ZeroMemory(wfilename,MAX_PATH);
// http://msdn.microsoft.com/en-us/library/ms646839%28VS.85%29.aspx
OPENFILENAME file;
ZeroMemory(&file, sizeof(file));
file.lStructSize = sizeof(file);
file.hwndOwner = GetDesktopWindow();
file.lpstrFilter = (LPCWSTR) wfilter;
file.lpstrFile = (LPWSTR) wfilename;
file.nMaxFile = MAX_PATH;
file.Flags = OFN_EXPLORER | OFN_OVERWRITEPROMPT | OFN_PATHMUSTEXIST;
file.lpstrDefExt = (LPCWSTR) wextension;
// http://msdn.microsoft.com/en-us/library/ms646928%28VS.85%29.aspx
BOOL result = GetSaveFileName(&file);
if (!result)
return E_WINDOW_CLOSED;
char cfilename[MAX_PATH];
ZeroMemory(cfilename,MAX_PATH);
buffersize = WideCharToMultiByte(CP_ACP, 0, wfilename, MAX_PATH, cfilename, MAX_PATH, '\0', '\0');
delete wfilter;
(*filename).assign(cfilename);
return E_OK;
}
int common_openFolderDialog(string * path)
{
// http://msdn.microsoft.com/en-us/library/bb773205%28VS.85%29.aspx
BROWSEINFO info;
ZeroMemory(&info, sizeof(info));
info.hwndOwner = GetDesktopWindow();
info.ulFlags = BIF_RETURNONLYFSDIRS | BIF_DONTGOBELOWDOMAIN | BIF_NEWDIALOGSTYLE;// | BIF_USENEWUI;
info.lpszTitle = L"Selecione a pasta desejada:";
// http://msdn.microsoft.com/en-us/library/bb762115%28VS.85%29.aspx
LPITEMIDLIST idList = SHBrowseForFolder(&info);
// se pressionou "cancelar" ou "fechar janela", retorna falso aqui!
if (!idList)
return E_WINDOW_CLOSED;
WCHAR wfolder[MAX_PATH];
ZeroMemory(wfolder, MAX_PATH);
BOOL result = SHGetPathFromIDList(idList,(LPWSTR) wfolder);
// se selecionou uma pasta inválida, retorna falso aqui!
if (!result)
return E_INVALID_FOLDER;
char cfolder[MAX_PATH];
ZeroMemory(cfolder,MAX_PATH);
int buffersize = WideCharToMultiByte(CP_ACP, 0, wfolder, MAX_PATH, cfolder, MAX_PATH, '\0', '\0');
(*path).assign(cfolder);
return E_OK;
}
| gpl-3.0 |
satishagrwal/Assignment | freeswitch_git/mod/languages/mod_java/src/org/freeswitch/swig/SWIGTYPE_p_switch_channel_state_t.java | 780 | /* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 2.0.12
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package org.freeswitch.swig;
public class SWIGTYPE_p_switch_channel_state_t {
private long swigCPtr;
protected SWIGTYPE_p_switch_channel_state_t(long cPtr, boolean futureUse) {
swigCPtr = cPtr;
}
protected SWIGTYPE_p_switch_channel_state_t() {
swigCPtr = 0;
}
protected static long getCPtr(SWIGTYPE_p_switch_channel_state_t obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
}
| gpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.