repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
loftuxab/community-edition-old
|
projects/repository/source/java/org/alfresco/repo/lock/mem/AbstractLockStore.java
|
5688
|
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.lock.mem;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentMap;
import org.alfresco.repo.lock.LockUtils;
import org.alfresco.repo.security.authentication.AuthenticationUtil;
import org.alfresco.repo.transaction.TransactionalResourceHelper;
import org.alfresco.service.cmr.lock.LockStatus;
import org.alfresco.service.cmr.lock.UnableToAquireLockException;
import org.alfresco.service.cmr.repository.NodeRef;
import org.springframework.dao.ConcurrencyFailureException;
import org.springframework.transaction.support.TransactionSynchronizationManager;
/**
* Base class for LockStore implementations that use a ConcurrentMap as storage.
*
* @author Matt Ward
*/
public abstract class AbstractLockStore<T extends ConcurrentMap<NodeRef, LockState>> implements LockStore
{
protected T map;
public AbstractLockStore(T map)
{
this.map = map;
}
@Override
public LockState get(NodeRef nodeRef)
{
LockState lockState;
Map<NodeRef, LockState> txMap = getTxMap();
if (txMap != null && txMap.containsKey(nodeRef))
{
// The transactional map is able to provide the LockState
lockState = txMap.get(nodeRef);
}
else
{
lockState = map.get(nodeRef);
if (txMap != null)
{
// As the txMap doesn't have the LockState, cache it for later.
txMap.put(nodeRef, lockState);
}
}
return lockState;
}
@Override
public void set(NodeRef nodeRef, LockState lockState)
{
Map<NodeRef, LockState> txMap = getTxMap();
LockState previousLockState = null;
if (txMap != null)
{
if (txMap.containsKey(nodeRef))
{
// There is known previous state.
previousLockState = txMap.get(nodeRef);
}
else
{
// No previous known state - get the current state, this becomes
// the previous known state.
previousLockState = get(nodeRef);
}
}
else
{
// No transaction, but we still need to know the previous state, before attempting
// to set new state.
previousLockState = get(nodeRef);
}
// Has the lock been succesfully placed into the lock store?
boolean updated = false;
if (previousLockState != null)
{
String userName = AuthenticationUtil.getFullyAuthenticatedUser();
String owner = previousLockState.getOwner();
Date expires = previousLockState.getExpires();
if (LockUtils.lockStatus(userName, owner, expires) == LockStatus.LOCKED)
{
throw new UnableToAquireLockException(nodeRef);
}
// Use ConcurrentMap.replace(key, old, new) so that we can ensure we don't encounter a
// 'lost update' (i.e. someone else has locked a node while we were thinking about it).
updated = map.replace(nodeRef, previousLockState, lockState);
}
else
{
if (map.putIfAbsent(nodeRef, lockState) == null)
{
updated = true;
}
}
if (!updated)
{
String msg = String.format("Attempt to update lock state failed, old=%s, new=%s, noderef=%s",
previousLockState, lockState, nodeRef);
throw new ConcurrencyFailureException(msg);
}
else
{
// Keep the new value for future reads within this TX.
if (txMap != null)
{
txMap.put(nodeRef, lockState);
}
}
}
@Override
public void clear()
{
map.clear();
Map<NodeRef, LockState> txMap = getTxMap();
if (txMap != null)
{
txMap.clear();
}
}
/**
* Returns a transactionally scoped Map that is used to provide repeatable lock store queries
* for a given NodeRef. If no transaction is present, then null is returned.
*
* @return Transactional Map or null if not available.
*/
protected Map<NodeRef, LockState> getTxMap()
{
if (!TransactionSynchronizationManager.isSynchronizationActive())
{
return null;
}
Map<NodeRef, LockState> map = TransactionalResourceHelper.getMap(getClass().getName()+".repeatableReadMap");
return map;
}
@Override
public Set<NodeRef> getNodes()
{
return map.keySet();
}
}
|
lgpl-3.0
|
wesamhaboush/pogo
|
src/test/java/com/codebreeze/testing/tools/pogo/test/dto/pdm3/Pdm3PojoConstructor.java
|
551
|
package com.codebreeze.testing.tools.pogo.test.dto.pdm3;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class Pdm3PojoConstructor<T extends RuntimeException>
{
private final T name;
public Pdm3PojoConstructor( T name )
{
this.name = name;
}
public T getName()
{
return name;
}
@Override
public String toString()
{
return ReflectionToStringBuilder.toString( this, ToStringStyle.JSON_STYLE );
}
}
|
lgpl-3.0
|
martin-wikipixel/openDAM
|
opendam/lib/model/map/FileTagTableMap.php
|
1986
|
<?php
/**
* This class defines the structure of the 'file_tag' table.
*
*
* This class was autogenerated by Propel 1.4.2 on:
*
* Thu Oct 31 14:46:48 2013
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
* @package lib.model.map
*/
class FileTagTableMap extends TableMap {
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'lib.model.map.FileTagTableMap';
/**
* Initialize the table attributes, columns and validators
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('file_tag');
$this->setPhpName('FileTag');
$this->setClassname('FileTag');
$this->setPackage('lib.model');
$this->setUseIdGenerator(true);
// columns
$this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null);
$this->addColumn('FILE_ID', 'FileId', 'INTEGER', true, null, null);
$this->addForeignKey('TAG_ID', 'TagId', 'INTEGER', 'tag', 'ID', true, null, null);
$this->addColumn('TYPE', 'Type', 'VARCHAR', true, 255, null);
// validators
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
$this->addRelation('Tag', 'Tag', RelationMap::MANY_TO_ONE, array('tag_id' => 'id', ), 'CASCADE', 'CASCADE');
} // buildRelations()
/**
*
* Gets the list of behaviors registered for this table
*
* @return array Associative array (name => parameters) of behaviors
*/
public function getBehaviors()
{
return array(
'symfony' => array('form' => 'true', 'filter' => 'true', ),
'symfony_behaviors' => array(),
);
} // getBehaviors()
} // FileTagTableMap
|
lgpl-3.0
|
zenframework/z8
|
org.zenframework.z8.server/src/main/java/org/zenframework/z8/server/db/sql/functions/InVector.java
|
1895
|
package org.zenframework.z8.server.db.sql.functions;
import java.util.Collection;
import org.zenframework.z8.server.base.table.value.Field;
import org.zenframework.z8.server.base.table.value.IField;
import org.zenframework.z8.server.db.DatabaseVendor;
import org.zenframework.z8.server.db.FieldType;
import org.zenframework.z8.server.db.sql.FormatOptions;
import org.zenframework.z8.server.db.sql.SqlConst;
import org.zenframework.z8.server.db.sql.SqlField;
import org.zenframework.z8.server.db.sql.SqlToken;
import org.zenframework.z8.server.runtime.RCollection;
import org.zenframework.z8.server.types.primary;
import org.zenframework.z8.server.types.sql.sql_bool;
public class InVector extends SqlToken {
private In inToken = null;
public InVector(Field field, RCollection<? extends primary> param2) {
this(new SqlField(field), (Collection<? extends primary>)param2);
}
public InVector(SqlToken what, RCollection<? extends primary> values) {
this(what, (Collection<? extends primary>)values);
}
public InVector(Field field, Collection<? extends primary> values) {
this(new SqlField(field), values);
}
public InVector(SqlToken what, Collection<? extends primary> values) {
if(values.size() != 0) {
inToken = new In();
inToken.setCondition(what);
for(primary i : values)
inToken.addValues(new SqlConst(i));
}
}
@Override
public void collectFields(Collection<IField> fields) {
if(inToken != null) {
inToken.collectFields(fields);
}
}
@Override
public String format(DatabaseVendor vendor, FormatOptions options, boolean logicalContext) {
if(inToken != null) {
return inToken.format(vendor, options, logicalContext);
} else {
return new sql_bool(false).format(vendor, options, logicalContext);
}
}
@Override
public FieldType type() {
return FieldType.Boolean;
}
}
|
lgpl-3.0
|
AznStyle/lwb2
|
core/lib/Thelia/Action/Product.php
|
14691
|
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Action;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Model\Map\ProductTableMap;
use Thelia\Model\ProductQuery;
use Thelia\Model\Product as ProductModel;
use Thelia\Model\ProductAssociatedContent;
use Thelia\Model\ProductAssociatedContentQuery;
use Thelia\Model\ProductCategory;
use Thelia\Model\TaxRuleQuery;
use Thelia\Model\AccessoryQuery;
use Thelia\Model\Accessory;
use Thelia\Model\FeatureProduct;
use Thelia\Model\FeatureProductQuery;
use Thelia\Model\ProductCategoryQuery;
use Thelia\Model\ProductSaleElementsQuery;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\Product\ProductUpdateEvent;
use Thelia\Core\Event\Product\ProductCreateEvent;
use Thelia\Core\Event\Product\ProductDeleteEvent;
use Thelia\Core\Event\Product\ProductToggleVisibilityEvent;
use Thelia\Core\Event\Product\ProductAddContentEvent;
use Thelia\Core\Event\Product\ProductDeleteContentEvent;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\UpdateSeoEvent;
use Thelia\Core\Event\FeatureProduct\FeatureProductUpdateEvent;
use Thelia\Core\Event\FeatureProduct\FeatureProductDeleteEvent;
use Thelia\Core\Event\Product\ProductSetTemplateEvent;
use Thelia\Core\Event\Product\ProductDeleteCategoryEvent;
use Thelia\Core\Event\Product\ProductAddCategoryEvent;
use Thelia\Core\Event\Product\ProductAddAccessoryEvent;
use Thelia\Core\Event\Product\ProductDeleteAccessoryEvent;
use Propel\Runtime\Propel;
class Product extends BaseAction implements EventSubscriberInterface
{
/**
* Create a new product entry
*
* @param \Thelia\Core\Event\Product\ProductCreateEvent $event
*/
public function create(ProductCreateEvent $event)
{
$product = new ProductModel();
$product
->setDispatcher($event->getDispatcher())
->setRef($event->getRef())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setVisible($event->getVisible() ? 1 : 0)
->setLwbmodelivraison($event->getLwbmodelivraison())
// Set the default tax rule to this product
->setTaxRule(TaxRuleQuery::create()->findOneByIsDefault(true))
->create(
$event->getDefaultCategory(),
$event->getBasePrice(),
$event->getCurrencyId(),
$event->getTaxRuleId(),
$event->getBaseWeight(),
$event->getLwbmodelivraison()
);
;
$event->setProduct($product);
}
/**
* Change a product
*
* @param \Thelia\Core\Event\Product\ProductUpdateEvent $event
*/
public function update(ProductUpdateEvent $event)
{
if (null !== $product = ProductQuery::create()->findPk($event->getProductId())) {
$product
->setDispatcher($event->getDispatcher())
->setRef($event->getRef())
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setDescription($event->getDescription())
->setChapo($event->getChapo())
->setPostscriptum($event->getPostscriptum())
->setVisible($event->getVisible() ? 1 : 0)
->setBrandId($event->getBrandId() <= 0 ? null : $event->getBrandId())
->setLwbmodelivraison($event->getLwbmodelivraison())
->save()
;
// Update default category (ifd required)
$product->updateDefaultCategory($event->getDefaultCategory());
$event->setProduct($product);
}
}
/**
* Change a product SEO
*
* @param \Thelia\Core\Event\UpdateSeoEvent $event
*/
public function updateSeo(UpdateSeoEvent $event)
{
return $this->genericUpdateSeo(ProductQuery::create(), $event);
}
/**
* Delete a product entry
*
* @param \Thelia\Core\Event\Product\ProductDeleteEvent $event
*/
public function delete(ProductDeleteEvent $event)
{
if (null !== $product = ProductQuery::create()->findPk($event->getProductId())) {
$product
->setDispatcher($event->getDispatcher())
->delete()
;
$event->setProduct($product);
}
}
/**
* Toggle product visibility. No form used here
*
* @param ActionEvent $event
*/
public function toggleVisibility(ProductToggleVisibilityEvent $event)
{
$product = $event->getProduct();
$product
->setDispatcher($event->getDispatcher())
->setVisible($product->getVisible() ? false : true)
->save()
;
$event->setProduct($product);
}
/**
* Changes position, selecting absolute ou relative change.
*
* @param ProductChangePositionEvent $event
*/
public function updatePosition(UpdatePositionEvent $event)
{
$this->genericUpdatePosition(ProductQuery::create(), $event);
}
public function addContent(ProductAddContentEvent $event)
{
if (ProductAssociatedContentQuery::create()
->filterByContentId($event->getContentId())
->filterByProduct($event->getProduct())->count() <= 0) {
$content = new ProductAssociatedContent();
$content
->setDispatcher($event->getDispatcher())
->setProduct($event->getProduct())
->setContentId($event->getContentId())
->save()
;
}
}
public function removeContent(ProductDeleteContentEvent $event)
{
$content = ProductAssociatedContentQuery::create()
->filterByContentId($event->getContentId())
->filterByProduct($event->getProduct())->findOne()
;
if ($content !== null)
$content
->setDispatcher($event->getDispatcher())
->delete()
;
}
public function addCategory(ProductAddCategoryEvent $event)
{
if (ProductCategoryQuery::create()
->filterByProduct($event->getProduct())
->filterByCategoryId($event->getCategoryId())
->count() <= 0) {
$productCategory = new ProductCategory();
$productCategory
->setProduct($event->getProduct())
->setCategoryId($event->getCategoryId())
->setDefaultCategory(false)
->save()
;
}
}
public function removeCategory(ProductDeleteCategoryEvent $event)
{
$productCategory = ProductCategoryQuery::create()
->filterByProduct($event->getProduct())
->filterByCategoryId($event->getCategoryId())
->findOne();
if ($productCategory != null) $productCategory->delete();
}
public function addAccessory(ProductAddAccessoryEvent $event)
{
if (AccessoryQuery::create()
->filterByAccessory($event->getAccessoryId())
->filterByProductId($event->getProduct()->getId())->count() <= 0) {
$accessory = new Accessory();
$accessory
->setDispatcher($event->getDispatcher())
->setProductId($event->getProduct()->getId())
->setAccessory($event->getAccessoryId())
->save()
;
}
}
public function removeAccessory(ProductDeleteAccessoryEvent $event)
{
$accessory = AccessoryQuery::create()
->filterByAccessory($event->getAccessoryId())
->filterByProductId($event->getProduct()->getId())->findOne()
;
if ($accessory !== null)
$accessory
->setDispatcher($event->getDispatcher())
->delete()
;
}
public function setProductTemplate(ProductSetTemplateEvent $event)
{
$con = Propel::getWriteConnection(ProductTableMap::DATABASE_NAME);
$con->beginTransaction();
try {
$product = $event->getProduct();
// Delete all product feature relations
if (null !== $featureProducts = FeatureProductQuery::create()->findByProductId($product->getId())) {
/** @var \Thelia\Model\FeatureProduct $featureProduct */
foreach ($featureProducts as $featureProduct) {
$eventDelete = new FeatureProductDeleteEvent($product->getId(), $featureProduct->getFeatureId());
$event->getDispatcher()->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $eventDelete);
}
}
// Delete all product attributes sale elements
ProductSaleElementsQuery::create()->filterByProduct($product)->delete($con);
// Update the product template
$template_id = $event->getTemplateId();
// Set it to null if it's zero.
if ($template_id <= 0) $template_id = NULL;
$product->setTemplateId($template_id)->save($con);
// Create a new default product sale element
$product->createProductSaleElement($con, 0, 0, 0, $event->getCurrencyId(), true);
$product->clearProductSaleElementss();
$event->setProduct($product);
// Store all the stuff !
$con->commit();
} catch (\Exception $ex) {
$con->rollback();
throw $ex;
}
}
/**
* Changes accessry position, selecting absolute ou relative change.
*
* @param ProductChangePositionEvent $event
*/
public function updateAccessoryPosition(UpdatePositionEvent $event)
{
return $this->genericUpdatePosition(AccessoryQuery::create(), $event);
}
/**
* Changes position, selecting absolute ou relative change.
*
* @param ProductChangePositionEvent $event
*/
public function updateContentPosition(UpdatePositionEvent $event)
{
return $this->genericUpdatePosition(ProductAssociatedContentQuery::create(), $event);
}
/**
* Update the value of a product feature.
*
* @param FeatureProductUpdateEvent $event
*/
public function updateFeatureProductValue(FeatureProductUpdateEvent $event)
{
// If the feature is not free text, it may have one ore more values.
// If the value exists, we do not change it
// If the value does not exists, we create it.
//
// If the feature is free text, it has only a single value.
// Etiher create or update it.
$featureProductQuery = FeatureProductQuery::create()
->filterByFeatureId($event->getFeatureId())
->filterByProductId($event->getProductId())
;
if ($event->getIsTextValue() !== true) {
$featureProductQuery->filterByFeatureAvId($event->getFeatureValue());
}
$featureProduct = $featureProductQuery->findOne();
if ($featureProduct == null) {
$featureProduct = new FeatureProduct();
$featureProduct
->setDispatcher($event->getDispatcher())
->setProductId($event->getProductId())
->setFeatureId($event->getFeatureId())
;
}
if ($event->getIsTextValue() == true) {
$featureProduct->setFreeTextValue($event->getFeatureValue());
} else {
$featureProduct->setFeatureAvId($event->getFeatureValue());
}
$featureProduct->save();
$event->setFeatureProduct($featureProduct);
}
/**
* Delete a product feature value
*
* @param FeatureProductDeleteEvent $event
*/
public function deleteFeatureProductValue(FeatureProductDeleteEvent $event)
{
FeatureProductQuery::create()
->filterByProductId($event->getProductId())
->filterByFeatureId($event->getFeatureId())
->delete()
;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
TheliaEvents::PRODUCT_CREATE => array("create", 128),
TheliaEvents::PRODUCT_UPDATE => array("update", 128),
TheliaEvents::PRODUCT_DELETE => array("delete", 128),
TheliaEvents::PRODUCT_TOGGLE_VISIBILITY => array("toggleVisibility", 128),
TheliaEvents::PRODUCT_UPDATE_POSITION => array("updatePosition", 128),
TheliaEvents::PRODUCT_UPDATE_SEO => array("updateSeo", 128),
TheliaEvents::PRODUCT_ADD_CONTENT => array("addContent", 128),
TheliaEvents::PRODUCT_REMOVE_CONTENT => array("removeContent", 128),
TheliaEvents::PRODUCT_UPDATE_CONTENT_POSITION => array("updateContentPosition", 128),
TheliaEvents::PRODUCT_ADD_ACCESSORY => array("addAccessory", 128),
TheliaEvents::PRODUCT_REMOVE_ACCESSORY => array("removeAccessory", 128),
TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION => array("updateAccessoryPosition", 128),
TheliaEvents::PRODUCT_ADD_CATEGORY => array("addCategory", 128),
TheliaEvents::PRODUCT_REMOVE_CATEGORY => array("removeCategory", 128),
TheliaEvents::PRODUCT_SET_TEMPLATE => array("setProductTemplate", 128),
TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE => array("updateFeatureProductValue", 128),
TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE => array("deleteFeatureProductValue", 128),
);
}
}
|
lgpl-3.0
|
UniPixen/Niradrien
|
applications/product/controles/screenshots.php
|
585
|
<?php
_setView(__FILE__);
_setLayout("screenshots");
$memberID = get_id(2);
$productClass = new product();
$member = $productClass->get($memberID);
if ($member['status'] == 'deleted') {
header('Location: http://' . DOMAIN . '/product/' . $memberID);
}
if (!is_array($member) || (check_login_bool() && $member['status'] == 'unapproved' && $member['member_id'] != $_SESSION['member']['member_id']) || $member['status'] == 'queue' || $member['status'] == 'extended_buy') {
header('Location: http://' . DOMAIN . '/error');
}
abr('member', $member);
?>
|
lgpl-3.0
|
abeatte/angular_webpage
|
flapper-news/routes/index.js
|
2350
|
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res) {
res.render('index', { title: 'Express' });
});
module.exports = router;
var mongoose = require('mongoose');
var Post = mongoose.model('Post');
var Comment = mongoose.model('Comment');
/* GET posts */
router.get('/posts', function(req, res, next) {
Post.find(function(err, posts){
if(err){ return next(err); }
res.json(posts);
});
});
/* POST posts */
router.post('/posts', function(req, res, next) {
var post = new Post(req.body);
post.save(function(err, post){
if(err){ return next(err); }
res.json(post);
});
});
/* PARAM pre-load post */
router.param('post', function(req, res, next, id) {
var query = Post.findById(id);
query.exec(function (err, post){
if (err) { return next(err); }
if (!post) { return next(new Error("can't find post")); }
req.post = post;
return next();
});
});
/* GET post */
router.get('/posts/:post', function(req, res, next) {
req.post.populate('comments', function(err, post) {
res.json(post);
});
});
/* PUT upvote post */
router.put('/posts/:post/upvote', function(req, res, next) {
req.post.upvote(function(err, post){
if (err) { return next(err); }
res.json(post);
});
});
/* POST comment */
router.post('/posts/:post/comments', function(req, res, next) {
var comment = new Comment(req.body);
comment.post = req.post;
comment.save(function(err, comment){
if(err){ return next(err); }
req.post.comments.push(comment);
req.post.save(function(err, post) {
if(err){ return next(err); }
res.json(comment);
});
});
});
/* PUT upvote comment */
router.put('/posts/:post/comments/:comment/upvote', function(req, res, next) {
req.comment.upvote(function(err, post){
if (err) { return next(err); }
res.json(post);
});
});
/* PARAM pre-load comment */
router.param('comment', function(req, res, next, id) {
var query = Comment.findById(id);
query.exec(function (err, comment){
if (err) { return next(err); }
if (!comment) { return next(new Error("can't find comment")); }
req.comment = comment;
return next();
});
});
|
lgpl-3.0
|
skadyrov/CSipSimple
|
sipHome/src/main/java/com/csipsimple/api/ApiRequestReceiver.java
|
10359
|
package com.csipsimple.api;
/**
* Created by kadyrovs on 18.01.2016.
*/
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import com.csipsimple.db.DBProvider;
import com.csipsimple.ui.SipHome;
import com.csipsimple.ui.account.AccountsEditList;
import com.csipsimple.utils.PreferencesWrapper;
import com.csipsimple.utils.VersionUtil;
import com.csipsimple.wizards.WizardUtils;
import java.util.UUID;
import eu.miraculouslife.android.csipsimple.apilib.ApiConstants;
/**
* Receiver that listens to broadcast events for starting call UI
*/
public class ApiRequestReceiver extends BroadcastReceiver {
private final String TAG = ApiRequestReceiver.class.getSimpleName();
@Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "onReceive");
int requestType = intent.getIntExtra(ApiConstants.REQUEST_TYPE_INTENT_KEY, -1);
if (requestType == ApiConstants.REQUEST_TYPE_MAKE_CALL) {
Log.i(TAG, "received request for making call");
Intent serviceIntent = new Intent(Intent.ACTION_SYNC, null, context, MakeCallService.class);
serviceIntent.putExtras(intent);
context.startService(serviceIntent);
} else if (requestType == ApiConstants.REQUEST_TYPE_OPEN_SETTINGS_PAGE) {
Log.i(TAG, "received request for opening account settings page");
context.startActivity(new Intent(context, AccountsEditList.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
} else if (requestType == ApiConstants.REQUEST_TYPE_SEND_MESSAGE) {
Log.i(TAG, "received request for sending a message");
Intent serviceIntent = new Intent(Intent.ACTION_SYNC, null, context, SendMessageService.class);
serviceIntent.putExtras(intent);
context.startService(serviceIntent);
} else if (requestType == ApiConstants.REQUEST_TYPE_INSTALLATION_CHECK) {
Log.i(TAG, "received request for checking installation");
Intent intentInstallationResponse = new Intent(ApiConstants.API_RESPONSE_BROADCAST_ACTION);
intentInstallationResponse.putExtra(ApiConstants.API_RESPONSE_TYPE_INTENT_KEY, ApiConstants.API_RESPONSE_TYPE_INSTALLATION_CHECK);
context.sendBroadcast(intentInstallationResponse);
} else if (requestType == ApiConstants.REQUEST_TYPE_VERSION_REQUEST) {
try {
Log.i(TAG, "received request for checking version");
Intent intentVersion = new Intent(ApiConstants.API_RESPONSE_BROADCAST_ACTION);
intentVersion.putExtra(ApiConstants.API_RESPONSE_TYPE_INTENT_KEY, ApiConstants.API_RESPONSE_TYPE_CSIPSIMPLE_VERSION);
intentVersion.putExtra(ApiConstants.CSIPIMPLE_VERSION_INTENT_KEY, ApiConstants.APPNAME + ": " + VersionUtil.getVersionName(context));
context.sendBroadcast(intentVersion);
} catch (Exception e) {
Log.e(TAG, "An error occured while trying to send version information. " + e);
Intent intentVersion = new Intent(ApiConstants.API_RESPONSE_BROADCAST_ACTION);
intentVersion.putExtra(ApiConstants.API_RESPONSE_TYPE_INTENT_KEY, ApiConstants.API_RESPONSE_TYPE_CSIPSIMPLE_VERSION);
intentVersion.putExtra(ApiConstants.CSIPIMPLE_VERSION_INTENT_KEY, "An error occurred");
context.sendBroadcast(intentVersion);
}
} else if (requestType == ApiConstants.REQUEST_TYPE_UPDATE_REGISTRATION) {
Log.i(TAG, "received request for updating registration");
String displayName = intent.getStringExtra(ApiConstants.CONTACT_NUMBER_INTENT_KEY);
String userName = intent.getStringExtra(ApiConstants.CONTACT_NAME_INTENT_KEY);
String domain = intent.getStringExtra(ApiConstants.CONTACT_DOMAIN_INTENT_KEY);
String data = intent.getStringExtra(ApiConstants.CONTACT_PASS_INTENT_KEY);
if (TextUtils.isEmpty(displayName)) {
Log.e(TAG, "displayName empty!");
} else if (TextUtils.isEmpty(userName)) {
Log.e(TAG, "userName empty!");
}
updateAccountRegistration(context, displayName, userName, domain, data);
startSipService(context);
} else {
Log.e(TAG, "Unknown requestType: " + requestType + " . Make sure the request type is correct.");
}
}
private void updateAccountRegistration(Context context, String displayName, String userName, String domain, String data) {
Log.d(TAG, "updateAccountRegistration");
Log.d(TAG, "new number: " + displayName);
Log.d(TAG, "new name: " + userName);
Log.d(TAG, "new domain: " + domain);
Log.d(TAG, "new data: " + data);
// Get current account if any
Cursor c = context.getContentResolver().query(SipProfile.ACCOUNT_URI, new String[]{
SipProfile.FIELD_ID,
SipProfile.FIELD_ACC_ID,
SipProfile.FIELD_REG_URI
}, null, null, SipProfile.FIELD_PRIORITY + " ASC");
if (c != null) {
try {
if (c.moveToLast()) {
SipProfile foundProfile = new SipProfile(c);
Log.d(TAG, "found profile: " + foundProfile.toString());
SipProfile account = SipProfile.getProfileFromDbId(context, foundProfile.id, DBProvider.ACCOUNT_FULL_PROJECTION);
Log.d(TAG, "full account before change: " + account.toString());
updateAccount(context, buildFromAccount(account, userName, displayName, domain, data));
} else {
Log.w(TAG, "no existing account found, adding a new account");
SipProfile acc = SipProfile.getProfileFromDbId(context, SipProfile.INVALID_ID, DBProvider.ACCOUNT_FULL_PROJECTION);
addNewAccount(context, buildFromAccount(acc, userName, displayName, domain, data));
}
} catch (Exception e) {
Log.e(TAG, "Some problem occured while accessing cursor", e);
} finally {
c.close();
}
} else {
Log.w(TAG, "no existing account found, adding a new account");
SipProfile acc = SipProfile.getProfileFromDbId(context, SipProfile.INVALID_ID, DBProvider.ACCOUNT_FULL_PROJECTION);
addNewAccount(context, buildFromAccount(acc, userName, displayName, domain, data));
}
}
/**
* Apply default settings for a new account to check very basic coherence of settings and auto-modify settings missing
*
* @param account
*/
private void applyNewAccountDefault(SipProfile account) {
if (account.use_rfc5626) {
if (TextUtils.isEmpty(account.rfc5626_instance_id)) {
String autoInstanceId = (UUID.randomUUID()).toString();
account.rfc5626_instance_id = "<urn:uuid:" + autoInstanceId + ">";
}
}
}
/**
* This account does not exists yet
*/
private void addNewAccount(Context context, SipProfile account) {
Log.d(TAG, "addNewAccount");
PreferencesWrapper prefs = new PreferencesWrapper(context);
prefs.startEditing();
prefs.setPreferenceStringValue(SipConfigManager.DEFAULT_CALLER_ID, account.display_name);
prefs.endEditing();
applyNewAccountDefault(account);
Log.d(TAG, "account getDbContentValues: " + account.getDbContentValues());
Uri uri = context.getContentResolver().insert(SipProfile.ACCOUNT_URI, account.getDbContentValues());
Log.d(TAG, "uri after inserting new account: " + uri);
}
/**
* Updating an existing account
*
* @param context
* @param account
*/
private void updateAccount(Context context, SipProfile account) {
Log.d(TAG, "updateAccount");
PreferencesWrapper prefs = new PreferencesWrapper(context);
prefs.startEditing();
Log.d(TAG, "account display name:" + account.display_name);
prefs.setPreferenceStringValue(SipConfigManager.DEFAULT_CALLER_ID, account.display_name);
prefs.endEditing();
int rows = context.getContentResolver().update(ContentUris.withAppendedId(SipProfile.ACCOUNT_ID_URI_BASE, account.id), account.getDbContentValues(), null, null);
Log.d(TAG, "number of rows affected: " + rows);
}
public SipProfile buildFromAccount(SipProfile account, String displayname, String username, String domain, String data) {
Log.d(TAG, "buildFromAccount");
account.display_name = displayname;
username = username.trim();
domain = domain.trim();
String[] serverParts = domain.split(":");
account.acc_id = "<sip:" + SipUri.encodeUser(username) + "@" + serverParts[0].trim() + ">";
String regUri = "sip:" + domain;
account.reg_uri = regUri;
account.proxies = new String[]{regUri};
account.wizard = WizardUtils.BASIC_WIZARD_TAG;
account.realm = "*";
account.username = username;
com.csipsimple.utils.Log.d(TAG, "username: " + account.username);
account.data = data;
account.scheme = SipProfile.CRED_SCHEME_DIGEST;
account.datatype = SipProfile.CRED_DATA_PLAIN_PASSWD;
account.transport = SipProfile.TRANSPORT_UDP;
return account;
}
// Service monitoring stuff
private void startSipService(final Context context) {
Thread t = new Thread("StartSip") {
public void run() {
Intent serviceIntent = new Intent(SipManager.INTENT_SIP_SERVICE);
// Optional, but here we bundle so just ensure we are using csipsimple package
serviceIntent.setPackage(context.getPackageName());
serviceIntent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, new ComponentName(context, SipHome.class));
context.startService(serviceIntent);
//postStartSipService();
}
};
t.start();
}
}
|
lgpl-3.0
|
loftuxab/community-edition-old
|
projects/slingshot/source/web/components/search/search.js
|
35910
|
/**
* Copyright (C) 2005-2012 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Search component.
*
* @namespace Alfresco
* @class Alfresco.Search
*/
(function()
{
/**
* YUI Library aliases
*/
var Dom = YAHOO.util.Dom,
Event = YAHOO.util.Event;
/**
* Alfresco Slingshot aliases
*/
var $html = Alfresco.util.encodeHTML;
/**
* Search constructor.
*
* @param {String} htmlId The HTML id of the parent element
* @return {Alfresco.Search} The new Search instance
* @constructor
*/
Alfresco.Search = function(htmlId)
{
Alfresco.Search.superclass.constructor.call(this, "Alfresco.Search", htmlId, ["button", "container", "datasource", "datatable", "paginator", "json"]);
// Decoupled event listeners
YAHOO.Bubbling.on("onSearch", this.onSearch, this);
return this;
};
YAHOO.extend(Alfresco.Search, Alfresco.component.SearchBase,
{
/**
* Object container for initialization options
*
* @property options
* @type object
*/
options:
{
/**
* Current siteId
*
* @property siteId
* @type string
*/
siteId: "",
/**
* Current site title
*
* @property siteTitle
* @type string
*/
siteTitle: "",
/**
* Maximum number of results displayed.
*
* @property maxSearchResults
* @type int
* @default 250
*/
maxSearchResults: 250,
/**
* Results page size.
*
* @property pageSize
* @type int
* @default 50
*/
pageSize: 50,
/**
* Search term to use for the initial search
* @property initialSearchTerm
* @type string
* @default ""
*/
initialSearchTerm: "",
/**
* Search tag to use for the initial search
* @property initialSearchTag
* @type string
* @default ""
*/
initialSearchTag: "",
/**
* States whether all sites should be searched.
*
* @property initialSearchAllSites
* @type boolean
*/
initialSearchAllSites: true,
/**
* States whether repository should be searched.
* This is in preference to current or all sites.
*
* @property initialSearchRepository
* @type boolean
*/
initialSearchRepository: false,
/**
* Sort property to use for the initial search.
* Empty default value will use score relevance default.
* @property initialSort
* @type string
* @default ""
*/
initialSort: "",
/**
* Advanced Search query - forms data json format based search.
* @property searchQuery
* @type string
* @default ""
*/
searchQuery: "",
/**
* Search root node.
* @property searchRootNode
* @type string
* @default ""
*/
searchRootNode: "",
/**
* Number of characters required for a search.
*
* @property minSearchTermLength
* @type int
* @default 1
*/
minSearchTermLength: 1
},
/**
* Search term used for the last search.
*/
searchTerm: "",
/**
* Search tag used for the last search.
*/
searchTag: "",
/**
* Whether the search was over all sites or just the current one
*/
searchAllSites: true,
/**
* Whether the search is over the entire repository - in preference to site or all sites
*/
searchRepository: false,
/**
* Search sort used for the last search.
*/
searchSort: "",
/**
* Number of search results.
*/
resultsCount: 0,
/**
* Current visible page index - counts from 1
*/
currentPage: 1,
/**
* True if there are more results than the ones listed in the table.
*/
hasMoreResults: false,
/**
* Fired by YUI when parent element is available for scripting.
* Component initialisation, including instantiation of YUI widgets and event listener binding.
*
* @method onReady
*/
onReady: function Search_onReady()
{
var me = this;
// DataSource definition
var uriSearchResults = Alfresco.constants.PROXY_URI_RELATIVE + "slingshot/search?";
this.widgets.dataSource = new YAHOO.util.DataSource(uriSearchResults,
{
responseType: YAHOO.util.DataSource.TYPE_JSON,
connXhrMode: "queueRequests",
responseSchema:
{
resultsList: "items",
metaFields:
{
paginationRecordOffset: "startIndex",
totalRecords: "totalRecords",
totalRecordsUpper: "totalRecordsUpper"
}
}
});
// YUI Paginator definition
var handlePagination = function Search_handlePagination(state, me)
{
me.currentPage = state.page;
me.widgets.paginator.setState(state);
// run the search with page settings
me._performSearch(
{
searchTerm: me.searchTerm,
searchTag: me.searchTag,
searchAllSites: me.searchAllSites,
searchRepository: me.searchRepository,
searchSort: me.searchSort,
page: me.currentPage
});
};
this.widgets.paginator = new YAHOO.widget.Paginator(
{
containers: [this.id + "-paginator-top", this.id + "-paginator-bottom"],
rowsPerPage: this.options.pageSize,
initialPage: 1,
template: this.msg("pagination.template"),
pageReportTemplate: this.msg("pagination.template.page-report"),
previousPageLinkLabel: this.msg("pagination.previousPageLinkLabel"),
nextPageLinkLabel: this.msg("pagination.nextPageLinkLabel")
});
this.widgets.paginator.subscribe("changeRequest", handlePagination, this);
// setup of the datatable.
this._setupDataTable();
// set initial value and register the "enter" event on the search text field
var queryInput = Dom.get(this.id + "-search-text");
queryInput.value = this.options.initialSearchTerm;
this.widgets.enterListener = new YAHOO.util.KeyListener(queryInput,
{
keys: YAHOO.util.KeyListener.KEY.ENTER
},
{
fn: me._searchEnterHandler,
scope: this,
correctScope: true
}, "keydown");
this.widgets.enterListener.enable();
// trigger the initial search
YAHOO.Bubbling.fire("onSearch",
{
searchTerm: this.options.initialSearchTerm,
searchTag: this.options.initialSearchTag,
searchSort: this.options.initialSort,
searchAllSites: this.options.initialSearchAllSites,
searchRepository: this.options.initialSearchRepository
});
// search YUI button
this.widgets.searchButton = Alfresco.util.createYUIButton(this, "search-button", this.onSearchClick);
this._disableItems();
// menu button for sort options
this.widgets.sortButton = new YAHOO.widget.Button(this.id + "-sort-menubutton",
{
type: "menu",
menu: this.id + "-sort-menu",
menualignment: ["tr", "br"],
lazyloadmenu: false
});
// set initially selected sort button label
var menuItems = this.widgets.sortButton.getMenu().getItems();
for (var m in menuItems)
{
if (menuItems[m].value === this.options.initialSort)
{
this.widgets.sortButton.set("label", this.msg("label.sortby", menuItems[m].cfg.getProperty("text")));
break;
}
}
// event handler for sort menu
this.widgets.sortButton.getMenu().subscribe("click", function(p_sType, p_aArgs)
{
var menuItem = p_aArgs[1];
if (menuItem)
{
me.refreshSearch(
{
searchSort: menuItem.value
});
}
});
// Hook action events
var fnActionHandler = function Search_fnActionHandler(layer, args)
{
var owner = YAHOO.Bubbling.getOwnerByTagName(args[1].anchor, "span");
if (owner !== null)
{
if (typeof me[owner.className] == "function")
{
args[1].stop = true;
var tagId = owner.id.substring(me.id.length + 1);
me[owner.className].call(me, tagId);
}
}
return true;
};
YAHOO.Bubbling.addDefaultAction("search-tag", fnActionHandler);
// Finally show the component body here to prevent UI artifacts on YUI button decoration
Dom.setStyle(this.id + "-body", "visibility", "visible");
},
_setupDataTable: function Search_setupDataTable()
{
/**
* DataTable Cell Renderers
*
* Each cell has a custom renderer defined as a custom function. See YUI documentation for details.
* These MUST be inline in order to have access to the Alfresco.Search class (via the "me" variable).
*/
var me = this;
/**
* Thumbnail custom datacell formatter
*
* @method renderCellThumbnail
* @param elCell {object}
* @param oRecord {object}
* @param oColumn {object}
* @param oData {object|string}
*/
renderCellThumbnail = function Search_renderCellThumbnail(elCell, oRecord, oColumn, oData)
{
oColumn.width = 100;
Dom.setStyle(elCell.parentNode, "width", oColumn.width + "px");
Dom.setStyle(elCell.parentNode, "background-color", "#f4f4f4");
Dom.addClass(elCell, "thumbnail-cell");
if (oRecord.getData("type") === "document")
{
Dom.addClass(elCell, "thumbnail");
}
elCell.innerHTML = me.buildThumbnailHtml(oRecord);
};
/**
* Description/detail custom cell formatter
*
* @method renderCellDescription
* @param elCell {object}
* @param oRecord {object}
* @param oColumn {object}
* @param oData {object|string}
*/
renderCellDescription = function Search_renderCellDescription(elCell, oRecord, oColumn, oData)
{
// apply class to the appropriate TD cell
Dom.addClass(elCell.parentNode, "description");
// site and repository items render with different information available
var site = oRecord.getData("site");
var url = me._getBrowseUrlForRecord(oRecord);
// displayname and link to details page
var displayName = oRecord.getData("displayName");
var desc = '<h3 class="itemname"><a href="' + url + '" class="theme-color-1">' + $html(displayName) + '</a>';
// add title (if any) to displayname area
var title = oRecord.getData("title");
if (title && title !== displayName)
{
desc += '<span class="title">(' + $html(title) + ')</span>';
}
desc += '</h3>';
// description (if any)
var txt = oRecord.getData("description");
if (txt)
{
desc += '<div class="details meta">' + $html(txt) + '</div>';
}
// detailed information, includes site etc. type specific
desc += '<div class="details">';
var type = oRecord.getData("type");
desc += me.buildTextForType(type);
// link to the site and other meta-data details
if (site)
{
desc += ' ' + me.msg("message.insite");
desc += ' <a href="' + Alfresco.constants.URL_PAGECONTEXT + 'site/' + $html(site.shortName) + '/dashboard">' + $html(site.title) + '</a>';
}
if (oRecord.getData("size") !== -1)
{
desc += ' ' + me.msg("message.ofsize");
desc += ' <span class="meta">' + Alfresco.util.formatFileSize(oRecord.getData("size")) + '</span>';
}
if (oRecord.getData("modifiedBy"))
{
desc += ' ' + me.msg("message.modifiedby");
desc += ' <a href="' + Alfresco.constants.URL_PAGECONTEXT + 'user/' + encodeURI(oRecord.getData("modifiedByUser")) + '/profile">' + $html(oRecord.getData("modifiedBy")) + '</a>';
}
desc += ' ' + me.msg("message.modifiedon") + ' <span class="meta">' + Alfresco.util.formatDate(oRecord.getData("modifiedOn")) + '</span>';
desc += '</div>';
// folder path (if any)
var path = oRecord.getData("path");
desc += me.buildPath(type, path, site);
// tags (if any)
var tags = oRecord.getData("tags");
if (tags.length !== 0)
{
var i, j;
desc += '<div class="details"><span class="tags">';
for (i = 0, j = tags.length; i < j; i++)
{
desc += '<span id="' + me.id + '-' + $html(tags[i]) + '" class="searchByTag"><a class="search-tag" href="#">' + $html(tags[i]) + '</a> </span>';
}
desc += '</span></div>';
}
elCell.innerHTML = desc;
};
// DataTable column defintions
var columnDefinitions = [
{
key: "image", label: me.msg("message.preview"), sortable: false, formatter: renderCellThumbnail, width: 100
},
{
key: "summary", label: me.msg("label.description"), sortable: false, formatter: renderCellDescription
}];
// DataTable definition
this.widgets.dataTable = new YAHOO.widget.DataTable(this.id + "-results", columnDefinitions, this.widgets.dataSource,
{
renderLoopSize: Alfresco.util.RENDERLOOPSIZE,
initialLoad: false,
paginator: this.widgets.paginator,
MSG_LOADING: ""
});
// show initial message
this._setDefaultDataTableErrors(this.widgets.dataTable);
if (this.options.initialSearchTerm.length === 0 && this.options.initialSearchTag.length === 0)
{
this.widgets.dataTable.set("MSG_EMPTY", "");
}
// Override abstract function within DataTable to set custom error message
this.widgets.dataTable.doBeforeLoadData = function Search_doBeforeLoadData(sRequest, oResponse, oPayload)
{
if (oResponse.error)
{
try
{
var response = YAHOO.lang.JSON.parse(oResponse.responseText);
me.widgets.dataTable.set("MSG_ERROR", response.message);
}
catch(e)
{
me._setDefaultDataTableErrors(me.widgets.dataTable);
}
}
else if (oResponse.results)
{
// clear the empty error message
me.widgets.dataTable.set("MSG_EMPTY", "");
// display help text if no results were found
if (oResponse.results.length === 0)
{
Dom.removeClass(me.id + "-help", "hidden");
}
}
// Must return true to have the "Loading..." message replaced by the error message
return true;
};
// Update totalRecords on the fly with value from server
me.widgets.dataTable.handleDataReturnPayload = function handleDataReturnPayload(oRequest, oResponse, oPayload)
{
me.resultsCount = oResponse.meta.totalRecordsUpper;
// update the results count, update hasMoreResults.
if (me.hasMoreResults = (me.resultsCount > me.options.maxSearchResults))
{
// user just needs to know there are "more" not exactly how many were in server-side resultset
me.resultsCount = me.options.maxSearchResults;
}
// show the pagination controls as needed
if (me.resultsCount > me.options.pageSize)
{
Dom.removeClass(me.id + "-paginator-top", "hidden");
Dom.removeClass(me.id + "-search-bar-bottom", "hidden");
}
return oResponse.meta;
};
// Rendering complete event handler
me.widgets.dataTable.subscribe("renderEvent", function()
{
// Update the paginator
me.widgets.paginator.setState(
{
page: me.currentPage,
totalRecords: me.resultsCount
});
me.widgets.paginator.render();
});
},
/**
* Constructs the completed browse url for a record.
* @param record {string} the record
*/
_getBrowseUrlForRecord: function Search__getBrowseUrlForRecord(record)
{
return this.getBrowseUrlForRecord(record);
},
/**
* Constructs the folder url for a record.
* @param path {string} folder path
* For a site relative item this can be empty (root of doclib) or any path - without a leading slash
* For a repository item, this can never be empty - but will contain leading slash and Company Home root
*/
_getBrowseUrlForFolderPath: function Search__getBrowseUrlForFolderPath(path, site)
{
return this.getBrowseUrlForFolderPath(path, site);
},
_buildSpaceNamePath: function Search__buildSpaceNamePath(pathParts, name)
{
return this.buildSpaceNamePath(pathParts, name);
},
/**
* DEFAULT ACTION EVENT HANDLERS
* Handlers for standard events fired from YUI widgets, e.g. "click"
*/
/**
* Perform a search for a given tag
* The tag is simply handled as search term
*/
searchByTag: function Search_searchTag(param)
{
this.refreshSearch(
{
searchTag: param,
searchTerm: "",
searchQuery: ""
});
},
/**
* Refresh the search page by full URL refresh
*
* @method refreshSearch
* @param args {object} search args
*/
refreshSearch: function Search_refreshSearch(args)
{
var searchTerm = this.searchTerm;
if (args.searchTerm !== undefined)
{
searchTerm = args.searchTerm;
}
var searchTag = this.searchTag;
if (args.searchTag !== undefined)
{
searchTag = args.searchTag;
}
var searchAllSites = this.searchAllSites;
if (args.searchAllSites !== undefined)
{
searchAllSites = args.searchAllSites;
}
var searchRepository = this.searchRepository;
if (args.searchRepository !== undefined)
{
searchRepository = args.searchRepository;
}
var searchSort = this.searchSort;
if (args.searchSort !== undefined)
{
searchSort = args.searchSort;
}
var searchQuery = this.options.searchQuery;
if (args.searchQuery !== undefined)
{
searchQuery = args.searchQuery;
}
// redirect back to the search page - with appropriate site context
var url = Alfresco.constants.URL_PAGECONTEXT;
if (this.options.siteId.length !== 0)
{
url += "site/" + this.options.siteId + "/";
}
// add search data webscript arguments
url += "search?t=" + encodeURIComponent(searchTerm);
url += "&s=" + searchSort;
if (searchQuery.length !== 0)
{
// if we have a query (already encoded), then apply it
// most other options such as tag, terms are trumped
url += "&q=" + searchQuery;
}
else if (searchTag.length !== 0)
{
url += "&tag=" + encodeURIComponent(searchTag);
}
url += "&a=" + searchAllSites + "&r=" + searchRepository;
window.location = url;
},
/**
* BUBBLING LIBRARY EVENT HANDLERS FOR PAGE EVENTS
* Disconnected event handlers for inter-component event notification
*/
/**
* Execute Search event handler
*
* @method onSearch
* @param layer {object} Event fired
* @param args {array} Event parameters (depends on event type)
*/
onSearch: function Search_onSearch(layer, args)
{
var obj = args[1];
if (obj !== null)
{
var searchTerm = this.searchTerm;
if (obj.searchTerm !== undefined)
{
searchTerm = obj.searchTerm;
}
var searchTag = this.searchTag;
if (obj.searchTag !== undefined)
{
searchTag = obj.searchTag;
}
var searchAllSites = this.searchAllSites;
if (obj.searchAllSites !== undefined)
{
searchAllSites = obj.searchAllSites;
}
var searchRepository = this.searchRepository;
if (obj.searchRepository !== undefined)
{
searchRepository = obj.searchRepository;
}
var searchSort = this.searchSort;
if (obj.searchSort !== undefined)
{
searchSort = obj.searchSort;
}
this._performSearch(
{
searchTerm: searchTerm,
searchTag: searchTag,
searchAllSites: searchAllSites,
searchRepository: searchRepository,
searchSort: searchSort
});
}
},
/**
* Event handler that gets fired when user clicks the Search button.
*
* @method onSearchClick
* @param e {object} DomEvent
* @param obj {object} Object passed back from addListener method
*/
onSearchClick: function Search_onSearchClick(e, obj)
{
this.refreshSearch(
{
searchTag: "",
searchTerm: YAHOO.lang.trim(Dom.get(this.id + "-search-text").value),
searchQuery: ""
});
},
/**
* Click event for Current Site search link
*
* @method onSiteSearch
*/
onSiteSearch: function Search_onSiteSearch(e, args)
{
this.refreshSearch(
{
searchAllSites: false,
searchRepository: false
});
},
/**
* Click event for All Sites search link
*
* @method onAllSiteSearch
*/
onAllSiteSearch: function Search_onAllSiteSearch(e, args)
{
this.refreshSearch(
{
searchAllSites: true,
searchRepository: false
});
},
/**
* Click event for Repository search link
*
* @method onRepositorySearch
*/
onRepositorySearch: function Search_onRepositorySearch(e, args)
{
this.refreshSearch(
{
searchRepository: true
});
},
/**
* Search text box ENTER key event handler
*
* @method _searchEnterHandler
*/
_searchEnterHandler: function Search__searchEnterHandler(e, args)
{
this.refreshSearch(
{
searchTag: "",
searchTerm: YAHOO.lang.trim(Dom.get(this.id + "-search-text").value),
searchQuery: ""
});
},
/**
* Updates search results list by calling data webscript with current site and query term
*
* @method _performSearch
* @param args {object} search args
*/
_performSearch: function Search__performSearch(args)
{
var searchTerm = YAHOO.lang.trim(args.searchTerm),
searchTag = YAHOO.lang.trim(args.searchTag),
searchAllSites = args.searchAllSites,
searchRepository = args.searchRepository,
searchSort = args.searchSort,
page = args.page || 1;
if (this.options.searchQuery.length === 0 &&
searchTag.length === 0 &&
searchTerm.replace(/\*/g, "").length < this.options.minSearchTermLength)
{
Alfresco.util.PopupManager.displayMessage(
{
text: this.msg("message.minimum-length", this.options.minSearchTermLength)
});
this._enableItems();
return;
}
// empty results table
this.widgets.dataTable.deleteRows(0, this.widgets.dataTable.getRecordSet().getLength());
// hide paginator controls
Dom.addClass(this.id + "-paginator-top", "hidden");
Dom.addClass(this.id + "-search-bar-bottom", "hidden");
// update the ui to show that a search is on-going
Dom.get(this.id + '-search-info').innerHTML = this.msg("search.info.searching");
this.widgets.dataTable.set("MSG_EMPTY", "");
this.widgets.dataTable.render();
// Success handler
function successHandler(sRequest, oResponse, oPayload)
{
// update current state on success
this.searchTerm = searchTerm;
this.searchTag = searchTag;
this.searchAllSites = searchAllSites;
this.searchRepository = searchRepository;
this.searchSort = searchSort;
this.widgets.dataTable.onDataReturnInitializeTable.call(this.widgets.dataTable, sRequest, oResponse, oPayload);
// update the results info text
this._updateResultsInfo();
// set focus to search input textbox
Dom.get(this.id + "-search-text").focus();
this._enableItems();
}
// Failure handler
function failureHandler(sRequest, oResponse)
{
switch (oResponse.status)
{
case 401:
// Session has likely timed-out, so refresh to display login page
window.location.reload();
break;
case 408:
// Timeout waiting on Alfresco server - probably due to heavy load
Dom.get(this.id + '-search-info').innerHTML = this.msg("message.timeout");
break;
default:
// General server error code
if (oResponse.responseText)
{
var response = YAHOO.lang.JSON.parse(oResponse.responseText);
Dom.get(this.id + '-search-info').innerHTML = response.message;
}
else
{
Dom.get(this.id + '-search-info').innerHTML = oResponse.statusText;
}
break;
}
this._enableItems();
}
this.widgets.dataSource.sendRequest(this._buildSearchParams(
searchRepository, searchAllSites, searchTerm, searchTag, searchSort, page),
{
success: successHandler,
failure: failureHandler,
scope: this
});
},
/**
* Disables Search button and links
*
* @method _disableItems
*/
_disableItems: function Search__disableItems()
{
// disables "All Sites" link
var toggleLink = Dom.get(this.id + "-all-sites-link");
if (toggleLink)
{
Event.removeListener(toggleLink, "click");
toggleLink.style.color="#aaa";
}
// disables "Repository" link
toggleLink = Dom.get(this.id + "-repo-link");
if (toggleLink)
{
Event.removeListener(toggleLink, "click");
toggleLink.style.color="#aaa";
}
//disables Site link
toggleLink = Dom.get(this.id + "-site-link");
if (toggleLink)
{
Event.removeListener(toggleLink, "click");
toggleLink.style.color="#aaa";
}
// disables Search button
this.widgets.searchButton.set("disabled", true);
// disables KeyListener (Enter)
if (this.widgets.enterListener)
{
this.widgets.enterListener.disable();
}
},
/**
* Enables Search button and links
*
* @method _enableItems
*/
_enableItems: function Search__enableItems()
{
// enables "All Sites" link
var toggleLink = Dom.get(this.id + "-all-sites-link");
if (toggleLink)
{
Event.addListener(toggleLink, "click", this.onAllSiteSearch, this, true);
toggleLink.style.color="";
}
// enables "Repository" link
toggleLink = Dom.get(this.id + "-repo-link");
if (toggleLink)
{
Event.addListener(toggleLink, "click", this.onRepositorySearch, this, true);
toggleLink.style.color="";
}
// enables "Site" link
toggleLink = Dom.get(this.id + "-site-link");
if (toggleLink)
{
Event.addListener(toggleLink, "click", this.onSiteSearch, this, true);
toggleLink.style.color="";
}
// enables Search button
this.widgets.searchButton.set("disabled", false);
// enables KeyListener (Enter)
if (this.widgets.enterListener)
{
this.widgets.enterListener.enable();
}
},
/**
* Updates the results info text.
*
* @method _updateResultsInfo
*/
_updateResultsInfo: function Search__updateResultsInfo()
{
// update the search results field
var text;
var resultsCount = "" + this.resultsCount;
if (this.hasMoreResults)
{
text = this.msg("search.info.resultinfomore", resultsCount);
}
else
{
text = this.msg("search.info.resultinfo", resultsCount);
}
// apply the context
if (this.searchRepository || this.options.searchQuery.length !== 0)
{
text += ' ' + this.msg("search.info.foundinrepository");
}
else if (this.searchAllSites)
{
text += ' ' + this.msg("search.info.foundinallsite");
}
else
{
text += ' ' + this.msg("search.info.foundinsite", $html(this.options.siteTitle));
}
// set the text
Dom.get(this.id + '-search-info').innerHTML = text;
},
/**
* Build URI parameter string for search JSON data webscript
*
* @method _buildSearchParams
*/
_buildSearchParams: function Search__buildSearchParams(searchRepository, searchAllSites, searchTerm, searchTag, searchSort, page)
{
var site = searchAllSites ? "" : this.options.siteId;
var params = YAHOO.lang.substitute("site={site}&term={term}&tag={tag}&maxResults={maxResults}&sort={sort}&query={query}&repo={repo}&rootNode={rootNode}&pageSize={pageSize}&startIndex={startIndex}",
{
site: encodeURIComponent(site),
repo: searchRepository.toString(),
term: encodeURIComponent(searchTerm),
tag: encodeURIComponent(searchTag),
sort: encodeURIComponent(searchSort),
query: encodeURIComponent(this.options.searchQuery),
rootNode: encodeURIComponent(this.options.searchRootNode),
maxResults: this.options.maxSearchResults + 1, // to calculate whether more results were available
pageSize: this.options.pageSize,
startIndex: (page - 1) * this.options.pageSize
});
return params;
},
/**
* Resets the YUI DataTable errors to our custom messages
* NOTE: Scope could be YAHOO.widget.DataTable, so can't use "this"
*
* @method _setDefaultDataTableErrors
* @param dataTable {object} Instance of the DataTable
*/
_setDefaultDataTableErrors: function Search__setDefaultDataTableErrors(dataTable)
{
var msg = Alfresco.util.message;
dataTable.set("MSG_EMPTY", msg("message.empty", "Alfresco.Search"));
dataTable.set("MSG_ERROR", msg("message.error", "Alfresco.Search"));
}
});
})();
|
lgpl-3.0
|
tepperly/MixDown
|
test/test_project.py
|
56933
|
# Copyright (c) 2010-2012, Lawrence Livermore National Security, LLC
# Produced at Lawrence Livermore National Laboratory
# LLNL-CODE-462894
# All rights reserved.
#
# This file is part of MixDown. Please read the COPYRIGHT file
# for Our Notice and the LICENSE file for the GNU Lesser General Public
# License.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License (as published by
# the Free Software Foundation) version 3 dated June 2007.
#
# 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 terms and
# conditions of the GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import os, sys, textwrap, unittest, mdTestUtilities
if not ".." in sys.path:
sys.path.append("..")
from md import defines, logger, options, project, utilityFunctions
class Test_project(unittest.TestCase):
def test_readSingleTargetProject(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
PreConfig: autoreconf -i
Config: ./configure --prefix=$(_prefix)
Build: make
Install: make install
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
self.assertTrue(myProject.read(), "Project file could not be read")
#Project
self.assertEqual(myProject.name, os.path.split(projectFilePath)[1][:-3], "Project returned wrong name")
self.assertEqual(myProject.path, projectFilePath, "Project returned wrong path")
#Target a
self.assertEqual(myProject.targets[0].name, "a", "Project returned wrong target 'a' name")
self.assertEqual(myProject.targets[0].path, "a-1.11.tar.gz", "Project returned wrong target 'a' path")
self.assertEqual(myProject.targets[0].findBuildStep("preconfig").command, "autoreconf -i", "Project returned wrong target 'a' preconfig command")
self.assertEqual(myProject.targets[0].findBuildStep("config").command, "./configure --prefix=$(_prefix)", "Project returned wrong target 'a' config command")
self.assertEqual(myProject.targets[0].findBuildStep("build").command, "make", "Project returned wrong target 'a' build command")
self.assertEqual(myProject.targets[0].findBuildStep("install").command, "make install", "Project returned wrong target 'a' install command")
finally:
utilityFunctions.removeDir(tempDir)
def test_readDetectDuplicateTarget(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
Name: a
Path: a-1.11.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
self.assertFalse(myProject.read(), "Project read should have detected duplicate target")
finally:
utilityFunctions.removeDir(tempDir)
def test_readMultiTargetProject(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c
PreConfig: autoreconf -i
Config: ./configure --prefix=$(_prefix) --with-b=$(_prefix) --with-c=$(_prefix)
Build: make
Install: make install
Name: b
Path: b-2.22.tar.gz
DependsOn: c
PreConfig: bautoreconf -i
Config: ./configure --prefix=$(_prefix) --with-c=$(_prefix)
Build: bmake
Install: bmake install
Name: c
Path: c-3.33.tar.gz
PreConfig: cautoreconf -i
Config: ./configure --prefix=$(_prefix)
Build: cmake
Install: cmake install
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
self.assertTrue(myProject.read(), "Project file could not be read")
#Project
self.assertEqual(myProject.name, os.path.split(projectFilePath)[1][:-3], "Project returned wrong name")
self.assertEqual(myProject.path, projectFilePath, "Project returned wrong path")
#Target a
self.assertEqual(myProject.targets[0].name, "a", "Project returned wrong target 'a' name")
self.assertEqual(myProject.targets[0].path, "a-1.11.tar.gz", "Project returned wrong target 'a' path")
self.assertEqual(myProject.targets[0].dependsOn, ['b', 'c'], "Project returned wrong target 'a' dependsOn")
self.assertEqual(myProject.targets[0].findBuildStep("preconfig").command, "autoreconf -i", "Project returned wrong target 'a' preconfig command")
self.assertEqual(myProject.targets[0].findBuildStep("config").command, "./configure --prefix=$(_prefix) --with-b=$(_prefix) --with-c=$(_prefix)", "Project returned wrong target 'a' config command")
self.assertEqual(myProject.targets[0].findBuildStep("build").command, "make", "Project returned wrong target build 'a' command")
self.assertEqual(myProject.targets[0].findBuildStep("install").command, "make install", "Project returned wrong target install 'a' command")
#Target b
self.assertEqual(myProject.targets[1].name, "b", "Project returned wrong target 'b' name")
self.assertEqual(myProject.targets[1].path, "b-2.22.tar.gz", "Project returned wrong target 'b' path")
self.assertEqual(myProject.targets[1].dependsOn, ['c'], "Project returned wrong target 'b' dependsOn")
self.assertEqual(myProject.targets[1].findBuildStep("preconfig").command, "bautoreconf -i", "Project returned wrong target 'b' preconfig command")
self.assertEqual(myProject.targets[1].findBuildStep("config").command, "./configure --prefix=$(_prefix) --with-c=$(_prefix)", "Project returned wrong target 'b' config command")
self.assertEqual(myProject.targets[1].findBuildStep("build").command, "bmake", "Project returned wrong target 'b' build command")
self.assertEqual(myProject.targets[1].findBuildStep("install").command, "bmake install", "Project returned wrong target 'b' install command")
#Target c
self.assertEqual(myProject.targets[2].name, "c", "Project returned wrong target 'c' name")
self.assertEqual(myProject.targets[2].path, "c-3.33.tar.gz", "Project returned wrong target 'c' path")
self.assertEqual(myProject.targets[2].findBuildStep("preconfig").command, "cautoreconf -i", "Project returned wrong target 'c' preconfig command")
self.assertEqual(myProject.targets[2].findBuildStep("config").command, "./configure --prefix=$(_prefix)", "Project returned wrong target 'c' config command")
self.assertEqual(myProject.targets[2].findBuildStep("build").command, "cmake", "Project returned wrong target 'c' build command")
self.assertEqual(myProject.targets[2].findBuildStep("install").command, "cmake install", "Project returned wrong target 'c' install command")
finally:
utilityFunctions.removeDir(tempDir)
def test_readWriteMultiTargetProject(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c
PreConfig: autoreconf -i
Config: ./configure --prefix=$(_prefix) --with-b=$(_prefix) --with-c=$(_prefix)
Build: make
Install: make install
Name: b
Path: b-2.22.tar.gz
DependsOn: c
PreConfig: bautoreconf -i
Config: ./configure --prefix=$(_prefix) --with-c=$(_prefix)
Build: bmake
Install: bmake install
Name: c
Path: c-3.33.tar.gz
PreConfig: cautoreconf -i
Config: ./configure --prefix=$(_prefix)
Build: cmake
Install: cmake install
""")
try:
#Read initial values
tempDir = mdTestUtilities.makeTempDir()
projectOrigFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
projectOrig = project.Project(projectOrigFilePath)
self.assertTrue(projectOrig.read(), "Initial project file could not be read")
#Write values to new file
projectFilePath = mdTestUtilities.makeTempFile(tempDir, suffix=".md")
projectOrig.write(projectFilePath)
#Read values from written file and test to make sure they are correct
myProject = project.Project(projectFilePath)
self.assertTrue(myProject.read(), "Project file could not be read")
#Project
self.assertEqual(myProject.name, os.path.split(projectFilePath)[1][:-3], "Project returned wrong name")
self.assertEqual(myProject.path, projectFilePath, "Project returned wrong path")
#Target a
self.assertEqual(myProject.targets[0].name, "a", "Project returned wrong target 'a' name")
self.assertEqual(myProject.targets[0].path, "a-1.11.tar.gz", "Project returned wrong target 'a' path")
self.assertEqual(myProject.targets[0].dependsOn, ['b', 'c'], "Project returned wrong target 'a' dependsOn")
self.assertEqual(myProject.targets[0].findBuildStep("preconfig").command, "autoreconf -i", "Project returned wrong target 'a' preconfig command")
self.assertEqual(myProject.targets[0].findBuildStep("config").command, "./configure --prefix=$(_prefix) --with-b=$(_prefix) --with-c=$(_prefix)", "Project returned wrong target 'a' config command")
self.assertEqual(myProject.targets[0].findBuildStep("build").command, "make", "Project returned wrong target build 'a' command")
self.assertEqual(myProject.targets[0].findBuildStep("install").command, "make install", "Project returned wrong target install 'a' command")
#Target b
self.assertEqual(myProject.targets[1].name, "b", "Project returned wrong target 'b' name")
self.assertEqual(myProject.targets[1].path, "b-2.22.tar.gz", "Project returned wrong target 'b' path")
self.assertEqual(myProject.targets[1].dependsOn, ['c'], "Project returned wrong target 'b' dependsOn")
self.assertEqual(myProject.targets[1].findBuildStep("preconfig").command, "bautoreconf -i", "Project returned wrong target 'b' preconfig command")
self.assertEqual(myProject.targets[1].findBuildStep("config").command, "./configure --prefix=$(_prefix) --with-c=$(_prefix)", "Project returned wrong target 'b' config command")
self.assertEqual(myProject.targets[1].findBuildStep("build").command, "bmake", "Project returned wrong target 'b' build command")
self.assertEqual(myProject.targets[1].findBuildStep("install").command, "bmake install", "Project returned wrong target 'b' install command")
#Target c
self.assertEqual(myProject.targets[2].name, "c", "Project returned wrong target 'c' name")
self.assertEqual(myProject.targets[2].path, "c-3.33.tar.gz", "Project returned wrong target 'c' path")
self.assertEqual(myProject.targets[2].findBuildStep("preconfig").command, "cautoreconf -i", "Project returned wrong target 'c' preconfig command")
self.assertEqual(myProject.targets[2].findBuildStep("config").command, "./configure --prefix=$(_prefix)", "Project returned wrong target 'c' config command")
self.assertEqual(myProject.targets[2].findBuildStep("build").command, "cmake", "Project returned wrong target 'c' build command")
self.assertEqual(myProject.targets[2].findBuildStep("install").command, "cmake install", "Project returned wrong target 'c' install command")
finally:
utilityFunctions.removeDir(tempDir)
def test_readProjectInvalidDependsCase1(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b c
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertEquals(myProject.read(), False, "Project file read should have failed")
finally:
utilityFunctions.removeDir(tempDir)
def test_readProjectInvalidDependsCase2(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b{c
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertEquals(myProject.read(), False, "Project file read should have failed")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateSingleTargetProjectWithSteps(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
PreConfig: autoreconf -i
Config: ./configure --prefix=$(_prefix)
Build: make
Install: make install
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
defines.setPrefixDefines(option.defines, os.path.abspath(os.path.join(tempDir, "prefix")))
option.prefixDefined = True
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateMultiTargetProjectWithStepsAndDependencies(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
PreConfig: autoreconf -i
Config: ./configure --prefix=$(_prefix) --with-b=$(_prefix) --with-c=$(_prefix)
Build: make
Install: make install
Name: b
Path: b-2.22.tar.gz
DependsOn: c
PreConfig: bautoreconf -i
Config: ./configure --prefix=$(_prefix) --with-c=$(_prefix)
Build: bmake
Install: bmake install
Name: c
Path: c-3.33.tar.gz
PreConfig: cautoreconf -i
Config: ./configure --prefix=$(_prefix)
Build: cmake
Install: cmake install
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
defines.setPrefixDefines(option.defines, os.path.abspath(os.path.join(tempDir, "prefix")))
option.prefixDefined = True
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateSingleTargetProjectWithoutSteps(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateMultiTargetProjectWithoutStepsOrDependencies(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
Name: b
Path: b-2.22.tar.gz
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateNonCyclicalProjectCase1(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateNonCyclicalProjectCase2(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c
Name: b
Path: b-2.22.tar.gz
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateNonCyclicalProjectCase3(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
Name: b
Path: b-2.22.tar.gz
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateNonCyclicalProjectCase4(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: c, b
Name: b
Path: b-2.22.tar.gz
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateNonCyclicalProjectCase5(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
Name: b
Path: b-2.22.tar.gz
DependsOn: a
Name: c
Path: c-3.33.tar.gz
DependsOn: b
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_validateNonCyclicalProjectCase6(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.validate(option), "Project could not validate")
finally:
utilityFunctions.removeDir(tempDir)
def test_detectCyclicalProjectCase1(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
DependsOn: a
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertFalse(myProject.validate(option), "Project validated when it should not have due to cyclical dependency graph")
finally:
utilityFunctions.removeDir(tempDir)
def test_detectCyclicalProjectCase2(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
DependsOn: b
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertFalse(myProject.validate(option), "Project validated when it should not have due to cyclical dependency graph")
finally:
utilityFunctions.removeDir(tempDir)
def test_detectCyclicalProjectCase3(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: a
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
self.assertFalse(myProject.read(), "Reading project file should have failed")
finally:
utilityFunctions.removeDir(tempDir)
def test_detectCyclicalProjectCase4(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
DependsOn: c
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
self.assertFalse(myProject.read(), "Reading project file should have failed")
finally:
utilityFunctions.removeDir(tempDir)
def test_detectProjectWithNonExistantDependency(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertFalse(myProject.validate(option), "Project validated when it should not have due to non-existant dependency")
finally:
utilityFunctions.removeDir(tempDir)
def test_getTarget(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
Name: b
Path: b-2.22.tar.gz
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
self.assertTrue(myProject.read(), "Project file could not be read")
#Targets that exist in project
self.assertNotEquals(myProject.getTarget("a"), None, "Target 'a' could not be found in project")
self.assertNotEquals(myProject.getTarget("b"), None, "Target 'b' could not be found in project")
self.assertNotEquals(myProject.getTarget("c"), None, "Target 'c' could not be found in project")
self.assertNotEquals(myProject.getTarget("A"), None, "Target 'a' could not be found in project")
self.assertNotEquals(myProject.getTarget("B "), None, "Target 'b' could not be found in project")
self.assertNotEquals(myProject.getTarget(" C"), None, "Target 'c' could not be found in project")
#Targets that do NOT exist in project
self.assertEquals(myProject.getTarget("d"), None, "Target 'd' should not have been found in project")
self.assertEquals(myProject.getTarget(""), None, "Target '' should not have been found in project")
finally:
utilityFunctions.removeDir(tempDir)
def test_examineSingleTarget(self):
projectFileContents = textwrap.dedent("""
Name: TestCaseA
Path: cases/simpleGraphAutoTools/TestCaseA
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
option.buildDir = os.path.join(tempDir, option.buildDir)
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project failed to examine")
self.assertEquals(myProject.getTarget("TestCaseA").dependencyDepth, 0, "TestCaseA had wrong dependency depth")
self.assertEquals(len(myProject.targets), 1, "Number of Targets in project is wrong")
self.assertEquals(myProject.targets[0].name, "TestCaseA", "Sorting failed. TestCaseA should have been the first target.")
finally:
utilityFunctions.removeDir(tempDir)
def test_examineMultiTargetCase1(self):
projectFileContents = textwrap.dedent("""
Name: TestCaseA
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: TestCaseB
Name: TestCaseB
Path: cases/simpleGraphAutoTools/TestCaseB
DependsOn: TestCaseC
Name: TestCaseC
Path: cases/simpleGraphAutoTools/TestCaseC
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
option.buildDir = os.path.join(tempDir, option.buildDir)
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project failed to examine")
self.assertEquals(myProject.getTarget("TestCaseA").dependencyDepth, 0, "TestCaseA had wrong dependency depth")
self.assertEquals(myProject.getTarget("TestCaseB").dependencyDepth, 1, "TestCaseB had wrong dependency depth")
self.assertEquals(myProject.getTarget("TestCaseC").dependencyDepth, 2, "TestCaseC had wrong dependency depth")
self.assertEquals(len(myProject.targets), 3, "Number of Targets in project is wrong")
self.assertEquals(myProject.targets[0].name, "TestCaseA", "Sorting failed. TestCaseA should have been the first target.")
self.assertEquals(myProject.targets[1].name, "TestCaseB", "Sorting failed. TestCaseB should have been the first target.")
self.assertEquals(myProject.targets[2].name, "TestCaseC", "Sorting failed. TestCaseC should have been the first target.")
finally:
utilityFunctions.removeDir(tempDir)
def test_examineMultiTargetCase2(self):
projectFileContents = textwrap.dedent("""
Name: TestCaseA
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: TestCaseB, TestCaseC
Name: TestCaseB
Path: cases/simpleGraphAutoTools/TestCaseB
DependsOn: TestCaseC
Name: TestCaseC
Path: cases/simpleGraphAutoTools/TestCaseC
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
option.buildDir = os.path.join(tempDir, option.buildDir)
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project failed to examine")
self.assertEquals(myProject.getTarget("TestCaseA").dependencyDepth, 0, "TestCaseA had wrong dependency depth")
self.assertEquals(myProject.getTarget("TestCaseB").dependencyDepth, 1, "TestCaseB had wrong dependency depth")
self.assertEquals(myProject.getTarget("TestCaseC").dependencyDepth, 2, "TestCaseC had wrong dependency depth")
self.assertEquals(len(myProject.targets), 3, "Number of Targets in project is wrong")
self.assertEquals(myProject.targets[0].name, "TestCaseA", "Sorting failed. TestCaseA should have been the first target.")
self.assertEquals(myProject.targets[1].name, "TestCaseB", "Sorting failed. TestCaseB should have been the first target.")
self.assertEquals(myProject.targets[2].name, "TestCaseC", "Sorting failed. TestCaseC should have been the first target.")
finally:
utilityFunctions.removeDir(tempDir)
def test_examineMultiTargetCase3(self):
projectFileContents = textwrap.dedent("""
Name: A
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: B, C
Name: B
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: C
Name: C
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: D
Name: D
Path: cases/simpleGraphAutoTools/TestCaseA
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
option.buildDir = os.path.join(tempDir, option.buildDir)
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project failed to examine")
self.assertEquals(myProject.getTarget("A").dependencyDepth, 0, "A had wrong dependency depth")
self.assertEquals(myProject.getTarget("B").dependencyDepth, 1, "B had wrong dependency depth")
self.assertEquals(myProject.getTarget("C").dependencyDepth, 2, "C had wrong dependency depth")
self.assertEquals(myProject.getTarget("D").dependencyDepth, 3, "D had wrong dependency depth")
self.assertEquals(len(myProject.targets), 4, "Number of Targets in project is wrong")
self.assertEquals(myProject.targets[0].name, "A", "Sorting failed. A should have been the first target.")
self.assertEquals(myProject.targets[1].name, "B", "Sorting failed. B should have been the first target.")
self.assertEquals(myProject.targets[2].name, "C", "Sorting failed. C should have been the first target.")
self.assertEquals(myProject.targets[3].name, "D", "Sorting failed. D should have been the first target.")
finally:
utilityFunctions.removeDir(tempDir)
def test_examineMultiTargetCase4(self):
projectFileContents = textwrap.dedent("""
Name: A
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: B, C
Name: B
Path: cases/simpleGraphAutoTools/TestCaseA
Name: C
Path: cases/simpleGraphAutoTools/TestCaseA
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
option.buildDir = os.path.join(tempDir, option.buildDir)
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project failed to examine")
self.assertEquals(myProject.getTarget("A").dependencyDepth, 0, "A had wrong dependency depth")
self.assertEquals(myProject.getTarget("B").dependencyDepth, 1, "B had wrong dependency depth")
self.assertEquals(myProject.getTarget("C").dependencyDepth, 1, "C had wrong dependency depth")
self.assertEquals(len(myProject.targets), 3, "Number of Targets in project is wrong")
self.assertEquals(myProject.targets[0].name, "A", "Sorting failed. A should have been the first target.")
self.assertEquals(myProject.targets[1].name, "B", "Sorting failed. B should have been the first target.")
self.assertEquals(myProject.targets[2].name, "C", "Sorting failed. C should have been the first target.")
finally:
utilityFunctions.removeDir(tempDir)
def test_examineMultiTargetCase5(self):
projectFileContents = textwrap.dedent("""
Name: A
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: B, C, D
Name: B
Path: cases/simpleGraphAutoTools/TestCaseA
Name: C
Path: cases/simpleGraphAutoTools/TestCaseA
DependsOn: D
Name: D
Path: cases/simpleGraphAutoTools/TestCaseA
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
option.buildDir = os.path.join(tempDir, option.buildDir)
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project failed to examine")
self.assertEquals(myProject.getTarget("A").dependencyDepth, 0, "A had wrong dependency depth")
self.assertEquals(myProject.getTarget("B").dependencyDepth, 1, "B had wrong dependency depth")
self.assertEquals(myProject.getTarget("C").dependencyDepth, 1, "C had wrong dependency depth")
self.assertEquals(myProject.getTarget("D").dependencyDepth, 2, "D had wrong dependency depth")
self.assertEquals(len(myProject.targets), 4, "Number of Targets in project is wrong")
self.assertEquals(myProject.targets[0].name, "A", "Sorting failed. A should have been the first target.")
self.assertEquals(myProject.targets[1].name, "B", "Sorting failed. B should have been the first target.")
self.assertEquals(myProject.targets[2].name, "C", "Sorting failed. C should have been the first target.")
self.assertEquals(myProject.targets[3].name, "D", "Sorting failed. D should have been the first target.")
finally:
utilityFunctions.removeDir(tempDir)
def test_expandDependsOnListsCase1(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-3.33.tar.gz
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project could not validate")
self.assertEquals(myProject.targets[0].expandedDependsOn, ["b", "c"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[1].expandedDependsOn, ["c"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[2].expandedDependsOn, [], "expandedDependsOn was wrong")
finally:
utilityFunctions.removeDir(tempDir)
def test_expandDependsOnListsCase2(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b
Name: b
Path: b-2.22.tar.gz
DependsOn:
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project could not validate")
self.assertEquals(myProject.targets[0].expandedDependsOn, ["b"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[1].expandedDependsOn, [], "expandedDependsOn was wrong")
finally:
utilityFunctions.removeDir(tempDir)
def test_expandDependsOnListsCase3(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c
Name: b
Path: b-2.22.tar.gz
DependsOn: d
Name: c
Path: c-2.22.tar.gz
DependsOn: d
Name: d
Path: d-2.22.tar.gz
DependsOn:
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project could not validate")
self.assertEquals(myProject.targets[0].expandedDependsOn, ["b", "c", "d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[1].expandedDependsOn, ["d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[2].expandedDependsOn, ["d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[3].expandedDependsOn, [], "expandedDependsOn was wrong")
finally:
utilityFunctions.removeDir(tempDir)
def test_expandDependsOnListsCase4(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c, d
Name: b
Path: b-2.22.tar.gz
DependsOn: d
Name: c
Path: c-2.22.tar.gz
DependsOn: d
Name: d
Path: d-2.22.tar.gz
DependsOn:
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project could not validate")
self.assertEquals(myProject.targets[0].expandedDependsOn, ["b", "c", "d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[1].expandedDependsOn, ["d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[2].expandedDependsOn, ["d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[3].expandedDependsOn, [], "expandedDependsOn was wrong")
finally:
utilityFunctions.removeDir(tempDir)
def test_expandDependsOnListsCase5(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, c, d
Name: b
Path: b-2.22.tar.gz
DependsOn:
Name: c
Path: c-2.22.tar.gz
DependsOn:
Name: d
Path: d-2.22.tar.gz
DependsOn:
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project could not validate")
self.assertEquals(myProject.targets[0].expandedDependsOn, ["b", "c", "d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[1].expandedDependsOn, [], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[2].expandedDependsOn, [], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[3].expandedDependsOn, [], "expandedDependsOn was wrong")
finally:
utilityFunctions.removeDir(tempDir)
def test_expandDependsOnListsCase6(self):
projectFileContents = textwrap.dedent("""
Name: a
Path: a-1.11.tar.gz
DependsOn: b, d
Name: b
Path: b-2.22.tar.gz
DependsOn: c
Name: c
Path: c-2.22.tar.gz
DependsOn: d
Name: d
Path: d-2.22.tar.gz
DependsOn:
""")
try:
tempDir = mdTestUtilities.makeTempDir()
projectFilePath = mdTestUtilities.makeTempFile(tempDir, projectFileContents, ".md")
myProject = project.Project(projectFilePath)
option = options.Options()
self.assertTrue(myProject.read(), "Project file could not be read")
self.assertTrue(myProject.examine(option), "Project could not validate")
self.assertEquals(myProject.targets[0].expandedDependsOn, ["b", "c", "d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[1].expandedDependsOn, ["c", "d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[2].expandedDependsOn, ["d"], "expandedDependsOn was wrong")
self.assertEquals(myProject.targets[3].expandedDependsOn, [], "expandedDependsOn was wrong")
finally:
utilityFunctions.removeDir(tempDir)
def suite():
suite = unittest.TestSuite()
suite.addTest(unittest.makeSuite(Test_project))
return suite
if __name__ == "__main__":
logger.setLogger("Console")
unittest.main()
|
lgpl-3.0
|
md748/QtRPC
|
QtRPCCo/QtRPCFunction.cpp
|
6421
|
#include "QtRPCFunction.h"
#include <QDebug>
QtRPCFunction::QtRPCFunction()
{
}
void QtRPCFunction::setKeywordItems(const QList<KeyWordItem> &itemRet, const QList<KeyWordItem> &itemContent)
{
itemRets_ = itemRet;
itemContent_ = itemContent;
}
void QtRPCFunction::setFuncType(FuncType type)
{
funcType_ = type;
}
void QtRPCFunction::setAccessType(AccessType type)
{
accessType_ = type;
}
int QtRPCFunction::parse()
{
if (itemRets_.isEmpty())
RETURN_1;
for (int i = 0; i < itemRets_.count(); ++i)
{
const KeyWordItem &item = itemRets_.at(i);
bool contains = GlobalData::instance().isContains(item.type);
if (contains)
{
if (item.type != KwTypeVoid)
funcItem_.retType.depends.append("<" + item.item + ">");
}
else
{
if (item.type == KwWord)
funcItem_.retType.depends.append("\"" + item.item + "\"");
}
funcItem_.retType.text.append(item.item + " ");
}
if (itemRets_.last().type == KwAsterisk)
{
funcItem_.retType.isPointer = true;
}
if (itemRets_.count() > 2)
{
funcItem_.retType.type = itemRets_.first().item;
}
else
{
funcItem_.retType.type = itemRets_.first().item;
}
if (itemContent_.isEmpty())
RETURN_1;
funcItem_.name = itemContent_.first().item;
qDebug() << funcItem_.retType.text << " " << funcItem_.name;
for (int i = 1; i < itemContent_.count(); )
{
const KeyWordItem *item = &(itemContent_.at(i++));
if (item->type != KwParenLeft && i == 1)
RETURN_1;
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type == KwParenRight)
{
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type != KwSemicolon)
RETURN_1;
continue;
}
int argBegin = i - 1;
TypeItem typeItem;
bool isOutArgNull = false;
if (item->type == KwConst)
{
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
typeItem.isOutArg = false;
isOutArgNull = true;
}
if (item->type == KwWord && !GlobalData::instance().isContains(item->type))
{
typeItem.depends.append("\"" + item->item + "\"");
typeItem.type = item->item;
//no template
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type == KwDomain)
{
qDebug() << "not supported syntax like this : " << typeItem.type + item->item;
RETURN_1;
}
}
else if (item->type == KwWord)
{
typeItem.type = item->item;
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type == KwLess) //template
{
i = templateProc(i, typeItem.depends);
if (i < 0)
RETURN_1;
}
}
else if (GlobalData::instance().isContains(item->type))
{
typeItem.type = item->item;
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type == KwLess) //template
{
i = templateProc(i, typeItem.depends);
if (i < 0)
RETURN_1;
}
}
else
{
RETURN_1;
}
if (item->type == KwAmpersand)
{
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (!isOutArgNull)
typeItem.isOutArg = true;
}
else if (item->type == KwAsterisk)
{
if (i >= itemContent_.count())
RETURN_1;
typeItem.isPointer = true;
item = &(itemContent_.at(i++));
if (!isOutArgNull)
typeItem.isOutArg = true;
}
int argEnd = i - 1;
//push text;
for (int t = argBegin; t < argEnd; ++t)
{
typeItem.text.append(itemContent_.at(t).item + " ");
}
if (item->type != KwWord)
RETURN_1;
typeItem.name = item->item;
funcItem_.args.append(typeItem);
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type == KwComma)
{
i -= 1;
continue;
}
else if (item->type == KwParenRight)
{
if (i >= itemContent_.count())
RETURN_1;
item = &(itemContent_.at(i++));
if (item->type != KwSemicolon)
RETURN_1;
}
} //end for
if (!funcItem_.args.isEmpty())
{
for (int i = 0; i < funcItem_.args.count(); ++i)
qDebug() << "args:" << funcItem_.args.at(i).text << " " << funcItem_.args.at(i).name;
}
qDebug() << funcItem_.retType.depends;
return 0;
}
const FuncItem &QtRPCFunction::getFunction()
{
return funcItem_;
}
int QtRPCFunction::templateProc(int index, QStringList &depends)
{
const KeyWordItem *item = 0;
do
{
if (index < 0)
RETURN_1;
if (index >= this->itemContent_.count())
RETURN_1;
item = &(this->itemContent_.at(index++));
if (item->type != KwComma && item->type != KwLess && item->type != KwGreater)
{
if (item->type != KwWord)
{
if (GlobalData::instance().isContains(item->type))
depends.append("<" + item->item + ">");
else
RETURN_1;
}
}
else
{
if (item->type == KwComma)
{
continue;
}
if (item->type == KwLess)
{
index = templateProc(index, depends);
}
}
} while(item->type != KwGreater);
if (item->type == KwGreater)
return index;
RETURN_1;
}
|
lgpl-3.0
|
lbndev/sonarqube
|
sonar-plugin-api/src/main/java/org/sonar/api/batch/fs/internal/Metadata.java
|
1678
|
/*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.api.batch.fs.internal;
public class Metadata {
private final int lines;
private final int nonBlankLines;
private final String hash;
private final int[] originalLineOffsets;
private final int lastValidOffset;
public Metadata(int lines, int nonBlankLines, String hash, int[] originalLineOffsets, int lastValidOffset) {
this.lines = lines;
this.nonBlankLines = nonBlankLines;
this.hash = hash;
this.originalLineOffsets = originalLineOffsets;
this.lastValidOffset = lastValidOffset;
}
public int lines() {
return lines;
}
public int nonBlankLines() {
return nonBlankLines;
}
public String hash() {
return hash;
}
public int[] originalLineOffsets() {
return originalLineOffsets;
}
public int lastValidOffset() {
return lastValidOffset;
}
}
|
lgpl-3.0
|
chuidiang/chuidiang-ejemplos
|
JAVA/hazelcast-example/src/main/java/com/chuidiang/ejemplos/subscription/SubscriptionMain.java
|
1365
|
package com.chuidiang.ejemplos.subscription;
import com.hazelcast.config.Config;
import com.hazelcast.config.GlobalSerializerConfig;
import com.hazelcast.core.Hazelcast;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.map.IMap;
import java.util.Date;
public class SubscriptionMain {
public static void main(String[] args){
GlobalSerializerConfig myGlobalConfig = new GlobalSerializerConfig();
myGlobalConfig.setOverrideJavaSerialization(true).setImplementation(new MyDataSerializer());
Config config = new Config();
config.getSerializationConfig().setGlobalSerializerConfig(myGlobalConfig);
HazelcastInstance instance = Hazelcast.newHazelcastInstance(config);
IMap<String, String> aMap = instance.getMap("aMap");
aMap.addEntryListener(new MyListener(), true);
aMap.put("key", "value");
aMap.put("key", "Another value");
aMap.remove("key");
aMap.put("other key", "other value");
aMap.clear();
IMap<String, Data> otherMap = instance.getMap("otherMap");
otherMap.addEntryListener(new MyListener(), true);
otherMap.put("key", new Data());
Data data = otherMap.get("key");
data.date=new Date();
data.value=1000;
otherMap.put("key",data);
instance.shutdown();
}
}
|
lgpl-3.0
|
loftuxab/community-edition-old
|
projects/repository/source/java/org/alfresco/repo/avm/util/UriSchemeNameMatcher.java
|
6493
|
/*-----------------------------------------------------------------------------
* Copyright 2007-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*
*
* Author Jon Cox <jcox@alfresco.com>
* File UriSchemeNameMatcher.java
*----------------------------------------------------------------------------*/
package org.alfresco.repo.avm.util;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import org.alfresco.util.NameMatcher;
/**
* A NameMatcher that matches an incoming URL against list of schemes
* (less formally known as "protocols"), case insensitively.
* The formal spec for parsing URIs is RFC-3986
* <p>
* Perhaps someday, it might be worthwhile to create a specific
* parser for each registered scheme-specific part, and validate
* that; for now, we'll just be be more lax, and assume the URI
* is alwasy scheme-qualified. This matcher will look no further
* than the leading colon, and declare "no match" otherwise.
* The discussion below explains why.
* <p>
* See: http://tools.ietf.org/html/rfc3986):
* <pre>
* The following regex parses URIs:
* ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
*
* Given the following URI:
* http://www.ics.uci.edu/pub/ietf/uri/#Related
*
* The captured subexpressions are:
*
* $1 = http:
* $2 = http
* $3 = //www.ics.uci.edu
* $4 = www.ics.uci.edu
* $5 = /pub/ietf/uri/
* $6 = <undefined>
* $7 = <undefined>
* $8 = #Related
* $9 = Related
*
* N0TE:
* A URI can be non-scheme qualified because $1 is optional. Therefore,
* the following are all exaples of valid non-scheme qualified URIS:
*
* ""
* "moo@cow.com"
* "moo@cow.com?wow"
* "moo@cow.com?wow#zow"
* "moo@cow.com#zow"
* "/"
* "/moo/cow"
* "/moo/cow?wow"
* "/moo/cow?wow#zow"
* "/moo/cow#zow"
* "//moo/cow"
* "//moo.com/cow"
* "//moo.com/cow/"
* "//moo.com/cow?wow"
* "//moo.com/cow?wow#zow"
* "//moo.com/cow#zow"
* "//moo.com:8080/cow"
* "//moo.com:/cow"
* "//moo.com:8080/cow?wow"
* "//moo.com:8080/cow?wow#zow"
* "//moo.com:8080/cow#zow"
* "///moo/cow"
* "///moo/cow?wow"
* "///moo/cow?wow#zow"
* "///moo/cow#zow"
*
* And so forth...
*
* <pre>
*
* Thus the business end of things as far as scheme matching is: $2,
* Most schemes will have a $3 that starts with '//', but not all.
* Specificially, the following have no "network path '//' segment,
* or aren't required to (source: http://en.wikipedia.org/wiki/URI_scheme):
* <pre>
*
* cid data dns fax go h323 iax2 mailto mid news pres sip
* sips tel urn xmpp about aim callto feed magnet msnim
* psyc skype sms stream xfire ymsgr
*
* </pre>
*
* Visually the parts are as follows:
* <pre>
*
* foo://example.com:10042/over/there?name=ferret#nose
* \_/ \_______________/\_________/ \_________/ \__/
* | | | | |
* scheme authority path query fragment
* | _____________________|__
* / \ / \
* urn:example:animal:ferret:nose
*
* </pre>
*
* This is useful for classifying URLs for things like whether or not
* they're supported by an application.
*
* For example, the LinkValidationService supports http, and https,
* is willing to ignore certain well-formed URLs, but treats URLs
* will unknown and unsupported protocols as broken. Concretely,
* we'd like to avoid treating something like the following one
* as being non-broken even though you can't apply GET or HEAD
* to it.
*
* <pre>
* <a href="mailto:alice@example.com">Email</a>
* </pre>
*
* As of June 2007,IANA had over 70 registered and provisional protocols
* listed at http://www.iana.org/assignments/uri-schemes.html but sometimes
* people create their own too (e.g.: cvs). Here's the official list:
* <pre>
*
* aaa aaas acap afs cap cid crid data dav dict dns dtn fax file
* ftp go gopher h323 http https iax2 icap im imap info ipp iris
* iris.beep iris.lwz iris.xpc iris.xpcs ldap mailserver mailto
* mid modem msrp msrps mtqp mupdate news nfs nntp opaquelocktoken
* pop pres prospero rtsp service shttp sip sips snmp soap.beep
* soap.beeps tag tel telnet tftp thismessage tip tn3270 tv urn
* vemmi wais xmlrpc.beep xmlrpc.beeps xmpp z39.50r z39.50s
* </pre>
*
*/
public class UriSchemeNameMatcher implements NameMatcher, Serializable
{
/**
* The extensions to match.
*/
HashMap<String,String> scheme_;
/**
* Default constructor.
*/
public UriSchemeNameMatcher()
{
scheme_ = new HashMap<String,String>();
}
/**
* Set the protocols case insensitively (cannonicalized to lower-case).
*
* @param protocols
*/
public void setExtensions(List<String> protocols)
{
for (String protocol : protocols)
{
scheme_.put( protocol.toLowerCase(), null );
}
}
/**
* Returns true if the URL's protocol is in the of
* being matched. Everything up to but not including
* the intial colon is
*/
public boolean matches(String uri)
{
if ( uri == null ) { return false; }
int colon_index = uri.indexOf(':');
if ( colon_index >= 0)
{
String proto =
uri.substring(0, colon_index).toLowerCase();
return scheme_.containsKey( proto );
}
return false;
}
}
|
lgpl-3.0
|
omega-hub/osgearth
|
src/osgEarthDrivers/engine_rex/MPTexture.cpp
|
5871
|
/* -*-c++-*- */
/* osgEarth - Dynamic map generation toolkit for OpenSceneGraph
* Copyright 2008-2014 Pelican Mapping
* http://osgearth.org
*
* osgEarth is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
#include "MPTexture"
using namespace osgEarth::Drivers::RexTerrainEngine;
using namespace osgEarth;
#define LC "[MPTexture] "
MPTexture::MPTexture() :
osg::Texture2D()
{
//nop
}
void
MPTexture::setLayer(const ImageLayer* layer, osg::Texture* tex, int order)
{
Passes::iterator insertionPoint = _passes.end();
// If the layer already exists as a pass, update it
for(Passes::iterator pass = _passes.begin(); pass != _passes.end(); ++pass)
{
if ( pass->_layer.get() == layer )
{
pass->_texture = tex;
pass->_ownsTexture = true;
pass->_textureMatrix = osg::Matrixf::identity();
return;
}
else if ( order < pass->_order )
{
insertionPoint = pass;
}
}
// Layer didn't already exist; add it (in the proper order)
Pass& pass = *_passes.insert( insertionPoint, Pass() );
pass._layer = layer;
pass._texture = tex;
pass._parentTexture = tex;
pass._order = order;
pass._ownsTexture = true;
}
void
MPTexture::merge(MPTexture* rhs)
{
if ( rhs )
{
for(Passes::const_iterator pass = rhs->getPasses().begin(); pass != rhs->getPasses().end(); ++pass)
{
setLayer( pass->_layer.get(), pass->_texture.get(), pass->_order );
}
}
}
void
MPTexture::inheritState(MPTexture* parent, const osg::Matrixf& scaleBias)
{
if ( parent )
{
// First time around, copy the parent's data in whole, and then scale/bias
// the texture matrix to the appropriate quadrant
if ( _passes.empty() )
{
// copy it:
_passes = parent->getPasses();
for(Passes::iterator pass = _passes.begin(); pass != _passes.end(); ++pass)
{
// scale and bias the texture matrix; then the new parent texture just
// points to the main texture until the main texture gets replaced later.
pass->_textureMatrix.preMult( scaleBias );
pass->_parentTexture = pass->_texture.get();
pass->_parentTextureMatrix = pass->_textureMatrix;
pass->_ownsTexture = false;
}
}
// If this object already has data, recalculate the sub-matrixing on all
// existing textures and parent-textures:
else
{
for(Passes::const_iterator parentPass = parent->getPasses().begin(); parentPass != parent->getPasses().end(); ++parentPass)
{
for(Passes::iterator pass = _passes.begin(); pass != _passes.end(); ++pass)
{
if ( parentPass->_layer.get() == pass->_layer.get())
{
// If the texture matrix is non-identity, that means we are inheriting from another tile.
// In this case, re-copy from the parent (in case it changed) and recalculate the
// texture matrix.
if ( !pass->_textureMatrix.isIdentity() )
{
pass->_texture = parentPass->_texture.get();
pass->_textureMatrix = parentPass->_textureMatrix;
pass->_textureMatrix.preMult( scaleBias );
}
// Update the parent texture always.
if ( parentPass->_texture.valid() )
{
pass->_parentTexture = parentPass->_texture.get();
pass->_parentTextureMatrix = parentPass->_textureMatrix;
pass->_parentTextureMatrix.preMult( scaleBias );
}
else
{
pass->_parentTexture = pass->_texture.get();
pass->_parentTextureMatrix = pass->_textureMatrix;
}
}
}
}
}
}
}
void
MPTexture::compileGLObjects(osg::State& state) const
{
for(Passes::const_iterator pass = _passes.begin(); pass != _passes.end(); ++pass)
{
if ( pass->_texture.valid() ) //&& pass->_ownsTexture )
{
pass->_texture->apply(state);
}
}
}
void
MPTexture::resizeGLObjectBuffers(unsigned int maxSize)
{
for(Passes::const_iterator pass = _passes.begin(); pass != _passes.end(); ++pass)
{
if ( pass->_texture.valid() && pass->_ownsTexture )
{
pass->_texture->resizeGLObjectBuffers(maxSize);
}
}
}
void
MPTexture::releaseGLObjects(osg::State* state) const
{
for(Passes::const_iterator pass = _passes.begin(); pass != _passes.end(); ++pass)
{
// check the refcount since textures are shared across MPTexture instances.
if ( pass->_texture.valid() && pass->_texture->referenceCount() == 1 )
{
pass->_texture->releaseGLObjects(state);
}
}
}
|
lgpl-3.0
|
SirmaITT/conservation-space-1.7.0
|
docker/sirma-platform/platform/seip-parent/platform/domain-model/instance-search/src/main/java/com/sirma/itt/seip/search/ResultValue.java
|
2195
|
package com.sirma.itt.seip.search;
import java.io.Serializable;
/**
* Represents a name value pair for a single value in a {@link ResultItem}
*
* @author <a href="mailto:borislav.bonev@sirma.bg">Borislav Bonev</a>
* @since 11/06/2017
*/
public interface ResultValue extends Serializable {
/**
* The result value name.
*
* @return the name
*/
String getName();
/**
* The actual value represented by the current instance
*
* @return the value, never {@code null}
*/
Serializable getValue();
/**
* Creates a simple {@link ResultValue} instance
*
* @param name the value name
* @param value the actual value
* @return new result value instance
*/
static ResultValue create(String name, Serializable value) {
return new SimpleResultValue(name, value);
}
/**
* Simple result value implementation. The implementation provides a {@link #equals(Object)} and
* {@link #hashCode()} implementations that take into account the name and the value.
*/
class SimpleResultValue implements ResultValue {
private final String name;
private final Serializable value;
/**
* Instantiate new result value instance
*
* @param name thr value name
* @param value the actual value
*/
public SimpleResultValue(String name, Serializable value) {
this.name = name;
this.value = value;
}
@Override
public String getName() {
return name;
}
@Override
public Serializable getValue() {
return value;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ResultValue)) {
return false;
}
ResultValue that = (ResultValue) o;
if (name != null ? !name.equals(that.getName()) : that.getName() != null) {
return false;
}
return value != null ? value.equals(that.getValue()) : that.getValue() == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return new StringBuilder(60).append("{").append(name).append('=').append(value).append('}').toString();
}
}
}
|
lgpl-3.0
|
ccat/goyaw
|
user.go
|
2519
|
package goyaw
import (
"encoding/hex"
"errors"
_ "github.com/go-sql-driver/mysql"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
"github.com/naoina/genmai"
"golang.org/x/crypto/bcrypt"
"strings"
"time"
)
type User struct {
Id int64 `db:"pk"` // column:"tbl_id"
UserName string `db:"unique"` // size:"255"
HashedPassword string
Active bool
CreatedAt *time.Time
}
type UserMgmt struct {
UserDB *genmai.DB
}
type UserDBconfig struct {
Type string
Config string
}
func NewUserDB(userDBconfig *UserDBconfig) *UserMgmt {
var dbIns *UserMgmt = new(UserMgmt)
var err error
if userDBconfig.Type == "sqlite3" {
dbIns.UserDB, err = genmai.New(&genmai.SQLite3Dialect{}, userDBconfig.Config)
} else if userDBconfig.Type == "mysql" {
dbIns.UserDB, err = genmai.New(&genmai.MySQLDialect{}, userDBconfig.Config)
} else if userDBconfig.Type == "postgresql" {
dbIns.UserDB, err = genmai.New(&genmai.PostgresDialect{}, userDBconfig.Config)
}
if err != nil {
panic(err)
}
err = dbIns.UserDB.CreateTableIfNotExists(&User{})
if err != nil {
panic(err)
}
return dbIns
}
func (self *UserMgmt) CreateUser(username string, password string) error {
converted, err := bcrypt.GenerateFromPassword([]byte(password), 10)
if err != nil {
return errors.New("Invalid Password")
}
hashedPass := hex.EncodeToString(converted[:])
t := time.Now()
records := []User{
{UserName: username, HashedPassword: hashedPass, Active: true, CreatedAt: &t},
}
_, err = self.UserDB.Insert(records)
if err != nil {
if strings.Contains(err.Error(), "UNIQUE") {
return errors.New("Username already used")
} else {
return errors.New("Invalid Password")
}
}
return nil
}
func (self *UserMgmt) Auth(username string, password string) error {
var results []User
err := self.UserDB.Select(&results, self.UserDB.Where("user_name", "=", username))
//err := self.UserDB.Select(&results)
if err != nil {
panic(err)
}
if len(results) == 0 {
return errors.New("Invalid username")
}
if results[0].Active == false {
return errors.New("User is not active")
}
hashedPass, err := hex.DecodeString(results[0].HashedPassword)
if err != nil {
panic(err)
}
err = bcrypt.CompareHashAndPassword(hashedPass, []byte(password))
if err != nil {
return errors.New("Invalid Password")
}
return nil
}
/*func nilFunc() {
var tempMysql *mysql.NullTime = nil
var tempPq *pq.Error = nil
sqlite3.Version()
tempMysql = tempMysql
tempPq = tempPq
}*/
|
lgpl-3.0
|
alex73/mmscomputing
|
src/uk/co/mmscomputing/device/capi/ncc/ConnectB3Resp.java
|
653
|
package uk.co.mmscomputing.device.capi.ncc;
import uk.co.mmscomputing.device.capi.*;
public class ConnectB3Resp extends MsgOut{
public ConnectB3Resp(int appid, int ncci, int reject, StructOut ncpi){
super(2+ncpi.getLength(),appid,CAPI_CONNECT_B3,CAPI_RESP,ncci);
writeWord(reject); // 0= accept, 1..n=reject
writeStruct(ncpi); // ncpi struct
}
public ConnectB3Resp(int appid, int ncci, int reject){
super(3,appid,CAPI_CONNECT_B3,CAPI_RESP,ncci);
writeWord(reject); // 0= accept, 1..n=reject
writeStruct(); // ncpi struct
}
public ConnectB3Resp(int appid, int ncci){
this(appid,ncci,ACCEPT);
}
}
|
lgpl-3.0
|
devbus/devbus
|
daos/user_dao.go
|
1365
|
package daos
import (
"strings"
"github.com/devbus/devbus/common"
"github.com/devbus/devbus/models"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
)
type UserDao struct {
*gorm.DB
}
func NewUserDao(db *gorm.DB) *UserDao {
return &UserDao{db}
}
func (dao *UserDao) GetUserByEmail(email string) *models.User {
user := &models.User{}
if err := dao.Where("email = ?", email).First(user).Error; err != nil {
log.Debugf("failed to query user email: %v", err)
return nil
}
return user
}
func (dao *UserDao) AddUser(user *models.User) error {
if err := dao.Create(user).Error; err != nil {
log.Debugf("%+v", errors.Wrapf(err, "failed to create new user, user: %+v", user))
errStr := err.Error()
errCode := common.ErrUnknown
if strings.Contains(errStr, "devbus_user_name_key") {
errCode = common.ErrUserConflictName
} else if strings.Contains(errStr, "devbus_user_email_key") {
errCode = common.ErrUserConflictEmail
}
return common.OpError{Code: errCode}
}
return nil
}
func (dao *UserDao) ModifyPassword(user *models.User) error {
err := dao.Model(user).UpdateColumn("password", user.Password).Error
if err != nil {
errStr := err.Error()
errCode := common.ErrUnknown
if strings.Contains(errStr, "devbus_user_email_key") {
errCode = common.ErrUserNotFound
}
return common.OpError{Code: errCode}
}
return nil
}
|
lgpl-3.0
|
sporniket/game
|
sporniket-game-papi-android/src/main/java/com/sporniket/libre/game/papi/android/GameView.java
|
7653
|
/**
*
*/
package com.sporniket.libre.game.papi.android;
import java.util.List;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceView;
import com.sporniket.libre.game.gamelet.input.GameControllerStateProvider;
import com.sporniket.libre.game.gamelet.input.KeyboardStateProvider;
import com.sporniket.libre.game.gamelet.input.PointerStateProvider;
import com.sporniket.libre.game.gamelet.input.PointerStateProviderSupport;
import com.sporniket.libre.game.papi.Game;
import com.sporniket.libre.game.papi.InputAbstractionLayerInterface;
import com.sporniket.libre.game.papi.profile.ScreenFeatureSet;
/**
* View to instanciate to display the game.
*
* <p>
* © Copyright 2010-2013 David Sporn
* </p>
* <hr>
*
* <p>
* This file is part of <i>The Sporniket Game Library – Platform API for Android</i>.
*
* <p>
* <i>The Sporniket Game Library – Platform API for Android</i> is free software: you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* <p>
* <i>The Sporniket Game Library – Platform API for Android</i> is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* <p>
* You should have received a copy of the GNU Lesser General Public License along with <i>The Sporniket Game Library –
* Platform API for Android</i>. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>. 2
*
* <hr>
*
* @author David SPORN
* @see http://developer.android.com/guide/topics/graphics/2d-graphics.html
*/
public class GameView extends SurfaceView implements InputAbstractionLayerInterface
{
/**
* Tag for android logging.
*/
private static final String TAG = GameView.class.getSimpleName();
private GameActivity myGameActivity ;
private ScreenFeatureSet myScreenFeatureSet ;
/**
* @param context
*/
public GameView(Context context, ScreenFeatureSet screenFeatureSet)
{
super(context);
setScreenFeatureSet(screenFeatureSet);
}
/**
* @param measureSpec
*/
private void dumpMeasureSpec(String message, int measureSpec)
{
AndroidUtils.dumpMeasureSpec(TAG, message, measureSpec);
}
/**
* @return the gameActivity
*/
public GameActivity getGameActivity()
{
return myGameActivity;
}
/**
* @return
*/
private GamePlatform getPlatform()
{
return getGameActivity().getPlatform();
}
public boolean isAttachedToGameActivity()
{
return null != getGameActivity() ;
}
/*
* (non-Javadoc)
*
* @see android.view.SurfaceView#onMeasure(int, int)
*/
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
Log.i(TAG, "====> [onMeasure(widthMeasureSpec, heightMeasureSpec)] ");
// log requested measure, for info
dumpMeasureSpec("widthSpec", widthMeasureSpec);
dumpMeasureSpec("heightSpec", heightMeasureSpec);
// Don't care about those dimensions, use the Platform screen feature instead.
final ScreenFeatureSet _screenFeatures = getPlatform().getScreenFeatures();
setMeasuredDimension(_screenFeatures.getWidth() * _screenFeatures.getXfactor(), _screenFeatures.getHeight()
* _screenFeatures.getYfactor());
Log.i(TAG, "<---- [onMeasure(widthMeasureSpec, heightMeasureSpec)]");
}
/*
* (non-Javadoc)
*
* @see android.view.View#onTouchEvent(android.view.MotionEvent)
*/
@Override
public boolean onTouchEvent(MotionEvent event)
{
processTouchEvent(event);
return true ;
}
/**
* @param gameActivity the gameActivity to set
*/
public void setGameActivity(GameActivity gameActivity)
{
myGameActivity = gameActivity;
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#isGameControllerAware()
*/
@Override
public boolean isGameControllerAware()
{
return false;
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#isKeyboardAware()
*/
@Override
public boolean isKeyboardAware()
{
return false;
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#isPointerAware()
*/
@Override
public boolean isPointerAware()
{
return true;
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#update()
*/
@Override
public void update()
{
// TODO Auto-generated method stub
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#getGameControllerStateProvider()
*/
@Override
public GameControllerStateProvider getGameControllerStateProvider() throws UnsupportedOperationException
{
throw new UnsupportedOperationException("Input abstraction layer does not support game controllers.");
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#getPointerStateProvider()
*/
@Override
public PointerStateProvider getPointerStateProvider() throws UnsupportedOperationException
{
return myPointerStateProvider;
}
/* (non-Javadoc)
* @see com.sporniket.libre.game.papi.InputAbstractionLayerInterface#getKeyboardStateProvider()
*/
@Override
public KeyboardStateProvider getKeyboardStateProvider() throws UnsupportedOperationException
{
throw new UnsupportedOperationException("Input abstraction layer does not support keyboards.");
}
/**
* Pointer state provider, support multitouch for up to 12 fingers.
*/
private PointerStateProviderSupport myPointerStateProvider = new PointerStateProviderSupport(12);
private void processTouchEvent(MotionEvent event)
{
int _actionCode = event.getActionMasked();
// find notified pointers
// ok, now we are ready to process...
int _factorX = getScreenFeatureSet().getXfactor();
int _factorY = getScreenFeatureSet().getYfactor();
for (int _pointerId = 0; _pointerId < event.getPointerCount(); _pointerId++)
{
int _pointerIndex = event.findPointerIndex(_pointerId);
if (-1 == _pointerIndex)
{
//current pointer is not concerned by the event
continue;
}
int _x = (int) event.getX(_pointerIndex);
int _y = (int) event.getY(_pointerIndex);
switch (_actionCode)
{
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_POINTER_DOWN:
case MotionEvent.ACTION_MOVE:
myPointerStateProvider.recordPressedPointer(_pointerId, _x / _factorX, _y / _factorY);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_POINTER_UP:
myPointerStateProvider.recordReleasedPointer(_pointerId, _x / _factorX, _y / _factorY);
break;
case MotionEvent.ACTION_CANCEL:
myPointerStateProvider.recordUndefinedPointer(_pointerId, _x / _factorX, _y / _factorY);
break;
default:
// do nothing...
}
}
}
/**
* @param _actionCode
* @return
*/
private boolean processTouchEvent__isEventInteresting(int _actionCode)
{
return MotionEvent.ACTION_POINTER_UP == _actionCode || MotionEvent.ACTION_POINTER_DOWN == _actionCode
|| MotionEvent.ACTION_UP == _actionCode || MotionEvent.ACTION_DOWN == _actionCode;
}
/**
* @return the screenFeatureSet
*/
private ScreenFeatureSet getScreenFeatureSet()
{
return myScreenFeatureSet;
}
/**
* @param screenFeatureSet the screenFeatureSet to set
*/
private void setScreenFeatureSet(ScreenFeatureSet screenFeatureSet)
{
myScreenFeatureSet = screenFeatureSet;
}
}
|
lgpl-3.0
|
premium-minds/billy
|
billy-france/src/main/java/com/premiumminds/billy/france/persistence/dao/DAOFRShippingPoint.java
|
1134
|
/*
* Copyright (C) 2017 Premium Minds.
*
* This file is part of billy france (FR Pack).
*
* billy france (FR Pack) is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* billy france (FR Pack) is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with billy france (FR Pack). If not, see <http://www.gnu.org/licenses/>.
*/
package com.premiumminds.billy.france.persistence.dao;
import com.premiumminds.billy.core.persistence.dao.DAOShippingPoint;
import com.premiumminds.billy.france.persistence.entities.FRShippingPointEntity;
public interface DAOFRShippingPoint extends DAOShippingPoint {
@Override
public FRShippingPointEntity getEntityInstance();
}
|
lgpl-3.0
|
MesquiteProject/MesquiteArchive
|
releases/Mesquite2.01/Mesquite Project/Source/mesquite/diverse/lib/RKF45Solver.java
|
7941
|
/* Mesquite source code. Copyright 1997-2007 W. Maddison and D. Maddison.
Version 2.01, December 2007.
Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code.
The commenting leaves much to be desired. Please approach this source code with the spirit of helping out.
Perhaps with your help we can be more than a few, and make Mesquite better.
Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY.
Mesquite's web site is http://mesquiteproject.org
This source code and its compiled class files are free and modifiable under the terms of
GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html)
*/
package mesquite.diverse.lib;
import java.util.Vector;
import mesquite.lib.MesquiteDouble;
public class RKF45Solver implements DEQNumSolver {
DESystem mySystem;
double[] nextY;
double minh;
double maxh;
MesquiteDouble step = new MesquiteDouble();
final static double fourthRootOneHalf = Math.exp(Math.log(0.5)/4);
final static double tol = 0.000001;
/**
* Solves the system specified by ds over the interval [x0,xend] with initial condition y0 using RKF45
* @arg x0 starting point
* @arg y0 starting values
* @arg step size
* @arg xend
* @arg ds system of equations to solve
* @arg results saves intermediate values, last element is (estimated) y at xend
*/
public double[] integrate(double x0, double[] y0, double h, double xend, DESystem ds, double[] results){
mySystem = ds;
minh = 0.1*h;
maxh = 10*h;
step.setValue(h);
if (results == null || results.length != y0.length)
results = new double[y0.length];
nextY = results;
for(int i=0;i<nextY.length;i++)
nextY[i]=y0[i];
if (x0 >= xend)
return null;
double x = x0;
while(x < xend){
oneStep(x,nextY,step);
if (step.getValue()<minh)
step.setValue(minh);
if (step.getValue()>maxh)
step.setValue(maxh);
x += step.getValue();
}
return results;
}
/**
* Solves the system specified by ds over the interval [x0,xend] with initial condition y0 using RKF45
* @arg x0 starting point
* @arg y0 starting values
* @arg step size
* @arg xend
* @arg ds system of equations to solve
* @arg results saves intermediate values, last element is (estimated) y at xend
*/
public Vector integrate(double x0, double[] y0, double h, double xend, DESystem ds,Vector results,boolean saveResults) {
mySystem = ds;
minh = 0.1*h;
maxh = 10*h;
step.setValue(h);
double[] lastResult = null;
if (results == null && saveResults)
results = new Vector();
if (results != null)
results.clear();
if (nextY == null || nextY.length != y0.length)
nextY = new double[y0.length];
for(int i=0;i<nextY.length;i++)
nextY[i]=y0[i];
if (x0 >= xend)
return null;
double x = x0;
while(x<xend){
double oldStep = step.getValue();
if ((x+oldStep) > xend){
oldStep = xend-x;
step.setValue(oldStep);
}
oneStep(x,nextY,step);
x += oldStep;
if (step.getValue()<minh)
step.setValue(minh);
if (step.getValue()>maxh)
step.setValue(maxh);
if (saveResults && results != null)
results.add(nextY.clone());
else
lastResult = nextY;
}
if (!saveResults){
if (results == null)
results = new Vector(1);
results.add(lastResult.clone());
}
return results;
}
private double[] k1 = null;
private double[] k2 = null;
private double[] k3 = null;
private double[] k4 = null;
private double[] k5 = null;
private double[] k6 = null;
private double[] yk1 = null;
private double[] yk2 = null;
private double[] yk3 = null;
private double[] yk4 = null;
private double[] yk5 = null;
private double[] z = null;
private double[] err2 = null;
private double[] oneStep(double x, double [] y, MesquiteDouble h){
int ylen = y.length;
double hval = h.getValue();
double quarter_h = 0.25*hval;
double threeEights_h = 0.375*hval;
double half_h = 0.5*hval;
double twelveThirteenths_h = 12.0*hval/13;
if (k1 == null || k1.length != ylen){
k1 = new double[ylen];
k2 = new double[ylen];
k3 = new double[ylen];
k4 = new double[ylen];
k5 = new double[ylen];
k6 = new double[ylen];
yk1 = new double[ylen];
yk2 = new double[ylen];
yk3 = new double[ylen];
yk4 = new double[ylen];
yk5 = new double[ylen];
z = new double[ylen];
err2 = new double[ylen];
}
if (y.length == 0 || k1.length == 0)
System.out.println("oops");
k1 = mySystem.calculateDerivative(x,y,k1);
for(int i=0;i<ylen;i++){
k1[i] *= hval;
yk1[i]=y[i]+k1[i]*0.25;
}
k2 = mySystem.calculateDerivative(x+quarter_h,yk1,k2);
for(int i=0;i<ylen;i++){
k2[i] *= hval;
yk2[i]=y[i]+k1[i]*3.0/32.0+k2[i]*9.0/32.0;
}
k3 = mySystem.calculateDerivative(x+threeEights_h,yk2,k3);
for(int i=0;i<ylen;i++){
k3[i] *= hval;
yk3[i]=y[i]+k1[i]*1932.0/2197.0 - k2[i]*7200.0/2197.0 + k3[i]*7296.0/2197.0;
}
k4 = mySystem.calculateDerivative(x+twelveThirteenths_h,yk3,k4);
for(int i=0;i<ylen;i++){
k4[i] *= hval;
yk4[i]= y[i]+k1[i]*(439.0/216.0)-k2[i]*8.0 + k3[i]*(3680.0/513.0) - k4[i]*(845.0/4104.0);
}
k5 = mySystem.calculateDerivative(x+hval,yk4,k5);
for(int i=0;i<ylen;i++){
k5[i] *= hval;
yk5[i] = y[i] -k1[i]*(8.0/27.0) + k2[i]*2 - k3[i]*(3544.0/2565.0) + k4[i]*(1859.0/4104.0) - k5[i]*(11.0/40.0);
}
k6 = mySystem.calculateDerivative(x+half_h,yk5,k6);
for(int i=0;i<ylen;i++)
k6[i] *= hval;
double s=MesquiteDouble.infinite;
for(int i=0;i<nextY.length;i++){
nextY[i] = y[i] + (25.0/216.0)*k1[i]+(1408.0/2565.0)*k3[i]+(2197.0/4104.0)*k4[i]-(1.0/5.0)*k5[i];
z[i] = y[i] + (16.0/135.0)*k1[i] + (6656.0/12825.0)*k3[i] + (28561.0/56430.0)*k4[i] - (9.0/50.0)*k5[i] + (2.0/55.0)*k6[i];
err2[i] = Math.abs((1.0/360.0)*k1[i] + (-128.0/4275.0)*k3[i] + (-2197.0/75240.0)*k4[i] + (1.0/50.0)*k5[i] + (2.0/55.0)*k6[i]);
double part5a = (y[i] + (16.0/135.0)*k1[i] + (6656.0/12825.0)*k3[i] + (28561.0/56430.0)*k4[i] - (9.0/50.0)*k5[i] + (2.0/55.0)*k6[i]);
double part5b = (y[i] + (25.0/216.0)*k1[i]+(1408.0/2565.0)*k3[i]+(2197.0/4104.0)*k4[i]-(1.0/5.0)*k5[i]);
double part5c = part5a-part5b;
double part5 = (y[i] + (16.0/135.0)*k1[i] + (6656.0/12825.0)*k3[i] + (28561.0/56430.0)*k4[i] - (9.0/50.0)*k5[i] + (2.0/55.0)*k6[i]) - (y[i] + (25.0/216.0)*k1[i]+(1408.0/2565.0)*k3[i]+(2197.0/4104.0)*k4[i]-(1.0/5.0)*k5[i]);
double myerr = z[i]-nextY[i];
if (myerr != 0.0){
double si = fourthRootOneHalf*Math.exp(0.25*Math.log(((tol*hval)/Math.abs(part5c))));
if (si < s)
s = si;
}
}
if (s != MesquiteDouble.infinite)
h.setValue(hval*s);
return nextY;
}
}
|
lgpl-3.0
|
SunDwarf/ButterflyNet
|
bfnet/packets/Packets.py
|
3163
|
import struct
import collections
from bfnet import util
class _MetaPacket(type):
"""
This Metaclass exists only to prepare an ordered dict.
"""
@classmethod
def __prepare__(mcs, name, bases):
return collections.OrderedDict()
class BasePacket(object, metaclass=_MetaPacket):
"""
A BasePacket is the base class for all Packet types.
This just creates a few stub methods.
"""
# Define a default id.
# Packet IDs are ALWAYS unsigned, so this will never meet.
id = -1
# Define a default endianness.
# This is ">" for network endianness by default.
_endianness = ">"
def __init__(self, pbf):
"""
Default init method.
"""
self.butterfly = pbf
def on_creation(self):
"""
Called just after your packet object is created.
"""
pass
def create(self, data: bytes):
"""
Create a new Packet.
:param data: The data to use.
:return: If the creation succeeded or not.
"""
self.on_creation()
def autopack(self) -> bytes:
"""
Attempt to autopack your data correctly.
This does two things:
- Scan your class dictionary for all non-function and struct-packable
items.
- Infer their struct format type, build a format string, then pack them.
:return: The packed bytes data.
"""
# Get the variables.
to_fmt = []
v = vars(self)
for variable, val in v.items():
# Get a list of valid types.
if type(val) not in [bytes, str, int, float]:
self.butterfly.logger.debug("Found un-packable type: {}, skipping".format(type(val)))
elif variable.startswith("_"):
self.butterfly.logger.debug("Found private variable {}, skipping".format(variable))
elif variable.lower() == "id":
self.butterfly.logger.debug("Skipping ID variable")
else:
to_fmt.append(val)
packed = util.auto_infer_struct_pack(*to_fmt, pack=True)
return packed
class Packet(BasePacket):
"""
A standard Packet type.
This extends from BasePacket, and adds useful details that you'll want to use.
"""
def __init__(self, pbf):
"""
Create a new Packet type.
:return:
"""
super().__init__(pbf)
self._original_data = {}
def create(self, data: dict) -> bool:
"""
Create a new Packet.
:param data: The data to use.
This data should have the PacketButterfly header stripped.
:return: A boolean, True if we need no more processing, and False if we process ourself.
"""
self._original_data = data
self.unpack(data)
return True
def unpack(self, data: dict) -> bool:
"""
Unpack the data for the packet.
:return: A boolean, if it was unpacked.
"""
return True
def gen(self) -> bytes:
"""
Generate a new set of data to write to the connection.
:return:
"""
|
lgpl-3.0
|
contao-bootstrap/grid
|
src/Component/ContentElement/GridStartElement.php
|
1994
|
<?php
/**
* Contao Bootstrap grid.
*
* @package contao-bootstrap
* @subpackage Grid
* @author David Molineus <david.molineus@netzmacht.de>
* @copyright 2017-2020 netzmacht David Molineus. All rights reserved.
* @license https://github.com/contao-bootstrap/grid/blob/master/LICENSE LGPL 3.0-or-later
* @filesource
*/
declare(strict_types=1);
namespace ContaoBootstrap\Grid\Component\ContentElement;
use ContaoBootstrap\Grid\Exception\GridNotFound;
use ContaoBootstrap\Grid\GridIterator;
/**
* Class GridStartElement.
*
* @package ContaoBootstrap\Grid\Component\ContentElement
*/
final class GridStartElement extends AbstractGridElement
{
/**
* Template name.
*
* @var string
*/
protected $templateName = 'ce_bs_gridStart';
/**
* {@inheritdoc}
*/
public function generate(): string
{
if ($this->isBackendRequest()) {
$iterator = $this->getIterator();
return $this->renderBackendView($this->getModel(), $iterator);
}
return parent::generate();
}
/**
* {@inheritdoc}
*/
protected function prepareTemplateData(array $data): array
{
$data = parent::prepareTemplateData($data);
$iterator = $this->getIterator();
if ($iterator) {
$data['rowClasses'] = $iterator->row();
$data['columnClasses'] = $iterator->current();
}
return $data;
}
/**
* {@inheritDoc}
*/
protected function getIterator():? GridIterator
{
try {
$provider = $this->getGridProvider();
$iterator = $provider->getIterator('ce:' . $this->get('id'), (int) $this->get('bs_grid'));
$this->responseTagger->addTags(['contao.db.tl_bs_grid.' . $this->get('bs_grid')]);
return $iterator;
} catch (GridNotFound $e) {
// Do nothing. In backend view an error is shown anyway.
return null;
}
}
}
|
lgpl-3.0
|
artirix/browsercms
|
lib/cms/authentication/test_password_strategy.rb
|
1133
|
module Cms
module Authentication
# For testing external authentication.
class TestPasswordStrategy < Devise::Strategies::Authenticatable
EXPECTED_LOGIN = EXPECTED_PASSWORD = 'test'
def authenticate!
if(authentication_hash[:login] == password && password == EXPECTED_PASSWORD)
user = Cms::ExternalUser.authenticate(authentication_hash[:login], 'Test Password', {first_name: "Test", last_name: "User"})
user.authorize(Cms::UsersService::GROUP_CMS_ADMIN, Cms::UsersService::GROUP_CONTENT_EDITOR)
success!(user)
else
pass
end
end
end
end
end
Warden::Strategies.add(:test_password, Cms::Authentication::TestPasswordStrategy)
# NOTE: To enable a custom password strategy for BrowserCMS you must also add it to to the devise configuration.
#
# For example enable the test_password strategy above by adding the following to config/initializers/devise.rb
# # Add test_password strategy BEFORE other CMS authentication strategies
# config.warden do |manager|
# manager.default_strategies(:scope => :cms_user).unshift :test_password
# end
|
lgpl-3.0
|
linxdcn/iS3
|
IS3-Extensions/IS3-ShieldTunnel/Serialization/TunnelDGObjectLoader.cs
|
2686
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IS3.Core;
using IS3.Core.Serialization;
namespace IS3.ShieldTunnel.Serialization
{
#region Copyright Notice
//************************ Notice **********************************
//** This file is part of iS3
//**
//** Copyright (c) 2015 Tongji University iS3 Team. All rights reserved.
//**
//** This library is free software; you can redistribute it and/or
//** modify it under the terms of the GNU Lesser General Public
//** License as published by the Free Software Foundation; either
//** version 3 of the License, or (at your option) any later version.
//**
//** This library is distributed in the hope that it will be useful,
//** but WITHOUT ANY WARRANTY; without even the implied warranty of
//** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//** Lesser General Public License for more details.
//**
//** In addition, as a special exception, that plugins developed for iS3,
//** are allowed to remain closed sourced and can be distributed under any license .
//** These rights are included in the file LGPL_EXCEPTION.txt in this package.
//**
//**************************************************************************
#endregion
public class TunnelDGObjectLoader
{
protected TunnelDbDataLoader _dbLoader;
public TunnelDGObjectLoader(DbContext dbContext)
{
_dbLoader = new TunnelDbDataLoader(dbContext);
}
public bool LoadTunnels(DGObjects objs)
{
DGObjectsDefinition def = objs.definition;
if (def == null)
return false;
bool success = _dbLoader.ReadTunnels(objs,
def.TableNameSQL, def.ConditionSQL, def.OrderSQL);
return success;
}
public bool LoadAxes(DGObjects objs)
{
DGObjectsDefinition def = objs.definition;
if (def == null)
return false;
bool success = _dbLoader.ReadTunnelAxes(objs,
def.TableNameSQL, def.ConditionSQL, def.OrderSQL);
return success;
}
public bool LoadSLType(DGObjects objs)
{
DGObjectsDefinition def = objs.definition;
if (def == null)
return false;
bool success = _dbLoader.ReadSLType(objs,
def.TableNameSQL, def.ConditionSQL, def.OrderSQL);
return success;
}
}
}
|
lgpl-3.0
|
dbolkensteyn/sonarlint-vs
|
src/Tests/SonarLint.UnitTest/TestCases/StreamReadStatement.cs
|
731
|
using System.Collections.Generic;
using System.IO;
namespace Tests.Diagnostics
{
public class StreamReadStatement
{
public StreamReadStatement(string fileName)
{
using (var stream = File.Open(fileName, FileMode.Open))
{
var result = new byte[stream.Length];
stream.Read(result, 0, (int)stream.Length); // Noncompliant
var l = stream.Read(result, 0, (int)stream.Length);
stream.ReadAsync(result, 0, (int)stream.Length); // Noncompliant
await stream.ReadAsync(result, 0, (int)stream.Length); // Noncompliant
stream.Write(result, 0, (int)stream.Length);
}
}
}
}
|
lgpl-3.0
|
gingerjiang/easycms
|
src/main/java/easycms/base/CrudDao.java
|
925
|
/**
*
*/
package easycms.base;
import java.util.List;
/**
* DAO支持类实现
*/
public interface CrudDao<T> {
/**
* 获取单条数据
* @param id
* @return
*/
public T get(Integer id);
/**
* 获取单条数据
* @param entity
* @return
*/
public T get(T entity);
/**
* 查询数据列表
* @param entity
* @return
*/
public List<T> findList(T entity);
/**
* 分页查询数据
* @param entity
* @return
*/
public List<T> findPage(T entity);
public int findCount(T entity);
/**
* 插入数据
* @param entity
* @return
*/
public int insert(T entity);
/**
* 更新数据
* @param entity
* @return
*/
public int update(T entity);
/**
* 删除数据
* @param id
* @see public int delete(T entity)
* @return
*/
public int delete(Integer id);
/**
* 删除数据
* @param entity
* @return
*/
public int delete(T entity);
}
|
lgpl-3.0
|
aimeos/ai-admin-jqadm
|
admin/jqadm/src/Admin/JQAdm/Common/Decorator/Iface.php
|
676
|
<?php
/**
* @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
* @copyright Aimeos (aimeos.org), 2015-2022
* @package Admin
* @subpackage JQAdm
*/
namespace Aimeos\Admin\JQAdm\Common\Decorator;
/**
* Decorator interface for JQAdm clients.
*
* @package Admin
* @subpackage JQAdm
*/
interface Iface
extends \Aimeos\Admin\JQAdm\Iface
{
/**
* Initializes a new client decorator object.
*
* @param \Aimeos\Admin\JQAdm\Iface $client Admin object
* @param \Aimeos\MShop\Context\Item\Iface $context Context object with required objects
*/
public function __construct( \Aimeos\Admin\JQAdm\Iface $client, \Aimeos\MShop\Context\Item\Iface $context );
}
|
lgpl-3.0
|
Superbeest/Core
|
core4/system/error/exception/DuplicateFilterException.class.php
|
1150
|
<?php
/**
* DuplicateFilterException.class.php
*
* Copyright c 2015, SUPERHOLDER. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or at your option any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
namespace System\Error\Exception;
if (!defined('System'))
{
die ('Hacking attempt');
}
/**
* The DuplicateFilterException class.
* This exception is thrown when there is already a filter attached to the given field
* @package \System\Error\Exception
*/
class DuplicateFilterException extends \Exception
{
}
|
lgpl-3.0
|
daitangio/exchangews
|
src/msgviewer/java/net/sourceforge/MSGViewer/Plugins/poi/Plugin.java
|
1859
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.sourceforge.MSGViewer.Plugins.poi;
import at.redeye.FrameWork.base.AutoMBox;
import at.redeye.FrameWork.base.Root;
import at.redeye.FrameWork.widgets.helpwindow.HelpFileLoader;
/**
*
* @author martin
*/
public class Plugin implements at.redeye.FrameWork.Plugin.Plugin
{
public static String NAME = "Apache POI";
Root root;
public String getName()
{
return NAME;
}
public String getLicenceText()
{
final StringBuilder builder = new StringBuilder();
new AutoMBox( Plugin.class.getSimpleName() )
{
@Override
public void do_stuff() throws Exception {
HelpFileLoader helper = new HelpFileLoader();
String licence = helper.loadHelp("/net/sourceforge/MSGViewer/Plugins/poi", "Apache");
builder.append(licence);
}
};
return builder.toString();
}
public void initPlugin(Object obj)
{
}
public boolean isAvailable() {
return true;
}
@Override
public String toString()
{
return getName() + " " + getVersion();
}
public String getChangeLog() {
final StringBuilder builder = new StringBuilder();
new AutoMBox( Plugin.class.getSimpleName() )
{
@Override
public void do_stuff() throws Exception {
HelpFileLoader helper = new HelpFileLoader();
String changelog = helper.loadHelp("/net/sourceforge/MSGViewer/Plugins/poi", "ChangeLog");
builder.append(changelog);
}
};
return builder.toString();
}
public String getVersion() {
return Version.getVersion();
}
}
|
lgpl-3.0
|
joergdw/antconflictbeh
|
src/sim/app/antDefenseAIs/model/LasiusNiger.scala
|
3951
|
/*
* Copyright © 2013 by Jörg D. Weisbarth
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License 3 as published by
* the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY.
*
* See the License.txt file for more details.
*/
package sim.app.antDefenseAIs.model
import sim.engine.SimState
/**
* Behaviour configuration of an Lasius Niger ant ant
*
* @param emotionalDwellTime How long an individual stays in an individual state before going to another
* @param notBored Value of boredom if the ant is not bored at all
*/
private[antDefenseAIs] class LN_BehaviourConf(
val emotionalDwellTime: Int,
val notBored: Int,
override val alpha: Double,
override val explorationRate: Double,
override val gamma: Double)
extends BehaviourConf(alpha, explorationRate, gamma)
/**
* AntWorker with the usual strategies.
*
* Differs only in emotion changing behaviour.
*
* @param tribeID Tribe the ant belongs to
* @param world World the ant lives on
*/
private[antDefenseAIs] abstract class LasiusNiger(
override val tribeID: Int,
override val world: World,
val behaviourConf: LN_BehaviourConf)
extends AntWorker with StandardPheroSystem with EconomicStandardBehaviour with ConflictBehaviour {
//------------------------------ Initialise configuration ----------------------------------------
override val alpha = behaviourConf.alpha
override val explorationRate = behaviourConf.explorationRate
override val gamma = behaviourConf.gamma
override val notBored = behaviourConf.notBored
/** How long an individual stays in an individual state before going to another */
val emotionalDwellTime: Int = behaviourConf.emotionalDwellTime
/**
* Constructs ant with the information of the given ant
*
* @param ant Ant ant giving the information of construction
* @return Ant of the same colony in the same simulation
*/
def this(ant: Ant, behaviourConf: LN_Normal_BehaviourConf) = this(ant.tribeID, ant.world, behaviourConf)
/**
* Possible emotional states of an ant
*/
protected[this] object Emotion extends Enumeration {
val aggressive = Value("Aggressive") /** Ant attacks near foreign-colony ants */
val fleeing = Value("Fleeing") /** Ant flees into direction of its home */
/** Ant ignores ants of stranger colonies and changes emotional state if it receives a hit */
val normal = Value("Normal")
/** Ant changes emotional state as soon as it sees ants of stranger colonies or receives a hit */
val undecided = Value("Undecided")
}
protected[this] var emotion: Emotion.Value = Emotion.undecided /** Current emotional state */
protected[this] var nextEmotionChange = emotionalDwellTime /** Time until the next state relaxation */
/**
* Cools down the emotional state of the ant until `undecided`
*/
protected[this] def relax() {
if (nextEmotionChange <= 0)
emotion = Emotion.undecided
else
nextEmotionChange -= 1
}
//-------------------------- (Additional) Basic operations ----------------------------------------
/**
* Adapts the emotional state of the ant by changing it either to aggressive state, normal state
* or to defensive state.
*/
def adaptState()
//------------------------- Behaviour description -----------------------------------------------
/**
* Ant acts based on its current emotional state.
*
* @param state Parameter not used
*/
override def step(state: SimState) {
if (emotion == Emotion.undecided && enemyClose())
adaptState()
emotion match {
case Emotion.aggressive => if (enemyClose()) attackNearEnemy() else actEconomically()
case Emotion.fleeing => followHomeWay()
case e if e == Emotion.normal || e == Emotion.undecided => actEconomically()
}
relax()
}
}
|
lgpl-3.0
|
pingping-jiang6141/uexXmlHttpMgr
|
src/org/zywx/wbpalmstar/plugin/uexmultiHttp/EHttpPost.java
|
19367
|
package org.zywx.wbpalmstar.plugin.uexmultiHttp;
import android.os.Process;
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.zywx.wbpalmstar.base.BDebug;
import org.zywx.wbpalmstar.base.BUtility;
import org.zywx.wbpalmstar.platform.certificates.Http;
import org.zywx.wbpalmstar.widgetone.dataservice.WWidgetData;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.UUID;
import java.util.zip.GZIPInputStream;
public class EHttpPost extends Thread implements HttpTask, HttpClientListener {
private String boundary;
private static final String LINE_FEED = "\r\n";
private int mTimeOut;
private boolean mRunning;
private boolean mCancelled;
private String mUrl;
private String mXmlHttpID;
private EUExXmlHttpMgr mXmlHttpMgr;
private URL mURL;
private HttpURLConnection mConnection;
private String mCertPassword;
private String mCertPath;
private InputStream mInStream;
private boolean mHasLocalCert;
private String mBody;
private String mRedirects;
private File mOnlyFile;
private ArrayList<HPair> mMultiData;
private boolean mFromRedirects;
private Hashtable<String, String> mHttpHead;
private PrintWriter writer;
private Map<String, List<String>> headers;
static final int BODY_TYPE_TEXT = 0;
static final int BODY_TYPE_FILE = 1;
private WWidgetData curWData = null;
private int responseCode = -1;
private String responseMessage = "";
private String charset = HTTPConst.UTF_8;
private OutputStream outputStream;
private long mTotalSize = 0;
private int mUploadedSize = 0;
private int mOnDataCallbackId;
private int mOnProgressCallbackId;
public EHttpPost(String inXmlHttpID, String url, int timeout,
EUExXmlHttpMgr xmlHttpMgr) {
setName("SoTowerMobile-HttpPost");
mUrl = url;
mTimeOut = timeout;
mXmlHttpMgr = xmlHttpMgr;
mXmlHttpID = inXmlHttpID;
initNecessaryHeader();
boundary = UUID.randomUUID().toString();;
}
@Override
public void setData(int inDataType, String inKey, String inValue) {
if (null == inKey || inKey.length() == 0) {
inKey = "";
}
if (null == inValue || inValue.length() == 0) {
inValue = "";
}
if (null == mMultiData) {
mMultiData = new ArrayList<HPair>();
}
try {
if (BODY_TYPE_FILE == inDataType) {
String wp = mXmlHttpMgr.getWidgetPath();
// int wtp = mXmlHttpMgr.getWidgetType();
// inValue = BUtility.makeRealPath(inValue, wp, wtp);
inValue=BUtility.getRealPathWithCopyRes(mXmlHttpMgr.mBrwView,inValue);
}
if (checkData(inKey, inValue)) {
return;
}
HPair en = new HPair(inDataType, inKey, inValue);
mMultiData.add(en);
} catch (Exception e) {
e.printStackTrace();
}
}
public void setCertificate(String cPassWord, String cPath) {
mHasLocalCert = true;
mCertPassword = cPassWord;
mCertPath = cPath;
}
private boolean checkData(String key, String value) {
for (HPair pair : mMultiData) {
if (key.equals(pair.key)) {
pair.value = value;
return true;
}
}
return false;
}
@Override
public void send() {
if (mRunning || mCancelled) {
return;
}
mRunning = true;
start();
}
@Override
public void run() {
if (mCancelled) {
return;
}
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
doInBackground();
}
protected void doInBackground() {
if (mCancelled) {
return;
}
String result = "";
boolean isSuccess = false;
final String curUrl;
if (null == mUrl) {
return;
}
if (mFromRedirects && null != mRedirects) {
curUrl = mRedirects;
} else {
curUrl = mUrl;
}
try {
mURL = new URL(curUrl);
if (curUrl.startsWith("https")) {
if (mHasLocalCert) {
mConnection = Http.getHttpsURLConnectionWithCert(mURL, mCertPassword,
mCertPath, mXmlHttpMgr.getContext());
} else {
mConnection = Http.getHttpsURLConnection(curUrl);
}
} else {
mConnection = (HttpURLConnection) mURL.openConnection();
}
mConnection.setConnectTimeout(mTimeOut);
mConnection.setUseCaches(false);
mConnection.setDoOutput(true);
mConnection.setDoInput(true);
addHeaders(curUrl);
} catch (MalformedURLException e) {
if (BDebug.DEBUG) {
e.printStackTrace();
}
} catch (Exception e) {
if (BDebug.DEBUG) {
e.printStackTrace();
}
}
try {
//设置总大小
calculateTotalSize();
if (mTotalSize!=0) {
mConnection.setChunkedStreamingMode(4096);
}
outputStream = mConnection.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset));
if (null != mOnlyFile) {
createInputStemEntity();
} else if (null != mMultiData) {
if (!containOctet()) {
createFormEntity();
} else {
//含有文件
createMultiEntity();
}
} else if (null != mBody) {
writer.write(mBody);
}
result=finish(curUrl);
handleCookie(curUrl);
isSuccess = true;
} catch (Exception e) {
if (BDebug.DEBUG){
e.printStackTrace();
}
isSuccess = false;
if (e instanceof SocketTimeoutException) {
result = EUExXmlHttpMgr.CONNECT_FAIL_TIMEDOUT;
} else {
result = EUExXmlHttpMgr.CONNECT_FAIL_CONNECTION_FAILURE;
}
} finally {
if (null != mInStream) {
try {
mInStream.close();
} catch (Exception e) {
if (BDebug.DEBUG) {
e.printStackTrace();
}
}
}
if (mConnection!=null) {
mConnection.disconnect();
mConnection=null;
}
}
mXmlHttpMgr.onFinish(mXmlHttpID);
if (mCancelled) {
return;
}
mXmlHttpMgr.printResult(mXmlHttpID, curUrl, result);
callbackResult(isSuccess, result);
return;
}
private void callbackResult(boolean isSuccess, String result) {
if (isSuccess) {
JSONObject jsonObject = new JSONObject();
try {
if (headers != null && !headers.isEmpty()) {
JSONObject jsonHeaders = new JSONObject();
for (Map.Entry<String, List<String>> header : headers.entrySet()) {
if (header.getKey()!=null) {
jsonHeaders.put(header.getKey(),
header.getValue());
}
}
jsonObject.put(EUExXmlHttpMgr.PARAMS_JSON_KEY_HEADERS,
jsonHeaders);
}
jsonObject.put(EUExXmlHttpMgr.PARAMS_JSON_KEY_STATUSCODE,
responseCode);
jsonObject.put(EUExXmlHttpMgr.PARAMS_JSON_KEY_STATUSMESSAGE,
responseMessage);
jsonObject
.put(EUExXmlHttpMgr.PARAMS_JSON_KEY_RESPONSEERROR, "");
} catch (Exception e) {
if (BDebug.DEBUG){
e.printStackTrace();
}
}
mXmlHttpMgr.callBack(mXmlHttpID, result, responseCode,
jsonObject,mOnDataCallbackId);
} else {
mXmlHttpMgr.errorCallBack(mXmlHttpID, result, responseCode, "",mOnDataCallbackId
,mOnProgressCallbackId);
}
}
private String finish(String curUrl) throws Exception {
String response = null;
if (mMultiData!=null&&containOctet()) {
writer.flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
}
writer.close();
responseCode = mConnection.getResponseCode();
headers=mConnection.getHeaderFields();
mXmlHttpMgr.printHeader(responseCode, mXmlHttpID, curUrl, false, headers);
switch (responseCode) {
case HttpURLConnection.HTTP_OK:
byte[] bResult = toByteArray(mConnection);
response = BUtility.transcoding(new String(bResult, HTTPConst.UTF_8));
mConnection.disconnect();
break;
case HttpURLConnection.HTTP_MOVED_PERM:
case HttpURLConnection.HTTP_MOVED_TEMP:
case 307:
String reUrl = mConnection.getHeaderField("Location");
if (null != reUrl && reUrl.length() > 0) {
mRedirects = reUrl;
mFromRedirects = true;
handleCookie(curUrl);
doInBackground();
return "";
}
break;
default:
break;
}
writer.close();
return response;
}
private byte[] toByteArray(HttpURLConnection conn) throws Exception {
if (null == conn) {
return new byte[]{};
}
mInStream = conn.getInputStream();
if (mInStream == null) {
return new byte[]{};
}
long len = conn.getContentLength();
if (len > Integer.MAX_VALUE) {
throw new Exception(
"HTTP entity too large to be buffered in memory");
}
String contentEncoding = conn.getContentEncoding();
if (null != contentEncoding) {
if ("gzip".equalsIgnoreCase(contentEncoding)) {
mInStream = new GZIPInputStream(mInStream, 2048);
}
}
return IOUtils.toByteArray(mInStream);
}
private void handleCookie(String url) {
Map<String,List<String>> map=mConnection.getHeaderFields();
Set<String> set=map.keySet();
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
if (HTTPConst.SET_COOKIE.equals(key)) {
List<String> list = map.get(key);
for (String setCookie : list) {
mXmlHttpMgr.setCookie(url, setCookie);
}
}
}
mXmlHttpMgr.setCookie(url, mConnection.getHeaderField(HTTPConst.COOKIE));
mXmlHttpMgr.setCookie(url, mConnection.getHeaderField(HTTPConst.COOKIE2));
}
private boolean containOctet() {
for (HPair pair : mMultiData) {
if (pair.type == BODY_TYPE_FILE) {
return true;
}
}
return false;
}
/**
* Adds a form field to the request
*
* @param name field name
* @param value field value
*/
public void addFormField(String name, String value) {
writer.append(("--" + boundary)).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
.append(LINE_FEED);
writer.append("Content-Type: text/plain; charset=" + charset).append(
LINE_FEED);
writer.append(LINE_FEED);
writer.append(value).append(LINE_FEED);
writer.flush();
}
public void addFilePart(String fieldName, File uploadFile)
throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append(
"Content-Disposition: form-data; name=\"" + fieldName
+ "\"; filename=\"" + fileName + "\"")
.append(LINE_FEED);
writer.append(
"Content-Type: "
+ URLConnection.guessContentTypeFromName(fileName))
.append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
flushOutputStream(uploadFile);
writer.append(LINE_FEED);
writer.flush();
}
private void flushOutputStream(File uploadFile) throws IOException {
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
mUploadedSize+=bytesRead;
onProgressChanged(100*(float) mUploadedSize/(float) mTotalSize);
}
outputStream.flush();
inputStream.close();
}
private void createFormEntity() {
try {
writer.write(getQuery(mMultiData));
} catch (UnsupportedEncodingException e) {
if (BDebug.DEBUG) {
e.printStackTrace();
}
}
}
private String getQuery(List<HPair> params) throws UnsupportedEncodingException
{
StringBuilder result = new StringBuilder();
boolean first = true;
for (HPair pair : params)
{
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(pair.key,charset));
result.append("=");
result.append(URLEncoder.encode(pair.value,charset));
}
return result.toString();
}
private void createInputStemEntity() throws IOException {
flushOutputStream(mOnlyFile);
}
private void calculateTotalSize(){
if (null != mOnlyFile) {
mTotalSize=mOnlyFile.length();
} else if (null != mMultiData) {
for (HPair pair : mMultiData) {
if (BODY_TYPE_FILE == pair.type) {
File itemFile=new File(pair.value);
mTotalSize+=itemFile.length();
}
}
}
}
private void createMultiEntity() {
try {
for (HPair pair : mMultiData) {
if (BODY_TYPE_FILE == pair.type) {
addFilePart(pair.key,new File(pair.value));
} else if (BODY_TYPE_TEXT == pair.type) {
addFormField(pair.key, pair.value);
}
}
} catch (Exception e) {
}
}
@Override
public void onProgressChanged(float newProgress) {
int progress = (int) newProgress;
mXmlHttpMgr.progressCallBack(mXmlHttpID, progress,mOnProgressCallbackId);
}
@Override
public void cancel() {
mCancelled = true;
if (null != mMultiData) {
mMultiData.clear();
}
if (null != mInStream) {
try {
mInStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (null != mConnection) {
mConnection.disconnect();
mConnection = null;
}
try {
interrupt();
} catch (Exception e) {
}
mTimeOut = 0;
mUrl = null;
mRunning = false;
mCertPassword = null;
mCertPath = null;
mBody = null;
}
@Override
public void setBody(String body) {
mBody = body;
}
@Override
public void setInputStream(File file) {
mOnlyFile = file;
}
@Override
public void setHeaders(String headJson) {
try {
JSONObject json = new JSONObject(headJson);
Iterator<?> keys = json.keys();
while (keys.hasNext()) {
String key = (String) keys.next();
String value = json.getString(key);
mHttpHead.put(key, value);
}
} catch (Exception e) {
e.printStackTrace();
}
}
private void addHeaders(String curUrl) {
String cookie = mXmlHttpMgr.getCookie(curUrl);
if (null != cookie) {
mConnection.setRequestProperty(HTTPConst.COOKIE, cookie);
}
Set<Entry<String, String>> entrys = mHttpHead.entrySet();
for (Map.Entry<String, String> entry : entrys) {
mConnection.setRequestProperty(entry.getKey(), entry.getValue());
}
if (null != curWData) {
mConnection.setRequestProperty(XmlHttpUtil.KEY_APPVERIFY, XmlHttpUtil.getAppVerifyValue(curWData, System.currentTimeMillis()));
mConnection.setRequestProperty(XmlHttpUtil.XMAS_APPID, curWData.m_appId);
}
if (null != mMultiData&&containOctet()){
mConnection.setRequestProperty("Content-Type","multipart/form-data;boundary="+boundary);
}
}
private void initNecessaryHeader() {
mHttpHead = new Hashtable<String, String>();
mHttpHead.put("Accept", "*/*");
mHttpHead.put("Charset", charset);
mHttpHead.put("User-Agent", EHttpGet.UA);
mHttpHead.put("Connection", "Keep-Alive");
mHttpHead.put("Accept-Encoding", "gzip, deflate");
}
@Override
public void setAppVerifyHeader(WWidgetData curWData) {
this.curWData = curWData;
}
@Override
public void setCallbackId(int onDataCallbackId, int onProgressCallbackId) {
this.mOnDataCallbackId=onDataCallbackId;
this.mOnProgressCallbackId=onProgressCallbackId;
}
}
|
lgpl-3.0
|
ptitjes/jlato
|
src/main/java/org/jlato/tree/expr/MemberValuePair.java
|
2680
|
/*
* Copyright (C) 2015-2016 Didier Villevalois.
*
* This file is part of JLaTo.
*
* JLaTo is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* JLaTo is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JLaTo. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jlato.tree.expr;
import org.jlato.tree.Node;
import org.jlato.tree.TreeCombinators;
import org.jlato.tree.name.Name;
import org.jlato.util.Mutation;
/**
* An annotation member value pair.
*/
public interface MemberValuePair extends Node, TreeCombinators<MemberValuePair> {
/**
* Returns the name of this annotation member value pair.
*
* @return the name of this annotation member value pair.
*/
Name name();
/**
* Replaces the name of this annotation member value pair.
*
* @param name the replacement for the name of this annotation member value pair.
* @return the resulting mutated annotation member value pair.
*/
MemberValuePair withName(Name name);
/**
* Mutates the name of this annotation member value pair.
*
* @param mutation the mutation to apply to the name of this annotation member value pair.
* @return the resulting mutated annotation member value pair.
*/
MemberValuePair withName(Mutation<Name> mutation);
/**
* Replaces the name of this annotation member value pair.
*
* @param name the replacement for the name of this annotation member value pair.
* @return the resulting mutated annotation member value pair.
*/
MemberValuePair withName(String name);
/**
* Returns the value of this annotation member value pair.
*
* @return the value of this annotation member value pair.
*/
Expr value();
/**
* Replaces the value of this annotation member value pair.
*
* @param value the replacement for the value of this annotation member value pair.
* @return the resulting mutated annotation member value pair.
*/
MemberValuePair withValue(Expr value);
/**
* Mutates the value of this annotation member value pair.
*
* @param mutation the mutation to apply to the value of this annotation member value pair.
* @return the resulting mutated annotation member value pair.
*/
MemberValuePair withValue(Mutation<Expr> mutation);
}
|
lgpl-3.0
|
snim2mirror/openihm
|
src/openihm/outputs/routines/report_householdsincome.py
|
22368
|
#!/usr/bin/env python
"""
This file is part of open-ihm.
open-ihm 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.
open-ihm 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 open-ihm. If not, see <http://www.gnu.org/licenses/>.
"""
# -*- coding: cp1252 -*-
import includes.mysql.connector as connector
from data.config import Config
from data.database import Database
from data.report_settingsmanager import ReportsSettingsManager
from report_householdsincome_query import HouseholdIncomeQuery
from report_adultequivalent import AdultEquivalent
class HouseholdIncome:
def __init__(self):
self.database = Database()
self.config = Config.dbinfo().copy()
def buildPCharacteristicsQuery(self,pcharacteristics, projectid):
''' build query for selecting households that meet selected personal characteristics from the report interface'''
basequery = ''
if len(pcharacteristics)!=0:
basequery = '''SELECT personalcharacteristics.hhid, personalcharacteristics.pid FROM personalcharacteristics WHERE
personalcharacteristics.pid=%s''' % (projectid)
for pcharacteristic in pcharacteristics:
basequery = basequery + " AND personalcharacteristics.characteristic='%s' AND personalcharacteristics.charvalue='Yes'" % (pcharacteristic)
return basequery
def buildHCharacteristicsQuery(self,hcharacteristics, projectid):
''' build query for selecting households that meet selected household characteristics from the report interface'''
basequery = ''
if len(hcharacteristics)!=0:
basequery = '''SELECT householdcharacteristics.hhid, householdcharacteristics.pid FROM householdcharacteristics WHERE
householdcharacteristics.pid=%s''' % (projectid)
for hcharacteristic in hcharacteristics:
basequery = basequery + " AND householdcharacteristics.characteristic='%s' AND householdcharacteristics.charvalue='Yes'" % (hcharacteristic)
return basequery
def getReportHouseholdIDs(self,query):
reporthouseholdIDs=[]
databaseConnector = Database()
if query !='':
databaseConnector.open()
reporthouseholdIDs = databaseConnector.execSelectQuery( query )
databaseConnector.close()
return reporthouseholdIDs
def buildReportHouseholdIDsQuery(self,projectid,selectedhouseholds,pcharselected,hcharselected):
''' generate report household ids'''
selectedpchars =[]
selectedhchars = []
selectedpchars = pcharselected
selectedhchars = hcharselected
hcharssetting = ReportsSettingsManager()
hcharsTable= hcharssetting.setHCharacteristicsTableName(projectid)
pcharssetting = ReportsSettingsManager()
pharsTable = pcharssetting.setPCharacteristicsTableName(projectid)
householdsquery = self.buildHouseholdsQuery(selectedhouseholds,projectid)
query = ''
if len(selectedhouseholds)!=0:
if len(selectedpchars) ==0 and len(selectedhchars) ==0:
query = householdsquery
householdids = self.getReportHouseholdIDs(query)
elif len(selectedpchars) !=0 and len(selectedhchars) !=0:
pcharsQuery =self.buildPCharacteristicsQuery(pcharselected, projectid)
hcharsQuery = self.buildHCharacteristicsQuery(hcharselected, projectid)
query = '''SELECT * FROM (%s UNION ALL %s UNION ALL %s) AS tbl GROUP BY tbl.hhid HAVING COUNT(*) = 3 ''' % (householdsquery,pcharsQuery,hcharsQuery)
elif len(selectedhchars) !=0:
hcharsQuery = self.buildHCharacteristicsQuery(hcharselected, projectid)
query = '''SELECT * FROM (%s UNION ALL %s) AS tbl GROUP BY tbl.hhid HAVING COUNT(*) = 2 ''' % (householdsquery,hcharsQuery)
elif len(selectedpchars) !=0:
pcharsQuery =self.buildPCharacteristicsQuery(pcharselected, projectid)
query = '''SELECT * FROM (%s UNION ALL %s) AS tbl GROUP BY tbl.hhid HAVING COUNT(*) = 2 ''' % (householdsquery,pcharsQuery)
return query
def buildHouseholdsQuery(self,selectedhouseholds,projectid):
households = tuple(selectedhouseholds)
if len(households)==1:
query = ''' SELECT hhid, pid FROM households WHERE householdname ='%s' AND pid=%s ''' % (households[0],projectid)
else:
query = ''' SELECT hhid, pid FROM households WHERE householdname IN %s AND pid=%s ''' % (households,projectid)
return query
def getFinalIncomeReportTableQuery(self,reporttype,projectid,householdIDs,cropdetails,employmentdetails, livestockdetails,loandetails,transferdetails,wildfoodsdetails):
if reporttype =='Cash Income - Raw' or reporttype =='Cash Income - Standardised':
cropsQuery = self.buildCropIncomeQuery(projectid,cropdetails,householdIDs)
employmentQuery = self.buildEmploymentIncomeQuery(projectid,employmentdetails,householdIDs)
livestockQuery = self.buildLivestockIncomeQuery(projectid,livestockdetails,householdIDs)
loansQuery =''
#loansQuery = self.buildLoanIncomeQuery(projectid,loandetails,householdIDs)
transfersQuery = self.buildTransferIncomeQuery(projectid,transferdetails,householdIDs)
wildfoodsQuery = self.buildWildFoodsIncomeQuery(projectid,wildfoodsdetails,householdIDs)
elif reporttype =='Food Income - Raw' or reporttype =='Food Income - Standardised':
cropsQuery = self.buildCropFIncomeQuery(projectid,cropdetails,householdIDs)
employmentQuery = self.buildEmploymentFIncomeQuery(projectid,employmentdetails,householdIDs)
livestockQuery = self.buildLivestockFIncomeQuery(projectid,livestockdetails,householdIDs)
transfersQuery = self.buildTransferFIncomeQuery(projectid,transferdetails,householdIDs)
wildfoodsQuery = self.buildWildFoodsFIncomeQuery(projectid,wildfoodsdetails,householdIDs)
loansQuery =''
queryconnector = HouseholdIncomeQuery()
query = queryconnector.buildFinalReportQuery (projectid,householdIDs,cropsQuery,employmentQuery,livestockQuery,loansQuery,transfersQuery,wildfoodsQuery)
return query
def buildCropIncomeQuery(self,projectid,cropdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in cropdetails)
allincomesources = 'All'
query =''
if len(cropdetails)!=0:
if allincomesources in cropdetails:
query = '''SELECT hhid,SUM(unitssold * unitprice) AS cropincome FROM cropincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in cropdetails:
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitssold * unitprice,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM cropincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def buildEmploymentIncomeQuery(self,projectid,employmentdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in employmentdetails)
allincomesources = 'All'
query =''
if len(employmentdetails)!=0:
if allincomesources in employmentdetails:
query = '''SELECT hhid,SUM(cashincome) AS employmentcashincome FROM employmentincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in employmentdetails:
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', cashincome,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM employmentincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def buildLivestockIncomeQuery(self,projectid,livestockdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in livestockdetails)
allincomesources = 'All'
query =''
if len(livestockdetails)!=0:
if allincomesources in livestockdetails:
query = '''SELECT hhid,SUM(unitssold * unitprice) AS livestockincome FROM livestockincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in livestockdetails:
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitssold * unitprice,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM livestockincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def buildLoanIncomeQuery(self,projectid,loandetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in loandetails)
allincomesources = 'All'
query =''
if len(loandetails)!=0:
if allincomesources in loandetails:
query = '''SELECT hhid,SUM(creditvalue) AS loanincome FROM creditandloans WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in loandetails:
query = query + ", GROUP_CONCAT(IF (creditsource = '%s', creditvalue,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM creditandloans WHERE pid=%s AND hhid IN (%s) AND creditsource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def buildTransferIncomeQuery(self,projectid,transferdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in transferdetails)
allincomesources = 'All'
query =''
if len(transferdetails)!=0:
if allincomesources in transferdetails:
query = '''SELECT hhid,SUM(cashperyear) AS transferincome FROM transfers WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in transferdetails:
query = query + ", GROUP_CONCAT(IF (sourceoftransfer = '%s', cashperyear,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM transfers WHERE pid=%s AND hhid IN (%s)" % (projectid,houseids)
query = query + " GROUP BY hhid"
return query
def buildWildFoodsIncomeQuery(self,projectid,wildfoodsdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in wildfoodsdetails)
allincomesources = 'All'
query =''
if len(wildfoodsdetails)!=0:
if allincomesources in wildfoodsdetails:
query = '''SELECT hhid,SUM(unitssold * unitprice) AS wildfoodsincome FROM wildfoods WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in wildfoodsdetails:
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitssold * unitprice,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM wildfoods WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def getReportTable(self,query,pid,reporttype):
result = []
databaseConnector = Database()
if query !='':
db = connector.Connect(**self.config)
cursor = db.cursor()
cursor.execute(query)
columns = tuple( [d[0].decode('utf8') for d in cursor.description] ) #get column headers
rows = cursor.fetchall()
for row in rows:
if reporttype == 'Cash Income - Standardised' or reporttype == 'Food Income - Standardised':
hhid = row[0]
householdAE = self.getAdultEquivalent(hhid,pid)
standardisedList = tuple(self.standardiseIncome(row,householdAE))
result.append(dict(zip(columns, standardisedList)))
else:
result.append(dict(zip(columns, row)))
# close database connection
cursor.close()
db.close()
return result
def getAdultEquivalent(self, hhid,pid):
connector = AdultEquivalent()
householdEnergyNeed = connector.calculateHouseholdEnergyReq(hhid,pid)
houseAE = connector.caclulateHouseholdAE(householdEnergyNeed)
return houseAE
def standardiseIncome(self,row,householdAE):
standardisedList =[]
standardisedList.append(row[0])
listlength = len(row)
houseAE = householdAE
for i in range(1,listlength):
stardisedincome = row[i]
if row[i] and householdAE!=0:
print 'house ', row[0]
income = float(row[i])/householdAE
stardisedincome= round(income,2)
standardisedList.append(stardisedincome)
return standardisedList
#Build Queries for Raw Food Income
def buildCropFIncomeQuery(self,projectid,cropdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in cropdetails)
allincomesources = 'All'
query =''
if len(cropdetails)!=0:
if allincomesources in cropdetails:
query = '''SELECT hhid,SUM(unitsconsumed * (SELECT energyvalueperunit FROM setup_foods_crops WHERE setup_foods_crops.name=cropincome.incomesource)) AS 'CropFoodIncome (KCals)'
FROM cropincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in cropdetails:
outputname = myincomesource + '(KCal)'
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitsconsumed * ( SELECT energyvalueperunit FROM setup_foods_crops WHERE name ='%s'),NULL)) AS '%s'" %(myincomesource,myincomesource,outputname)
query = query + " FROM cropincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def buildEmploymentFIncomeQuery(self,projectid,employmentdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in employmentdetails)
allincomesources = 'All'
query =''
if len(employmentdetails)!=0:
if allincomesources in employmentdetails:
query = '''SELECT hhid,SUM(incomekcal) AS 'EmploymentFoodIncome (KCals)' FROM employmentincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in employmentdetails:
outputname = myincomesource + '(KCal)'
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', incomekcal,NULL)) AS '%s'" %(myincomesource,outputname)
query = query + " FROM employmentincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def buildLivestockFIncomeQuery(self,projectid,livestockdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in livestockdetails)
allincomesources = 'All'
query =''
if len(livestockdetails)!=0:
if allincomesources in livestockdetails:
query = '''SELECT hhid,SUM(unitsconsumed * (SELECT energyvalueperunit FROM setup_foods_crops WHERE setup_foods_crops.name=livestockincome.incomesource))
AS 'LivestockFoodIncome (KCals)' FROM livestockincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in livestockdetails:
outputname = myincomesource + '(KCal)'
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitsconsumed * ( SELECT energyvalueperunit FROM setup_foods_crops WHERE name='%s'),NULL)) AS '%s'" %(myincomesource,myincomesource,outputname)
query = query + " FROM livestockincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
print query
return query
def buildTransferFIncomeQuery(self,projectid,transferdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in transferdetails)
allincomesources = 'All'
query =''
if len(transferdetails)!=0:
if allincomesources in transferdetails:
query = '''SELECT hhid,SUM(unitsconsumed * (SELECT energyvalueperunit FROM setup_foods_crops WHERE setup_foods_crops.name=transfers.foodtype)) AS 'TransferFoodIncome (KCals)'
FROM transfers WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in transferdetails:
outputname = myincomesource + '(KCal)'
query = query + ", GROUP_CONCAT(IF (sourceoftransfer = '%s', unitsconsumed *(SELECT energyvalueperunit FROM setup_foods_crops WHERE name='%s' ),NULL)) AS '%s'" %(myincomesource,myincomesource,outputname)
query = query + " FROM transfers WHERE pid=%s AND hhid IN (%s)" % (projectid,houseids)
query = query + " GROUP BY hhid"
return query
def buildWildFoodsFIncomeQuery(self,projectid,wildfoodsdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in wildfoodsdetails)
allincomesources = 'All'
query =''
if len(wildfoodsdetails)!=0:
if allincomesources in wildfoodsdetails:
query = '''SELECT hhid,SUM(unitsconsumed * (SELECT energyvalueperunit FROM setup_foods_crops WHERE setup_foods_crops.name=wildfoods.incomesource))
AS 'WildFoodsIncome (KCals)' FROM wildfoods WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in wildfoodsdetails:
outputname = myincomesource + '(KCal)'
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitsconsumed * ( SELECT energyvalueperunit FROM setup_foods_crops WHERE name ='%s'),NULL)) AS '%s'" %(myincomesource,myincomesource,outputname)
query = query + " FROM wildfoods WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
#Standardised income - Cash Income
def buildStandardisedCropIncomeQuery(self,projectid,cropdetails,householdids):
houseids = ','.join(householdids)
incomesources = ','.join("'" + p + "'" for p in cropdetails)
allincomesources = 'All'
query =''
if len(cropdetails)!=0:
if allincomesources in cropdetails:
query = '''SELECT hhid,SUM(unitssold * unitprice) AS cropincome
FROM cropincome WHERE pid = %s AND hhid IN (%s) GROUP BY hhid''' % (projectid,houseids)
else:
query = "SELECT hhid"
for myincomesource in cropdetails:
query = query + ", GROUP_CONCAT(IF (incomesource = '%s', unitssold * unitprice,NULL)) AS '%s'" %(myincomesource,myincomesource)
query = query + " FROM cropincome WHERE pid=%s AND hhid IN (%s) AND incomesource IN (%s)" % (projectid,houseids,incomesources)
query = query + " GROUP BY hhid"
return query
def getHouseholdAdultEquivalent(self,projectid,householdids):
adultEquivalentCalculator = AdultEquivalent()
householdAdultEquivalent = adultEquivalentCalculator.calculateHouseholdEnergyReq(householdids,projectid)
return householdAdultEquivalent
|
lgpl-3.0
|
n2n/n2n
|
src/app/n2n/core/container/AppCache.php
|
1356
|
<?php
/*
* Copyright (c) 2012-2016, Hofmänner New Media.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This file is part of the N2N FRAMEWORK.
*
* The N2N FRAMEWORK is free software: you can redistribute it and/or modify it under the terms of
* the GNU Lesser General Public License as published by the Free Software Foundation, either
* version 2.1 of the License, or (at your option) any later version.
*
* N2N is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details: http://www.gnu.org/licenses/
*
* The following people participated in this project:
*
* Andreas von Burg.....: Architect, Lead Developer
* Bert Hofmänner.......: Idea, Frontend UI, Community Leader, Marketing
* Thomas Günther.......: Developer, Hangar
*/
namespace n2n\core\container;
use n2n\util\cache\CacheStore;
interface AppCache {
/**
* @param string namespace or type name of a related package or type
* @return CacheStore
*/
public function lookupCacheStore(string $namespace): CacheStore;
/**
* Clear the cache of every cachestore belonging to this {@see AppCache} instance.
*/
public function clear();
}
|
lgpl-3.0
|
Agem-Bilisim/lider-console
|
lider-console-core/src/tr/org/liderahenk/liderconsole/core/model/Profile.java
|
3029
|
/*
*
* Copyright © 2015-2016 Agem Bilişim
*
* This file is part of Lider Ahenk.
*
* Lider Ahenk 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.
*
* Lider Ahenk 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 Lider Ahenk. If not, see <http://www.gnu.org/licenses/>.
*/
package tr.org.liderahenk.liderconsole.core.model;
import java.io.Serializable;
import java.util.Date;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class Profile implements Serializable {
private static final long serialVersionUID = 6401256297602058418L;
private Long id;
private String label;
private String description;
private boolean overridable;
private boolean active;
private boolean deleted;
private Map<String, Object> profileData;
private Date createDate;
private Date modifyDate;
public Profile() {
}
public Profile(Long id, String label, String description, boolean overridable, boolean active, boolean deleted,
Map<String, Object> profileData, Date createDate, Date modifyDate) {
super();
this.id = id;
this.label = label;
this.description = description;
this.overridable = overridable;
this.active = active;
this.deleted = deleted;
this.profileData = profileData;
this.createDate = createDate;
this.modifyDate = modifyDate;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isOverridable() {
return overridable;
}
public void setOverridable(boolean overridable) {
this.overridable = overridable;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isDeleted() {
return deleted;
}
public void setDeleted(boolean deleted) {
this.deleted = deleted;
}
public Map<String, Object> getProfileData() {
return profileData;
}
public void setProfileData(Map<String, Object> profileData) {
this.profileData = profileData;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
|
lgpl-3.0
|
Godin/sonar
|
sonar-ws/src/main/java/org/sonarqube/ws/client/properties/IndexRequest.java
|
1954
|
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonarqube.ws.client.properties;
import java.util.List;
import javax.annotation.Generated;
/**
* This is part of the internal API.
* This is a POST request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/properties/index">Further information about this action online (including a response example)</a>
* @since 2.6
*/
@Generated("sonar-ws-generator")
public class IndexRequest {
private String format;
private String id;
private String resource;
/**
* Possible values:
* <ul>
* <li>"json"</li>
* </ul>
*/
public IndexRequest setFormat(String format) {
this.format = format;
return this;
}
public String getFormat() {
return format;
}
/**
* Example value: "sonar.test.inclusions"
*/
public IndexRequest setId(String id) {
this.id = id;
return this;
}
public String getId() {
return id;
}
/**
* Example value: "my_project"
*/
public IndexRequest setResource(String resource) {
this.resource = resource;
return this;
}
public String getResource() {
return resource;
}
}
|
lgpl-3.0
|
kralisch/jams
|
JAMSmain/src/jams/workspace/stores/ShapeFileDataStore.java
|
5782
|
/*
* ShapeFileDataStore.java
* Created on 13. April 2009, 19:00
*
* This file is part of JAMS
* Copyright (C) FSU Jena
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*
*/
package jams.workspace.stores;
import jams.tools.StringTools;
import jams.tools.XMLTools;
import jams.workspace.DefaultDataSet;
import jams.workspace.JAMSWorkspace;
import jams.workspace.Workspace;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* @author Sven Kralisch <sven.kralisch at uni-jena.de>
*/
public class ShapeFileDataStore extends GeoDataStore {
/**
* the name of the shapefile
*/
private String fileName = null;
/**
* the uri
*/
private URI uri = null;
/**
* the key column, necessary for identifying values
*/
private String keyColumn = null;
/**
* the shapeFile itself
*/
private File shapeFile;
/**
* constructor with xml-document
*
* @param ws
* @param id
* @param doc
* @throws URISyntaxException
*/
public ShapeFileDataStore(JAMSWorkspace ws, String id, Document doc) throws URISyntaxException {
super(ws);
// source can have uri or filename
String wkUri = null;
String wkFileName = null;
String wkKeyColumn = null;
Element sourceElement = (Element) doc.getElementsByTagName("source").item(0);
if (sourceElement != null) {
wkUri = getNodeValue(sourceElement, "uri");
wkFileName = getNodeValue(sourceElement, "filename");
}
Element keyElement = (Element) doc.getElementsByTagName("key").item(0);
if (keyElement != null) {
wkKeyColumn = keyElement.getTextContent();
}
init(id, wkUri, wkFileName, wkKeyColumn);
}
/**
* alternative Constructor with uri or filename
* @param ws
* @param id
* @param uriString
* @param fileName (alternative to uri)
* @param keyColumn
* @throws URISyntaxException
*/
public ShapeFileDataStore(JAMSWorkspace ws, String id, String uriString, String fileName, String keyColumn) throws URISyntaxException {
super(ws);
init(id, uriString, fileName, keyColumn);
}
/**
* init the shapeFileDataStore
*
* @param id
* @param uriString
* @param fileName
* @param keyColumn
* @throws URISyntaxException
*/
private void init(String id, String uriString, String fileName, String keyColumn) throws URISyntaxException {
this.id = id;
if (!StringTools.isEmptyString(uriString)) {
this.uri = new URI(uriString);
this.shapeFile = new File(this.uri);
}
if (this.shapeFile == null || !this.shapeFile.exists()) {
if (!StringTools.isEmptyString(fileName)) {
this.shapeFile = new File(ws.getLocalInputDirectory(), fileName);
}
}
if (shapeFile == null) {
this.shapeFile = new File(ws.getLocalInputDirectory(), id + ".shp");
}
if (this.shapeFile.exists()) {
ws.getRuntime().println("Trying to use shape file from " + shapeFile.toString() + " ..");
this.uri = this.shapeFile.toURI();
this.fileName = this.shapeFile.getName();
if (keyColumn != null) {
this.keyColumn = keyColumn;
}
} else {
ws.getRuntime().println("No shape file found for shape datastore \"" + id + "\" ..");
}
}
public Document getDocument() throws Exception {
String xmlString = "<shapefiledatastore>";
xmlString += "<source>";
xmlString += "<uri>";
String uriString = this.uri.toASCIIString();
if (!StringTools.isEmptyString(uriString)) {
xmlString += uriString;
}
xmlString += "</uri>";
xmlString += "<filename>";
if (!StringTools.isEmptyString(this.fileName)) {
xmlString += this.fileName;
}
xmlString += "</filename>";
xmlString += "</source>";
xmlString += "<key>";
if (!StringTools.isEmptyString(this.keyColumn)) {
xmlString += this.keyColumn;
}
xmlString += "</key>";
xmlString += "</shapefiledatastore>";
return XMLTools.getDocumentFromString(xmlString);
}
@Override
public boolean hasNext() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public DefaultDataSet getNext() {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void close() throws IOException {
}
public String getFileName() {
return fileName;
}
public File getShapeFile() {
return shapeFile;
}
public URI getUri() {
return uri;
}
public String getKeyColumn() {
return keyColumn;
}
public void setWorkspace(Workspace ws)throws IOException {
close();
//todo
}
}
|
lgpl-3.0
|
openbase/jul
|
visual/swing/src/main/java/org/openbase/jul/visual/swing/component/ColorChooserFrame.java
|
7884
|
package org.openbase.jul.visual.swing.component;
/*-
* #%L
* JUL Visual Swing
* %%
* Copyright (C) 2015 - 2022 openbase.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This 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 Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-3.0.html>.
* #L%
*/
import java.awt.Color;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import org.openbase.jul.exception.CouldNotPerformException;
import org.openbase.jul.exception.printer.ExceptionPrinter;
import org.openbase.jul.schedule.GlobalCachedExecutorService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author <a href="mailto:divine@openbase.org">Divine Threepwood</a>
*/
public class ColorChooserFrame extends javax.swing.JFrame {
public enum UserFeedback {
Ok, Cancel
}
private static final Logger LOGGER = LoggerFactory.getLogger(ColorChooserFrame.class);
private final Object WAITER_LOCK = new Object();
private UserFeedback feedback = UserFeedback.Cancel;
/**
* Creates new form ColorChooserFrame
*
* @throws org.openbase.jul.exception.InstantiationException
*/
public ColorChooserFrame() throws org.openbase.jul.exception.InstantiationException {
try {
initComponents();
okButton.setEnabled(false);
cancelButton.setEnabled(false);
setVisible(true);
setAlwaysOnTop(true);
} catch (Exception ex) {
throw new org.openbase.jul.exception.InstantiationException(this, ex);
}
}
public static Color getColor() throws CouldNotPerformException {
Future<Color> colorFuture = GlobalCachedExecutorService.submit(new Callable<Color>() {
@Override
public Color call() throws CouldNotPerformException {
ColorChooserFrame colorChooserFrame = null;
try {
colorChooserFrame = new ColorChooserFrame();
synchronized (colorChooserFrame.WAITER_LOCK) {
try {
colorChooserFrame.okButton.setEnabled(true);
colorChooserFrame.cancelButton.setEnabled(true);
colorChooserFrame.WAITER_LOCK.wait();
} catch (InterruptedException ex) {
}
}
if (colorChooserFrame.feedback == UserFeedback.Cancel) {
throw new CouldNotPerformException("User cancel action!");
}
return colorChooserFrame.colorChooser.getColor();
} finally {
if (colorChooserFrame != null) {
try {
colorChooserFrame.setVisible(false);
} catch (Throwable ex) {
ExceptionPrinter.printHistory("Coult not close " + ColorChooserFrame.class.getSimpleName() + "!", ex, LOGGER);
}
}
}
}
});
try {
return colorFuture.get();
} catch (ExecutionException | InterruptedException ex) {
throw new CouldNotPerformException("Could not get color!", ex);
}
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
colorChooser = new javax.swing.JColorChooser();
okButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
okButton.setText("OK");
okButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
okButtonActionPerformed(evt);
}
});
cancelButton.setText("Cancel");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(colorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(okButton, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap())
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(colorChooser, javax.swing.GroupLayout.PREFERRED_SIZE, 370, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelButton)
.addComponent(okButton))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void okButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_okButtonActionPerformed
feedback = UserFeedback.Ok;
synchronized (WAITER_LOCK) {
okButton.setEnabled(false);
cancelButton.setEnabled(false);
WAITER_LOCK.notifyAll();
}
}//GEN-LAST:event_okButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
feedback = UserFeedback.Cancel;
synchronized (WAITER_LOCK) {
okButton.setEnabled(false);
cancelButton.setEnabled(false);
WAITER_LOCK.notifyAll();
}
}//GEN-LAST:event_cancelButtonActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton cancelButton;
private javax.swing.JColorChooser colorChooser;
private javax.swing.JButton okButton;
// End of variables declaration//GEN-END:variables
}
|
lgpl-3.0
|
SirmaITT/conservation-space-1.7.0
|
docker/sirma-platform/platform/seip-parent/platform/domain-model/user-management-permissions/src/main/java/com/sirma/itt/seip/permissions/observers/InheritedPermissionObserver.java
|
8635
|
package com.sirma.itt.seip.permissions.observers;
import static com.sirma.itt.seip.domain.instance.DefaultProperties.INHERIT_LIBRARY_PERMISSIONS;
import static com.sirma.itt.seip.domain.instance.DefaultProperties.INHERIT_PARENT_PERMISSIONS;
import java.util.Map;
import java.util.stream.Stream;
import javax.enterprise.event.Observes;
import javax.inject.Inject;
import com.sirma.itt.seip.annotation.DisableAudit;
import com.sirma.itt.seip.domain.ObjectTypes;
import com.sirma.itt.seip.domain.instance.Instance;
import com.sirma.itt.seip.domain.instance.InstanceReference;
import com.sirma.itt.seip.instance.context.InstanceContextService;
import com.sirma.itt.seip.instance.event.AfterInstancePersistEvent;
import com.sirma.itt.seip.instance.event.ParentChangedEvent;
import com.sirma.itt.seip.instance.save.event.AfterInstanceSaveEvent;
import com.sirma.itt.seip.permissions.EntityPermissions;
import com.sirma.itt.seip.permissions.InstancePermissionsHierarchyResolver;
import com.sirma.itt.seip.permissions.PermissionService;
import com.sirma.itt.seip.permissions.SecurityModel;
import com.sirma.itt.seip.permissions.role.PermissionsChange.PermissionsChangeBuilder;
import com.sirma.itt.seip.permissions.role.RoleService;
import com.sirma.itt.seip.permissions.role.TransactionalPermissionChanges;
import com.sirma.itt.seip.security.context.SecurityContext;
/**
* Update permission model of created instances in relation to their parent/context. Sets the inherited roles from the
* current parents or special permissions for the creator if no parent is specified
*
* @author BBonev
*/
public class InheritedPermissionObserver {
@Inject
private RoleService roleService;
@Inject
private SecurityContext securityContext;
@Inject
private InstancePermissionsHierarchyResolver hierarchyResolver;
@Inject
private TransactionalPermissionChanges permissionsChangeBuilder;
@Inject
private PermissionService permissionService;
@Inject
private InstanceContextService contextService;
/**
* Instance creation assign inherited permissions if there is a parent of the instance or special permission to the
* creator of the instance
*
* @param event the event
*/
@DisableAudit
public <I extends Instance> void onAfterInstanceCreated(@Observes AfterInstancePersistEvent<I, ?> event) {
I instance = event.getInstance();
if (instance.type().is(ObjectTypes.USER)) {
// users does not inherit or manage any inheritance permissions
// all needed permissions are set in the observer for user creation integration
// see UserInstanceCreationObserver.assignPermissions | CMF-26128
return;
}
InstanceReference inheritFrom = contextService.getContext(instance).orElse(null);
InstanceReference reference = instance.toReference();
InstanceReference library = hierarchyResolver.getLibrary(reference);
PermissionsChangeBuilder builder = permissionsChangeBuilder.builder(reference);
builder.libraryChange(library.getId());
boolean enabledLibraryInheritance = instance.type().hasTrait(INHERIT_LIBRARY_PERMISSIONS);
builder.inheritFromLibraryChange(enabledLibraryInheritance);
boolean enableParentInheritance = instance.type().hasTrait(INHERIT_PARENT_PERMISSIONS);
// if the created instance has no enabled parent or library inheritance we should
// assign manager permissions to the instance for the creator as he/she may not get any other permissions for
// the instance he/she is creating
boolean noEffectivePermissionInheritance = !(enabledLibraryInheritance || enableParentInheritance);
// by default the parent is not allowed for inheritance
// so if there is no parent special permissions will be assigned to the instance
boolean isParentAllowedForInheritance = false;
if (inheritFrom != null) {
// if the instance's parent is eligible then parent inheritance will be enabled
isParentAllowedForInheritance = isEligibleForInheritance(inheritFrom);
// all instances will be set as parents but if they are not allowed for parent inheritance it will not be
// enabled even if configured in the model
// these information is stored in the semantic database but it's omitted from the permissions database model
// that leads to wrong assumptions for the permissions
enableParentInheritance &= isParentAllowedForInheritance;
// we set the parent no mater if it's eligible or not
// the inheritance flag will control if we take the permissions from him or not
builder.parentChange(inheritFrom.getId());
}
builder.inheritFromParentChange(enableParentInheritance);
if (inheritFrom == null || !isParentAllowedForInheritance || noEffectivePermissionInheritance) {
// ensure at least one manager
String currentUser = securityContext.getAuthenticated().getSystemId().toString();
builder.addRoleAssignmentChange(currentUser, roleService.getManagerRole().getIdentifier());
}
}
/**
* Updates the permission data by setting the new parent when the instance is moved.
*
* @param event holds information about the instance and its new parent.
*/
@DisableAudit
public void onParentChanged(@Observes ParentChangedEvent event) {
if (event.getNewParent() != null) {
processWithParent(event);
} else {
processWithoutParent(event);
}
}
/**
* Listens for semantic type change for the instance. If such change is detected then the library permissions are
* updated to reflect the new library.
*
* @param event the event carrying the modified instance
*/
@DisableAudit
public void onLibraryChange(@Observes AfterInstanceSaveEvent event) {
Instance instanceToSave = event.getInstanceToSave();
Instance currentInstance = event.getCurrentInstance();
if (currentInstance == null || instanceToSave.type().getId().equals(currentInstance.type().getId())) {
// it's either new instance or the same type, so we have nothing to do
return;
}
InstanceReference reference = instanceToSave.toReference();
InstanceReference newLibrary = hierarchyResolver.getLibrary(reference);
PermissionsChangeBuilder builder = permissionsChangeBuilder.builder(reference);
builder.libraryChange(newLibrary.getId());
boolean enabledLibraryInheritance = instanceToSave.type().hasTrait(INHERIT_LIBRARY_PERMISSIONS);
builder.inheritFromLibraryChange(enabledLibraryInheritance);
boolean enableParentInheritance = instanceToSave.type().hasTrait(INHERIT_PARENT_PERMISSIONS);
// if instance is in a context that is not applicable for permission inheritance (user/group)
// then we should not enable the parent inheritance
if (enableParentInheritance) {
InstanceReference inheritFrom = contextService.getContext(instanceToSave).orElse(null);
if (inheritFrom != null) {
enableParentInheritance = isEligibleForInheritance(inheritFrom);
}
}
builder.inheritFromParentChange(enableParentInheritance);
}
private void processWithParent(ParentChangedEvent event) {
Instance newParent = event.getNewParent();
InstanceReference movedReference = event.getInstance().toReference();
InstanceReference newParentReference = newParent.toReference();
PermissionsChangeBuilder builder = permissionsChangeBuilder.builder(movedReference);
boolean isParentInheritanceEnabled = permissionService.getPermissionsInfo(movedReference)
.filter(EntityPermissions::isInheritFromParent)
.isPresent();
if (isParentInheritanceEnabled) {
// only keep the parent inheritance if it's already enabled and the new parent is eligible for such
boolean isParentAllowedForInheritance = isEligibleForInheritance(newParentReference);
builder.inheritFromParentChange(isParentAllowedForInheritance);
}
builder.parentChange(newParentReference.getId());
}
private void processWithoutParent(ParentChangedEvent event) {
InstanceReference movedReference = event.getInstance().toReference();
PermissionsChangeBuilder builder = permissionsChangeBuilder.builder(movedReference);
String managerRole = SecurityModel.BaseRoles.MANAGER.getIdentifier();
getUsersWithRole(movedReference, managerRole).forEach(
userId -> builder.addRoleAssignmentChange(userId, managerRole));
builder.parentChange(null);
}
private Stream<String> getUsersWithRole(InstanceReference instanceReference, String roleIdentifier) {
return permissionService.getPermissionAssignments(instanceReference)
.entrySet()
.stream()
.filter(entry -> roleIdentifier.equals(entry.getValue().getRole().getIdentifier()))
.map(Map.Entry::getKey);
}
private boolean isEligibleForInheritance(InstanceReference parentReference) {
return hierarchyResolver.isAllowedForPermissionSource(parentReference);
}
}
|
lgpl-3.0
|
artstyle/BoilingPot
|
protected/extensions/colorbox/EColorBox.php
|
5377
|
<?php
/**
* ColorBox extension (http://www.jacklmoore.com/colorbox/)
*
* @author Eugene V Chernyshev <evc@artstyle.ru>
* @license http://opensource.org/licenses/MIT
*/
class EColorBox extends CWidget
{
/**
* @var array colorbox default settings
*/
private $_defaultSettings = array(
'transition'=>'elastic',
'speed'=>350,
'href'=>false,
'title'=>false,
'titleTag'=>'title',
'rel'=>false,
'scalePhotos'=>true,
'scrolling'=>true,
'opacity'=>0.85,
'open'=>false,
'returnFocus'=>true,
'fastIframe'=>true,
'preloading'=>true,
'overlayClose'=>true,
'escKey'=>true,
'arrowKey'=>true,
'loop'=>true,
'data'=>false,
'className'=>false,
);
/**
* @var array colorbox default phrases
*/
private $_defaultLocale = array(
'current'=>'image {current} of {total}',
'previous'=>'previous',
'next'=>'next',
'close'=>'close',
'xhrError'=>'This content failed to load.',
'imgError'=>'This image failed to load.',
'slideshowStart'=>'start slideshow',
'slideshowStop'=>'stop slideshow',
);
private $_defaultContentType = array(
'iframe'=>false,
'inline'=>false,
'html'=>false,
'photo'=>false,
);
/**
* @var array colorbox default dimensions
*/
private $_defaultDimensions = array(
'width'=>false,
'height'=>false,
'innerWidth'=>false,
'innerHeight'=>false,
'initialWidth'=>300,
'initialHeight'=>100,
'maxWidth'=>false,
'maxHeight'=>false,
);
/**
* @var array colorbox default slide show params
*/
private $_defaultSlideShow = array(
'slideshow'=>false,
'slideshowSpeed'=>2500,
'slideshowAuto'=>'auto',
'slideshowStart'=>true,
);
/**
* @var array colorbox default position settings
*/
private $_defaultPositioning = array(
'fixed'=>false,
'top'=>false,
'bottom'=>false,
'left'=>false,
'right'=>false,
);
/**
* @var string URL of published assets
*/
private $assetsUrl;
/**
* @var CClientScript
*/
private $cs;
/**
* Script positioning
* @var integer
*/
public $scriptPosition = CClientScript::POS_HEAD;
/**
* @var array colorbox language, defaults to english
*/
public $language;
/**
* @var array colorbox settings
*/
public $settings = array();
/**
* @var array colorbox custom phrases
*/
public $locale = array();
/**
* @var array colorbox content type settings
*/
public $contentType = array();
/**
* @var array colorbox dimensions parameters
*/
public $dimensions = array();
/**
* @var array colorbox slideshow parameters
*/
public $slideshow = array();
/**
* @var array colorbox positioning parameters
*/
public $positioning = array();
/**
* @var string callback fires before colorbox opens
*/
public $onOpen;
/**
* @var string callback fires before attempting to load content
*/
public $onLoad;
/**
* @var string callback fires right after content is displayed
*/
public $onComplete;
/**
* @var string callback fires before close process activated
*/
public $onCleanup;
/**
* @var string callback fires after colorbox is closed
*/
public $onClosed;
/**
* @var string jQuery selector
*/
public $selector = '.colorbox';
/**
* @var boolean register assets CSS
*/
public $registerCss = true;
public function init()
{
$this->assetsUrl = Yii::app()->assetManager->publish(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'assets');
$this->cs = Yii::app()->clientScript;
$this->cs->registerCoreScript('jquery');
$this->cs->registerScriptFile($this->assetsUrl . '/js/jquery.colorbox' . (YII_DEBUG ? '' : '-min') . '.js',$this->scriptPosition);
if (empty($this->language)) {
$this->language = Yii::app()->language;
}
if (file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR .
'assets' . DIRECTORY_SEPARATOR .
'js' . DIRECTORY_SEPARATOR .
'i18n' . DIRECTORY_SEPARATOR .
'jquery.colorbox-' . $this->language . '.js')) {
$this->cs->registerScriptFile($this->assetsUrl . '/js/i18n/jquery.colorbox-' . $this->language . '.js',$this->scriptPosition);
}
if ($this->registerCss) {
$this->cs->registerCssFile($this->assetsUrl . '/css/colorbox.css');
}
}
public function run()
{
$options = array();
foreach (array('onOpen','onLoad','onComplete','onCleanup','onClosed') as $callback) {
if ($this->$callback) {
$options[$callback] = $this->$callback;
}
}
foreach ($this->settings as $key => $value) {
if ($this->_defaultSettings[$key] != $value) {
$options[$key] = $value;
}
}
foreach ($this->locale as $key => $value) {
if ($this->_defaultLocale[$key] != $value) {
$options[$key] = $value;
}
}
foreach ($this->contentType as $key => $value) {
if ($this->_defaultContentType[$key] != $value) {
$options[$key] = $value;
}
}
foreach ($this->dimensions as $key => $value) {
if ($this->_defaultDimensions[$key] != $value) {
$options[$key] = $value;
}
}
foreach ($this->slideshow as $key => $value) {
if ($this->_defaultSlideShow[$key] != $value) {
$options[$key] = $value;
}
}
foreach ($this->positioning as $key => $value) {
if ($this->_defaultPositioning[$key] != $value) {
$options[$key] = $value;
}
}
$options = empty($options) ? '' : CJavaScript::encode($options);
$this->cs->registerScript(get_class($this) . '#' . $this->id,"jQuery('{$this->selector}').colorbox({$options});");
}
}?>
|
lgpl-3.0
|
rossvs/Metaphone_Rus
|
example.php
|
252
|
<?php
require_once 'metaphone_rus.php';
header('Content-type: text/html; charset=utf-8');
echo 'Облигация → ' . MetaPhoneRus('Облигация') . '<br>';
echo 'Аблигация → ' . MetaPhoneRus('Аблигация') . '<br>';
|
lgpl-3.0
|
cikl/threatinator
|
spec/feeds/malwaredomains_dyndns-domain_reputation_spec.rb
|
1415
|
require 'spec_helper'
describe 'feeds/malwaredomains_dyndns-domain_reputation.feed', :feed do
let(:provider) { 'malwaredomains' }
let(:name) { 'dyndns_domain_reputation' }
it_fetches_url 'http://mirror2.malwaredomains.com/files/dynamic_dns.txt'
describe_parsing_the_file feed_data('malwaredomains_dyndns_domainlist.txt') do
it "should have parsed 19 records" do
expect(num_records_parsed).to eq(19)
end
it "should have filtered 15 records" do
expect(num_records_filtered).to eq(15)
end
end
describe_parsing_a_record '1040ezdotcom.com malicious siteinspector.comodo.com/' do
it "should have parsed" do
expect(status).to eq(:parsed)
end
it "should have parsed 1 event" do
expect(events.count).to eq(1)
end
describe 'event 0' do
subject { events[0] }
its(:type) { is_expected.to be(:scanning) }
its(:fqdns) { is_expected.to match_array(['1040ezdotcom.com']) }
end
end
describe_parsing_a_record '1stresponderservices.com malicious siteinspector.comodo.com/' do
it "should have parsed" do
expect(status).to eq(:parsed)
end
it "should have parsed 1 event" do
expect(events.count).to eq(1)
end
describe 'event 0' do
subject { events[0] }
its(:type) { is_expected.to be(:scanning) }
its(:fqdns) { is_expected.to match_array(['1stresponderservices.com']) }
end
end
end
|
lgpl-3.0
|
cswaroop/Catalano-Framework
|
Catalano.Core/src/Catalano/Core/Structs/BinaryHeap.java
|
3691
|
// Catalano Core Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2015
// diego.catalano at live.com
//
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Core.Structs;
import java.util.ArrayList;
import java.util.List;
/**
* Binary Heap.
* @author Diego Catalano
* @param <E> Item.
*/
public class BinaryHeap<E extends Comparable<E>> {
private int count = 0;
List<E> heap = new ArrayList<E>();
/**
* Get the count actually in the heap.
* @return Count.
*/
public int count() {
return count;
}
/**
* Get the size of the heap.
* @return Size.
*/
public int size(){
return heap.size();
}
/**
* Initializes a new instance of the BinaryHeap class.
*/
public BinaryHeap() {}
/**
* Initializes a new instance of the BinaryHeap class.
* @param keys Items.
*/
public BinaryHeap(E[] keys) {
for (E key : keys) {
heap.add(key);
}
for (int k = heap.size() / 2 - 1; k >= 0; k--) {
downHeap(k, heap.get(k));
}
}
/**
* Adds an item in the heap.
* @param node Item as node.
*/
public void add(E node) {
heap.add(null);
int k = heap.size() - 1;
upHeap(k, node);
count++;
}
/**
* Remove the last node from the heap.
* @return Item from the last node.
*/
public E remove() {
E removedNode = heap.get(0);
E lastNode = heap.remove(heap.size() - 1);
downHeap(0, lastNode);
count--;
return removedNode;
}
/**
* Remove a specified item from the heap.
* @param item Item.
*/
public void remove(E item){
heap.remove(item);
}
/**
* Get the minimum item from the heap.
* @return Item.
*/
public E min() {
return heap.get(0);
}
/**
* Check if the heap is empty.
* @return True if the heap is empty, otherwise false.
*/
public boolean isEmpty() {
return heap.isEmpty();
}
private void upHeap(int k, E node){
while (k > 0) {
int parent = (k - 1) / 2;
E p = heap.get(parent);
if (node.compareTo(p) >= 0) {
break;
}
heap.set(k, p);
k = parent;
}
heap.set(k, node);
}
private void downHeap(int k, E node) {
if (heap.isEmpty()) {
return;
}
while (k < heap.size() / 2) {
int child = 2 * k + 1;
if (child < heap.size() - 1 && heap.get(child).compareTo(heap.get(child + 1)) > 0) {
child++;
}
if (node.compareTo(heap.get(child)) < 0) {
break;
}
heap.set(k, heap.get(child));
k = child;
}
heap.set(k, node);
}
}
|
lgpl-3.0
|
remontees/EliteHebergPanel
|
eliteheberg/wsgi.py
|
397
|
"""
WSGI config for eliteheberg project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eliteheberg.settings")
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
lgpl-3.0
|
Godin/sonar
|
sonar-plugin-api/src/test/java/org/sonar/api/issue/NoSonarFilterTest.java
|
1545
|
/*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.api.issue;
import java.util.Arrays;
import java.util.HashSet;
import org.junit.Test;
import org.sonar.api.batch.fs.internal.DefaultInputFile;
import org.sonar.api.batch.fs.internal.TestInputFileBuilder;
import static org.assertj.core.api.Assertions.assertThat;
public class NoSonarFilterTest {
@Test
public void should_store_nosonar_lines_on_inputfile() {
DefaultInputFile f = TestInputFileBuilder.create("module1", "myfile.java").setLines(8).build();
new NoSonarFilter().noSonarInFile(f, new HashSet<>(Arrays.asList(1,4)));
assertThat(f.hasNoSonarAt(1)).isTrue();
assertThat(f.hasNoSonarAt(2)).isFalse();
assertThat(f.hasNoSonarAt(4)).isTrue();
}
}
|
lgpl-3.0
|
OpenSoftwareSolutions/PDFReporter-Studio
|
com.jaspersoft.studio/src/com/jaspersoft/studio/property/IPostSetValue.java
|
887
|
/*******************************************************************************
* Copyright (C) 2005 - 2014 TIBCO Software Inc. All rights reserved.
* http://www.jaspersoft.com.
*
* Unless you have purchased a commercial license agreement from Jaspersoft,
* the following license terms apply:
*
* This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
******************************************************************************/
package com.jaspersoft.studio.property;
import org.eclipse.gef.commands.Command;
import org.eclipse.ui.views.properties.IPropertySource;
public interface IPostSetValue {
public Command postSetValue(IPropertySource target, Object prop, Object newValue, Object oldValue);
}
|
lgpl-3.0
|
SonarSource/sonarqube
|
sonar-plugin-api/src/main/java/org/sonar/api/utils/HttpDownloader.java
|
2743
|
/*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.api.utils;
import org.sonar.api.scanner.ScannerSide;
import org.sonar.api.server.ServerSide;
import java.io.File;
import java.io.InputStream;
import java.net.URI;
/**
* This component is available in IoC container, so it should be injected through
* a constructor parameter. It is available in both scanner and server.
*/
@ScannerSide
@ServerSide
public abstract class HttpDownloader extends UriReader.SchemeProcessor {
/**
* Catch-all default timeout, replaced by
* {@link #DEFAULT_READ_TIMEOUT_IN_MILLISECONDS}
* {@link #DEFAULT_CONNECT_TIMEOUT_IN_MILLISECONDS}
*
* @deprecated since 7.0
*/
@Deprecated
public static final int TIMEOUT_MILLISECONDS = 20 * 1000;
/**
* @since 7.0
*/
public static final int DEFAULT_READ_TIMEOUT_IN_MILLISECONDS = 60 * 1000;
/**
* @since 7.0
*/
public static final int DEFAULT_CONNECT_TIMEOUT_IN_MILLISECONDS = 20 * 1000;
public abstract String downloadPlainText(URI uri, String encoding);
public abstract byte[] download(URI uri);
public abstract InputStream openStream(URI uri);
public abstract void download(URI uri, File toFile);
public static class HttpException extends RuntimeException {
private final URI uri;
private final int responseCode;
private final String responseContent;
public HttpException(URI uri, int responseContent) {
this(uri, responseContent, "");
}
public HttpException(URI uri, int responseCode, String responseContent) {
super("Fail to download [" + uri + "]. Response code: " + responseCode);
this.uri = uri;
this.responseCode = responseCode;
this.responseContent = responseContent;
}
public int getResponseCode() {
return responseCode;
}
public URI getUri() {
return uri;
}
public String getResponseContent() {
return responseContent;
}
}
}
|
lgpl-3.0
|
SonarQubeCommunity/sonar-lua
|
sonar-lua-plugin/src/main/java/org/sonar/plugins/lua/LuaTokensVisitor.java
|
4263
|
/*
* SonarQube Lua Plugin
* Copyright (C) 2013-2016-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 org.sonar.plugins.lua;
import com.google.common.collect.Sets;
import com.sonar.sslr.api.AstNode;
import com.sonar.sslr.api.GenericTokenType;
import com.sonar.sslr.api.Token;
import com.sonar.sslr.api.TokenType;
import com.sonar.sslr.api.Trivia;
import com.sonar.sslr.impl.Lexer;
import org.sonar.api.batch.fs.InputFile;
import org.sonar.api.batch.sensor.SensorContext;
import org.sonar.api.batch.sensor.cpd.NewCpdTokens;
import org.sonar.api.batch.sensor.highlighting.NewHighlighting;
import org.sonar.api.batch.sensor.highlighting.TypeOfText;
import org.sonar.lua.api.LuaKeyword;
import org.sonar.lua.api.LuaTokenType;
import org.sonar.squidbridge.SquidAstVisitor;
import org.sonar.sslr.parser.LexerlessGrammar;
import javax.annotation.Nullable;
import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set;
public class LuaTokensVisitor extends SquidAstVisitor<LexerlessGrammar> {
private static final String NORMALIZED_CHARACTER_LITERAL = "$CHARS";
private static final String NORMALIZED_NUMERIC_LITERAL = "$NUMBER";
private static final Set<LuaKeyword> KEYWORDS = Sets.immutableEnumSet(Arrays.asList(LuaKeyword.values()));
private final SensorContext context;
private final Lexer lexer;
public LuaTokensVisitor(SensorContext context, Lexer lexer) {
this.context = context;
this.lexer = lexer;
}
@Override
public void visitFile(@Nullable AstNode astNode) {
NewHighlighting highlighting = context.newHighlighting();
File file = getContext().getFile();
InputFile inputFile = context.fileSystem().inputFile(context.fileSystem().predicates().is(file));
highlighting.onFile(inputFile);
NewCpdTokens cpdTokens = context.newCpdTokens();
cpdTokens.onFile(inputFile);
Iterator<Token> iterator = lexer.lex(file).iterator();
while (iterator.hasNext()) {
Token token = iterator.next();
TokenType tokenType = token.getType();
if (!tokenType.equals(GenericTokenType.EOF)) {
TokenLocation tokenLocation = new TokenLocation(token);
cpdTokens.addToken(tokenLocation.startLine(), tokenLocation.startCharacter(), tokenLocation.endLine(), tokenLocation.endCharacter(), getTokenImage(token));
}
if (tokenType.equals(LuaTokenType.NUMBER)) {
highlight(highlighting, token, TypeOfText.CONSTANT);
} else if (tokenType.equals(GenericTokenType.LITERAL)) {
highlight(highlighting, token, TypeOfText.STRING);
} else if (KEYWORDS.contains(tokenType)) {
highlight(highlighting, token, TypeOfText.KEYWORD);
}
for (Trivia trivia : token.getTrivia()) {
highlight(highlighting, trivia.getToken(), TypeOfText.COMMENT);
}
}
highlighting.save();
cpdTokens.save();
}
private static String getTokenImage(Token token) {
if (token.getType().equals(GenericTokenType.LITERAL)) {
return NORMALIZED_CHARACTER_LITERAL;
} else if (token.getType().equals(LuaTokenType.NUMBER)) {
return NORMALIZED_NUMERIC_LITERAL;
}
return token.getValue();
}
private static void highlight(NewHighlighting highlighting, Token token, TypeOfText typeOfText) {
TokenLocation tokenLocation = new TokenLocation(token);
highlighting.highlight(tokenLocation.startLine(), tokenLocation.startCharacter(), tokenLocation.endLine(), tokenLocation.endCharacter(), typeOfText);
}
}
|
lgpl-3.0
|
aspratyush/QtDBusSimpleExample
|
QDBusClient/menucreator.cpp
|
1594
|
#include "menucreator.h"
MenuCreator::MenuCreator(com::wp::asp::Calculator* iFaceObj)
{
mIFace = iFaceObj;
}
void MenuCreator::createMenu(){
int ch = 0;
int res;
//loop over choices
do{
std::cout<<"Enter choice:\n"
"1) helloWorld\n"
"2) Addition\n"
"3) Subtraction\n"
"4) Multiple\n"
"5) Divide\n"
"0) exit\n";
std::cin>>ch;
switch(ch){
case 0:{
std::cout<<"Exiting Menu...\n";
emit finished();
break;
}
case 1:{
QString str = mIFace->helloWorld();
std::cout<<"Server says = "<<str.toStdString()<<"\n";
break;
}
case 2:{
res = mIFace->addition(12,13);
std::cout<<"12+13 = "<<res<<std::endl;
break;
}
case 3:{
res = mIFace->subtraction(13,14);
std::cout<<"13-14 = "<<res<<std::endl;
break;
}
case 4:{
res = mIFace->multiply(14,15);
std::cout<<"14*15 = "<<res<<std::endl;
break;
}
case 5:{
res = mIFace->divide(15,4);
std::cout<<"15/4 = "<<res<<std::endl;
break;
}
default:{
std::cout<<"Invalid choice.. enter again";
break;
}
}
}while(ch!=0);
}
|
lgpl-3.0
|
mateusduboli/arquillian-example
|
src/main/java/br/com/realmtech/bean/ZipCode.java
|
244
|
package br.com.realmtech.bean;
/**
* Created with IntelliJ IDEA.
* User: mateus
* Date: 10/29/13
* Time: 10:19 PM
* To change this template use File | Settings | File Templates.
*/
public interface ZipCode {
public String getValue();
}
|
lgpl-3.0
|
kidaa/Awakening-Core3
|
bin/scripts/mobile/lair/creature_dynamic/corellia_war_gronda_pack_neutral_none.lua
|
298
|
corellia_war_gronda_pack_neutral_none = Lair:new {
mobiles = {},
spawnLimit = 15,
buildingsVeryEasy = {},
buildingsEasy = {},
buildingsMedium = {},
buildingsHard = {},
buildingsVeryHard = {},
}
addLairTemplate("corellia_war_gronda_pack_neutral_none", corellia_war_gronda_pack_neutral_none)
|
lgpl-3.0
|
williechen/DailyApp
|
15/py201501/sample/sample.py
|
848
|
#-*- coding: utf-8 -*-
'''
Created on 2015年1月15日
將名稱映射至序列元素
@author: Guan-yu Willie Chen
'''
from collections import namedtuple
def sample(*args):
Subscriber = namedtuple("Subscriber", ["addr", "joined"])
sub = Subscriber(*args)
return sub
def sample1(kwargs):
Stock = namedtuple("Stock", ["name", "shares", "price", "date", "time"])
stockPrototype = Stock('', 0, 0.0, None, None)
return stockPrototype._replace(**kwargs)
if __name__ == '__main__':
s = sample("bcskcnuj@hotmail.com", "2015-01-15")
print("Subscriber==> ", s)
print("Addr==> ", s.addr)
print("Joined==> ", s.joined)
a = {"name": "ACMD", "shares": 100, "price": 134}
s1 = sample1(a)
print("Stock==> ", s1)
print("Stock.name==>", s1.name)
|
lgpl-3.0
|
aozora/arashi
|
src/Web.Mvc/Validators/EqualToPropertyAttribute.cs
|
2678
|
namespace Arashi.Web.Mvc.Validators
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
/// <summary>
/// Attribute used to mark the requirement for a property to be equal
/// to another property.
/// </summary>
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EqualToPropertyAttribute : ValidationAttribute, ICrossFieldValidationAttribute
{
/// <summary>
/// Gets or sets the other property we are validating against.
/// </summary>
/// <value>The other property.</value>
public string OtherProperty { get; set; }
/// <summary>
/// Determines whether the specified property is valid.
/// </summary>
/// <param name="controllerContext">Complete controller context (if required).</param>
/// <param name="model">The model object to which the property belongs.</param>
/// <param name="modelMetadata">Model metadata relating to the property holding
/// the validation data annotation.</param>
/// <returns>
/// <c>true</c> if the specified property is valid; otherwise, <c>false</c>.
/// </returns>
public bool IsValid(ControllerContext controllerContext, object model, ModelMetadata modelMetadata)
{
if (model == null)
{
throw new ArgumentNullException("model");
}
// Find the value of the other property.
var propertyInfo = model.GetType().GetProperty(OtherProperty);
if (propertyInfo == null)
{
throw new InvalidOperationException(string.Format("Couldn't find {0} property on {1}.", OtherProperty, model));
}
var otherValue = propertyInfo.GetGetMethod().Invoke(model, null);
if (modelMetadata.Model == null)
{
modelMetadata.Model = string.Empty;
}
if (otherValue == null)
{
otherValue = string.Empty;
}
return modelMetadata.Model.ToString() == otherValue.ToString();
}
/// <summary>
/// Determines whether the specified value of the object is valid.
/// </summary>
/// <param name="value">The value of the specified validation object on which the <see cref="T:System.ComponentModel.DataAnnotations.ValidationAttribute"/> is declared.</param>
/// <returns>
/// <see langword="true"/> if the specified value is valid; otherwise, <see langword="false"/>.
/// </returns>
public override bool IsValid(object value)
{
// Work done in other IsValid
return true;
}
}
}
|
lgpl-3.0
|
yathit/crm
|
src/ydn/crm/data/storage.js
|
277
|
/**
* @fileoverview Provide storage.
*/
goog.provide('ydn.crm.data');
goog.require('ydn.crm.shared');
goog.require('ydn.crm.su.History');
goog.require('ydn.db.Storage');
goog.require('ydn.db.sync');
goog.require('ydn.gdata.ExtendedProperty');
goog.require('ydn.string');
|
lgpl-3.0
|
michaelpetruzzellocivicom/ari4java
|
classes/ch/loway/oss/ari4java/generated/ContactInfo.java
|
2766
|
package ch.loway.oss.ari4java.generated;
// ----------------------------------------------------
// THIS CLASS WAS GENERATED AUTOMATICALLY
// PLEASE DO NOT EDIT
// Generated on: Tue Dec 19 09:55:48 CET 2017
// ----------------------------------------------------
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.ArrayList;
import ch.loway.oss.ari4java.tools.RestException;
import ch.loway.oss.ari4java.tools.AriCallback;
import ch.loway.oss.ari4java.tools.tags.*;
/**********************************************************
*
* Generated by: JavaInterface
*********************************************************/
public interface ContactInfo {
// void setRoundtrip_usec String
/**********************************************************
* Current round trip time, in microseconds, for the contact.
*
* @since ari_1_9_0
*********************************************************/
public void setRoundtrip_usec(String val );
// String getContact_status
/**********************************************************
* The current status of the contact.
*
* @since ari_1_9_0
*********************************************************/
public String getContact_status();
// String getUri
/**********************************************************
* The location of the contact.
*
* @since ari_1_9_0
*********************************************************/
public String getUri();
// void setContact_status String
/**********************************************************
* The current status of the contact.
*
* @since ari_1_9_0
*********************************************************/
public void setContact_status(String val );
// void setAor String
/**********************************************************
* The Address of Record this contact belongs to.
*
* @since ari_1_9_0
*********************************************************/
public void setAor(String val );
// String getAor
/**********************************************************
* The Address of Record this contact belongs to.
*
* @since ari_1_9_0
*********************************************************/
public String getAor();
// String getRoundtrip_usec
/**********************************************************
* Current round trip time, in microseconds, for the contact.
*
* @since ari_1_9_0
*********************************************************/
public String getRoundtrip_usec();
// void setUri String
/**********************************************************
* The location of the contact.
*
* @since ari_1_9_0
*********************************************************/
public void setUri(String val );
}
;
|
lgpl-3.0
|
bcrosnier/ck-core
|
CK.Core/SetOperation.cs
|
2191
|
#region LGPL License
/*----------------------------------------------------------------------------
* This file (CK.Core\SetOperation.cs) is part of CiviKey.
*
* CiviKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CiviKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with CiviKey. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright © 2007-2015,
* Invenietis <http://www.invenietis.com>,
* In’Tech INFO <http://www.intechinfo.fr>,
* All rights reserved.
*-----------------------------------------------------------------------------*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CK.Core
{
/// <summary>
/// Defines the six basic operations available between two sets.
/// </summary>
public enum SetOperation
{
/// <summary>
/// No operation.
/// </summary>
None,
/// <summary>
/// Union of the sets (keeps items of first or second set).
/// </summary>
Union,
/// <summary>
/// Intersection of the sets (keeps only items that belong to both sets).
/// </summary>
Intersect,
/// <summary>
/// Exclusion (keeps only items of the first that do not belong to the second one).
/// </summary>
Except,
/// <summary>
/// Symetric exclusion (keeps items that belong to first or second set but not to both) - The XOR operation.
/// </summary>
SymetricExcept,
/// <summary>
/// Replace the first set by the second one.
/// </summary>
Replace
}
}
|
lgpl-3.0
|
trinko/contao-zad_docman
|
languages/it/tl_zad_docman_templates.php
|
1188
|
<?php
/**
* Contao Open Source CMS
*
* Copyright (c) 2005-2015 Leo Feyer
*
* @package zad_docman
* @author Antonello Dessì
* @license LGPL
* @copyright Antonello Dessì 2015
*/
/**
* Fields
*/
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['name'] = array('Nome', 'Inserisci il nome del modello.');
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['text'] = array('Testo', 'Inserisci il testo del modello. Si possono usare appositi tag per l\'inserimento di informazioni specifiche.');
/**
* Legends
*/
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['settings_legend'] = 'Impostazioni principali';
/**
* Buttons
*/
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['new'] = array('Nuovo', 'Crea un nuovo modello');
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['edit'] = array('Modifica', 'Modifica il modello con ID %s');
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['copy'] = array('Duplica', 'Duplica il modello con ID %s');
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['delete'] = array('Cancella', 'Cancella il modello con ID %s');
$GLOBALS['TL_LANG']['tl_zad_docman_templates']['show'] = array('Dettagli', 'Mostra i dettagli del modello con ID %s');
|
lgpl-3.0
|
qagwaai/StarMalaccamax
|
src/com/qagwaai/starmalaccamax/server/StarServiceImpl.java
|
13930
|
package com.qagwaai.starmalaccamax.server;
import java.util.ArrayList;
import java.util.logging.Logger;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig;
import com.google.appengine.tools.development.testing.LocalServiceTestHelper;
import com.google.appengine.tools.development.testing.LocalUserServiceTestConfig;
import com.google.gson.Gson;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.qagwaai.starmalaccamax.client.service.StarService;
import com.qagwaai.starmalaccamax.client.service.action.AbstractPolyAction;
import com.qagwaai.starmalaccamax.client.service.action.AbstractPolyResponse;
import com.qagwaai.starmalaccamax.client.service.action.Action;
import com.qagwaai.starmalaccamax.client.service.action.AddStar;
import com.qagwaai.starmalaccamax.client.service.action.AddStarResponse;
import com.qagwaai.starmalaccamax.client.service.action.BulkAddStar;
import com.qagwaai.starmalaccamax.client.service.action.BulkAddStarResponse;
import com.qagwaai.starmalaccamax.client.service.action.GetAllStars;
import com.qagwaai.starmalaccamax.client.service.action.GetAllStarsResponse;
import com.qagwaai.starmalaccamax.client.service.action.GetStarsForSolarSystem;
import com.qagwaai.starmalaccamax.client.service.action.GetStarsForSolarSystemResponse;
import com.qagwaai.starmalaccamax.client.service.action.GetStarsForSolarSystemResponseInJSON;
import com.qagwaai.starmalaccamax.client.service.action.GetStarsForSolarSystemResponseInRPC;
import com.qagwaai.starmalaccamax.client.service.action.RemoveAllSuns;
import com.qagwaai.starmalaccamax.client.service.action.RemoveAllSunsResponse;
import com.qagwaai.starmalaccamax.client.service.action.RemoveStar;
import com.qagwaai.starmalaccamax.client.service.action.RemoveStarResponse;
import com.qagwaai.starmalaccamax.client.service.action.Response;
import com.qagwaai.starmalaccamax.client.service.action.UpdateStar;
import com.qagwaai.starmalaccamax.client.service.action.UpdateStarResponse;
import com.qagwaai.starmalaccamax.server.config.Configuration;
import com.qagwaai.starmalaccamax.server.dao.DAOException;
import com.qagwaai.starmalaccamax.server.dao.DAOFactory;
import com.qagwaai.starmalaccamax.server.dao.StarDAO;
import com.qagwaai.starmalaccamax.shared.MimeType;
import com.qagwaai.starmalaccamax.shared.ServiceException;
import com.qagwaai.starmalaccamax.shared.model.StarDTO;
/**
*
* @author pgirard
*
*/
@SuppressWarnings("serial")
public final class StarServiceImpl extends RemoteServiceServlet implements StarService {
/**
* Logger for this service
*/
private static Logger log = Logger.getLogger(StarServiceImpl.class.getName());
/**
*
* {@inheritDoc}
*/
@SuppressWarnings("unchecked")
@Override
public <T extends Response> T execute(final Action<T> action) throws ServiceException {
Object response = null;
long startTime = Instrumentation.callStart("StarServiceImpl: " + action);
UserService userService = UserServiceFactory.getUserService();
try {
if (!userService.isUserLoggedIn()) {
log.warning("Not logged in user tried to execute action " + action.getClass().getName());
throw new ServiceException("User is not logged in");
}
} catch (NullPointerException npe) {
// assume that we are in a test unit
LocalServiceTestHelper helper =
new LocalServiceTestHelper(new LocalUserServiceTestConfig(), new LocalDatastoreServiceTestConfig())
.setEnvIsAdmin(true).setEnvIsLoggedIn(true);
helper.setUp();
}
if (!userService.isUserLoggedIn()) {
throw new ServiceException("User is not logged in");
}
if (action instanceof GetAllStars) {
response = (T) executeGetAllStars((GetAllStars) action);
} else if (action instanceof AddStar) {
response = (T) executeAddStar((AddStar) action);
} else if (action instanceof UpdateStar) {
response = (T) executeUpdateStar((UpdateStar) action);
} else if (action instanceof RemoveStar) {
response = (T) executeRemoveStar((RemoveStar) action);
} else if (action instanceof BulkAddStar) {
response = (T) executeBulkAddStar((BulkAddStar) action);
} else if (action instanceof RemoveAllSuns) {
response = (T) executeRemoveAllSuns((RemoveAllSuns) action);
} else if (action instanceof GetStarsForSolarSystem) {
response = (T) executeGetStarsForSolarSystem((GetStarsForSolarSystem) action);
}
if (response != null) {
Instrumentation.callEnd("StarServiceImpl: " + response, startTime, action.getClass().getSimpleName(),
response);
if (action instanceof AbstractPolyAction) {
if (!(((AbstractPolyAction) action).getMimeType().equals(((AbstractPolyResponse) response).getMimeType()))) {
throw new ServiceException("Implementation fault: request for mime type [" + ((AbstractPolyAction) action).getMimeType()
+ "] returned mime type [" + ((AbstractPolyResponse) response).getMimeType() + "]");
}
}
return (T) response;
}
log.severe("Action not Implemented: " + action.getClass().getName());
throw new ServiceException("Action not Implemented");
}
/**
*
* @param action
* the AddStar action
* @return an AddStarResponse object with the Star added
* @throws ServiceException
* if the datastore could not add the Star
*/
private AddStarResponse executeAddStar(final AddStar action) throws ServiceException {
AddStarResponse response = new AddStarResponse();
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
StarDTO foundStar = null;
try {
foundStar = starDAO.addStar(action.getStar());
} catch (DAOException e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command GetStar.");
}
response.setStar(foundStar);
return response;
}
/**
*
* @param action
* the BulkAddStar action
* @return a BulkAddStarReponse object with the Stars added
* @throws ServiceException
* if the datastore could not add the Stars
*/
private BulkAddStarResponse executeBulkAddStar(final BulkAddStar action) throws ServiceException {
BulkAddStarResponse response = new BulkAddStarResponse();
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
ArrayList<StarDTO> foundStar = null;
try {
foundStar = starDAO.bulkAddStar(action.getStars());
} catch (DAOException e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command GetStar.");
}
response.setSuccess(true);
return response;
}
/**
*
* @param action
* the get all stars action
* @return the get all stars response object with the array list of all
* stars enclosed
* @throws ServiceException
* if the action cannot be completed
*/
private GetAllStarsResponse executeGetAllStars(final GetAllStars action) throws ServiceException {
GetAllStarsResponse response = new GetAllStarsResponse();
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
ArrayList<StarDTO> foundStars = null;
try {
if (action.usePaging()) {
boolean useFilter = false;
if ((action.getCriteria() != null) && (action.getCriteria().size() > 0)) {
useFilter = true;
}
if (!useFilter) {
foundStars = starDAO.getAllStars(action.getStartRow(), action.getEndRow(), action.getSortBy());
response.setTotalStars(starDAO.getTotalStars());
} else {
foundStars =
starDAO.getAllStars(action.getStartRow(), action.getEndRow(), action.getCriteria(),
action.getSortBy());
if (foundStars.size() < action.getEndRow()) {
// shortcut
response.setTotalStars(foundStars.size());
} else {
response.setTotalStars(starDAO.getTotalStarsWithFilter(action.getCriteria()));
}
}
} else {
foundStars = starDAO.getAllStars();
response.setTotalStars(foundStars.size());
}
} catch (DAOException e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command GetAllStars.");
}
response.setStars(foundStars);
return response;
}
/**
*
* @param action
* an GetStarsForSolarSystem action
* @return an GetStarsForSolarSystemResponse with a list of stars
* @throws ServiceException
* if the action cannot be completed
*/
private GetStarsForSolarSystemResponse executeGetStarsForSolarSystem(final GetStarsForSolarSystem action)
throws ServiceException {
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
ArrayList<StarDTO> foundStars = null;
try {
foundStars = starDAO.getStarsForSolarSystem(action.getId());
} catch (DAOException e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command GetStarsForSolarSystem.");
}
GetStarsForSolarSystemResponse response = null;
if (action.getMimeType() == null) {
throw new ServiceException("Invalid mime type: [null]");
}
if (action.getMimeType().equals(MimeType.rpc)) {
response = new GetStarsForSolarSystemResponseInRPC();
((GetStarsForSolarSystemResponseInRPC) response).setStars(foundStars);
} else if (action.getMimeType().equals(MimeType.js)) {
response = new GetStarsForSolarSystemResponseInJSON();
Gson gson = new Gson();
((GetStarsForSolarSystemResponseInJSON) response).setStars(gson.toJson(foundStars));
} else {
throw new ServiceException("Invalid mime type: [" + action.getMimeType() + "]");
}
return response;
}
/**
*
* @param action
* an RemoveAllSuns action
* @return an RemoveAllSunsResponse with the status of the removal
* @throws ServiceException
* if the action cannot be completed
*/
private RemoveAllSunsResponse executeRemoveAllSuns(final RemoveAllSuns action) throws ServiceException {
RemoveAllSunsResponse response = new RemoveAllSunsResponse();
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
Boolean result = null;
try {
result = starDAO.deleteAllStars();
} catch (DAOException e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command RemoveAllSuns.");
}
response.setResponse(result);
return response;
}
/**
*
* @param action
* the RemoveStar action
* @return a RemoveStarResponse object with the Star removed
* @throws ServiceException
* if the datastore could not remove the Star
*/
private RemoveStarResponse executeRemoveStar(final RemoveStar action) throws ServiceException {
RemoveStarResponse response = new RemoveStarResponse();
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
// boolean foundStar = false;
try {
starDAO.removeStar(action.getStar());
} catch (Throwable e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command RemoveStar.");
}
response.setStar(action.getStar());
return response;
}
/**
*
* @param action
* the UpdateStar action
* @return an UpdateStarResponse object with the Star updated
* @throws ServiceException
* if the datastore could not update the Star
*/
private UpdateStarResponse executeUpdateStar(final UpdateStar action) throws ServiceException {
UpdateStarResponse response = new UpdateStarResponse();
DAOFactory factory = DAOFactory.getDAOFactory(DAOFactory.OBJECTIFY);
StarDAO starDAO = factory.getStarDAO();
StarDTO foundStar = null;
try {
foundStar = starDAO.updateStar(action.getStar());
} catch (DAOException e) {
log.severe(e.toString());
throw new ServiceException("Could not complete command UpdateStar.");
}
response.setStar(foundStar);
return response;
}
}
|
lgpl-3.0
|
Shade-/mybb
|
inc/functions_search.php
|
42692
|
<?php
/**
* MyBB 1.8
* Copyright 2014 MyBB Group, All Rights Reserved
*
* Website: http://www.mybb.com
* License: http://www.mybb.com/about/license
*
*/
/**
* Build a select box list of forums the current user has permission to search
*
* @param int $pid The parent forum ID to start at
* @param int $selitem The selected forum ID
* @param int $addselect Add select boxes at this call or not
* @param string $depth The current depth
* @return string The forum select boxes
*/
function make_searchable_forums($pid=0, $selitem=0, $addselect=1, $depth='')
{
global $db, $pforumcache, $permissioncache, $mybb, $selecteddone, $forumlist, $forumlistbits, $theme, $templates, $lang, $forumpass;
$pid = (int)$pid;
if(!is_array($pforumcache))
{
// Get Forums
$query = $db->simple_select("forums", "pid,disporder,fid,password,name", "linkto='' AND active!=0", array('order_by' => "pid, disporder"));
while($forum = $db->fetch_array($query))
{
$pforumcache[$forum['pid']][$forum['disporder']][$forum['fid']] = $forum;
}
}
if(!is_array($permissioncache))
{
$permissioncache = forum_permissions();
}
if(is_array($pforumcache[$pid]))
{
foreach($pforumcache[$pid] as $key => $main)
{
foreach($main as $key => $forum)
{
$perms = $permissioncache[$forum['fid']];
if(($perms['canview'] == 1 || $mybb->settings['hideprivateforums'] == 0) && $perms['cansearch'] != 0)
{
if($selitem == $forum['fid'])
{
$optionselected = "selected";
$selecteddone = "1";
}
else
{
$optionselected = '';
$selecteddone = "0";
}
if($forum['password'] != '')
{
if($mybb->cookies['forumpass'][$forum['fid']] === md5($mybb->user['uid'].$forum['password']))
{
$pwverified = 1;
}
else
{
$pwverified = 0;
}
}
if(empty($forum['password']) || $pwverified == 1)
{
eval("\$forumlistbits .= \"".$templates->get("search_forumlist_forum")."\";");
}
if(!empty($pforumcache[$forum['fid']]))
{
$newdepth = $depth." ";
$forumlistbits .= make_searchable_forums($forum['fid'], $selitem, 0, $newdepth);
}
}
}
}
}
if($addselect)
{
eval("\$forumlist = \"".$templates->get("search_forumlist")."\";");
}
return $forumlist;
}
/**
* Build a comma separated list of the forums this user cannot search
*
* @param int $pid The parent ID to build from
* @param int $first First rotation or not (leave at default)
* @return string return a CSV list of forums the user cannot search
*/
function get_unsearchable_forums($pid=0, $first=1)
{
global $db, $forum_cache, $permissioncache, $mybb, $unsearchableforums, $unsearchable, $templates, $forumpass;
$pid = (int)$pid;
if(!is_array($forum_cache))
{
// Get Forums
$query = $db->simple_select("forums", "fid,parentlist,password,active", '', array('order_by' => 'pid, disporder'));
while($forum = $db->fetch_array($query))
{
$forum_cache[$forum['fid']] = $forum;
}
}
if(!is_array($permissioncache))
{
$permissioncache = forum_permissions();
}
foreach($forum_cache as $fid => $forum)
{
if($permissioncache[$forum['fid']])
{
$perms = $permissioncache[$forum['fid']];
}
else
{
$perms = $mybb->usergroup;
}
$pwverified = 1;
if($forum['password'] != '')
{
if($mybb->cookies['forumpass'][$forum['fid']] !== md5($mybb->user['uid'].$forum['password']))
{
$pwverified = 0;
}
}
$parents = explode(",", $forum['parentlist']);
if(is_array($parents))
{
foreach($parents as $parent)
{
if($forum_cache[$parent]['active'] == 0)
{
$forum['active'] = 0;
}
}
}
if($perms['canview'] != 1 || $perms['cansearch'] != 1 || $pwverified == 0 || $forum['active'] == 0)
{
if($unsearchableforums)
{
$unsearchableforums .= ",";
}
$unsearchableforums .= "'{$forum['fid']}'";
}
}
$unsearchable = $unsearchableforums;
// Get our unsearchable password protected forums
$pass_protected_forums = get_password_protected_forums();
if($unsearchable && $pass_protected_forums)
{
$unsearchable .= ",";
}
if($pass_protected_forums)
{
$unsearchable .= implode(",", $pass_protected_forums);
}
return $unsearchable;
}
/**
* Build a array list of the forums this user cannot search due to password protection
*
* @param array $fids the fids to check (leave blank to check all forums)
* @return array return a array list of password protected forums the user cannot search
*/
function get_password_protected_forums($fids=array())
{
global $forum_cache, $mybb;
if(!is_array($fids))
{
return false;
}
if(!is_array($forum_cache))
{
$forum_cache = cache_forums();
if(!$forum_cache)
{
return false;
}
}
if(empty($fids))
{
$fids = array_keys($forum_cache);
}
$pass_fids = array();
foreach($fids as $fid)
{
if(empty($forum_cache[$fid]['password']))
{
continue;
}
if(md5($mybb->user['uid'].$forum_cache[$fid]['password']) !== $mybb->cookies['forumpass'][$fid])
{
$pass_fids[] = $fid;
$child_list = get_child_list($fid);
}
if(is_array($child_list))
{
$pass_fids = array_merge($pass_fids, $child_list);
}
}
return array_unique($pass_fids);
}
/**
* Clean search keywords and make them safe for querying
*
* @param string $keywords The keywords to be cleaned
* @return string The cleaned keywords
*/
function clean_keywords($keywords)
{
global $db;
$keywords = my_strtolower($keywords);
$keywords = $db->escape_string_like($keywords);
$keywords = preg_replace("#\*{2,}#s", "*", $keywords);
$keywords = str_replace("*", "%", $keywords);
$keywords = preg_replace("#\s+#s", " ", $keywords);
$keywords = str_replace('\\"', '"', $keywords);
// Search for "and" or "or" and remove if it's at the beginning
$keywords = trim($keywords);
if(my_strpos($keywords, "or") === 0)
{
$keywords = substr_replace($keywords, "", 0, 2);
}
if(my_strpos($keywords, "and") === 0)
{
$keywords = substr_replace($keywords, "", 0, 3);
}
return $keywords;
}
/**
* Clean search keywords for fulltext searching, making them safe for querying
*
* @param string $keywords The keywords to be cleaned
* @return string|bool The cleaned keywords or false on failure
*/
function clean_keywords_ft($keywords)
{
if(!$keywords)
{
return false;
}
$keywords = my_strtolower($keywords);
$keywords = str_replace("%", "\\%", $keywords);
$keywords = preg_replace("#\*{2,}#s", "*", $keywords);
$keywords = preg_replace("#([\[\]\|\.\,:])#s", " ", $keywords);
// Separate braces for further processing
$keywords = preg_replace("#((\+|-|<|>|~)?\(|\))#s", " $1 ", $keywords);
$keywords = preg_replace("#\s+#s", " ", $keywords);
$words = array(array());
// Fulltext search syntax validation: http://dev.mysql.com/doc/refman/5.6/en/fulltext-boolean.html
// Search for phrases
$keywords = explode("\"", $keywords);
$boolean = array('+');
// Brace depth
$depth = 0;
$phrase_operator = '+';
foreach($keywords as $phrase)
{
$phrase = trim($phrase);
if($phrase != '')
{
if($inquote)
{
if($phrase_operator)
{
$boolean[$depth] = $phrase_operator;
}
// Phrases do not need further processing
$words[$depth][] = "{$boolean[$depth]}\"{$phrase}\"";
$boolean[$depth] = $phrase_operator = '+';
}
else
{
// Split words
$split_words = preg_split("#\s{1,}#", $phrase, -1);
if(!is_array($split_words))
{
continue;
}
if(!$inquote)
{
// Save possible operator in front of phrase
$last_char = substr($phrase, -1);
if($last_char == '+' || $last_char == '-' || $last_char == '<' || $last_char == '>' || $last_char == '~')
{
$phrase_operator = $last_char;
}
}
foreach($split_words as $word)
{
$word = trim($word);
if($word == "or")
{
$boolean[$depth] = '';
// Remove "and" operator from previous element
$last = array_pop($words[$depth]);
if($last)
{
if(substr($last, 0, 1) == '+')
{
$last = substr($last, 1);
}
$words[$depth][] = $last;
}
}
elseif($word == "and")
{
$boolean[$depth] = "+";
}
elseif($word == "not")
{
$boolean[$depth] = "-";
}
// Closing braces
elseif($word == ")")
{
// Ignore when no brace was opened
if($depth > 0)
{
$words[$depth-1][] = $boolean[$depth-1].'('.implode(' ', $words[$depth]).')';
--$depth;
}
}
// Valid operators for opening braces
elseif($word == '+(' || $word == '-(' || $word == '<(' || $word == '>(' || $word == '~(' || $word == '(')
{
if(strlen($word) == 2)
{
$boolean[$depth] = substr($word, 0, 1);
}
$words[++$depth] = array();
$boolean[$depth] = '+';
}
else
{
$operator = substr($word, 0, 1);
switch($operator)
{
// Allowed operators
case '-':
case '+':
case '>':
case '<':
case '~':
$word = substr($word, 1);
break;
default:
$operator = $boolean[$depth];
break;
}
// Removed operators that are only allowed at the beginning
$word = preg_replace("#(-|\+|<|>|~|@)#s", '', $word);
// Removing wildcards at the beginning http://bugs.mysql.com/bug.php?id=72605
$word = preg_replace("#^\*#s", '', $word);
$word = $operator.$word;
if(strlen($word) <= 1)
{
continue;
}
$words[$depth][] = $word;
$boolean[$depth] = '+';
}
}
}
}
$inquote = !$inquote;
}
// Close mismatching braces
while($depth > 0)
{
$words[$depth-1][] = $boolean[$depth-1].'('.implode(' ', $words[$depth]).')';
--$depth;
}
$keywords = implode(' ', $words[0]);
return $keywords;
}
/* Database engine specific search functions */
/**
* Perform a thread and post search under MySQL or MySQLi
*
* @param array $search Array of search data
* @return array Array of search data with results mixed in
*/
function privatemessage_perform_search_mysql($search)
{
global $mybb, $db, $lang;
$keywords = clean_keywords($search['keywords']);
if(!$keywords && !$search['sender'])
{
error($lang->error_nosearchterms);
}
if($mybb->settings['minsearchword'] < 1)
{
$mybb->settings['minsearchword'] = 3;
}
$subject_lookin = "";
$message_lookin = "";
$searchsql = "uid='{$mybb->user['uid']}'";
if($keywords)
{
// Complex search
$keywords = " {$keywords} ";
switch($db->type)
{
case 'mysql':
case 'mysqli':
$sfield = 'subject';
$mfield = 'message';
break;
default:
$sfield = 'LOWER(subject)';
$mfield = 'LOWER(message)';
break;
}
if(preg_match("#\s(and|or)\s#", $keywords))
{
$string = "AND";
if($search['subject'] == 1)
{
$string = "OR";
$subject_lookin = " AND (";
}
if($search['message'] == 1)
{
$message_lookin = " {$string} (";
}
// Expand the string by double quotes
$keywords_exp = explode("\"", $keywords);
$inquote = false;
$boolean = '';
foreach($keywords_exp as $phrase)
{
// If we're not in a double quoted section
if(!$inquote)
{
// Expand out based on search operators (and, or)
$matches = preg_split("#\s{1,}(and|or)\s{1,}#", $phrase, -1, PREG_SPLIT_DELIM_CAPTURE);
$count_matches = count($matches);
for($i=0; $i < $count_matches; ++$i)
{
$word = trim($matches[$i]);
if(empty($word))
{
continue;
}
// If this word is a search operator set the boolean
if($i % 2 && ($word == "and" || $word == "or"))
{
if($i <= 1)
{
if($search['subject'] && $search['message'] && $subject_lookin == " AND (")
{
// We're looking for anything, check for a subject lookin
continue;
}
elseif($search['subject'] && !$search['message'] && $subject_lookin == " AND (")
{
// Just in a subject?
continue;
}
elseif(!$search['subject'] && $search['message'] && $message_lookin == " {$string} (")
{
// Just in a message?
continue;
}
}
$boolean = $word;
}
// Otherwise check the length of the word as it is a normal search term
else
{
$word = trim($word);
// Word is too short - show error message
if(my_strlen($word) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// Add terms to search query
if($search['subject'] == 1)
{
$subject_lookin .= " $boolean {$sfield} LIKE '%{$word}%'";
}
if($search['message'] == 1)
{
$message_lookin .= " $boolean {$mfield} LIKE '%{$word}%'";
}
$boolean = 'AND';
}
}
}
// In the middle of a quote (phrase)
else
{
$phrase = str_replace(array("+", "-", "*"), '', trim($phrase));
if(my_strlen($phrase) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// Add phrase to search query
$subject_lookin .= " $boolean {$sfield} LIKE '%{$phrase}%'";
if($search['message'] == 1)
{
$message_lookin .= " $boolean {$mfield} LIKE '%{$phrase}%'";
}
$boolean = 'AND';
}
// Check to see if we have any search terms and not a malformed SQL string
$error = false;
if($search['subject'] && $search['message'] && $subject_lookin == " AND (")
{
// We're looking for anything, check for a subject lookin
$error = true;
}
elseif($search['subject'] && !$search['message'] && $subject_lookin == " AND (")
{
// Just in a subject?
$error = true;
}
elseif(!$search['subject'] && $search['message'] && $message_lookin == " {$string} (")
{
// Just in a message?
$error = true;
}
if($error == true)
{
// There are no search keywords to look for
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
$inquote = !$inquote;
}
if($search['subject'] == 1)
{
$subject_lookin .= ")";
}
if($search['message'] == 1)
{
$message_lookin .= ")";
}
$searchsql .= "{$subject_lookin} {$message_lookin}";
}
else
{
$keywords = str_replace("\"", '', trim($keywords));
if(my_strlen($keywords) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// If we're looking in both, then find matches in either the subject or the message
if($search['subject'] == 1 && $search['message'] == 1)
{
$searchsql .= " AND ({$sfield} LIKE '%{$keywords}%' OR {$mfield} LIKE '%{$keywords}%')";
}
else
{
if($search['subject'] == 1)
{
$searchsql .= " AND {$sfield} LIKE '%{$keywords}%'";
}
if($search['message'] == 1)
{
$searchsql .= " AND {$mfield} LIKE '%{$keywords}%'";
}
}
}
}
if($search['sender'])
{
$userids = array();
$search['sender'] = my_strtolower($search['sender']);
switch($db->type)
{
case 'mysql':
case 'mysqli':
$field = 'username';
break;
default:
$field = 'LOWER(username)';
break;
}
$query = $db->simple_select("users", "uid", "{$field} LIKE '%".$db->escape_string_like($search['sender'])."%'");
while($user = $db->fetch_array($query))
{
$userids[] = $user['uid'];
}
if(count($userids) < 1)
{
error($lang->error_nosearchresults);
}
else
{
$userids = implode(',', $userids);
$searchsql .= " AND fromid IN (".$userids.")";
}
}
if(!is_array($search['folder']))
{
$search['folder'] = array($search['folder']);
}
if(!empty($search['folder']))
{
$folderids = array();
$search['folder'] = array_map("intval", $search['folder']);
$folderids = implode(',', $search['folder']);
if($folderids)
{
$searchsql .= " AND folder IN (".$folderids.")";
}
}
if($search['status'])
{
$searchsql .= " AND (";
if($search['status']['new'])
{
$statussql[] = " status='0' ";
}
if($search['status']['replied'])
{
$statussql[] = " status='3' ";
}
if($search['status']['forwarded'])
{
$statussql[] = " status='4' ";
}
if($search['status']['read'])
{
$statussql[] = " (status != '0' AND readtime > '0') ";
}
// Sent Folder
if(in_array(2, $search['folder']))
{
$statussql[] = " status='1' ";
}
$statussql = implode("OR", $statussql);
$searchsql .= $statussql.")";
}
$limitsql = "";
if((int)$mybb->settings['searchhardlimit'] > 0)
{
$limitsql = " LIMIT ".(int)$mybb->settings['searchhardlimit'];
}
$searchsql .= $limitsql;
// Run the search
$pms = array();
$query = $db->simple_select("privatemessages", "pmid", $searchsql);
while($pm = $db->fetch_array($query))
{
$pms[$pm['pmid']] = $pm['pmid'];
}
if(count($pms) < 1)
{
error($lang->error_nosearchresults);
}
$pms = implode(',', $pms);
return array(
"querycache" => $pms
);
}
/**
* Perform a help document search under MySQL or MySQLi
*
* @param array $search Array of search data
* @return array Array of search data with results mixed in
*/
function helpdocument_perform_search_mysql($search)
{
global $mybb, $db, $lang;
$keywords = clean_keywords($search['keywords']);
if(!$keywords && !$search['sender'])
{
error($lang->error_nosearchterms);
}
if($mybb->settings['minsearchword'] < 1)
{
$mybb->settings['minsearchword'] = 3;
}
$name_lookin = "";
$document_lookin = "";
$searchsql = "enabled='1'";
if($keywords)
{
switch($db->type)
{
case 'mysql':
case 'mysqli':
$nfield = 'name';
$dfield = 'document';
break;
default:
$nfield = 'LOWER(name)';
$dfield = 'LOWER(document)';
break;
}
// Complex search
$keywords = " {$keywords} ";
if(preg_match("#\s(and|or)\s#", $keywords))
{
$string = "AND";
if($search['name'] == 1)
{
$string = "OR";
$name_lookin = " AND (";
}
if($search['document'] == 1)
{
$document_lookin = " {$string} (";
}
// Expand the string by double quotes
$keywords_exp = explode("\"", $keywords);
$inquote = false;
foreach($keywords_exp as $phrase)
{
// If we're not in a double quoted section
if(!$inquote)
{
// Expand out based on search operators (and, or)
$matches = preg_split("#\s{1,}(and|or)\s{1,}#", $phrase, -1, PREG_SPLIT_DELIM_CAPTURE);
$count_matches = count($matches);
for($i=0; $i < $count_matches; ++$i)
{
$word = trim($matches[$i]);
if(empty($word))
{
continue;
}
// If this word is a search operator set the boolean
if($i % 2 && ($word == "and" || $word == "or"))
{
if($i <= 1)
{
if($search['name'] && $search['document'] && $name_lookin == " AND (")
{
// We're looking for anything, check for a name lookin
continue;
}
elseif($search['name'] && !$search['document'] && $name_lookin == " AND (")
{
// Just in a name?
continue;
}
elseif(!$search['name'] && $search['document'] && $document_lookin == " {$string} (")
{
// Just in a document?
continue;
}
}
$boolean = $word;
}
// Otherwise check the length of the word as it is a normal search term
else
{
$word = trim($word);
// Word is too short - show error message
if(my_strlen($word) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// Add terms to search query
if($search['name'] == 1)
{
$name_lookin .= " $boolean {$nfield} LIKE '%{$word}%'";
}
if($search['document'] == 1)
{
$document_lookin .= " $boolean {$dfield} LIKE '%{$word}%'";
}
}
}
}
// In the middle of a quote (phrase)
else
{
$phrase = str_replace(array("+", "-", "*"), '', trim($phrase));
if(my_strlen($phrase) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// Add phrase to search query
$name_lookin .= " $boolean {$nfield} LIKE '%{$phrase}%'";
if($search['document'] == 1)
{
$document_lookin .= " $boolean {$dfield} LIKE '%{$phrase}%'";
}
}
// Check to see if we have any search terms and not a malformed SQL string
$error = false;
if($search['name'] && $search['document'] && $name_lookin == " AND (")
{
// We're looking for anything, check for a name lookin
$error = true;
}
elseif($search['name'] && !$search['document'] && $name_lookin == " AND (")
{
// Just in a name?
$error = true;
}
elseif(!$search['name'] && $search['document'] && $document_lookin == " {$string} (")
{
// Just in a document?
$error = true;
}
if($error == true)
{
// There are no search keywords to look for
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
$inquote = !$inquote;
}
if($search['name'] == 1)
{
$name_lookin .= ")";
}
if($search['document'] == 1)
{
$document_lookin .= ")";
}
$searchsql .= "{$name_lookin} {$document_lookin}";
}
else
{
$keywords = str_replace("\"", '', trim($keywords));
if(my_strlen($keywords) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// If we're looking in both, then find matches in either the name or the document
if($search['name'] == 1 && $search['document'] == 1)
{
$searchsql .= " AND ({$nfield} LIKE '%{$keywords}%' OR {$dfield} LIKE '%{$keywords}%')";
}
else
{
if($search['name'] == 1)
{
$searchsql .= " AND {$nfield} LIKE '%{$keywords}%'";
}
if($search['document'] == 1)
{
$searchsql .= " AND {$dfield} LIKE '%{$keywords}%'";
}
}
}
}
// Run the search
$helpdocs = array();
$query = $db->simple_select("helpdocs", "hid", $searchsql);
while($help = $db->fetch_array($query))
{
$helpdocs[$help['hid']] = $help['hid'];
}
if(count($helpdocs) < 1)
{
error($lang->error_nosearchresults);
}
$helpdocs = implode(',', $helpdocs);
return array(
"querycache" => $helpdocs
);
}
/**
* Perform a thread and post search under MySQL or MySQLi
*
* @param array $search Array of search data
* @return array Array of search data with results mixed in
*/
function perform_search_mysql($search)
{
global $mybb, $db, $lang, $cache;
$keywords = clean_keywords($search['keywords']);
if(!$keywords && !$search['author'])
{
error($lang->error_nosearchterms);
}
if($mybb->settings['minsearchword'] < 1)
{
$mybb->settings['minsearchword'] = 3;
}
$subject_lookin = $message_lookin = '';
if($keywords)
{
switch($db->type)
{
case 'mysql':
case 'mysqli':
$tfield = 't.subject';
$pfield = 'p.message';
break;
default:
$tfield = 'LOWER(t.subject)';
$pfield = 'LOWER(p.message)';
break;
}
// Complex search
$keywords = " {$keywords} ";
if(preg_match("#\s(and|or)\s#", $keywords))
{
$subject_lookin = " AND (";
$message_lookin = " AND (";
// Expand the string by double quotes
$keywords_exp = explode("\"", $keywords);
$inquote = false;
$boolean = '';
foreach($keywords_exp as $phrase)
{
// If we're not in a double quoted section
if(!$inquote)
{
// Expand out based on search operators (and, or)
$matches = preg_split("#\s{1,}(and|or)\s{1,}#", $phrase, -1, PREG_SPLIT_DELIM_CAPTURE);
$count_matches = count($matches);
for($i=0; $i < $count_matches; ++$i)
{
$word = trim($matches[$i]);
if(empty($word))
{
continue;
}
// If this word is a search operator set the boolean
if($i % 2 && ($word == "and" || $word == "or"))
{
if($i <= 1 && $subject_lookin == " AND (")
{
continue;
}
$boolean = $word;
}
// Otherwise check the length of the word as it is a normal search term
else
{
$word = trim($word);
// Word is too short - show error message
if(my_strlen($word) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// Add terms to search query
$subject_lookin .= " $boolean {$tfield} LIKE '%{$word}%'";
if($search['postthread'] == 1)
{
$message_lookin .= " $boolean {$pfield} LIKE '%{$word}%'";
}
$boolean = 'AND';
}
}
}
// In the middle of a quote (phrase)
else
{
$phrase = str_replace(array("+", "-", "*"), '', trim($phrase));
if(my_strlen($phrase) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
// Add phrase to search query
$subject_lookin .= " $boolean {$tfield} LIKE '%{$phrase}%'";
if($search['postthread'] == 1)
{
$message_lookin .= " $boolean {$pfield} LIKE '%{$phrase}%'";
}
$boolean = 'AND';
}
if($subject_lookin == " AND (")
{
// There are no search keywords to look for
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
$inquote = !$inquote;
}
$subject_lookin .= ")";
$message_lookin .= ")";
}
else
{
$keywords = str_replace("\"", '', trim($keywords));
if(my_strlen($keywords) < $mybb->settings['minsearchword'])
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
$subject_lookin = " AND {$tfield} LIKE '%{$keywords}%'";
if($search['postthread'] == 1)
{
$message_lookin = " AND {$pfield} LIKE '%{$keywords}%'";
}
}
}
$post_usersql = '';
$thread_usersql = '';
if($search['author'])
{
$userids = array();
$search['author'] = my_strtolower($search['author']);
if($search['matchusername'])
{
$user = get_user_by_username($search['author']);
if($user)
{
$userids[] = $user['uid'];
}
}
else
{
switch($db->type)
{
case 'mysql':
case 'mysqli':
$field = 'username';
break;
default:
$field = 'LOWER(username)';
break;
}
$query = $db->simple_select("users", "uid", "{$field} LIKE '%".$db->escape_string_like($search['author'])."%'");
while($user = $db->fetch_array($query))
{
$userids[] = $user['uid'];
}
}
if(count($userids) < 1)
{
error($lang->error_nosearchresults);
}
else
{
$userids = implode(',', $userids);
$post_usersql = " AND p.uid IN (".$userids.")";
$thread_usersql = " AND t.uid IN (".$userids.")";
}
}
$datecut = $post_datecut = $thread_datecut = '';
if($search['postdate'])
{
if($search['pddir'] == 0)
{
$datecut = "<=";
}
else
{
$datecut = ">=";
}
$now = TIME_NOW;
$datelimit = $now-(86400 * $search['postdate']);
$datecut .= "'$datelimit'";
$post_datecut = " AND p.dateline $datecut";
$thread_datecut = " AND t.dateline $datecut";
}
$thread_replycut = '';
if($search['numreplies'] != '' && $search['findthreadst'])
{
if((int)$search['findthreadst'] == 1)
{
$thread_replycut = " AND t.replies >= '".(int)$search['numreplies']."'";
}
else
{
$thread_replycut = " AND t.replies <= '".(int)$search['numreplies']."'";
}
}
$thread_prefixcut = '';
$prefixlist = array();
if($search['threadprefix'] && $search['threadprefix'][0] != 'any')
{
foreach($search['threadprefix'] as $threadprefix)
{
$threadprefix = (int)$threadprefix;
$prefixlist[] = $threadprefix;
}
}
if(count($prefixlist) == 1)
{
$thread_prefixcut .= " AND t.prefix='$threadprefix' ";
}
else
{
if(count($prefixlist) > 1)
{
$thread_prefixcut = " AND t.prefix IN (".implode(',', $prefixlist).")";
}
}
$forumin = '';
$fidlist = array();
if(!empty($search['forums']) && (!is_array($search['forums']) || $search['forums'][0] != "all"))
{
if(!is_array($search['forums']))
{
$search['forums'] = array((int)$search['forums']);
}
foreach($search['forums'] as $forum)
{
$forum = (int)$forum;
if($forum > 0)
{
$fidlist[] = $forum;
$child_list = get_child_list($forum);
if(is_array($child_list))
{
$fidlist = array_merge($fidlist, $child_list);
}
}
}
$fidlist = array_unique($fidlist);
if(count($fidlist) >= 1)
{
$forumin = " AND t.fid IN (".implode(',', $fidlist).")";
}
}
$permsql = "";
$onlyusfids = array();
// Check group permissions if we can't view threads not started by us
if($group_permissions = forum_permissions())
{
foreach($group_permissions as $fid => $forum_permissions)
{
if(isset($forum_permissions['canonlyviewownthreads']) && $forum_permissions['canonlyviewownthreads'] == 1)
{
$onlyusfids[] = $fid;
}
}
}
if(!empty($onlyusfids))
{
$permsql .= "AND ((t.fid IN(".implode(',', $onlyusfids).") AND t.uid='{$mybb->user['uid']}') OR t.fid NOT IN(".implode(',', $onlyusfids)."))";
}
$unsearchforums = get_unsearchable_forums();
if($unsearchforums)
{
$permsql .= " AND t.fid NOT IN ($unsearchforums)";
}
$inactiveforums = get_inactive_forums();
if($inactiveforums)
{
$permsql .= " AND t.fid NOT IN ($inactiveforums)";
}
$visiblesql = $post_visiblesql = $plain_post_visiblesql = "";
if(isset($search['visible']))
{
if($search['visible'] == 1)
{
$visiblesql = " AND t.visible = '1'";
if($search['postthread'] == 1)
{
$post_visiblesql = " AND p.visible = '1'";
$plain_post_visiblesql = " AND visible = '1'";
}
}
elseif($search['visible'] == -1)
{
$visiblesql = " AND t.visible = '-1'";
if($search['postthread'] == 1)
{
$post_visiblesql = " AND p.visible = '-1'";
$plain_post_visiblesql = " AND visible = '-1'";
}
}
else
{
$visiblesql = " AND t.visible == '0'";
if($search['postthread'] == 1)
{
$post_visiblesql = " AND p.visible == '0'";
$plain_post_visiblesql = " AND visible == '0'";
}
}
}
// Searching a specific thread?
$tidsql = '';
if(!empty($search['tid']))
{
$tidsql = " AND t.tid='".(int)$search['tid']."'";
}
$limitsql = '';
if((int)$mybb->settings['searchhardlimit'] > 0)
{
$limitsql = "LIMIT ".(int)$mybb->settings['searchhardlimit'];
}
// Searching both posts and thread titles
$threads = array();
$posts = array();
$firstposts = array();
if($search['postthread'] == 1)
{
// No need to search subjects when looking for results within a specific thread
if(empty($search['tid']))
{
$query = $db->query("
SELECT t.tid, t.firstpost
FROM ".TABLE_PREFIX."threads t
WHERE 1=1 {$thread_datecut} {$thread_replycut} {$thread_prefixcut} {$forumin} {$thread_usersql} {$permsql} {$visiblesql} AND t.closed NOT LIKE 'moved|%' {$subject_lookin}
{$limitsql}
");
while($thread = $db->fetch_array($query))
{
$threads[$thread['tid']] = $thread['tid'];
if($thread['firstpost'])
{
$posts[$thread['tid']] = $thread['firstpost'];
}
}
}
$query = $db->query("
SELECT p.pid, p.tid
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
WHERE 1=1 {$post_datecut} {$thread_replycut} {$thread_prefixcut} {$forumin} {$post_usersql} {$permsql} {$tidsql} {$visiblesql} {$post_visiblesql} AND t.closed NOT LIKE 'moved|%' {$message_lookin}
{$limitsql}
");
while($post = $db->fetch_array($query))
{
$posts[$post['pid']] = $post['pid'];
$threads[$post['tid']] = $post['tid'];
}
if(count($posts) < 1 && count($threads) < 1)
{
error($lang->error_nosearchresults);
}
$threads = implode(',', $threads);
$posts = implode(',', $posts);
}
// Searching only thread titles
else
{
$query = $db->query("
SELECT t.tid, t.firstpost
FROM ".TABLE_PREFIX."threads t
WHERE 1=1 {$thread_datecut} {$thread_replycut} {$thread_prefixcut} {$forumin} {$thread_usersql} {$permsql} {$visiblesql} {$subject_lookin}
{$limitsql}
");
while($thread = $db->fetch_array($query))
{
$threads[$thread['tid']] = $thread['tid'];
if($thread['firstpost'])
{
$firstposts[$thread['tid']] = $thread['firstpost'];
}
}
if(count($threads) < 1)
{
error($lang->error_nosearchresults);
}
$threads = implode(',', $threads);
$firstposts = implode(',', $firstposts);
if($firstposts)
{
$query = $db->simple_select("posts", "pid", "pid IN ($firstposts) {$plain_post_visiblesql} {$limitsql}");
while($post = $db->fetch_array($query))
{
$posts[$post['pid']] = $post['pid'];
}
$posts = implode(',', $posts);
}
}
return array(
"threads" => $threads,
"posts" => $posts,
"querycache" => ''
);
}
/**
* Perform a thread and post search under MySQL or MySQLi using boolean fulltext capabilities
*
* @param array $search Array of search data
* @return array Array of search data with results mixed in
*/
function perform_search_mysql_ft($search)
{
global $mybb, $db, $lang;
$keywords = clean_keywords_ft($search['keywords']);
if(!$keywords && !$search['author'])
{
error($lang->error_nosearchterms);
}
// Attempt to determine minimum word length from MySQL for fulltext searches
$query = $db->query("SHOW VARIABLES LIKE 'ft_min_word_len';");
$min_length = $db->fetch_field($query, 'Value');
if(is_numeric($min_length))
{
$mybb->settings['minsearchword'] = $min_length;
}
// Otherwise, could not fetch - default back to MySQL fulltext default setting
else
{
$mybb->settings['minsearchword'] = 4;
}
if($keywords)
{
$keywords_exp = explode("\"", $keywords);
$inquote = false;
foreach($keywords_exp as $phrase)
{
if(!$inquote)
{
$split_words = preg_split("#\s{1,}#", $phrase, -1);
foreach($split_words as $word)
{
$word = str_replace(array("+", "-", "*"), '', $word);
if(!$word)
{
continue;
}
if(my_strlen($word) < $mybb->settings['minsearchword'])
{
$all_too_short = true;
}
else
{
$all_too_short = false;
break;
}
}
}
else
{
$phrase = str_replace(array("+", "-", "*"), '', $phrase);
if(my_strlen($phrase) < $mybb->settings['minsearchword'])
{
$all_too_short = true;
}
else
{
$all_too_short = false;
break;
}
}
$inquote = !$inquote;
}
// Show the minimum search term error only if all search terms are too short
if($all_too_short == true)
{
$lang->error_minsearchlength = $lang->sprintf($lang->error_minsearchlength, $mybb->settings['minsearchword']);
error($lang->error_minsearchlength);
}
$message_lookin = "AND MATCH(message) AGAINST('".$db->escape_string($keywords)."' IN BOOLEAN MODE)";
$subject_lookin = "AND MATCH(subject) AGAINST('".$db->escape_string($keywords)."' IN BOOLEAN MODE)";
}
$post_usersql = '';
$thread_usersql = '';
if($search['author'])
{
$userids = array();
$search['author'] = my_strtolower($search['author']);
if($search['matchusername'])
{
$user = get_user_by_username($search['author']);
if($user)
{
$userids[] = $user['uid'];
}
}
else
{
$query = $db->simple_select("users", "uid", "username LIKE '%".$db->escape_string_like($search['author'])."%'");
while($user = $db->fetch_array($query))
{
$userids[] = $user['uid'];
}
}
if(count($userids) < 1)
{
error($lang->error_nosearchresults);
}
else
{
$userids = implode(',', $userids);
$post_usersql = " AND p.uid IN (".$userids.")";
$thread_usersql = " AND t.uid IN (".$userids.")";
}
}
$datecut = '';
if($search['postdate'])
{
if($search['pddir'] == 0)
{
$datecut = "<=";
}
else
{
$datecut = ">=";
}
$now = TIME_NOW;
$datelimit = $now-(86400 * $search['postdate']);
$datecut .= "'$datelimit'";
$post_datecut = " AND p.dateline $datecut";
$thread_datecut = " AND t.dateline $datecut";
}
$thread_replycut = '';
if($search['numreplies'] != '' && $search['findthreadst'])
{
if((int)$search['findthreadst'] == 1)
{
$thread_replycut = " AND t.replies >= '".(int)$search['numreplies']."'";
}
else
{
$thread_replycut = " AND t.replies <= '".(int)$search['numreplies']."'";
}
}
$thread_prefixcut = '';
$prefixlist = array();
if($search['threadprefix'] && $search['threadprefix'][0] != 'any')
{
foreach($search['threadprefix'] as $threadprefix)
{
$threadprefix = (int)$threadprefix;
$prefixlist[] = $threadprefix;
}
}
if(count($prefixlist) == 1)
{
$thread_prefixcut .= " AND t.prefix='$threadprefix' ";
}
else
{
if(count($prefixlist) > 1)
{
$thread_prefixcut = " AND t.prefix IN (".implode(',', $prefixlist).")";
}
}
$forumin = '';
$fidlist = array();
$searchin = array();
if(!empty($search['forums']) && (!is_array($search['forums']) || $search['forums'][0] != "all"))
{
if(!is_array($search['forums']))
{
$search['forums'] = array((int)$search['forums']);
}
foreach($search['forums'] as $forum)
{
$forum = (int)$forum;
if($forum > 0)
{
$fidlist[] = $forum;
$child_list = get_child_list($forum);
if(is_array($child_list))
{
$fidlist = array_merge($fidlist, $child_list);
}
}
}
$fidlist = array_unique($fidlist);
if(count($fidlist) >= 1)
{
$forumin = " AND t.fid IN (".implode(',', $fidlist).")";
}
}
$permsql = "";
$onlyusfids = array();
// Check group permissions if we can't view threads not started by us
$group_permissions = forum_permissions();
foreach($group_permissions as $fid => $forum_permissions)
{
if($forum_permissions['canonlyviewownthreads'] == 1)
{
$onlyusfids[] = $fid;
}
}
if(!empty($onlyusfids))
{
$permsql .= "AND ((t.fid IN(".implode(',', $onlyusfids).") AND t.uid='{$mybb->user['uid']}') OR t.fid NOT IN(".implode(',', $onlyusfids)."))";
}
$unsearchforums = get_unsearchable_forums();
if($unsearchforums)
{
$permsql .= " AND t.fid NOT IN ($unsearchforums)";
}
$inactiveforums = get_inactive_forums();
if($inactiveforums)
{
$permsql .= " AND t.fid NOT IN ($inactiveforums)";
}
$visiblesql = $post_visiblesql = $plain_post_visiblesql = "";
if(isset($search['visible']))
{
if($search['visible'] == 1)
{
$visiblesql = " AND t.visible = '1'";
if($search['postthread'] == 1)
{
$post_visiblesql = " AND p.visible = '1'";
$plain_post_visiblesql = " AND visible = '1'";
}
}
elseif($search['visible'] == -1)
{
$visiblesql = " AND t.visible = '-1'";
if($search['postthread'] == 1)
{
$post_visiblesql = " AND p.visible = '-1'";
$plain_post_visiblesql = " AND visible = '-1'";
}
}
else
{
$visiblesql = " AND t.visible != '1'";
if($search['postthread'] == 1)
{
$post_visiblesql = " AND p.visible != '1'";
$plain_post_visiblesql = " AND visible != '1'";
}
}
}
// Searching a specific thread?
if($search['tid'])
{
$tidsql = " AND t.tid='".(int)$search['tid']."'";
}
$limitsql = '';
if((int)$mybb->settings['searchhardlimit'] > 0)
{
$limitsql = "LIMIT ".(int)$mybb->settings['searchhardlimit'];
}
// Searching both posts and thread titles
$threads = array();
$posts = array();
$firstposts = array();
if($search['postthread'] == 1)
{
// No need to search subjects when looking for results within a specific thread
if(!$search['tid'])
{
$query = $db->query("
SELECT t.tid, t.firstpost
FROM ".TABLE_PREFIX."threads t
WHERE 1=1 {$thread_datecut} {$thread_replycut} {$thread_prefixcut} {$forumin} {$thread_usersql} {$permsql} {$visiblesql} AND t.closed NOT LIKE 'moved|%' {$subject_lookin}
{$limitsql}
");
while($thread = $db->fetch_array($query))
{
$threads[$thread['tid']] = $thread['tid'];
if($thread['firstpost'])
{
$posts[$thread['tid']] = $thread['firstpost'];
}
}
}
$query = $db->query("
SELECT p.pid, p.tid
FROM ".TABLE_PREFIX."posts p
LEFT JOIN ".TABLE_PREFIX."threads t ON (t.tid=p.tid)
WHERE 1=1 {$post_datecut} {$thread_replycut} {$thread_prefixcut} {$forumin} {$post_usersql} {$permsql} {$tidsql} {$post_visiblesql} {$visiblesql} AND t.closed NOT LIKE 'moved|%' {$message_lookin}
{$limitsql}
");
while($post = $db->fetch_array($query))
{
$posts[$post['pid']] = $post['pid'];
$threads[$post['tid']] = $post['tid'];
}
if(count($posts) < 1 && count($threads) < 1)
{
error($lang->error_nosearchresults);
}
$threads = implode(',', $threads);
$posts = implode(',', $posts);
}
// Searching only thread titles
else
{
$query = $db->query("
SELECT t.tid, t.firstpost
FROM ".TABLE_PREFIX."threads t
WHERE 1=1 {$thread_datecut} {$thread_replycut} {$thread_prefixcut} {$forumin} {$thread_usersql} {$permsql} {$visiblesql} {$subject_lookin}
{$limitsql}
");
while($thread = $db->fetch_array($query))
{
$threads[$thread['tid']] = $thread['tid'];
if($thread['firstpost'])
{
$firstposts[$thread['tid']] = $thread['firstpost'];
}
}
if(count($threads) < 1)
{
error($lang->error_nosearchresults);
}
$threads = implode(',', $threads);
$firstposts = implode(',', $firstposts);
if($firstposts)
{
$query = $db->simple_select("posts", "pid", "pid IN ($firstposts) {$plain_post_visiblesql} {$limitsql}");
while($post = $db->fetch_array($query))
{
$posts[$post['pid']] = $post['pid'];
}
$posts = implode(',', $posts);
}
}
return array(
"threads" => $threads,
"posts" => $posts,
"querycache" => ''
);
}
|
lgpl-3.0
|
arcualberta/Catfish
|
Catfish/wwwroot/assets/js/form.js
|
581
|
function addValue(fieldId) {
//example string
//Item_Fields_3__Values_0__Values_0__Value
let itemToDupe = $('#' + fieldId).children().last();
let baseId = fieldId + "_Values_";
//get digits from original item
let split = itemToDupe.children().last()[0].id.replace(baseId, "").split("__", 2);
baseId += (+split[0] + 1);
let secondNumber = split[1].split("_");
baseId += "__Values_" + secondNumber[1] + "__Value";
let dupeItem = itemToDupe.clone();
dupeItem.children().last()[0].id = baseId;
$('#' + fieldId).append(dupeItem);
}
|
lgpl-3.0
|
qoollo/logger
|
src/Qoollo.Logger.Test/Properties/AssemblyInfo.cs
|
1448
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Qoollo.Logger.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Qoollo.Logger.Test")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c15bdf9d-f4ff-43d9-b502-d0d5061b8459")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
lgpl-3.0
|
collenirwin/BoinEdit
|
BoinEdit/obj/Debug/DirTreeViewWPF.g.cs
|
2955
|
#pragma checksum "..\..\DirTreeViewWPF.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "27D5FE2F4536B6BEFF6736BA6EB3D5DE"
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Effects;
using System.Windows.Media.Imaging;
using System.Windows.Media.Media3D;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Shell;
namespace BoinEditNS {
/// <summary>
/// DirTreeViewWPF
/// </summary>
public partial class DirTreeViewWPF : System.Windows.Controls.UserControl, System.Windows.Markup.IComponentConnector {
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Uri resourceLocater = new System.Uri("/BoinEdit;component/dirtreeviewwpf.xaml", System.UriKind.Relative);
#line 1 "..\..\DirTreeViewWPF.xaml"
System.Windows.Application.LoadComponent(this, resourceLocater);
#line default
#line hidden
}
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Design", "CA1033:InterfaceMethodsShouldBeCallableByChildTypes")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1800:DoNotCastUnnecessarily")]
void System.Windows.Markup.IComponentConnector.Connect(int connectionId, object target) {
this._contentLoaded = true;
}
}
}
|
lgpl-3.0
|
devmix/java-commons
|
commons-i18n/src/main/java/com/github/devmix/commons/i18n/core/values/KeyValues.java
|
1621
|
/*
* Commons Library
* Copyright (c) 2015 Sergey Grachev (sergey.grachev@yahoo.com). All rights reserved.
*
* This software is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this software. If not, see <http://www.gnu.org/licenses/>.
*/
package com.github.devmix.commons.i18n.core.values;
import com.github.devmix.commons.i18n.core.values.composite.CompositeParser;
import com.github.devmix.commons.i18n.core.values.reference.ReferenceParser;
import com.github.devmix.commons.i18n.core.values.string.StringParser;
/**
* @author Sergey Grachev
*/
public final class KeyValues {
private KeyValues() {
}
public static Value parse(final String text) {
final CompositeValue composite = CompositeParser.tryParse(text);
if (composite != null) {
return composite;
} else {
final ReferenceValue reference = ReferenceParser.tryParse(text);
if (reference != null) {
return reference;
} else {
return StringParser.tryParse(text);
}
}
}
}
|
lgpl-3.0
|
followcat/predator
|
tools/addtags.py
|
1677
|
# -*- coding: utf-8 -*-
import yaml
import os
import utils.builtin
from sources.industry_id import*
cvpath = 'output/jingying/RAW/'
cvlistpath = 'jingying/JOBTITLES'
def add_file(path, filename, filedate):
file_path = os.path.join(path, filename)
with open(file_path, 'w') as f:
f.write(filedate)
return True
def existscv(path, cv_id):
exists = False
filename = cv_id + '.yaml'
file_path = os.path.join(path, filename)
if os.path.exists(file_path):
exists = True
return exists
for _classify_id in industryID.values():
print _classify_id
_file = _classify_id + '.yaml'
try:
yamlfile = utils.builtin.load_yaml(cvlistpath, _file)
yamldata = yamlfile['datas']
except IOError:
continue
sorted_id = sorted(yamldata,
key = lambda cvid: yamldata[cvid]['peo'][-1],
reverse=True)
for cv_id in sorted_id:
if not existscv(cvpath, cv_id):
continue
else:
print cv_id
try:
cvdata = utils.builtin.load_yaml(cvpath, cv_id+'.yaml')
except Exception:
print "Load error :",cv_id
continue
try:
yamldata.pop('tag')
except KeyError:
pass
if 'tags' in cvdata.keys() and len(cvdata['tags'].keys())!=0:
continue
else:
cvdata['tags'] = {}
cvdata['tags'] = yamldata[cv_id]['tags']
dump_data = yaml.dump(cvdata, Dumper=yaml.CSafeDumper, allow_unicode=True)
add_file(cvpath, cv_id+'.yaml', dump_data)
|
lgpl-3.0
|
daxxcoin/daxxcore
|
p2p/discv5/udp.go
|
13074
|
// Copyright 2016 The daxxcoreAuthors
// This file is part of the daxxcore library.
//
// The daxxcore library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The daxxcore library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the daxxcore library. If not, see <http://www.gnu.org/licenses/>.
package discv5
import (
"bytes"
"crypto/ecdsa"
"errors"
"fmt"
"net"
"time"
"github.com/daxxcoin/daxxcore/common"
"github.com/daxxcoin/daxxcore/crypto"
"github.com/daxxcoin/daxxcore/logger"
"github.com/daxxcoin/daxxcore/logger/glog"
"github.com/daxxcoin/daxxcore/p2p/nat"
"github.com/daxxcoin/daxxcore/p2p/netutil"
"github.com/daxxcoin/daxxcore/rlp"
)
const Version = 4
// Errors
var (
errPacketTooSmall = errors.New("too small")
errBadHash = errors.New("bad hash")
errExpired = errors.New("expired")
errUnsolicitedReply = errors.New("unsolicited reply")
errUnknownNode = errors.New("unknown node")
errTimeout = errors.New("RPC timeout")
errClockWarp = errors.New("reply deadline too far in the future")
errClosed = errors.New("socket closed")
)
// Timeouts
const (
respTimeout = 500 * time.Millisecond
sendTimeout = 500 * time.Millisecond
expiration = 20 * time.Second
ntpFailureThreshold = 32 // Continuous timeouts after which to check NTP
ntpWarningCooldown = 10 * time.Minute // Minimum amount of time to pass before repeating NTP warning
driftThreshold = 10 * time.Second // Allowed clock drift before warning user
)
// RPC request structures
type (
ping struct {
Version uint
From, To rpcEndpoint
Expiration uint64
// v5
Topics []Topic
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// pong is the reply to ping.
pong struct {
// This field should mirror the UDP envelope address
// of the ping packet, which provides a way to discover the
// the external address (after NAT).
To rpcEndpoint
ReplyTok []byte // This contains the hash of the ping packet.
Expiration uint64 // Absolute timestamp at which the packet becomes invalid.
// v5
TopicHash common.Hash
TicketSerial uint32
WaitPeriods []uint32
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// findnode is a query for nodes close to the given target.
findnode struct {
Target NodeID // doesn't need to be an actual public key
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// findnode is a query for nodes close to the given target.
findnodeHash struct {
Target common.Hash
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
// reply to findnode
neighbors struct {
Nodes []rpcNode
Expiration uint64
// Ignore additional fields (for forward compatibility).
Rest []rlp.RawValue `rlp:"tail"`
}
topicRegister struct {
Topics []Topic
Idx uint
Pong []byte
}
topicQuery struct {
Topic Topic
Expiration uint64
}
// reply to topicQuery
topicNodes struct {
Echo common.Hash
Nodes []rpcNode
}
rpcNode struct {
IP net.IP // len 4 for IPv4 or 16 for IPv6
UDP uint16 // for discovery protocol
TCP uint16 // for RLPx protocol
ID NodeID
}
rpcEndpoint struct {
IP net.IP // len 4 for IPv4 or 16 for IPv6
UDP uint16 // for discovery protocol
TCP uint16 // for RLPx protocol
}
)
const (
macSize = 256 / 8
sigSize = 520 / 8
headSize = macSize + sigSize // space of packet frame data
)
// Neighbors replies are sent across multiple packets to
// stay below the 1280 byte limit. We compute the maximum number
// of entries by stuffing a packet until it grows too large.
var maxNeighbors = func() int {
p := neighbors{Expiration: ^uint64(0)}
maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
for n := 0; ; n++ {
p.Nodes = append(p.Nodes, maxSizeNode)
size, _, err := rlp.EncodeToReader(p)
if err != nil {
// If this ever happens, it will be caught by the unit tests.
panic("cannot encode: " + err.Error())
}
if headSize+size+1 >= 1280 {
return n
}
}
}()
var maxTopicNodes = func() int {
p := topicNodes{}
maxSizeNode := rpcNode{IP: make(net.IP, 16), UDP: ^uint16(0), TCP: ^uint16(0)}
for n := 0; ; n++ {
p.Nodes = append(p.Nodes, maxSizeNode)
size, _, err := rlp.EncodeToReader(p)
if err != nil {
// If this ever happens, it will be caught by the unit tests.
panic("cannot encode: " + err.Error())
}
if headSize+size+1 >= 1280 {
return n
}
}
}()
func makeEndpoint(addr *net.UDPAddr, tcpPort uint16) rpcEndpoint {
ip := addr.IP.To4()
if ip == nil {
ip = addr.IP.To16()
}
return rpcEndpoint{IP: ip, UDP: uint16(addr.Port), TCP: tcpPort}
}
func (e1 rpcEndpoint) equal(e2 rpcEndpoint) bool {
return e1.UDP == e2.UDP && e1.TCP == e2.TCP && e1.IP.Equal(e2.IP)
}
func nodeFromRPC(sender *net.UDPAddr, rn rpcNode) (*Node, error) {
if err := netutil.CheckRelayIP(sender.IP, rn.IP); err != nil {
return nil, err
}
n := NewNode(rn.ID, rn.IP, rn.UDP, rn.TCP)
err := n.validateComplete()
return n, err
}
func nodeToRPC(n *Node) rpcNode {
return rpcNode{ID: n.ID, IP: n.IP, UDP: n.UDP, TCP: n.TCP}
}
type ingressPacket struct {
remoteID NodeID
remoteAddr *net.UDPAddr
ev nodeEvent
hash []byte
data interface{} // one of the RPC structs
rawData []byte
}
type conn interface {
ReadFromUDP(b []byte) (n int, addr *net.UDPAddr, err error)
WriteToUDP(b []byte, addr *net.UDPAddr) (n int, err error)
Close() error
LocalAddr() net.Addr
}
// udp implements the RPC protocol.
type udp struct {
conn conn
priv *ecdsa.PrivateKey
ourEndpoint rpcEndpoint
nat nat.Interface
net *Network
}
// ListenUDP returns a new table that listens for UDP packets on laddr.
func ListenUDP(priv *ecdsa.PrivateKey, laddr string, natm nat.Interface, nodeDBPath string, netrestrict *netutil.Netlist) (*Network, error) {
transport, err := listenUDP(priv, laddr)
if err != nil {
return nil, err
}
net, err := newNetwork(transport, priv.PublicKey, natm, nodeDBPath, netrestrict)
if err != nil {
return nil, err
}
transport.net = net
go transport.readLoop()
return net, nil
}
func listenUDP(priv *ecdsa.PrivateKey, laddr string) (*udp, error) {
addr, err := net.ResolveUDPAddr("udp", laddr)
if err != nil {
return nil, err
}
conn, err := net.ListenUDP("udp", addr)
if err != nil {
return nil, err
}
return &udp{conn: conn, priv: priv, ourEndpoint: makeEndpoint(addr, uint16(addr.Port))}, nil
}
func (t *udp) localAddr() *net.UDPAddr {
return t.conn.LocalAddr().(*net.UDPAddr)
}
func (t *udp) Close() {
t.conn.Close()
}
func (t *udp) send(remote *Node, ptype nodeEvent, data interface{}) (hash []byte) {
hash, _ = t.sendPacket(remote.ID, remote.addr(), byte(ptype), data)
return hash
}
func (t *udp) sendPing(remote *Node, toaddr *net.UDPAddr, topics []Topic) (hash []byte) {
hash, _ = t.sendPacket(remote.ID, toaddr, byte(pingPacket), ping{
Version: Version,
From: t.ourEndpoint,
To: makeEndpoint(toaddr, uint16(toaddr.Port)), // TODO: maybe use known TCP port from DB
Expiration: uint64(time.Now().Add(expiration).Unix()),
Topics: topics,
})
return hash
}
func (t *udp) sendFindnode(remote *Node, target NodeID) {
t.sendPacket(remote.ID, remote.addr(), byte(findnodePacket), findnode{
Target: target,
Expiration: uint64(time.Now().Add(expiration).Unix()),
})
}
func (t *udp) sendNeighbours(remote *Node, results []*Node) {
// Send neighbors in chunks with at most maxNeighbors per packet
// to stay below the 1280 byte limit.
p := neighbors{Expiration: uint64(time.Now().Add(expiration).Unix())}
for i, result := range results {
p.Nodes = append(p.Nodes, nodeToRPC(result))
if len(p.Nodes) == maxNeighbors || i == len(results)-1 {
t.sendPacket(remote.ID, remote.addr(), byte(neighborsPacket), p)
p.Nodes = p.Nodes[:0]
}
}
}
func (t *udp) sendFindnodeHash(remote *Node, target common.Hash) {
t.sendPacket(remote.ID, remote.addr(), byte(findnodeHashPacket), findnodeHash{
Target: target,
Expiration: uint64(time.Now().Add(expiration).Unix()),
})
}
func (t *udp) sendTopicRegister(remote *Node, topics []Topic, idx int, pong []byte) {
t.sendPacket(remote.ID, remote.addr(), byte(topicRegisterPacket), topicRegister{
Topics: topics,
Idx: uint(idx),
Pong: pong,
})
}
func (t *udp) sendTopicNodes(remote *Node, queryHash common.Hash, nodes []*Node) {
p := topicNodes{Echo: queryHash}
if len(nodes) == 0 {
t.sendPacket(remote.ID, remote.addr(), byte(topicNodesPacket), p)
return
}
for i, result := range nodes {
if netutil.CheckRelayIP(remote.IP, result.IP) != nil {
continue
}
p.Nodes = append(p.Nodes, nodeToRPC(result))
if len(p.Nodes) == maxTopicNodes || i == len(nodes)-1 {
t.sendPacket(remote.ID, remote.addr(), byte(topicNodesPacket), p)
p.Nodes = p.Nodes[:0]
}
}
}
func (t *udp) sendPacket(toid NodeID, toaddr *net.UDPAddr, ptype byte, req interface{}) (hash []byte, err error) {
//fmt.Println("sendPacket", nodeEvent(ptype), toaddr.String(), toid.String())
packet, hash, err := encodePacket(t.priv, ptype, req)
if err != nil {
//fmt.Println(err)
return hash, err
}
glog.V(logger.Detail).Infof(">>> %v to %x@%v\n", nodeEvent(ptype), toid[:8], toaddr)
if _, err = t.conn.WriteToUDP(packet, toaddr); err != nil {
glog.V(logger.Detail).Infoln("UDP send failed:", err)
}
//fmt.Println(err)
return hash, err
}
// zeroed padding space for encodePacket.
var headSpace = make([]byte, headSize)
func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) (p, hash []byte, err error) {
b := new(bytes.Buffer)
b.Write(headSpace)
b.WriteByte(ptype)
if err := rlp.Encode(b, req); err != nil {
glog.V(logger.Error).Infoln("error encoding packet:", err)
return nil, nil, err
}
packet := b.Bytes()
sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
if err != nil {
glog.V(logger.Error).Infoln("could not sign packet:", err)
return nil, nil, err
}
copy(packet[macSize:], sig)
// add the hash to the front. Note: this doesn't protect the
// packet in any way.
hash = crypto.Keccak256(packet[macSize:])
copy(packet, hash)
return packet, hash, nil
}
// readLoop runs in its own goroutine. it injects ingress UDP packets
// into the network loop.
func (t *udp) readLoop() {
defer t.conn.Close()
// Discovery packets are defined to be no larger than 1280 bytes.
// Packets larger than this size will be cut at the end and treated
// as invalid because their hash won't match.
buf := make([]byte, 1280)
for {
nbytes, from, err := t.conn.ReadFromUDP(buf)
if netutil.IsTemporaryError(err) {
// Ignore temporary read errors.
glog.V(logger.Debug).Infof("Temporary read error: %v", err)
continue
} else if err != nil {
// Shut down the loop for permament errors.
glog.V(logger.Debug).Infof("Read error: %v", err)
return
}
t.handlePacket(from, buf[:nbytes])
}
}
func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error {
pkt := ingressPacket{remoteAddr: from}
if err := decodePacket(buf, &pkt); err != nil {
glog.V(logger.Debug).Infof("Bad packet from %v: %v\n", from, err)
//fmt.Println("bad packet", err)
return err
}
t.net.reqReadPacket(pkt)
return nil
}
func decodePacket(buffer []byte, pkt *ingressPacket) error {
if len(buffer) < headSize+1 {
return errPacketTooSmall
}
buf := make([]byte, len(buffer))
copy(buf, buffer)
hash, sig, sigdata := buf[:macSize], buf[macSize:headSize], buf[headSize:]
shouldhash := crypto.Keccak256(buf[macSize:])
if !bytes.Equal(hash, shouldhash) {
return errBadHash
}
fromID, err := recoverNodeID(crypto.Keccak256(buf[headSize:]), sig)
if err != nil {
return err
}
pkt.rawData = buf
pkt.hash = hash
pkt.remoteID = fromID
switch pkt.ev = nodeEvent(sigdata[0]); pkt.ev {
case pingPacket:
pkt.data = new(ping)
case pongPacket:
pkt.data = new(pong)
case findnodePacket:
pkt.data = new(findnode)
case neighborsPacket:
pkt.data = new(neighbors)
case findnodeHashPacket:
pkt.data = new(findnodeHash)
case topicRegisterPacket:
pkt.data = new(topicRegister)
case topicQueryPacket:
pkt.data = new(topicQuery)
case topicNodesPacket:
pkt.data = new(topicNodes)
default:
return fmt.Errorf("unknown packet type: %d", sigdata[0])
}
s := rlp.NewStream(bytes.NewReader(sigdata[1:]), 0)
err = s.Decode(pkt.data)
return err
}
|
lgpl-3.0
|
charxie/energy2d
|
energy2d/src/org/energy2d/model/Part.java
|
37618
|
package org.energy2d.model;
import java.awt.Color;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Line2D;
import java.awt.geom.Path2D;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.util.List;
import org.energy2d.math.Annulus;
import org.energy2d.math.Blob2D;
import org.energy2d.math.EllipticalAnnulus;
import org.energy2d.math.Polygon2D;
import org.energy2d.math.TransformableShape;
import org.energy2d.util.ColorFill;
import org.energy2d.util.FillPattern;
import org.energy2d.util.Texture;
import org.energy2d.util.XmlCharacterEncoder;
/**
* Default properties set to be that of polystyrene. See http://en.wikipedia.org/wiki/Polystyrene
*
* @author Charles Xie
*
*/
public class Part extends Manipulable {
// constant power input/output: positive = source, negative = sink, zero = off. Unit: W/m^3
private float power;
// this turns the power on and off: it should not be saved in the XML, or copied to another part
private boolean powerSwitch = true;
// http://en.wikipedia.org/wiki/Temperature_coefficient
private float thermistorTemperatureCoefficient = 0;
private float thermistorReferenceTemperature = 0;
// a fixed or initial temperature for this part
private float temperature;
// when this flag is true, temperature is maintained at the set value. Otherwise, it will be just the initial value that defines the heat energy this part initially possesses.
private boolean constantTemperature;
/*
* the thermal conductivity: Fourier's Law, the flow of heat energy
*
* q = - k dT/dx
*
* Unit: W/(mK). Water's is 0.08.
*/
private float thermalConductivity = 1f;
// the specific heat capacity: J/(kgK).
private float specificHeat = 1300f;
// density kg/m^3. The default value is foam's.
private float density = 25f;
// optical properties
private float absorptivity = 1;
private float transmissivity;
private float reflectivity;
private float emissivity;
private boolean scattering;
private boolean scatteringVisible = true;
// mechanical properties
private float elasticity = 1.0f;
private float windSpeed;
private float windAngle;
private final static DecimalFormat LABEL_FORMAT = new DecimalFormat("####.######");
private final static DecimalFormat TWO_DECIMALS_FORMAT = new DecimalFormat("####.##");
private final static DecimalFormat SHORT_LABEL_FORMAT = new DecimalFormat("###.##");
private FillPattern fillPattern;
private boolean filled = true;
private Model2D model;
public Part(Shape shape, Model2D model) {
super(shape);
this.model = model;
fillPattern = new ColorFill(Color.GRAY);
}
public void setFilled(boolean filled) {
this.filled = filled;
}
public boolean isFilled() {
return filled;
}
public void setFillPattern(FillPattern fillPattern) {
this.fillPattern = fillPattern;
}
public FillPattern getFillPattern() {
return fillPattern;
}
@Override
public Part duplicate(float x, float y) {
Shape s = getShape();
if (s instanceof Rectangle2D.Float) {
Rectangle2D.Float r = (Rectangle2D.Float) s;
s = new Rectangle2D.Float(x - 0.5f * r.width, y - 0.5f * r.height, r.width, r.height);
} else if (s instanceof Ellipse2D.Float) {
Ellipse2D.Float e = (Ellipse2D.Float) s;
s = new Ellipse2D.Float(x - 0.5f * e.width, y - 0.5f * e.height, e.width, e.height);
} else if (s instanceof Annulus) {
s = new Annulus((Annulus) s);
Rectangle2D r = s.getBounds2D();
((Annulus) s).translateBy(x - (float) r.getCenterX(), y - (float) r.getCenterY());
} else if (s instanceof EllipticalAnnulus) {
s = new EllipticalAnnulus((EllipticalAnnulus) s);
Rectangle2D r = s.getBounds2D();
((EllipticalAnnulus) s).translateBy(x - (float) r.getCenterX(), y - (float) r.getCenterY());
} else if (s instanceof Polygon2D) {
s = ((Polygon2D) s).duplicate();
Rectangle2D r = s.getBounds2D();
float dx = x - (float) r.getCenterX();
float dy = y - (float) r.getCenterY();
((Polygon2D) s).translateBy(dx, dy);
} else if (s instanceof Blob2D) {
s = ((Blob2D) s).duplicate();
Rectangle2D r = s.getBounds2D();
float dx = x - (float) r.getCenterX();
float dy = y - (float) r.getCenterY();
((Blob2D) s).translateBy(dx, dy);
((Blob2D) s).update();
}
Part p = new Part(s, model);
copyPropertiesTo(p);
return p;
}
@Override
public Part duplicate() {
Shape s = getShape();
if (s instanceof Rectangle2D.Float) {
Rectangle2D.Float r = (Rectangle2D.Float) s;
s = new Rectangle2D.Float(r.x, r.y, r.width, r.height);
} else if (s instanceof Ellipse2D.Float) {
Ellipse2D.Float e = (Ellipse2D.Float) s;
s = new Ellipse2D.Float(e.x, e.y, e.width, e.height);
} else if (s instanceof Annulus) {
s = new Annulus((Annulus) s);
} else if (s instanceof EllipticalAnnulus) {
s = new EllipticalAnnulus((EllipticalAnnulus) s);
} else if (s instanceof Polygon2D) {
s = ((Polygon2D) s).duplicate();
} else if (s instanceof Blob2D) {
s = ((Blob2D) s).duplicate();
}
Part p = new Part(s, model);
copyPropertiesTo(p);
return p;
}
public void copyPropertiesTo(Part p) {
p.filled = filled;
p.fillPattern = fillPattern;
p.power = power;
p.elasticity = elasticity;
p.thermistorTemperatureCoefficient = thermistorTemperatureCoefficient;
p.thermistorReferenceTemperature = thermistorReferenceTemperature;
p.temperature = temperature;
p.constantTemperature = constantTemperature;
p.thermalConductivity = thermalConductivity;
p.specificHeat = specificHeat;
p.density = density;
p.absorptivity = absorptivity;
p.reflectivity = reflectivity;
p.scattering = scattering;
p.scatteringVisible = scatteringVisible;
p.transmissivity = transmissivity;
p.emissivity = emissivity;
p.windAngle = windAngle;
p.windSpeed = windSpeed;
p.setLabel(getLabel());
}
@Override
public void translateBy(float dx, float dy) {
Shape s = getShape();
if (s instanceof Rectangle2D.Float) {
Rectangle2D.Float r = (Rectangle2D.Float) s;
r.x += dx;
r.y += dy;
} else if (s instanceof Ellipse2D.Float) {
Ellipse2D.Float e = (Ellipse2D.Float) s;
e.x += dx;
e.y += dy;
} else if (s instanceof Annulus) {
((Annulus) s).translateBy(dx, dy);
} else if (s instanceof EllipticalAnnulus) {
((EllipticalAnnulus) s).translateBy(dx, dy);
} else if (s instanceof Polygon2D) {
((Polygon2D) s).translateBy(dx, dy);
} else if (s instanceof Blob2D) {
((Blob2D) s).translateBy(dx, dy);
((Blob2D) s).update();
}
}
public void setWindSpeed(float windSpeed) {
this.windSpeed = windSpeed;
}
public float getWindSpeed() {
return windSpeed;
}
public void setWindAngle(float windAngle) {
this.windAngle = windAngle;
}
public float getWindAngle() {
return windAngle;
}
public void setEmissivity(float emissivity) {
this.emissivity = emissivity;
}
public float getEmissivity() {
return emissivity;
}
public void setTransmissivity(float transmission) {
this.transmissivity = transmission;
}
public float getTransmissivity() {
return transmissivity;
}
public void setAbsorptivity(float absorption) {
this.absorptivity = absorption;
}
public float getAbsorptivity() {
return absorptivity;
}
public void setReflectivity(float reflectivity) {
this.reflectivity = reflectivity;
}
public float getReflectivity() {
return reflectivity;
}
public void setScattering(boolean scattering) {
this.scattering = scattering;
}
public boolean getScattering() {
return scattering;
}
public void setScatteringVisible(boolean scatteringVisible) {
this.scatteringVisible = scatteringVisible;
}
public boolean isScatteringVisible() {
return scatteringVisible;
}
public void setElasticity(float elasticity) {
this.elasticity = elasticity;
}
public float getElasticity() {
return elasticity;
}
public void setConstantTemperature(boolean b) {
constantTemperature = b;
}
public boolean getConstantTemperature() {
return constantTemperature;
}
public void setTemperature(float temperature) {
this.temperature = temperature;
}
public float getTemperature() {
return temperature;
}
public void setPower(float power) {
this.power = power;
}
public float getPower() {
return power;
}
public void setPowerSwitch(boolean b) {
powerSwitch = b;
}
public boolean getPowerSwitch() {
return powerSwitch;
}
public void setThermistorTemperatureCoefficient(float temperatureCoefficient) {
thermistorTemperatureCoefficient = temperatureCoefficient;
}
public float getThermistorTemperatureCoefficient() {
return thermistorTemperatureCoefficient;
}
public void setThermistorReferenceTemperature(float referenceTemperature) {
thermistorReferenceTemperature = referenceTemperature;
}
public float getThermistorReferenceTemperature() {
return thermistorReferenceTemperature;
}
public void setThermalConductivity(float thermalConductivity) {
this.thermalConductivity = thermalConductivity;
}
public float getThermalConductivity() {
return thermalConductivity;
}
public void setSpecificHeat(float specificHeat) {
this.specificHeat = specificHeat;
}
public float getSpecificHeat() {
return specificHeat;
}
public void setDensity(float density) {
this.density = density;
}
public float getDensity() {
return density;
}
boolean contains(Photon p) {
return getShape().contains(p.getRx(), p.getRy());
}
/* return true if the line connecting the two specified segments intersects with this part. */
boolean intersectsLine(Segment s1, Segment s2) {
Point2D.Float p1 = s1.getCenter();
Point2D.Float p2 = s2.getCenter();
if (p1.distanceSq(p2) < 0.000001f * model.getLx())
return true;
Shape shape = getShape();
if (shape instanceof Rectangle2D.Float) { // a rectangle is convex
if (s1.getPart() == this && s2.getPart() == this)
return true;
// shrink it a bit to ensure that it intersects with this rectangular part
Rectangle2D.Float r0 = (Rectangle2D.Float) shape;
float indent = 0.001f;
float x0 = r0.x + indent * r0.width;
float y0 = r0.y + indent * r0.height;
float x1 = r0.x + (1 - indent) * r0.width;
float y1 = r0.y + (1 - indent) * r0.height;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, x0, y0, x1, y0))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, x1, y0, x1, y1))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, x1, y1, x0, y1))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, x0, y1, x0, y0))
return true;
} else if (shape instanceof Polygon2D || shape instanceof Blob2D) { // a polygon or blob may be concave or convex
float delta = model.getLx() / model.getNx();
float indent = 0.001f * delta;
float x3 = p1.x, y3 = p1.y, x4 = p2.x, y4 = p2.y;
if (Math.abs(p1.x - p2.x) < indent) {
delta = Math.signum(p2.y - p1.y) * indent;
y3 += delta;
y4 -= delta;
} else if (Math.abs(p1.y - p2.y) < indent) {
delta = Math.signum(p2.x - p1.x) * indent;
x3 += delta;
x4 -= delta;
} else {
float k = (p2.y - p1.y) / (p2.x - p1.x);
delta = Math.signum(p2.x - p1.x) * indent;
x3 += delta;
x4 -= delta;
y3 = p1.y + k * (x3 - p1.x);
y4 = p1.y + k * (x4 - p1.x);
}
List<Segment> partSegments = model.getPerimeterSegments(this);
int n = partSegments.size();
if (n > 0) {
boolean bothBelongToThisPart = s1.getPart() == this && s2.getPart() == this;
Shape shape2 = shape;
if (shape instanceof Blob2D) { // we will have to use the approximated polygon instead of the blob
Path2D.Float path = new Path2D.Float();
Segment s = partSegments.get(0);
path.moveTo(s.x1, s.y1);
path.lineTo(s.x2, s.y2);
if (n > 1) {
for (int i = 1; i < n; i++) {
s = partSegments.get(i);
path.lineTo(s.x2, s.y2);
}
}
path.closePath();
shape2 = path;
}
for (Segment s : partSegments) {
if (bothBelongToThisPart && (shape2.contains(x3, y3) || shape2.contains(x4, y4)))
return true;
if (s.intersectsLine(x3, y3, x4, y4))
return true;
}
}
} else if (shape instanceof Ellipse2D.Float) { // an ellipse is convex
if (s1.getPart() == this && s2.getPart() == this)
return true;
Ellipse2D.Float e0 = (Ellipse2D.Float) shape;
// shrink it a bit to ensure that it intersects with this elliptical part
float indent = 0.01f;
float ex = e0.x + indent * e0.width;
float ey = e0.y + indent * e0.height;
float ew = (1 - 2 * indent) * e0.width;
float eh = (1 - 2 * indent) * e0.height;
float a = ew * 0.5f;
float b = eh * 0.5f;
float x = ex + a;
float y = ey + b;
float h = (a - b) / (a + b);
h *= h;
double perimeter = Math.PI * (a + b) * (1 + 3 * h / (10 + Math.sqrt(4 - 3 * h)));
float patchSize = model.getLx() * model.getPerimeterStepSize();
int n = (int) (perimeter / patchSize);
if (n > 0) {
float[] vx = new float[n];
float[] vy = new float[n];
float theta;
float delta = (float) (2 * Math.PI / n);
for (int i = 0; i < n; i++) {
theta = delta * i;
vx[i] = (float) (x + a * Math.cos(theta));
vy[i] = (float) (y + b * Math.sin(theta));
}
for (int i = 0; i < n - 1; i++)
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[i], vy[i], vx[i + 1], vy[i + 1]))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[n - 1], vy[n - 1], vx[0], vy[0]))
return true;
}
} else if (shape instanceof Annulus) {
Annulus r0 = (Annulus) shape;
// shrink it a bit to ensure that it intersects with this outer line
float indent = 0.01f;
float x = r0.getX();
float y = r0.getY();
float d = r0.getOuterDiameter() * (1 - indent);
double perimeter = Math.PI * d;
float patchSize = model.getLx() * model.getPerimeterStepSize();
int n = (int) (perimeter / patchSize);
if (n > 0) {
float[] vx = new float[n];
float[] vy = new float[n];
float theta;
float delta = (float) (2 * Math.PI / n);
d /= 2;
for (int i = 0; i < n; i++) {
theta = delta * i;
vx[i] = (float) (x + d * Math.cos(theta));
vy[i] = (float) (y + d * Math.sin(theta));
}
for (int i = 0; i < n - 1; i++)
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[i], vy[i], vx[i + 1], vy[i + 1]))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[n - 1], vy[n - 1], vx[0], vy[0]))
return true;
// expand it a bit to ensure that it intersects with this inner line
d = r0.getInnerDiameter() * (1 + indent);
perimeter = Math.PI * d;
n = (int) (perimeter / patchSize);
vx = new float[n];
vy = new float[n];
delta = (float) (2 * Math.PI / n);
d /= 2;
for (int i = 0; i < n; i++) {
theta = delta * i;
vx[i] = (float) (x + d * Math.cos(theta));
vy[i] = (float) (y + d * Math.sin(theta));
}
for (int i = 0; i < n - 1; i++)
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[i], vy[i], vx[i + 1], vy[i + 1]))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[n - 1], vy[n - 1], vx[0], vy[0]))
return true;
}
} else if (shape instanceof EllipticalAnnulus) {
EllipticalAnnulus r0 = (EllipticalAnnulus) shape;
// shrink it a bit to ensure that it intersects with this outer line
float indent = 0.01f;
float x = r0.getX();
float y = r0.getY();
float outerA = r0.getOuterA() * (1 - indent);
float outerB = r0.getOuterB() * (1 - indent);
float h = (outerA - outerB) / (outerA + outerB);
h *= h;
double outerPerimeter = Math.PI * (outerA + outerB) * (1 + 3 * h / (10 + Math.sqrt(4 - 3 * h)));
float patchSize = model.getLx() * model.getPerimeterStepSize();
int n = (int) (outerPerimeter / patchSize);
if (n > 0) {
float[] vx = new float[n];
float[] vy = new float[n];
float theta;
float delta = (float) (2 * Math.PI / n);
for (int i = 0; i < n; i++) {
theta = delta * i;
vx[i] = (float) (x + outerA * Math.cos(theta));
vy[i] = (float) (y + outerB * Math.sin(theta));
}
for (int i = 0; i < n - 1; i++)
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[i], vy[i], vx[i + 1], vy[i + 1]))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[n - 1], vy[n - 1], vx[0], vy[0]))
return true;
// expand it a bit to ensure that it intersects with this inner line
float innerA = r0.getInnerA() * (1 + indent);
float innerB = r0.getInnerB() * (1 + indent);
h = (innerA - innerB) / (innerA + innerB);
h *= h;
double innerPerimeter = Math.PI * (innerA + innerB) * (1 + 3 * h / (10 + Math.sqrt(4 - 3 * h)));
n = (int) (innerPerimeter / patchSize);
vx = new float[n];
vy = new float[n];
delta = (float) (2 * Math.PI / n);
for (int i = 0; i < n; i++) {
theta = delta * i;
vx[i] = (float) (x + innerA * Math.cos(theta));
vy[i] = (float) (y + innerB * Math.sin(theta));
}
for (int i = 0; i < n - 1; i++)
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[i], vy[i], vx[i + 1], vy[i + 1]))
return true;
if (Line2D.linesIntersect(p1.x, p1.y, p2.x, p2.y, vx[n - 1], vy[n - 1], vx[0], vy[0]))
return true;
}
}
return false;
}
boolean reflect(Discrete p, boolean scatter) {
float dt = model.getTimeStep();
float predictedX = p.getRx() + p.getVx() * dt;
float predictedY = p.getRy() + p.getVy() * dt;
if (p instanceof Particle) {
float dt2 = 0.5f * dt * dt;
predictedX += ((Particle) p).ax * dt2;
predictedY += ((Particle) p).ay * dt2;
}
Shape shape = getShape();
boolean predictedToBeInShape = true; // optimization flag: if the predicted position is not within this part, skip the costly reflection calculation
if (p instanceof Photon)
predictedToBeInShape = shape.contains(predictedX, predictedY);
if (shape instanceof Rectangle2D.Float) {
if (predictedToBeInShape)
return reflect((Rectangle2D.Float) shape, p, predictedX, predictedY, scatter);
} else if (shape instanceof Polygon2D) {
if (predictedToBeInShape)
return reflect((Polygon2D) shape, p, predictedX, predictedY, scatter);
} else if (shape instanceof Blob2D) {
if (predictedToBeInShape)
return reflect((Blob2D) shape, p, predictedX, predictedY, scatter);
} else if (shape instanceof Ellipse2D.Float) {
if (predictedToBeInShape)
return reflect((Ellipse2D.Float) shape, p, predictedX, predictedY, scatter);
} else if (shape instanceof Annulus) {
if (predictedToBeInShape)
return reflect((Annulus) shape, p, predictedX, predictedY, scatter);
} else if (shape instanceof EllipticalAnnulus) {
if (predictedToBeInShape)
return reflect((EllipticalAnnulus) shape, p, predictedX, predictedY, scatter);
}
return false;
}
// simpler case, avoid trig for a faster implementation
private boolean reflect(Rectangle2D.Float r, Discrete p, float predictedX, float predictedY, boolean scatter) {
if (p instanceof Particle) {
Particle particle = (Particle) p;
float radius = particle.radius;
float x0 = r.x;
float y0 = r.y;
float x1 = r.x + r.width;
float y1 = r.y + r.height;
boolean predictedToHit = predictedX - radius <= x1 && predictedX + radius >= x0 && predictedY - radius <= y1 && predictedY + radius >= y0;
if (predictedToHit) {
float impulse = 0;
float hitX = predictedX, hitY = predictedY;
if (particle.rx - radius <= x0) { // use the farthest point to decide if the particle is to the left
impulse = Math.abs(particle.vx);
particle.vx = -impulse * elasticity;
hitX += radius + 0.5f * model.getLy() / model.getNy();
} else if (particle.rx + radius >= x1) { // particle to the right
impulse = Math.abs(particle.vx);
particle.vx = impulse * elasticity;
hitX -= radius + 0.5f * model.getLy() / model.getNy();
}
if (particle.ry - radius <= y0) { // particle above
impulse = Math.abs(particle.vy);
particle.vy = -impulse * elasticity;
hitY += radius + 0.5f * model.getLy() / model.getNy();
} else if (particle.ry + radius >= y1) { // particle below
impulse = Math.abs(particle.vy);
particle.vy = impulse * elasticity;
hitY -= radius + 0.5f * model.getLy() / model.getNy();
}
if (elasticity < 1) {
float energy = 0.5f * particle.mass * impulse * impulse * (1 - elasticity * elasticity);
float volume = model.getLx() * model.getLy() / (model.getNx() * model.getNy());
model.changeTemperatureAt(hitX, hitY, energy / (specificHeat * density * volume));
}
return true;
}
} else if (p instanceof Photon) {
if (p.getRx() <= r.x) {
if (scatter) {
p.setVelocityAngle((float) (Math.PI * (0.5 + Math.random())));
} else {
p.setVx(-Math.abs(p.getVx()));
}
} else if (p.getRx() >= r.x + r.width) {
if (scatter) {
p.setVelocityAngle((float) (Math.PI * (0.5 - Math.random())));
} else {
p.setVx(Math.abs(p.getVx()));
}
}
if (p.getRy() <= r.y) {
if (scatter) {
p.setVelocityAngle((float) (Math.PI * (1 + Math.random())));
} else {
p.setVy(-Math.abs(p.getVy()));
}
} else if (p.getRy() >= r.y + r.height) {
if (scatter) {
p.setVelocityAngle((float) (Math.PI * Math.random()));
} else {
p.setVy(Math.abs(p.getVy()));
}
}
return true;
}
return false;
}
private boolean reflect(Blob2D b, Discrete p, float predictedX, float predictedY, boolean scatter) {
boolean clockwise = b.isClockwise();
int n = b.getPathPointCount();
Point2D.Float v1, v2;
Line2D.Float line = new Line2D.Float();
for (int i = 0; i < n - 1; i++) {
v1 = b.getPathPoint(i);
v2 = b.getPathPoint(i + 1);
line.setLine(v1, v2);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, clockwise))
return true;
}
v1 = b.getPathPoint(n - 1);
v2 = b.getPathPoint(0);
line.setLine(v1, v2);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, clockwise))
return true;
return false;
}
private boolean reflect(Ellipse2D.Float e, Discrete p, float predictedX, float predictedY, boolean scatter) {
float a = e.width * 0.5f;
float b = e.height * 0.5f;
float x = e.x + a;
float y = e.y + b;
int polygonize = 50;
float[] vx = new float[polygonize];
float[] vy = new float[polygonize];
float theta;
float delta = (float) (2 * Math.PI / polygonize);
for (int i = 0; i < polygonize; i++) {
theta = -delta * i;
vx[i] = (float) (x + a * Math.cos(theta));
vy[i] = (float) (y + b * Math.sin(theta));
}
Line2D.Float line = new Line2D.Float();
for (int i = 0; i < polygonize - 1; i++) {
line.setLine(vx[i], vy[i], vx[i + 1], vy[i + 1]);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, true))
return true;
}
line.setLine(vx[polygonize - 1], vy[polygonize - 1], vx[0], vy[0]);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, true))
return true;
return false;
}
private boolean reflect(Annulus e, Discrete p, float predictedX, float predictedY, boolean scatter) {
float rInner = e.getInnerDiameter() * 0.5f;
float rOuter = e.getOuterDiameter() * 0.5f;
float x = e.getX();
float y = e.getY();
boolean inside = new Ellipse2D.Float(x - rInner, y - rInner, 2 * rInner, 2 * rInner).contains(p.getRx(), p.getRy());
float a = inside ? rInner : rOuter;
int polygonize = 50;
float[] vx = new float[polygonize];
float[] vy = new float[polygonize];
float theta;
float delta = (float) (2 * Math.PI / polygonize);
for (int i = 0; i < polygonize; i++) {
theta = -delta * i;
vx[i] = (float) (x + a * Math.cos(theta));
vy[i] = (float) (y + a * Math.sin(theta));
}
Line2D.Float line = new Line2D.Float();
for (int i = 0; i < polygonize - 1; i++) {
line.setLine(vx[i], vy[i], vx[i + 1], vy[i + 1]);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, !inside))
return true;
}
line.setLine(vx[polygonize - 1], vy[polygonize - 1], vx[0], vy[0]);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, !inside))
return true;
return false;
}
private boolean reflect(EllipticalAnnulus e, Discrete p, float predictedX, float predictedY, boolean scatter) {
float innerA = e.getInnerA();
float innerB = e.getInnerB();
float outerA = e.getOuterA();
float outerB = e.getOuterB();
float x = e.getX();
float y = e.getY();
boolean inside = new Ellipse2D.Float(x - innerA, y - innerB, 2 * innerA, 2 * innerB).contains(p.getRx(), p.getRy());
float a = inside ? innerA : outerA;
float b = inside ? innerB : outerB;
int polygonize = 50;
float[] vx = new float[polygonize];
float[] vy = new float[polygonize];
float theta;
float delta = (float) (2 * Math.PI / polygonize);
for (int i = 0; i < polygonize; i++) {
theta = -delta * i;
vx[i] = (float) (x + a * Math.cos(theta));
vy[i] = (float) (y + b * Math.sin(theta));
}
Line2D.Float line = new Line2D.Float();
for (int i = 0; i < polygonize - 1; i++) {
line.setLine(vx[i], vy[i], vx[i + 1], vy[i + 1]);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, !inside))
return true;
}
line.setLine(vx[polygonize - 1], vy[polygonize - 1], vx[0], vy[0]);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, !inside))
return true;
return false;
}
private boolean reflect(Polygon2D r, Discrete p, float predictedX, float predictedY, boolean scatter) {
boolean clockwise = r.isClockwise();
int n = r.getVertexCount();
Point2D.Float v1, v2;
Line2D.Float line = new Line2D.Float();
for (int i = 0; i < n - 1; i++) {
v1 = r.getVertex(i);
v2 = r.getVertex(i + 1);
line.setLine(v1, v2);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, clockwise))
return true;
}
v1 = r.getVertex(n - 1);
v2 = r.getVertex(0);
line.setLine(v1, v2);
if (reflectFromLine(p, line, predictedX, predictedY, scatter, clockwise))
return true;
return false;
}
private boolean reflectFromLine(Discrete p, Line2D.Float line, float predictedX, float predictedY, boolean scatter, boolean clockwise) {
if (line.x1 == line.x2 && line.y1 == line.y2)
return false;
boolean hit = false;
if (p instanceof Photon) { // a photon doesn't have any size, use its center to detect collision
hit = line.intersectsLine(p.getRx(), p.getRy(), predictedX, predictedY);
} else if (p instanceof Particle) {
Particle particle = (Particle) p;
float r = particle.radius;
hit = Line2D.ptSegDistSq(line.x1, line.y1, line.x2, line.y2, predictedX, predictedY) <= r * r;
}
if (hit) {
float d12 = (float) Math.hypot(line.x1 - line.x2, line.y1 - line.y2);
float sin = (clockwise ? line.y2 - line.y1 : line.y1 - line.y2) / d12;
float cos = (clockwise ? line.x2 - line.x1 : line.x1 - line.x2) / d12;
if (scatter) {
double angle = -Math.PI * Math.random(); // remember internally the y-axis points downward
double cos1 = Math.cos(angle);
double sin1 = Math.sin(angle);
double cos2 = cos1 * cos - sin1 * sin;
double sin2 = sin1 * cos + cos1 * sin;
p.setVx((float) (p.getSpeed() * cos2));
p.setVy((float) (p.getSpeed() * sin2));
} else {
float u; // velocity component parallel to the line
float w; // velocity component perpendicular to the line
if (p instanceof Particle) {
Particle particle = (Particle) p;
u = particle.vx * cos + particle.vy * sin;
w = particle.vy * cos - particle.vx * sin;
w *= elasticity;
if (Math.abs(w) < 0.01f)
w = -Math.abs(w); // force the w component to point outwards
p.setVx(u * cos + w * sin);
p.setVy(u * sin - w * cos);
} else {
u = p.getVx() * cos + p.getVy() * sin;
w = p.getVy() * cos - p.getVx() * sin;
p.setVx(u * cos + w * sin);
p.setVy(u * sin - w * cos);
}
if (p instanceof Particle && elasticity < 1) {
Particle particle = (Particle) p;
float hitX = predictedX + (particle.radius + 0.5f * model.getLx() / model.getNx()) * sin;
float hitY = predictedY - (particle.radius + 0.5f * model.getLy() / model.getNy()) * cos;
float energy = 0.5f * particle.mass * w * w * (1 - elasticity * elasticity);
float volume = model.getLx() * model.getLy() / (model.getNx() * model.getNy());
model.changeTemperatureAt(hitX, hitY, energy / (specificHeat * density * volume));
}
}
return true;
}
return false;
}
public String toXml() {
XmlCharacterEncoder xce = new XmlCharacterEncoder();
String xml = "<part>\n";
if (getShape() instanceof Rectangle2D.Float) {
Rectangle2D.Float r = (Rectangle2D.Float) getShape();
xml += "<rectangle";
xml += " x=\"" + r.x + "\"";
xml += " y=\"" + r.y + "\"";
xml += " width=\"" + r.width + "\"";
xml += " height=\"" + r.height + "\"/>";
} else if (getShape() instanceof Ellipse2D.Float) {
Ellipse2D.Float e = (Ellipse2D.Float) getShape();
xml += "<ellipse";
xml += " x=\"" + e.getCenterX() + "\"";
xml += " y=\"" + e.getCenterY() + "\"";
xml += " a=\"" + e.width + "\"";
xml += " b=\"" + e.height + "\"/>";
} else if (getShape() instanceof Polygon2D) {
Polygon2D p = (Polygon2D) getShape();
xml += "<polygon count=\"" + p.getVertexCount() + "\" vertices=\"";
int n = p.getVertexCount();
Point2D.Float p2d;
for (int i = 0; i < n - 1; i++) {
p2d = p.getVertex(i);
xml += p2d.x + ", " + p2d.y + ", ";
}
p2d = p.getVertex(n - 1);
xml += p2d.x + ", " + p2d.y + "\"/>\n";
} else if (getShape() instanceof Blob2D) {
Blob2D b = (Blob2D) getShape();
xml += "<blob count=\"" + b.getPointCount() + "\" points=\"";
int n = b.getPointCount();
Point2D.Float p2d;
for (int i = 0; i < n - 1; i++) {
p2d = b.getPoint(i);
xml += p2d.x + ", " + p2d.y + ", ";
}
p2d = b.getPoint(n - 1);
xml += p2d.x + ", " + p2d.y + "\"/>\n";
} else if (getShape() instanceof Annulus) {
Annulus ring = (Annulus) getShape();
xml += "<ring";
xml += " x=\"" + ring.getX() + "\"";
xml += " y=\"" + ring.getY() + "\"";
xml += " inner=\"" + ring.getInnerDiameter() + "\"";
xml += " outer=\"" + ring.getOuterDiameter() + "\"/>";
} else if (getShape() instanceof EllipticalAnnulus) {
EllipticalAnnulus e = (EllipticalAnnulus) getShape();
xml += "<annulus";
xml += " x=\"" + e.getX() + "\"";
xml += " y=\"" + e.getY() + "\"";
xml += " innerA=\"" + e.getInnerA() + "\"";
xml += " innerB=\"" + e.getInnerB() + "\"";
xml += " outerA=\"" + e.getOuterA() + "\"";
xml += " outerB=\"" + e.getOuterB() + "\"/>";
}
xml += "<elasticity>" + elasticity + "</elasticity>\n";
xml += "<thermal_conductivity>" + thermalConductivity + "</thermal_conductivity>\n";
xml += "<specific_heat>" + specificHeat + "</specific_heat>\n";
xml += "<density>" + density + "</density>\n";
xml += "<transmission>" + transmissivity + "</transmission>\n";
xml += "<reflection>" + reflectivity + "</reflection>\n";
xml += "<scattering>" + scattering + "</scattering>\n";
if (!scatteringVisible)
xml += "<scattering_visible>false</scattering_visible>\n";
xml += "<absorption>" + absorptivity + "</absorption>\n";
xml += "<emissivity>" + emissivity + "</emissivity>\n";
xml += "<temperature>" + temperature + "</temperature>\n";
xml += "<constant_temperature>" + constantTemperature + "</constant_temperature>\n";
if (power != 0)
xml += "<power>" + power + "</power>\n";
if (thermistorTemperatureCoefficient != 0)
xml += "<temperature_coefficient>" + thermistorTemperatureCoefficient + "</temperature_coefficient>\n";
if (thermistorReferenceTemperature != 0)
xml += "<reference_temperature>" + thermistorReferenceTemperature + "</reference_temperature>\n";
if (windSpeed != 0)
xml += "<wind_speed>" + windSpeed + "</wind_speed>\n";
if (windAngle != 0)
xml += "<wind_angle>" + windAngle + "</wind_angle>\n";
if (getUid() != null && !getUid().trim().equals(""))
xml += "<uid>" + xce.encode(getUid()) + "</uid>\n";
if (fillPattern instanceof ColorFill) {
Color color = ((ColorFill) fillPattern).getColor();
if (!color.equals(Color.GRAY)) {
xml += "<color>" + Integer.toHexString(0x00ffffff & color.getRGB()) + "</color>\n";
}
} else if (fillPattern instanceof Texture) {
Texture pf = (Texture) fillPattern;
xml += "<texture>";
int i = pf.getForeground();
xml += "<texture_fg>" + Integer.toString(i, 16) + "</texture_fg>\n";
i = pf.getBackground();
xml += "<texture_bg>" + Integer.toString(i, 16) + "</texture_bg>\n";
i = ((Texture) fillPattern).getStyle();
xml += "<texture_style>" + i + "</texture_style>\n";
i = pf.getCellWidth();
xml += "<texture_width>" + i + "</texture_width>\n";
i = pf.getCellHeight();
xml += "<texture_height>" + i + "</texture_height>\n";
xml += "</texture>\n";
}
if (!isFilled())
xml += "<filled>false</filled>\n";
String label = getLabel();
if (label != null && !label.trim().equals(""))
xml += "<label>" + xce.encode(label) + "</label>\n";
if (!isVisible())
xml += "<visible>false</visible>\n";
if (!isDraggable())
xml += "<draggable>false</draggable>\n";
xml += "</part>\n";
return xml;
}
public String getLabel(String label, Model2D model, boolean useFahrenheit) {
if (label == null)
return null;
if (label.indexOf('%') == -1)
return label;
String s = null;
if (label.equalsIgnoreCase("%temperature")) {
Rectangle2D bounds = getShape().getBounds2D();
float temp = model.getTemperatureAt((float) bounds.getCenterX(), (float) bounds.getCenterY());
s = useFahrenheit ? TWO_DECIMALS_FORMAT.format(temp * 1.8f + 32) + " \u00b0F" : TWO_DECIMALS_FORMAT.format(temp) + " \u00b0C";
} else if (label.equalsIgnoreCase("%thermal_energy"))
s = Math.round(model.getThermalEnergy(this)) + " J";
else if (label.equalsIgnoreCase("%density"))
s = (int) density + " kg/m\u00b3";
else if (label.equalsIgnoreCase("%elasticity"))
s = SHORT_LABEL_FORMAT.format(elasticity) + "";
else if (label.equalsIgnoreCase("%specific_heat"))
s = (int) specificHeat + " J/(kg\u00d7\u00b0C)";
else if (label.equalsIgnoreCase("%heat_capacity"))
s = SHORT_LABEL_FORMAT.format(specificHeat * density * getArea()) + " J/\u00b0C";
else if (label.equalsIgnoreCase("%volumetric_heat_capacity"))
s = SHORT_LABEL_FORMAT.format(specificHeat * density) + " J/(m\u00b3\u00d7\u00b0C)";
else if (label.equalsIgnoreCase("%thermal_diffusivity"))
s = LABEL_FORMAT.format(thermalConductivity / (specificHeat * density)) + " m\u00b2/s";
else if (label.equalsIgnoreCase("%thermal_conductivity"))
s = (float) thermalConductivity + " W/(m\u00d7\u00b0C)";
else if (label.equalsIgnoreCase("%power_density"))
s = (int) power + " W/m\u00b3";
else if (label.equalsIgnoreCase("%area"))
s = getAreaString();
else if (label.equalsIgnoreCase("%width"))
s = getWidthString();
else if (label.equalsIgnoreCase("%height"))
s = getHeightString();
else {
s = label.replace("%temperature", useFahrenheit ? TWO_DECIMALS_FORMAT.format(temperature * 1.8f + 32) + " \u00b0F" : TWO_DECIMALS_FORMAT.format(temperature) + " \u00b0C");
s = s.replace("%thermal_energy", Math.round(model.getThermalEnergy(this)) + " J");
s = s.replace("%density", (int) density + " kg/m\u00b3");
s = s.replace("%specific_heat", (int) specificHeat + " J/(kg\u00d7\u00b0C)");
s = s.replace("%heat_capacity", SHORT_LABEL_FORMAT.format(specificHeat * density * getArea()) + " J/\u00b0C");
s = s.replace("%volumetric_heat_capacity", SHORT_LABEL_FORMAT.format(specificHeat * density) + " J/(m\u00b3\u00d7\u00b0C)");
s = s.replace("%thermal_diffusivity", LABEL_FORMAT.format(thermalConductivity / (specificHeat * density)) + " m\u00b2/s");
s = s.replace("%thermal_conductivity", (float) thermalConductivity + " W/(m\u00d7\u00b0C)");
s = s.replace("%power_density", (int) power + " W/m\u00b3");
s = s.replace("%area", getAreaString());
s = s.replace("%width", getWidthString());
s = s.replace("%height", getHeightString());
}
return s;
}
private float getArea() {
float area = -1;
if (getShape() instanceof Rectangle2D.Float) {
Rectangle2D.Float r = (Rectangle2D.Float) getShape();
area = r.width * r.height;
} else if (getShape() instanceof Ellipse2D.Float) {
Ellipse2D.Float e = (Ellipse2D.Float) getShape();
area = (float) (e.width * e.height * 0.25 * Math.PI);
} else if (getShape() instanceof TransformableShape) {
area = ((TransformableShape) getShape()).getArea();
} else if (getShape() instanceof Annulus) {
area = ((Annulus) getShape()).getArea();
} else if (getShape() instanceof EllipticalAnnulus) {
area = ((EllipticalAnnulus) getShape()).getArea();
}
return area;
}
private String getAreaString() {
float area = getArea();
return area < 0 ? "Unknown" : LABEL_FORMAT.format(area) + " m\u00b2";
}
private String getWidthString() {
if (getShape() instanceof Rectangle2D.Float)
return LABEL_FORMAT.format(((Rectangle2D.Float) getShape()).width) + " m";
if (getShape() instanceof Ellipse2D.Float)
return LABEL_FORMAT.format(((Ellipse2D.Float) getShape()).width) + " m";
return "Unknown";
}
private String getHeightString() {
if (getShape() instanceof Rectangle2D.Float)
return LABEL_FORMAT.format(((Rectangle2D.Float) getShape()).height) + " m";
if (getShape() instanceof Ellipse2D.Float)
return LABEL_FORMAT.format(((Ellipse2D.Float) getShape()).height) + " m";
return "Unknown";
}
@Override
public String toString() {
return getUid() == null ? super.toString() : getUid();
}
}
|
lgpl-3.0
|
SOCR/HTML5_WebSite
|
SOCR2.8/src/edu/ucla/stat/SOCR/analyses/util/definicions/Id_To_Key.java
|
1607
|
/*
* Copyright (C) Justo Montiel, David Torres, Sergio Gomez, Alberto Fernandez
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see
* <http://www.gnu.org/licenses/>
*/
package edu.ucla.stat.SOCR.analyses.util.definicions;
import java.util.HashMap;
/**
* <p>
* <b>MultiDendrograms</b>
* </p>
*
* Assigns numbers to identifiers (0, 1, 2, 3, ...)
*
* @author Justo Montiel, David Torres, Sergio Gómez, Alberto Fernández
*
* @since JDK 6.0
*/
public class Id_To_Key<item> {
private Integer nextId = 0;
private final HashMap<item, Integer> keyToInd;
public Id_To_Key() {
keyToInd = new HashMap<item, Integer>();
}
public boolean containsKey(final item key) {
return keyToInd.containsKey(key);
}
public Integer getInd(final item key) {
return keyToInd.get(key);
}
public Integer setInd(final item key) {
keyToInd.put(key, nextId);
nextId++;
return (nextId - 1);
}
public int size() {
return nextId;
}
}
|
lgpl-3.0
|
RuedigerMoeller/kontraktor
|
attic/failover-routing-loadbalancing/src/main/java/kontraktor/krouter/KrouterMain.java
|
1119
|
package kontraktor.krouter;
import org.nustaq.kontraktor.remoting.encoding.SerializerType;
import org.nustaq.kontraktor.remoting.http.undertow.WebSocketPublisher;
import org.nustaq.kontraktor.remoting.tcp.TCPNIOPublisher;
import org.nustaq.kontraktor.routers.*;
public class KrouterMain {
public static void main(String[] args) {
Routing.start(
HotHotFailoverKrouter.class,
// new TCPNIOPublisher()
// .serType(SerializerType.FSTSer)
// .port(6667),
new WebSocketPublisher()
.hostName("localhost")
.urlPath("/binary")
.port(8888)
.serType(SerializerType.FSTSer)
// new WebSocketPublisher()
// .hostName("localhost")
// .urlPath("/json")
// .port(8888)
// .serType(SerializerType.JsonNoRef),
// new HttpPublisher()
// .hostName("localhost")
// .urlPath("/http")
// .port(8888)
// .serType(SerializerType.JsonNoRef)
);
}
}
|
lgpl-3.0
|
ibgdn/JavaLearning
|
SpringMVC/src/controller/IndexController0.java
|
968
|
package controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
/**
实现 Controller 接口,提供 handleRequest() 方法处理请求(处理 /index 的请求)
SpringMVC 通过 ModelAndView 对象把模型和视图结合在一起。
*/
public class IndexController0 implements Controller{
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// ModelAndView mav = new ModelAndView("indexController0.jsp"); // 视图 index.jsp only indexController0.
ModelAndView mav = new ModelAndView("indexController0"); // 视图 index.jsp add indexController1.
mav.addObject("message","indexController0"); // 模型数据 message,内容 Hello Spring MVC
return mav;
}
}
|
lgpl-3.0
|
henjo/libpsf
|
src/psfindexedcontainer.cc
|
2656
|
#include <assert.h>
#include "psf.h"
#include "psfdata.h"
#include "psfinternal.h"
int Index::deserialize(const char *buf) {
const char *startbuf = buf;
buf += Chunk::deserialize(buf);
uint32_t size = GET_INT32(buf);
buf += sizeof(uint32_t);
int id, offset;
for(int i=0; i < size; i+=8) {
id = GET_INT32(buf+i);
offset = GET_INT32(buf+i+4);
}
return buf + size - startbuf;
}
int TraceIndex::deserialize(const char *buf) {
const char *startbuf = buf;
buf += Chunk::deserialize(buf);
uint32_t size = GET_INT32(buf);
buf += sizeof(uint32_t);
int id, offset, extra1, extra2;
for(int i=0; i < size; i+=16) {
id = GET_INT32(buf+i);
offset = GET_INT32(buf+i+4);
extra1 = GET_INT32(buf+i+8);
extra2 = GET_INT32(buf+i+12);
// std::cout << "(" << std::hex << id << "," << offset << "," << extra1 << "," << extra2 << ")" << std::endl;
}
return buf + size - startbuf;
}
int IndexedContainer::deserialize(const char *buf, int abspos) {
const char *startbuf = buf;
buf += Chunk::deserialize(buf);
uint32_t endpos = GET_INT32(buf);
buf += sizeof(uint32_t);
// Sub container
uint32_t subcontainer_typeid = GET_INT32(buf);
buf += sizeof(uint32_t);
assert(subcontainer_typeid == 22);
uint32_t subendpos = GET_INT32(buf);
buf += sizeof(uint32_t);
int i = 0;
while(abspos + (buf-startbuf) < subendpos) {
Chunk *chunk = deserialize_child(&buf);
if(chunk)
add_child(chunk);
else
break;
}
if(dynamic_cast<TraceSection *>(this)) {
TraceIndex index;
buf += index.deserialize(buf);
} else {
Index index;
buf += index.deserialize(buf);
}
i=0;
for(Container::const_iterator child=begin(); child != end(); child++, i++) {
idmap[(*child)->get_id()] = *child;
const std::string &name = (*child)->get_name();
namemap[name] = i;
}
return endpos - abspos;
}
void IndexedContainer::print(std::ostream &stream) const {
stream << "IndexedContainer(";
for(Container::const_iterator child=begin(); child !=end(); child++)
stream << **child << " " ;
stream << ")";
}
const Chunk & IndexedContainer::get_child(int id) const {
return *idmap.find(id)->second;
}
const Chunk & IndexedContainer::get_child(std::string name) const {
NameIndexMap::const_iterator i = namemap.find(name);
if(i == namemap.end())
throw NotFound();
else
return *at(i->second);
}
int IndexedContainer::get_child_index(std::string name) const {
NameIndexMap::const_iterator i = namemap.find(name);
if(i == namemap.end())
return -1;
else
return i->second;
}
|
lgpl-3.0
|
seuretm/N-light-N
|
src/diuf/diva/dia/ms/script/command/ShowFeatureActivations.java
|
3710
|
/*****************************************************
N-light-N
A Highly-Adaptable Java Library for Document Analysis with
Convolutional Auto-Encoders and Related Architectures.
-------------------
Author:
2016 by Mathias Seuret <mathias.seuret@unifr.ch>
and Michele Alberti <michele.alberti@unifr.ch>
-------------------
This software is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation version 3.
This software is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this software; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
******************************************************************************/
package diuf.diva.dia.ms.script.command;
import diuf.diva.dia.ms.ml.ae.scae.SCAE;
import diuf.diva.dia.ms.script.XMLScript;
import diuf.diva.dia.ms.util.DataBlock;
import diuf.diva.dia.ms.util.Image;
import org.jdom2.Element;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
/**
*
* @author ms
*/
public class ShowFeatureActivations extends AbstractCommand {
/**
* Constructor of the class.
* @param script which creates the command
*/
public ShowFeatureActivations(XMLScript script) {
super(script);
}
@Override
public String execute(Element element) throws Exception {
String doc = readElement(element, "document");
String ref = readAttribute(element, "ref");
String res = readElement(element, "result");
SCAE scae = script.scae.get(ref);
Image img = new Image(doc);
img.convertTo(script.colorspace);
DataBlock idb = new DataBlock(img);
BufferedImage bi = new BufferedImage(idb.getWidth(), idb.getHeight(), BufferedImage.TYPE_INT_RGB);
int dx = scae.getInputPatchWidth() / 2;
int dy = scae.getInputPatchHeight() / 2;
for (int i=0; i<scae.getOutputDepth(); i++) {
float min = Float.MAX_VALUE;
float max = Float.MIN_VALUE;
for (int x = 0; x < idb.getWidth() - scae.getInputPatchWidth(); x++) {
int mm = bi.getWidth() - scae.getInputPatchWidth();
System.out.println(i+"/"+scae.getOutputDepth()+": "+(float)x/mm*100+"%");
for (int y = 0; y < idb.getHeight() - scae.getInputPatchHeight(); y++) {
scae.setInput(idb, x, y);
float act = scae.forward()[i];
float hue = (act+1)/2 * 0.4f; // Hue (note 0.4 = Green, see huge chart below)
bi.setRGB(x+dx, y+dy, Color.getHSBColor(hue, 0.9f, 0.9f).getRGB());
if (act<min) {
min = act;
}
if (act>max) {
max = act;
}
}
}
ImageIO.write(bi, "png", new File(res+"-"+i+".png"));
//System.out.println("Reconstruction range: ["+min+", "+max+"]");
//System.out.println("Class: "+scae.getLayer(scae.getLayers().size()-1).getAE().getClass().getSimpleName());
}
return "";
}
@Override
public String tagName() {
return "show-feature-activations";
}
}
|
lgpl-3.0
|
btrplace/scheduler-UCC-15
|
choco/src/main/java/org/btrplace/scheduler/choco/view/Cumulatives.java
|
1561
|
/*
* Copyright (c) 2014 University Nice Sophia Antipolis
*
* This file is part of btrplace.
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.btrplace.scheduler.choco.view;
import org.chocosolver.solver.variables.IntVar;
/**
* Interface to specify a multi-dimension cumulatives constraints.
* Dimensions can be added on the fly.
*
* @author Fabien Hermenier
*/
public interface Cumulatives extends ChocoView {
/**
* View identifier.
*/
String VIEW_ID = "choco.cumulatives";
/**
* Add a new dimension.
*
* @param c the capacity of each node. The variables *must be* ordered according to {@link org.btrplace.scheduler.choco.DefaultReconfigurationProblem#getNode(org.btrplace.model.Node)}.
* @param cUse the resource usage of each of the cSlices
* @param dUse the resource usage of each of the dSlices
*/
void addDim(IntVar[] c, int[] cUse, IntVar[] dUse);
}
|
lgpl-3.0
|
anndy201/mars-framework
|
manager/src/main/java/com/sqsoft/mars/inc/eventreport/service/IncScopeMapService.java
|
454
|
/**
*
*/
package com.sqsoft.mars.inc.eventreport.service;
import com.sqsoft.mars.core.common.service.CoreService;
import com.sqsoft.mars.inc.domain.IncScopeMap;
/**
* @author lenovo
*
*/
public interface IncScopeMapService extends CoreService<IncScopeMap, String> {
/**
*
* @param scopeGroup
* @param scopeType
* @param scopeKey
* @return
*/
public IncScopeMap findOne(String scopeGroup, String scopeType,
String scopeKey);
}
|
lgpl-3.0
|
Metaswitch/fmj
|
src/net/sf/fmj/media/protocol/res/DataSource.java
|
6794
|
package net.sf.fmj.media.protocol.res;
import java.io.*;
import java.net.*;
import java.util.logging.*;
import javax.media.*;
import javax.media.protocol.*;
import net.sf.fmj.media.*;
import net.sf.fmj.utility.*;
import com.lti.utils.*;
/**
* Protocol handler for res: protocol, loads stream from Java resource.
*
* @author Ken Larson
*
*/
public class DataSource extends PullDataSource implements SourceCloneable
{
class ResSourceStream implements PullSourceStream
{
private boolean endOfStream = false;
public boolean endOfStream()
{
return endOfStream;
}
public ContentDescriptor getContentDescriptor()
{
return contentType;
}
public long getContentLength()
{
return -1; // TODO
}
public Object getControl(String controlType)
{
return null;
}
public Object[] getControls()
{
return new Object[0];
}
public int read(byte[] buffer, int offset, int length)
throws IOException
{
final int result = inputStream.read(buffer, offset, length); // TODO:
// does
// this
// handle
// the
// requirement
// of
// not
// returning
// 0
// unless
// passed
// in
// 0?
if (result == -1) // end of stream
endOfStream = true;
return result;
}
public boolean willReadBlock()
{
try
{
return inputStream.available() <= 0;
} catch (IOException e)
{
return true;
}
}
}
private static final Logger logger = LoggerSingleton.logger;
private static String getContentTypeFor(String path)
{
final String ext = PathUtils.extractExtension(path);
// TODO: what if ext is null?
String result = MimeManager.getMimeType(ext);
// if we can't find it in our mime table, use URLConnection's
if (result != null)
return result;
result = URLConnection.getFileNameMap().getContentTypeFor(path);
return result;
}
private InputStream inputStream;
private ContentDescriptor contentType;
private boolean connected = false;
private ResSourceStream[] sources;
public DataSource()
{
super();
}
@Override
public void connect() throws IOException
{
// we allow a re-connection even if we are connected, due to an oddity
// in the way Manager works. See comments there
// in createPlayer(MediaLocator sourceLocator).
// if (connected) // TODO: FMJ tends to call this twice. Check with JMF
// to see if that is normal.
// return;
final String path = getLocator().getRemainder();
inputStream = DataSource.class.getResourceAsStream(path);
final String s = getContentTypeFor(path); // TODO: use our own mime
// mapping
if (s == null)
throw new IOException("Unknown content type for path: " + path);
// TODO: what is the right place to apply
// ContentDescriptor.mimeTypeToPackageName?
contentType = new ContentDescriptor(
ContentDescriptor.mimeTypeToPackageName(s));
sources = new ResSourceStream[1];
sources[0] = new ResSourceStream();
connected = true;
}
public javax.media.protocol.DataSource createClone()
{
final DataSource d;
d = new DataSource();
d.setLocator(getLocator());
if (connected)
{
try
{
d.connect();
} catch (IOException e)
{
logger.log(Level.WARNING, "" + e, e);
return null; // according to the API, return null on failure.
}
}
return d;
}
@Override
public void disconnect()
{
if (!connected)
return;
if (inputStream != null)
{
try
{
inputStream.close();
} catch (IOException e)
{
logger.log(Level.WARNING, "" + e, e);
}
}
connected = false;
}
@Override
public String getContentType()
{
if (!connected)
throw new Error("Source is unconnected.");
String path = getLocator().getRemainder();
String s = getContentTypeFor(path); // TODO: use our own mime mapping
return ContentDescriptor.mimeTypeToPackageName(s);
}
@Override
public Object getControl(String controlName)
{
return null;
}
@Override
public Object[] getControls()
{
return new Object[0];
}
@Override
public Time getDuration()
{
return Time.TIME_UNKNOWN; // TODO: any case where we know the duration?
}
@Override
public PullSourceStream[] getStreams()
{
if (!connected)
throw new Error("Unconnected source.");
return sources;
}
@Override
public void start() throws java.io.IOException
{
// throw new UnsupportedOperationException(); // TODO - what to do?
}
@Override
public void stop() throws java.io.IOException
{ // throw new UnsupportedOperationException(); // TODO - what to do?
}
/**
* Strips trailing ; and anything after it. Is generally only used for
* multipart content.
*/
private String stripTrailer(String contentType)
{
final int index = contentType.indexOf(";");
if (index < 0)
return contentType;
final String result = contentType.substring(0, index);
return result;
}
}
|
lgpl-3.0
|
konvergeio/konverge-android
|
library/src/io/konverge/library/utility/common/StringUtils.java
|
4158
|
/**
* Copyright (C) 2009-2013 Nasrollah Kavian - All rights reserved.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This 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 Lesser 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 io.konverge.library.utility.common;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.SortedMap;
@SuppressWarnings("javadoc")
public final class StringUtils
{
public static final String join(final List<String> items,final String delimiter)
{
final StringBuffer buffer = new StringBuffer();
for(int x = 0; x < items.size(); x++)
{
if(buffer.length() > 0)
{
buffer.append(delimiter);
}
buffer.append(items.get(x));
}
return buffer.toString();
}
public static final String join(final SortedMap<String,String> items,final String delimiter,final String seperator)
{
final StringBuffer buffer = new StringBuffer();
for(final String key : items.keySet())
{
if(buffer.length() > 0)
{
buffer.append(seperator);
}
buffer.append(key);
buffer.append(delimiter);
buffer.append(items.get(key));
}
return buffer.toString();
}
public static final String join(final String[] items,final String delimiter)
{
final StringBuffer buffer = new StringBuffer();
if(items.length > 0)
{
for(int x = 0; x < items.length - 1; x++)
{
buffer.append(items[x]);
buffer.append(delimiter);
}
buffer.append(items[items.length - 1]);
}
return buffer.toString();
}
public static final List<String> split(final String s,final String delimiter)
{
final List<String> result = new ArrayList<String>();
final int length = s.length();
int cur = -1;
int next;
if(length == 0)
{
return result;
}
while(true)
{
next = s.indexOf(delimiter,cur + 1);
if(next == -1)
{
result.add(s.substring(cur + 1));
break;
}
else if(next == length - 1)
{
result.add(s.substring(cur + 1,next));
break;
}
else
{
result.add(s.substring(cur + 1,next));
cur = next;
}
}
return result;
}
public static String toString(final InputStream input)
{
// TODO: Needs something similar to IOUtils instead of this.
final StringBuffer buffer = new StringBuffer();
try
{
final BufferedReader dataStream = new BufferedReader(new InputStreamReader(input,"UTF-8"),8192);
String line = null;
try
{
while((line = dataStream.readLine()) != null)
{
buffer.append(line).append("\n");
}
}
catch(final Exception ignore)
{
}
finally
{
try
{
input.close();
}
catch(final Exception ignore)
{
}
}
}
catch(final Exception ignore)
{
}
return buffer.toString();
}
}
|
lgpl-3.0
|
jmecosta/sonar
|
sonar-server/src/main/webapp/WEB-INF/app/controllers/api/metrics_controller.rb
|
3448
|
#
# Sonar, entreprise quality control tool.
# Copyright (C) 2008-2012 SonarSource
# mailto:contact AT sonarsource DOT com
#
# Sonar is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3 of the License, or (at your option) any later version.
#
# Sonar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with Sonar; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
#
require "json"
class Api::MetricsController < Api::RestController
# GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
verify :method => :put, :only => [ :update ]
verify :method => :post, :only => [ :create ]
verify :method => :delete, :only => [ :destroy ]
before_filter :admin_required, :only => [ :create, :update, :destroy ]
def index
metrics = Metric.all
rest_render(metrics)
end
def show
metric = Metric.by_key(params[:id])
if !metric
rest_status_ko('Metric [' + params[:id] + '] does not exist', 404)
else
rest_render([metric])
end
end
def create
metric_test = Metric.find(:first, :conditions => ['name=? OR id=?', params[:id], params[:id].to_i])
exist_and_is_disable = !metric_test.nil? && !metric_test.enabled?
if exist_and_is_disable
metric = metric_test
else
metric = Metric.new
end
begin
metric.attributes = params.merge({:name => params[:id], :short_name => params[:name], :enabled => true})
metric.origin = 'WS'
metric.save!
Metric.clear_cache
rest_status_ok
rescue
rest_status_ko(metric.errors.full_messages.join("."), 400)
end
end
def update
metric = Metric.find(:first, :conditions => ['(name=? OR id=?) AND enabled=? AND origin<>?', params[:id], params[:id].to_i, true, Metric::ORIGIN_JAVA])
if metric
begin
metric.attributes = params.merge({:name => params[:id], :short_name => params[:name], :enabled => true})
metric.save!
Metric.clear_cache
rest_status_ok
rescue
rest_status_ko(metric.errors.full_messages.join("."), 400)
end
else
rest_status_ko('Unable to update : Metric [' + params[:id] + '] does not exist', 404)
end
end
def destroy
metric = Metric.find(:first, :conditions => ['(name=? OR id=?) AND enabled=? AND origin<>?', params[:id], params[:id].to_i, true, Metric::ORIGIN_JAVA])
if !metric
rest_status_ko('Unable to delete : Metric [' + params[:id] + '] does not exist', 404)
else
metric.enabled = false
begin
metric.save!
Metric.clear_cache
rest_status_ok
rescue
rest_status_ko(metric.errors.full_messages.join("."), 400)
end
end
end
protected
def rest_to_json(metrics)
JSON(metrics.collect{|metric| metric.to_hash_json(params)})
end
def rest_to_xml(metrics)
xml = Builder::XmlMarkup.new(:indent => 0)
xml.instruct!
xml.metrics do
metrics.each do |metric|
xml << metric.to_xml(params)
end
end
end
end
|
lgpl-3.0
|
netide/netide
|
NetIde.Shell.Interop.1.0/INiTextLines.cs
|
721
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NetIde.Shell.Interop
{
public interface INiTextLines : INiTextBuffer, INiConnectionPoint
{
HResult Advise(INiTextLinesEvents sink, out int cookie);
HResult GetLineText(int startLine, int startIndex, int endLine, int endIndex, out string result);
HResult ReplaceLines(int startLine, int startIndex, int endLine, int endIndex, string text);
HResult CreateTextMarker(NiTextMarkerType type, NiTextMarkerHatchStyle hatchStyle, bool extendToBorder, int color, int foreColor, int startLine, int startIndex, int endLine, int endIndex, out INiTextMarker textMarker);
}
}
|
lgpl-3.0
|
customer41/profit
|
protected/Models/Category.php
|
773
|
<?php
namespace App\Models;
use T4\Core\Exception;
use T4\Orm\Model;
class Category
extends Model
{
protected static $schema = [
'table' => 'categories',
'columns' => [
'name' => ['type' => 'string', 'length' => 50],
'notDeleted' => ['type' => 'bool'],
],
'relations' => [
'user' => ['type' => self::BELONGS_TO, 'model' => User::class],
'operations' => ['type' => self::HAS_MANY, 'model' => Operation::class],
],
];
protected static $extensions = ['tree'];
protected function validateName($val)
{
if ('' == $val) {
throw new Exception('Заполните название категории');
}
return true;
}
}
|
lgpl-3.0
|
loftuxab/community-edition-old
|
projects/repository/source/java/org/alfresco/service/cmr/security/PersonService.java
|
16385
|
/*
* Copyright (C) 2005-2013 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Alfresco is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.service.cmr.security;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.alfresco.api.AlfrescoPublicApi;
import org.alfresco.query.PagingRequest;
import org.alfresco.query.PagingResults;
import org.alfresco.repo.security.permissions.PermissionCheckValue;
import org.alfresco.service.Auditable;
import org.alfresco.service.NotAuditable;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.namespace.QName;
import org.alfresco.util.Pair;
/**
* This service encapsulates the management of people and groups.
* <p>
* <p>
* People and groups may be managed entirely in the repository or entirely in
* some other implementation such as LDAP or via NTLM. Some properties may in
* the repository and some in another store. Individual properties may or may
* not be mutable.
* <p>
*
* @author Andy Hind
*/
@AlfrescoPublicApi
public interface PersonService
{
/**
* Get a person by userName. The person is store in the repository. The
* person may be created as a side effect of this call, depending on the
* setting of
* {@link #setCreateMissingPeople(boolean) to create missing people or not}.
* The home folder will also be created as a side effect if it does not exist.
*
* @param userName -
* the userName key to find the person
* @return Returns the person node, either existing or new
* @throws NoSuchPersonException
* if the user doesn't exist and could not be created
* automatically
*
* @see #setCreateMissingPeople(boolean)
* @see #createMissingPeople()
*/
@Auditable(parameters = {"userName"})
public NodeRef getPerson(String userName);
/**
* Get a person by userName. The person is store in the repository. No missing
* person objects will be created as a side effect of this call. If the person
* is missing from the repository null will be returned.
*
* @param userName -
* the userName key to find the person
* @return Returns the existing person node, or null if does not exist.
*
* @see #createMissingPeople()
*/
@Auditable(parameters = {"userName"})
public NodeRef getPersonOrNull(String userName);
/**
* Retrieve the person NodeRef for a {@code username}, optionally creating
* the home folder if it does not exist and optionally creating the person
* if they don't exist AND the PersonService is configured to allow the
* creation of missing persons {@see #setCreateMissingPeople(boolean)}.
*
* If not allowed to create missing persons and the person does not exist
* a {@code NoSuchPersonException} exception will be thrown.
*
* @param userName
* of the person NodeRef to retrieve
* @param autoCreateHomeFolderAndMissingPersonIfAllowed
* If the person exits:
* should we create the home folder if it does not exist?
* If the person exists AND the creation of missing persons is allowed
* should we create both the person and home folder.
* @return NodeRef of the person as specified by the username
* @throws NoSuchPersonException
* if the person doesn't exist and can't be created
*/
@Auditable(parameters = {"userName", "autoCreate"})
public NodeRef getPerson(final String userName, final boolean autoCreateHomeFolderAndMissingPersonIfAllowed);
/**
* Retrieve the person info for an existing {@code person NodeRef}
*
* @param person NodeRef
* @return PersonInfo (username, firstname, lastname)
* @throws NoSuchPersonException if the person doesn't exist
*/
@Auditable(parameters = {"personRef"})
public PersonInfo getPerson(NodeRef personRef) throws NoSuchPersonException;
/**
* Check if a person exists.
*
* @param userName
* the user name
* @return Returns true if the user exists, otherwise false
*/
@Auditable(parameters = {"userName"})
public boolean personExists(String userName);
/**
* Does this service create people on demand if they are missing. If this is
* true, a call to getPerson() will create a person if they are missing.
*
* @return true if people are created on demand and false otherwise.
*/
@Auditable
public boolean createMissingPeople();
/**
* Set if missing people should be created.
*
* @param createMissing
* set to true to create people
*
* @see #getPerson(String)
*/
@Auditable(parameters = {"createMissing"})
public void setCreateMissingPeople(boolean createMissing);
/**
* Get the list of properties that are mutable. Some service may only allow
* a limited list of properties to be changed. This may be those persisted
* in the repository or those that can be changed in some other
* implementation such as LDAP.
*
* @return A set of QNames that identify properties that can be changed
*/
@Auditable
public Set<QName> getMutableProperties();
/**
* Set the properties on a person - some of these may be persisted in
* different locations - <b>the home folder is created if it doesn't exist</b>
*
* @param userName -
* the user for which the properties should be set.
* @param properties -
* the map of properties to set (as the NodeService)
*/
@Auditable(parameters = {"userName", "properties"})
public void setPersonProperties(String userName, Map<QName, Serializable> properties);
/**
* Set the properties on a person - some of these may be persisted in different locations.
*
* @param userName
* - the user for which the properties should be set.
* @param properties
* - the map of properties to set (as the NodeService)
* @param autoCreateHomeFolder
* should we auto-create the home folder if it doesn't exist.
*/
@Auditable(parameters = {"userName", "properties", "autoCreate"})
public void setPersonProperties(String userName, Map<QName, Serializable> properties, boolean autoCreateHomeFolder);
/**
* Can this service create, delete and update person information?
*
* @return true if this service allows mutation to people.
*/
@Auditable
public boolean isMutable();
/**
* Create a new person with the given properties. The userName is one of the
* properties. Users with duplicate userNames are not allowed.
*
* @param properties
* @return
*/
@Auditable(parameters = {"properties"})
public NodeRef createPerson(Map<QName, Serializable> properties);
/**
* Create a new person with the given properties, recording them against the given zone name (usually identifying an
* external user registry from which the details were obtained). The userName is one of the properties. Users with
* duplicate userNames are not allowed.
*
* @param properties
* the properties
* @param zones
* a set if zones including the identifier for the external user registry owning the person information, or <code>null</code> or an empty set
* @return the node ref
*/
@Auditable(parameters = {"properties", "zones"})
public NodeRef createPerson(Map<QName, Serializable> properties, Set<String> zones);
/**
* Notifies a user by email that their account has been created, and the details of it.
* Normally called after {@link #createPerson(Map)} or {@link #createPerson(Map, Set)}
* where email notifications are required.
*
* @param userName
* of the person to notify
* @param password
* of the person to notify
* @throws NoSuchPersonException
* if the person doesn't exist
*/
@Auditable(parameters = {"userName"})
public void notifyPerson(final String userName, final String password);
/**
* Delete the person identified by the given user name.
*
* @param userName
*/
@Auditable(parameters = {"userName"})
public void deletePerson(String userName);
/**
* Delete the person identified by the given ref.
*
* @param personRef
*/
@Auditable(parameters = {"personRef"})
public void deletePerson(NodeRef personRef);
/**
* Delete the person identified by the given ref, and optionally delete
* the associated authentication, if one.
*
* @param personRef
* @param deleteAuthentication
*/
@Auditable(parameters = {"personRef", "deleteAuthentication"})
public void deletePerson(NodeRef personRef, boolean deleteAuthentication);
/**
* Get all the people we know about.
*
* @return a set of people in no specific order.
*
* @deprecated see {@link #getPeople(List, boolean, List, PagingRequest)}
*/
@Auditable
public Set<NodeRef> getAllPeople();
/**
* Data pojo to carry common person information
*
* @author janv
* @since 4.0
*/
public class PersonInfo implements PermissionCheckValue
{
private final NodeRef nodeRef;
private final String userName;
private final String firstName;
private final String lastName;
public PersonInfo(NodeRef nodeRef, String userName, String firstName, String lastName)
{
this.nodeRef = nodeRef;
this.userName = userName;
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public NodeRef getNodeRef()
{
return nodeRef;
}
public String getUserName()
{
return userName;
}
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
}
/**
* Get paged list of people optionally filtered and/or sorted
*
* Note: the pattern is applied to filter props (0 to 3) as startsWithIgnoreCase, which are OR'ed together, for example: cm:userName or cm:firstName or cm:lastName
*
* @param pattern pattern to apply to filter props - "startsWith" and "ignoreCase"
* @param filterProps list of filter properties (these are OR'ed)
* @param sortProps sort property, eg. cm:username ascending
* @param pagingRequest skip, max + optional query execution id
* @return
*
* @author janv
* @since 4.1.2
*/
@Auditable(parameters = {"pattern", "filterProps", "sortProps", "pagingRequest"})
public PagingResults<PersonInfo> getPeople(String pattern, List<QName> filterProps, List<Pair<QName, Boolean>> sortProps, PagingRequest pagingRequest);
/**
* Get paged list of people optionally filtered and/or sorted
*
* @param filterProps list of filter properties (with "startsWith" values), eg. cm:username "al" might match "alex", "alice", ...
* @param filterIgnoreCase true to ignore case when filtering, false to be case-sensitive when filtering
* @param sortProps sort property, eg. cm:username ascending
* @param pagingRequest skip, max + optional query execution id
*
* @author janv
* @since 4.0
* @deprecated see getPeople(String pattern, List<QName> filterProps, List<Pair<QName, Boolean>> sortProps, PagingRequest pagingRequest)
*/
@Auditable(parameters = {"stringPropFilters", "filterIgnoreCase", "sortProps", "pagingRequest"})
public PagingResults<PersonInfo> getPeople(List<Pair<QName,String>> stringPropFilters, boolean filterIgnoreCase, List<Pair<QName, Boolean>> sortProps, PagingRequest pagingRequest);
/**
* Get paged list of people optionally filtered and/or sorted
*
* @param filterProps list of filter properties (with "startsWith" values), eg. cm:username "al" might match "alex", "alice", ...
* @param filterIgnoreCase true to ignore case when filtering, false to be case-sensitive when filtering
* @param inclusiveAspects if set, filter out any people that don't have one of these aspects
* @param exclusiveAspects if set, filter out any people that do have one of these aspects
* @param includeAdministrators true to include administrators in the results.
* @param sortProps sort property, eg. cm:username ascending
* @param pagingRequest skip, max + optional query execution id
*
* @author Alex Miller
* @since 4.0
*/
@Auditable(parameters = {"stringPropFilters", "filterIgnoreCase", "inclusiveAspect", "exclusiveAspects", "sortProps", "pagingRequest"})
public PagingResults<PersonInfo> getPeople(String pattern, List<QName> filterStringProps, Set<QName> inclusiveAspects, Set<QName> exclusiveAspects, boolean includeAdministraotrs, List<Pair<QName, Boolean>> sortProps, PagingRequest pagingRequest);
/**
* Get people filtered by the given property name/value pair.
* <p/>
* In order to get paging, use {@link #getPeople(List, boolean, List, PagingRequest)}
*
* @param propertyKey property key of property to filter people by
* @param propertyValue property value of property to filter people by
* @param count the number of results to retrieve, up to a maximum of 1000
* @return people filtered by the given property name/value pair
*
* @see #getPeople(List, boolean, List, PagingRequest)
*/
@Auditable
public Set<NodeRef> getPeopleFilteredByProperty(QName propertyKey, Serializable propertyValue, int count);
/**
* Return the container that stores people.
*
* @return
*/
@Auditable
public NodeRef getPeopleContainer();
/**
* Are user names case sensitive?
*
* @return
*/
@Auditable
public boolean getUserNamesAreCaseSensitive();
/**
* Given the case sensitive user name find the approriate identifier from the person service.
* If the system is case sensitive it will return the same string.
* If case insentive it will return the common object.
* If the user does not exist it will return null;
*
* @param caseSensitiveUserName
* @return
*/
@NotAuditable
public String getUserIdentifier(String caseSensitiveUserName);
/**
* Counts the number of persons registered with the system.
*
* @return
*/
@NotAuditable
public int countPeople();
/**
* Is the specified user, enabled
* @throws NoSuchPersonException
* if the user doesn't exist
* @return true = enabled.
*/
@NotAuditable
public boolean isEnabled(final String userName);
}
|
lgpl-3.0
|
SensingKit/SensingKit-Android
|
SensingKitLib/src/main/java/org/sensingkit/sensingkitlib/modules/SKStepCounter.java
|
1855
|
/*
* Copyright (c) 2014. Queen Mary University of London
* Kleomenis Katevas, k.katevas@qmul.ac.uk
*
* This file is part of SensingKit-Android library.
* For more information, please visit http://www.sensingkit.org
*
* SensingKit-Android is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* SensingKit-Android is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with SensingKit-Android. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sensingkit.sensingkitlib.modules;
import android.content.Context;
import android.hardware.SensorEvent;
import org.sensingkit.sensingkitlib.SKException;
import org.sensingkit.sensingkitlib.SKSensorModuleType;
import org.sensingkit.sensingkitlib.data.SKAbstractData;
import org.sensingkit.sensingkitlib.data.SKStepCounterData;
public class SKStepCounter extends SKAbstractNativeSensorModule {
@SuppressWarnings("unused")
private static final String TAG = "SKStepCounter";
public SKStepCounter(final Context context) throws SKException {
super(context, SKSensorModuleType.STEP_COUNTER);
}
@Override
protected SKAbstractData buildData(SensorEvent event)
{
return new SKStepCounterData(System.currentTimeMillis(), event.values[0]);
}
@Override
protected boolean shouldPostSensorData(SKAbstractData data) {
// Always post sensor data
return true;
}
}
|
lgpl-3.0
|
totalcross/TotalCrossSDK
|
src/main/java/totalcross/ui/MainWindow.java
|
25831
|
/*********************************************************************************
* TotalCross Software Development Kit *
* Copyright (C) 1998, 1999 Wabasoft <www.wabasoft.com> *
* Copyright (C) 2000-2012 SuperWaba Ltda. *
* All Rights Reserved *
* *
* This library and virtual machine 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. *
* *
* This file is covered by the GNU LESSER GENERAL PUBLIC LICENSE VERSION 3.0 *
* A copy of this license is located in file license.txt at the root of this *
* SDK or can be downloaded here: *
* http://www.gnu.org/licenses/lgpl-3.0.txt *
* *
*********************************************************************************/
package totalcross.ui;
import com.totalcross.annotations.ReplacedByNativeOnDeploy;
import totalcross.firebase.FirebaseManager;
import totalcross.firebase.iid.FirebaseInstanceIdService;
import totalcross.io.ByteArrayStream;
import totalcross.io.File;
import totalcross.io.FileNotFoundException;
import totalcross.io.IOException;
import totalcross.res.Resources;
import totalcross.sys.CharacterConverter;
import totalcross.sys.Convert;
import totalcross.sys.Settings;
import totalcross.sys.Vm;
import totalcross.ui.dialog.MessageBox;
import totalcross.ui.effect.UIEffects;
import totalcross.ui.event.ControlEvent;
import totalcross.ui.event.TimerEvent;
import totalcross.ui.event.WindowListener;
import totalcross.ui.font.Font;
import totalcross.ui.gfx.Color;
import totalcross.ui.gfx.Graphics;
import totalcross.ui.image.Image;
import totalcross.unit.UIRobot;
import totalcross.util.Hashtable;
import totalcross.util.IOUtils;
import totalcross.util.Vector;
import totalcross.util.concurrent.Lock;
import totalcross.util.zip.CompressedStream;
import totalcross.util.zip.ZLibStream;
import totalcross.util.zip.ZipEntry;
import totalcross.util.zip.ZipStream;
/**
* MainWindow is the main window of a UI-based application.
* <p>
* All TotalCross programs with an user-interface must have <b>one and only one</b> main window.
* <p>
* Here is an example showing a basic application:
*
* <pre>
* public class MyProgram extends MainWindow
* {
* Edit edName;
* public void initUI()
* {
* ... initialization code ...
* add(new Label("Name:"), LEFT,TOP+2);
* add(edName = new Edit(""), AFTER,SAME-2);
* }
* }
* </pre>
*/
public class MainWindow extends Window implements totalcross.MainClass {
protected TimerEvent firstTimer;
private TimerEvent startTimer;
static MainWindow mainWindowInstance;
private static int lastMinInterval;
private boolean initUICalled;
private static int timeAvailable;
static Font defaultFont;
private static Thread mainThread;
private Lock runnersLock = new Lock();
private Vector runners = new Vector(1);
/** Constructs a main window with no title and no border. */
public MainWindow() {
this(null, NO_BORDER);
}
/** Constructs a main window with the given title and border style.
* @see #NO_BORDER
* @see #RECT_BORDER
* @see #ROUND_BORDER
* @see #TAB_BORDER
* @see #TAB_ONLY_BORDER
* @since SuperWaba 2.0b4
*/
public MainWindow(String title, byte style) // guich@112
{
super(title, style);
setX = 0;
setY = 0;
setW = Settings.screenWidth;
setH = Settings.screenHeight;
setFont = this.font;
Settings.scrollDistanceOnMouseWheelMove = fmH;
boolean isAndroid = Settings.platform.equals(Settings.ANDROID);
boolean isIphone = Settings.isIOS();
if (isAndroid || isIphone) {
Settings.unmovableSIP = true;
}
// guich@tc120_48
if (Settings.fingerTouch) {
Settings.touchTolerance = fmH / 2;
}
// update some settings
setBackColor(UIColors.controlsBack = Color.WHITE); // guich@200b4_39 - guich@tc100: set the controlsBack to this color
uitip = new ToolTip(null, "");
if (mainWindowInstance == null) {
mainWindowInstance = this;
mainWindowCreate();
zStack.push(this); // guich
topMost = this;
}
canDrag = false; // we can't drag the mainwindow.
byte[] bytes = Vm.getFile("tcapp.prop");
if (bytes != null) {
Settings.appProps = new Hashtable(new String(bytes));
}
FirebaseManager.getInstance().registerFirebaseInstanceIdService(initFirebaseInstanceIdService());
}
/**
* Register your own FirebaseInstanceIdService when initializing the app
* @return
*/
protected FirebaseInstanceIdService initFirebaseInstanceIdService() {
return null;
}
/** Returns true if this is the main thread.
* @since TotalCross 2.0
*/
public static boolean isMainThread() {
return mainThread == Thread.currentThread();
}
void mainWindowCreate() {
totalcross.Launcher.instance.registerMainWindow(this);
}
void mainWindowCreate4D() {
} // not needed at device
/** Sets the default font used in all controls created. To change the default font, assign it to this member in the MainWindow constructor,
* making it the FIRST LINE in the constructor; you'll not be able to use super(title,border): change by setBorderStyle and setTitle, after
* the defaultFont assignment. Example:
* <pre>
* public MyApp()
* {
* MainWindow.setDefaultFont(Font.getFont(false, Font.NORMAL_SIZE+2));
* setBorderStyle(TAB_ONLY_BORDER);
* setTitle("My application");
* }
* </pre>
* @since TotalCross 1.0 beta3
*/
public static void setDefaultFont(Font newFont) {
defaultFont = newFont;
mainWindowInstance.setFont(newFont);
uitip.setFont(newFont); // guich@tc100b5_58
mainWindowInstance.setTitleFont(newFont.asBold()); // guich@tc125_4
mainWindowInstance.titleGap = 0;
// guich@tc120_48
if (Settings.fingerTouch) {
Settings.touchTolerance = newFont.fm.height / 2;
}
}
/** Returns the default font.
* @since TotalCross 1.0 beta3
*/
public static Font getDefaultFont() {
return defaultFont;
}
/** Changes the user interface style to the given one.
* This method must be called in the MainWindow's constructor, and only once. E.g.:
* <pre>
* public class Foo extends MainWindow
* {
* public Foo()
* {
* super("Hi bar",TAB_ONLY_BORDER);
* setUIStyle(totalcross.sys.Settings.Flat);
* </pre>
* Changing to Android style will also set Settings.fingerTouch to true.
* If you don't like such behaviour in non finger devices, set this property to false after calling setUIStyle.
*
* @see totalcross.sys.Settings#Flat
* @see totalcross.sys.Settings#Vista
* @see totalcross.sys.Settings#Android
* @see totalcross.sys.Settings#Holo
* @see totalcross.sys.Settings#Material
* @since SuperWaba 5.05
*/
public void setUIStyle(byte style) {
Settings.uiStyle = style;
if (style >= Settings.Android) {
Settings.fingerTouch = true;
}
if (style == Settings.Material) {
UIEffects.defaultEffect = UIEffects.Effects.MATERIAL;
}
Control.uiStyleChanged();
Resources.uiStyleChanged();
if (uiAndroid) {
androidBorderThickness = Settings.screenWidth <= 320 ? 1 : Settings.screenWidth <= 640 ? 2 : 3;
borderGaps[ROUND_BORDER] = androidBorderThickness == 3 ? 3 : 2;
}
}
/**
* Notifies the application that it should stop executing and exit. It will
* exit after executing any pending events. If the underlying system supports
* it, the exitCode passed is returned to the program that started the app.
* Note: On AppletViewer/Browser the exitCode is useless.
* Note 2: On Android, you can exit softly by using SOFT_EXIT as the exit code.
* <p>If you want your code to be called when the VM exits, extend the onExit method.
* @see #onExit
*/
@ReplacedByNativeOnDeploy
public static final void exit(int exitCode) {
totalcross.Launcher.instance.exit(exitCode);
}
/**
* Notifies the application that it should be minimized, that is, transfered
* to the background. Whenever the application is minimized, the following call back function
* will be called: {@link #onMinimize()}. Note: On Android, calling {@link #minimize()} will
* pause the application execution and it can only be restored manually by the user. This method is
* also supported on Windows 32.
* @see #onMinimize
* @see #onRestore
* @since TotalCross 1.10
*/
@ReplacedByNativeOnDeploy
public static void minimize() // bruno@tc110_89
{
totalcross.Launcher.instance.minimize();
}
/**
* Notifies the application that it should be restored, that is, transfered
* to the foreground.
* Whenever the application is restored, the following call back function will be called:
* {@link #onRestore()}. Note: This method is supported on Android but the user must restore
* the application manually. This method is also supported on Windows 32.
* @since TotalCross 1.10
*/
@ReplacedByNativeOnDeploy
public static void restore() // bruno@tc110_89
{
totalcross.Launcher.instance.restore();
}
/**
* Returns the instance of the current main window. You can use it to get access to methods of the <code>MainWindow</code> class from outside the class.
* It is also possible to cast the returned class to the class that is extending <code>MainWindow</code> (this is a normal Java behavior).
* So, if UiGadgets is running, it is correct to do:
* <pre>
* UIGadgets instance = (UIGadgets)MainWindow.getMainWindow();
* </pre>
*/
public static MainWindow getMainWindow() {
return mainWindowInstance;
}
/**
* Adds a timer to a control. This method is protected, the public
* method to add a timer to a control is the addTimer() method in
* the Control class. The Timer event will be issued to the target every millis milliseconds.
*/
protected TimerEvent addTimer(Control target, int millis) {
TimerEvent t = new TimerEvent();
addTimer(t, target, millis);
return t;
}
/**
* Adds the timer t to the target control. This method is protected, the public
* method to add a timer to a control is the addTimer() method in
* the Control class. The Timer event will be issued to the target every millis milliseconds.
*/
protected void addTimer(TimerEvent t, Control target, int millis) {
addTimer(t, target, millis, true);
}
/**
* Adds the timer t to the target control. This method is protected, the public
* method to add a timer to a control is the addTimer() method in
* the Control class. The Timer event will be issued to the target every millis milliseconds.
*/
protected void addTimer(TimerEvent te, Control target, int millis, boolean append) {
te.target = target;
te.millis = millis;
te.lastTick = Vm.getTimeStamp();
if (firstTimer == null) // first timer to be added
{
te.next = null;
firstTimer = te;
} else if (append) // appending timer to the end of the list
{
TimerEvent last = null;
for (TimerEvent t = firstTimer; t != null; t = t.next) {
if (t == te) {
// already inserted? get out!
return;
}
last = t;
}
if (last != null) {
last.next = te;
}
te.next = null;
} else // inserting timer to the beginning of the list
{
te.next = firstTimer;
firstTimer = te;
}
setTimerInterval(1); // forces a call to _onTimerTick inside the TC Event Thread
}
/**
* Removes the given timer from the timers queue. This method returns true if the timer was found
* and removed and false if the given timer could not be found.
* The <code>target</code> member is set to null.
*/
@Override
public boolean removeTimer(TimerEvent timer) {
if (timer == null) {
return false;
}
TimerEvent t = firstTimer;
TimerEvent prev = null;
while (t != timer) {
if (t == null) {
return false;
}
prev = t;
t = t.next;
}
if (prev == null) {
firstTimer = t.next;
} else {
prev.next = t.next;
}
// not already removed?
if (timer.target != null) {
setTimerInterval(1); // forces a call to _onTimerTick inside the TC Event Thread
}
timer.target = null; // guich@tc120_46
return true;
}
/** Removes any timers that belongs to this window or whose paren't is null */
void removeTimers(Window win) {
boolean changed;
do {
changed = false;
TimerEvent t = firstTimer;
while (t != null) {
Control c = (Control) t.target;
Window w = c.getParentWindow();
if (w == null || w == win) {
changed = true;
if (Flick.currentFlick != null && Flick.currentFlick.timer == t) {
Flick.currentFlick.stop(true);
} else {
removeTimer(t);
}
break;
}
t = t.next;
}
} while (changed);
}
/** Called by the VM when the application is starting. Setups a
* timer that will call initUI after the event loop is started.
* Never call this method directly; this method is not private
* to prevent the compiler from removing it during optimization.
* The timeAvail parameter is passed by the vm to show how much
* time the user have to keep testing the demo vm. Even if this
* value is not shown to the user, it is internally computed and
* the vm will exit when the counter reaches 0.
*/
@Override
final public void appStarting(int timeAvail) // guich@200b4_107 - guich@tc126_46: added timeAvail parameter to show MessageBox from inside here.
{
mainThread = Thread.currentThread();
timeAvailable = timeAvail;
gfx = new Graphics(this); // revalidate the pixels
startTimer = addTimer(1); // guich@567_17
}
static boolean quittingApp;
/** Called by the system so we can finish things correctly.
* Never call this method directly; this method is not private
* to prevent the compiler from removing it during optimization.
*/
@Override
final public void appEnding() // guich@200final_11: fixed when switching apps not calling killThreads.
{
if (!Settings.onJavaSE) {
try {
new File(Convert.appendPath(Settings.appPath, "appCr4shed"), File.READ_WRITE).delete();
} catch (Throwable t) {
} // finished fine
}
quittingApp = true;
// guich@tc100: do this at device side - if (resetSipToBottom) setStatePosition(0, Window.VK_BOTTOM); // fixes a problem of the window of the sip not correctly being returned to the bottom
// guich@tc126_46: don't call app's onExit if time expired, since initUI was not called.
if (initUICalled) {
onExit(); // guich@200b4_85
}
}
final protected void _onMinimize() {
if (!Settings.onJavaSE) {
try {
new File(Convert.appendPath(Settings.appPath, "appCr4shed"), File.READ_WRITE).delete();
} catch (Throwable t) {
} // finished fine
}
onMinimize();
}
final protected void _onRestore() {
if (!Settings.onJavaSE) {
try {
new File(Convert.appendPath(Settings.appPath, "appCr4shed"), File.CREATE_EMPTY).close();
} catch (Throwable t) {
} // restarting app
}
onRestore();
}
/**
* Called just before an application exits.
* When this is called, all threads are already killed.
* You should return from this method as soon as possible, because the OS can kill the application if
* it takes too much to return.
*
* Note that on Windows Phone this method is NEVER called.
*/
public void onExit() {
}
/**
* Called just after the application is minimized.
*
* If the user press the home key and then forces the application to stop (by going to the Settings / Applications), then
* all Litebase tables may be corrupted (actually, no data is lost, but a TableNotClosedException will be issued). So, its a good
* thing to call LitebaseConnection.closeAll in your litebase instances and recover them in the onRestore method.
* <br><br>
* When the onMinimize is called, the screen will only be able to be updated after it resumes (in other words,
* calling repaint or repaintNow from the onMinimize method has no effect).
*
* On Windows Phone, the onMinimize is called and, if the user don't call the application again
* within 10 seconds, the application is KILLED without notifications. So, you should save all your application's state
* in this method and restore it in the onRestore method.
* @see #minimize()
* @since TotalCross 1.10
*/
public void onMinimize() // bruno@tc110_89 - bruno@tc122_31: now supported on wince and win32
{
}
/**
* Called just after the application is restored.
*
* @see #onRestore()
* @since TotalCross 1.10
*/
public void onRestore() // bruno@tc110_89 - bruno@tc122_31: now supported on wince and win32
{
}
private void startProgram() {
initUICalled = Window.needsPaint = true;
initUI();
Window.needsPaint = Graphics.needsUpdate = true; // required by device
started = true; // guich@567_17: moved this from appStarting to here to let popup check if the screen was already painted
repaintActiveWindows();
// start a robot if one is passed as parameter
String cmd = getCommandLine();
if (cmd != null && cmd.endsWith(".robot")) {
try {
new UIRobot(cmd + " (cmdline)");
} catch (Exception e) {
MessageBox.showException(e, true);
}
}
if (cmd != null && cmd.equals("/pushnotification")) {
postPushNotifications();
}
}
/**
* Called by the VM to process timer interrupts. This method is not private
* to prevent the compiler from removing it during optimization.
*/
@Override
final public void _onTimerTick(boolean canUpdate) {
if (startTimer != null) // guich@567_17
{
TimerEvent t = startTimer;
startTimer = null; // removeTimer calls again onTimerTick, so we have to null out this before calling it
removeTimer(t);
if (timeAvailable >= 0 && Settings.platform.equals(Settings.WIN32)
&& (Settings.romSerialNumber == null || Settings.romSerialNumber.length() == 0)) {
new MessageBox("Fatal Error",
"Failed to retrieve a unique device identification to activate the TotalCross VM. Please check your network settings and activate any disabled networks.")
.popup();
exit(0);
return;
}
startProgram();
}
int minInterval = 0;
TimerEvent timer = firstTimer;
while (timer != null) {
if (timer.target == null) // aleady removed but still in the queue?
{
TimerEvent t = timer.next;
removeTimer(timer);
timer = t != null ? t.next : null;
continue;
}
int now = Vm.getTimeStamp(); // guich@tc100b4
int diff = now - timer.lastTick;
if (diff < 0) {
diff += (1 << 30); // wrap around - max stamp is (1 << 30)
}
int interval;
if (diff >= timer.millis) {
// post TIMER event
timer.triggered = true; // guich@220_39
((Control) timer.target).postEvent(timer);
timer.triggered = false;
timer.lastTick = now;
interval = timer.millis;
} else {
interval = timer.millis - diff;
}
if (interval < minInterval || minInterval == 0) {
minInterval = interval;
}
timer = timer.next;
}
// guich@tc100: call only if there's a timer to run
if (minInterval > 0 || lastMinInterval > 0) {
setTimerInterval(lastMinInterval = minInterval);
}
// run everything that needs to run on main thread
Object[] runners = getRunners();
if (runners != null) {
Control.enableUpdateScreen = false; // we'll update the screen below
for (int i = 0; i < runners.length; i++) {
((Runnable) runners[i]).run();
}
Control.enableUpdateScreen = true;
}
// guich@200b4_1: corrected the infinit repaint on popup windows
if (Window.needsPaint) {
repaintActiveWindows(); // already calls updateScreen
} else if (canUpdate && Graphics.needsUpdate) {
// guich@tc100: make sure that any pending screen update is committed. - if not called from addTimer/removeTimer (otherwise, an open combobox will flicker)
safeUpdateScreen();
}
}
@ReplacedByNativeOnDeploy
void setTimerInterval(int n) {
totalcross.Launcher.instance.setTimerInterval(n);
}
/** Returns the command line passed by the application that called this application in the Vm.exec method.
*
* In Android, you can start an application using adb:
* <pre>
* adb shell am start -a android.intent.action.MAIN -n totalcross.app.uigadgets/.UIGadgets -e cmdline "Hello world"
* </pre>
* In the sample above, we're starting UIGadgets. Your app should be: totalcross.app.yourMainWindowClass/.yourMainWindowClass
*
* Note: When you click on the application's icon, there's no command line.
*/
@ReplacedByNativeOnDeploy
final public static String getCommandLine() // guich@tc120_8: now is static
{
return totalcross.Launcher.instance.commandLine;
}
/** This method can't be called for a MainWindow */
@Override
public void setRect(int x, int y, int width, int height, Control relative, boolean screenChanged) // guich@567_19
{
// no messages, please. just ignore
}
/** Takes a screen shot of the current screen. Since TotalCross 3.06, it uses Control.takeScreenShot.
* Here's a sample:
* <pre>
* Image img = MainWindow.getScreenShot();
* File f = new File(Settings.onJavaSE ? "screen.png" : "/sdcard/screen.png",File.CREATE_EMPTY);
* img.createPng(f);
* f.close();
* </pre>
* Note that the font varies from device to device and even to desktop. So, if you want to compare a device's
* screen shot with one taken at desktop, be sure to set the default font in both to the same, like using
* <code>setDefaultFont(Font.getFont(false,20))</code>.
*
* @since TotalCross 1.3
*/
public static Image getScreenShot() {
try {
// get main window
mainWindowInstance.takeScreenShot();
Image img = mainWindowInstance.offscreen;
mainWindowInstance.releaseScreenShot();
// now paint other windows
int lastFade = 1000;
for (int j = 0, n = zStack.size(); j < n; j++) {
if (((Window) zStack.items[j]).fadeOtherWindows) {
lastFade = j;
}
}
for (int i = 0, n = zStack.size(); i < n; i++) // repaints every window, from the nearest with the MainWindow size to last parent
{
if (i == lastFade) {
img.applyFade(fadeValue);
}
if (i > 0 && zStack.items[i] != null) {
Window w = (Window) zStack.items[i];
Graphics g = img.getGraphics();
g.translate(w.x, w.y);
w.paint2shot(g, true);
}
}
img.lockChanges();
return img;
} catch (Throwable e) {
}
return null;
}
// stuff to let a thread update the screen
private Object[] getRunners() {
Object[] o = null;
synchronized (runnersLock) {
try {
int n = runners.size();
if (n != 0) {
o = runners.toObjectArray();
runners = new Vector(1);
}
} catch (Exception e) {
}
}
return o;
}
/** The same of <code>runOnMainThread(r, true)</code>.
* @see #runOnMainThread(Runnable, boolean)
* Note that this
* */
public void runOnMainThread(Runnable r) {
runOnMainThread(r, true);
}
/** Runs the given code in the main thread. As of TotalCross 2.0, a thread cannot update the screen.
* So, asking the code to be called in the main thread solves the problem. Of course, this call is asynchronous, ie,
* the thread may run again before the screen is updated. This method is thread-safe.
* If singleInstance is true and the array contains an element of this class, it is replaced by the given one.
* Note that passing as false may result in memory leak.
* Sample:
* <pre>
* new Thread()
{
public void run()
{
while (true)
{
Vm.sleep(1000);
MainWindow.getMainWindow().runOnMainThread(new Runnable()
{
public void run()
{
log("babi "+ ++contador);
}
});
}
}
}.start();
* </pre>
* @since TotalCross 2.1
*/
public void runOnMainThread(Runnable r, boolean singleInstance) {
synchronized (runnersLock) {
try {
if (singleInstance && runners.size() > 0) {
String origname = r.getClass().getName() + "@";
for (int i = 0, n = runners.size(); i < n; i++) {
if (runners.items[i].toString().startsWith(origname)) {
runners.removeElementAt(i);
break;
}
}
}
runners.addElement(r);
setTimerInterval(1);
} catch (Exception e) {
}
}
Vm.sleep(1);
}
}
|
lgpl-3.0
|
Austinb/GameQ
|
tests/Protocols/Gtar.php
|
2187
|
<?php
/**
* This file is part of GameQ.
*
* GameQ is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* GameQ is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GameQ\Tests\Protocols;
class Gtar extends Base
{
/**
* Holds stub on setup
*
* @type \GameQ\Protocols\Gtan
*/
protected $stub;
/**
* Holds the expected packets for this protocol class
*
* @type array
*/
protected $packets = [
\GameQ\Protocol::PACKET_STATUS => "GET /master/ HTTP/1.0\r\nHost: cdn.rage.mp\r\nAccept: */*\r\n\r\n",
];
/**
* Setup
*/
public function setUp()
{
// Create the stub class
$this->stub = $this->getMockBuilder('\GameQ\Protocols\Gtar')
->enableProxyingToOriginalMethods()
->getMock();
}
/**
* Test the packets to make sure they are correct for source
*/
public function testPackets()
{
// Test to make sure packets are defined properly
$this->assertEquals($this->packets, \PHPUnit\Framework\Assert::readAttribute($this->stub, 'packets'));
}
/**
* Test responses for Grand Theft Auto Network
*
* @dataProvider loadData
*
* @param $responses
* @param $result
*/
public function testResponses($responses, $result)
{
// Pull the first key off the array this is the server ip:port
$server = key($result);
$testResult = $this->queryTest(
$server,
'gtar',
$responses
);
$this->assertEquals($result[ $server ], $testResult, '', 0.000000001);
}
}
|
lgpl-3.0
|
ProjectInfinity/PocketMine-MP
|
src/pocketmine/entity/Human.php
|
15213
|
<?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace pocketmine\entity;
use pocketmine\event\entity\EntityDamageEvent;
use pocketmine\event\entity\EntityRegainHealthEvent;
use pocketmine\event\player\PlayerExhaustEvent;
use pocketmine\inventory\InventoryHolder;
use pocketmine\inventory\PlayerInventory;
use pocketmine\item\Item as ItemItem;
use pocketmine\nbt\NBT;
use pocketmine\nbt\tag\ByteTag;
use pocketmine\nbt\tag\CompoundTag;
use pocketmine\nbt\tag\FloatTag;
use pocketmine\nbt\tag\IntTag;
use pocketmine\nbt\tag\ListTag;
use pocketmine\nbt\tag\ShortTag;
use pocketmine\nbt\tag\StringTag;
use pocketmine\network\protocol\AddPlayerPacket;
use pocketmine\network\protocol\RemovePlayerPacket;
use pocketmine\Player;
use pocketmine\utils\UUID;
class Human extends Creature implements ProjectileSource, InventoryHolder{
const DATA_PLAYER_FLAG_SLEEP = 1;
const DATA_PLAYER_FLAG_DEAD = 2;
const DATA_PLAYER_FLAGS = 16;
const DATA_PLAYER_BED_POSITION = 17;
/** @var PlayerInventory */
protected $inventory;
/** @var UUID */
protected $uuid;
protected $rawUUID;
public $width = 0.6;
public $length = 0.6;
public $height = 1.8;
public $eyeHeight = 1.62;
protected $skinName;
protected $skin;
protected $foodTickTimer = 0;
protected $totalXp = 0;
protected $xpSeed;
public function getSkinData(){
return $this->skin;
}
public function getSkinName(){
return $this->skinName;
}
/**
* @return UUID|null
*/
public function getUniqueId(){
return $this->uuid;
}
/**
* @return string
*/
public function getRawUniqueId(){
return $this->rawUUID;
}
/**
* @param string $str
* @param string $skinName
*/
public function setSkin($str, $skinName){
$this->skin = $str;
$this->skinName = $skinName;
}
public function getFood() : float{
return $this->attributeMap->getAttribute(Attribute::HUNGER)->getValue();
}
/**
* WARNING: This method does not check if full and may throw an exception if out of bounds.
* Use {@link Human::addFood()} for this purpose
*
* @param float $new
*
* @throws \InvalidArgumentException
*/
public function setFood(float $new){
$attr = $this->attributeMap->getAttribute(Attribute::HUNGER);
$old = $attr->getValue();
$attr->setValue($new);
// ranges: 18-20 (regen), 7-17 (none), 1-6 (no sprint), 0 (health depletion)
foreach([17, 6, 0] as $bound){
if(($old > $bound) !== ($new > $bound)){
$reset = true;
}
}
if(isset($reset)){
$this->foodTickTimer = 0;
}
}
public function getMaxFood() : float{
return $this->attributeMap->getAttribute(Attribute::HUNGER)->getMaxValue();
}
public function addFood(float $amount){
$attr = $this->attributeMap->getAttribute(Attribute::HUNGER);
$amount += $attr->getValue();
$amount = max(min($amount, $attr->getMaxValue()), $attr->getMinValue());
$this->setFood($amount);
}
public function getSaturation() : float{
return $this->attributeMap->getAttribute(Attribute::HUNGER)->getValue();
}
/**
* WARNING: This method does not check if saturated and may throw an exception if out of bounds.
* Use {@link Human::addSaturation()} for this purpose
*
* @param float $saturation
*
* @throws \InvalidArgumentException
*/
public function setSaturation(float $saturation){
$this->attributeMap->getAttribute(Attribute::HUNGER)->setValue($saturation);
}
public function addSaturation(float $amount){
$attr = $this->attributeMap->getAttribute(Attribute::SATURATION);
$attr->setValue($attr->getValue() + $amount, true);
}
public function getExhaustion() : float{
return $this->attributeMap->getAttribute(Attribute::EXHAUSTION)->getValue();
}
/**
* WARNING: This method does not check if exhausted and does not consume saturation/food.
* Use {@link Human::exhaust()} for this purpose.
*
* @param float $exhaustion
*/
public function setExhaustion(float $exhaustion){
$this->attributeMap->getAttribute(Attribute::EXHAUSTION)->setValue($exhaustion);
}
/**
* Increases a human's exhaustion level.
*
* @param float $amount
* @param int $cause
*
* @return float the amount of exhaustion level increased
*/
public function exhaust(float $amount, int $cause = PlayerExhaustEvent::CAUSE_CUSTOM) : float{
$this->server->getPluginManager()->callEvent($ev = new PlayerExhaustEvent($this, $amount, $cause));
if($ev->isCancelled()){
return 0.0;
}
$exhaustion = $this->getExhaustion();
$exhaustion += $ev->getAmount();
while($exhaustion >= 4.0){
$exhaustion -= 4.0;
$saturation = $this->getSaturation();
if($saturation > 0){
$saturation = max(0, $saturation - 1.0);
$this->setSaturation($saturation);
}else{
$food = $this->getFood();
if($food > 0){
$food--;
$this->setFood($food);
}
}
}
$this->setExhaustion($exhaustion);
return $ev->getAmount();
}
public function getXpLevel() : int{
return (int) $this->attributeMap->getAttribute(Attribute::EXPERIENCE_LEVEL)->getValue();
}
public function setXpLevel(int $level){
$this->attributeMap->getAttribute(Attribute::EXPERIENCE_LEVEL)->setValue($level);
}
public function getXpProgress() : float{
return $this->attributeMap->getAttribute(Attribute::EXPERIENCE)->getValue();
}
public function setXpProgress(float $progress){
$this->attributeMap->getAttribute(Attribute::EXPERIENCE)->setValue($progress);
}
public function getTotalXp() : float{
return $this->totalXp;
}
public function getRemainderXp() : int{
return $this->getTotalXp() - self::getTotalXpForLevel($this->getXpLevel());
}
public function recalculateXpProgress() : float{
$this->setXpProgress($this->getRemainderXp() / self::getTotalXpForLevel($this->getXpLevel()));
}
public static function getTotalXpForLevel(int $level) : int{
if($level <= 16){
return $level ** 2 + $level * 6;
}elseif($level < 32){
return $level ** 2 * 2.5 - 40.5 * $level + 360;
}
return $level ** 2 * 4.5 - 162.5 * $level + 2220;
}
public function getInventory(){
return $this->inventory;
}
protected function initEntity(){
$this->setDataFlag(self::DATA_PLAYER_FLAGS, self::DATA_PLAYER_FLAG_SLEEP, false);
$this->setDataProperty(self::DATA_PLAYER_BED_POSITION, self::DATA_TYPE_POS, [0, 0, 0]);
$this->inventory = new PlayerInventory($this);
if($this instanceof Player){
$this->addWindow($this->inventory, 0);
}else{
if(isset($this->namedtag->NameTag)){
$this->setNameTag($this->namedtag["NameTag"]);
}
if(isset($this->namedtag->Skin) and $this->namedtag->Skin instanceof CompoundTag){
$this->setSkin($this->namedtag->Skin["Data"], $this->namedtag->Skin["Name"]);
}
$this->uuid = UUID::fromData($this->getId(), $this->getSkinData(), $this->getNameTag());
}
if(isset($this->namedtag->Inventory) and $this->namedtag->Inventory instanceof ListTag){
foreach($this->namedtag->Inventory as $item){
if($item["Slot"] >= 0 and $item["Slot"] < 9){ //Hotbar
$this->inventory->setHotbarSlotIndex($item["Slot"], isset($item["TrueSlot"]) ? $item["TrueSlot"] : -1);
}elseif($item["Slot"] >= 100 and $item["Slot"] < 104){ //Armor
$this->inventory->setItem($this->inventory->getSize() + $item["Slot"] - 100, NBT::getItemHelper($item));
}else{
$this->inventory->setItem($item["Slot"] - 9, NBT::getItemHelper($item));
}
}
}
parent::initEntity();
if(!isset($this->namedtag->foodLevel) or !($this->namedtag->foodLevel instanceof IntTag)){
$this->namedtag->foodLevel = new IntTag("foodLevel", $this->getFood());
}else{
$this->setFood($this->namedtag["foodLevel"]);
}
if(!isset($this->namedtag->foodExhaustionLevel) or !($this->namedtag->foodExhaustionLevel instanceof IntTag)){
$this->namedtag->foodExhaustionLevel = new FloatTag("foodExhaustionLevel", $this->getExhaustion());
}else{
$this->setExhaustion($this->namedtag["foodExhaustionLevel"]);
}
if(!isset($this->namedtag->foodSaturationLevel) or !($this->namedtag->foodSaturationLevel instanceof IntTag)){
$this->namedtag->foodSaturationLevel = new FloatTag("foodSaturationLevel", $this->getSaturation());
}else{
$this->setSaturation($this->namedtag["foodSaturationLevel"]);
}
if(!isset($this->namedtag->foodTickTimer) or !($this->namedtag->foodTickTimer instanceof IntTag)){
$this->namedtag->foodTickTimer = new IntTag("foodTickTimer", $this->foodTickTimer);
}else{
$this->foodTickTimer = $this->namedtag["foodTickTimer"];
}
if(!isset($this->namedtag->XpLevel) or !($this->namedtag->XpLevel instanceof IntTag)){
$this->namedtag->XpLevel = new IntTag("XpLevel", $this->getXpLevel());
}else{
$this->setXpLevel($this->namedtag["XpLevel"]);
}
if(!isset($this->namedtag->XpP) or !($this->namedtag->XpP instanceof FloatTag)){
$this->namedtag->XpP = new FloatTag("XpP", $this->getXpProgress());
}
if(!isset($this->namedtag->XpTotal) or !($this->namedtag->XpTotal instanceof IntTag)){
$this->namedtag->XpTotal = new IntTag("XpTotal", $this->totalXp);
}else{
$this->totalXp = $this->namedtag["XpTotal"];
}
if(!isset($this->namedtag->XpSeed) or !($this->namedtag->XpSeed instanceof IntTag)){
$this->namedtag->XpSeed = new IntTag("XpSeed", $this->xpSeed ?? ($this->xpSeed = mt_rand(PHP_INT_MIN, PHP_INT_MAX)));
}else{
$this->xpSeed = $this->namedtag["XpSeed"];
}
}
protected function addAttributes(){
parent::addAttributes();
$this->attributeMap->addAttribute(Attribute::getAttribute(Attribute::SATURATION));
$this->attributeMap->addAttribute(Attribute::getAttribute(Attribute::EXHAUSTION));
$this->attributeMap->addAttribute(Attribute::getAttribute(Attribute::HUNGER));
$this->attributeMap->addAttribute(Attribute::getAttribute(Attribute::EXPERIENCE_LEVEL));
$this->attributeMap->addAttribute(Attribute::getAttribute(Attribute::EXPERIENCE));
}
public function entityBaseTick($tickDiff = 1){
$hasUpdate = parent::entityBaseTick($tickDiff);
$food = $this->getFood();
$health = $this->getHealth();
if($food >= 18){
$this->foodTickTimer++;
if($this->foodTickTimer >= 80 and $health < $this->getMaxHealth()){
$this->heal(1, new EntityRegainHealthEvent($this, 1, EntityRegainHealthEvent::CAUSE_SATURATION));
$this->exhaust(3.0, PlayerExhaustEvent::CAUSE_HEALTH_REGEN);
$this->foodTickTimer = 0;
}
}elseif($food === 0){
$this->foodTickTimer++;
if($this->foodTickTimer >= 80){
$diff = $this->server->getDifficulty();
$can = false;
if($diff === 1){
$can = $health > 10;
}elseif($diff === 2){
$can = $health > 1;
}elseif($diff === 3){
$can = true;
}
if($can){
$this->attack(1, new EntityDamageEvent($this, EntityDamageEvent::CAUSE_STARVATION, 1));
}
}
}
if($food <= 6){
if($this->isSprinting()){
$this->setSprinting(false);
}
}
return $hasUpdate;
}
public function getName(){
return $this->getNameTag();
}
public function getDrops(){
$drops = [];
if($this->inventory !== null){
foreach($this->inventory->getContents() as $item){
$drops[] = $item;
}
}
return $drops;
}
public function saveNBT(){
parent::saveNBT();
$this->namedtag->Inventory = new ListTag("Inventory", []);
$this->namedtag->Inventory->setTagType(NBT::TAG_Compound);
if($this->inventory !== null){
for($slot = 0; $slot < 9; ++$slot){
$hotbarSlot = $this->inventory->getHotbarSlotIndex($slot);
if($hotbarSlot !== -1){
$item = $this->inventory->getItem($hotbarSlot);
if($item->getId() !== 0 and $item->getCount() > 0){
$tag = NBT::putItemHelper($item, $slot);
$tag->TrueSlot = new ByteTag("TrueSlot", $hotbarSlot);
$this->namedtag->Inventory[$slot] = $tag;
continue;
}
}
$this->namedtag->Inventory[$slot] = new CompoundTag("", [
new ByteTag("Count", 0),
new ShortTag("Damage", 0),
new ByteTag("Slot", $slot),
new ByteTag("TrueSlot", -1),
new ShortTag("id", 0),
]);
}
//Normal inventory
$slotCount = Player::SURVIVAL_SLOTS + 9;
//$slotCount = (($this instanceof Player and ($this->gamemode & 0x01) === 1) ? Player::CREATIVE_SLOTS : Player::SURVIVAL_SLOTS) + 9;
for($slot = 9; $slot < $slotCount; ++$slot){
$item = $this->inventory->getItem($slot - 9);
$this->namedtag->Inventory[$slot] = NBT::putItemHelper($item, $slot);
}
//Armor
for($slot = 100; $slot < 104; ++$slot){
$item = $this->inventory->getItem($this->inventory->getSize() + $slot - 100);
if($item instanceof ItemItem and $item->getId() !== ItemItem::AIR){
$this->namedtag->Inventory[$slot] = NBT::putItemHelper($item, $slot);
}
}
}
if(strlen($this->getSkinData()) > 0){
$this->namedtag->Skin = new CompoundTag("Skin", [
"Data" => new StringTag("Data", $this->getSkinData()),
"Name" => new StringTag("Name", $this->getSkinName())
]);
}
}
public function spawnTo(Player $player){
if($player !== $this and !isset($this->hasSpawned[$player->getLoaderId()])){
$this->hasSpawned[$player->getLoaderId()] = $player;
if(strlen($this->skin) < 64 * 32 * 4){
throw new \InvalidStateException((new \ReflectionClass($this))->getShortName() . " must have a valid skin set");
}
if(!($this instanceof Player)){
$this->server->updatePlayerListData($this->getUniqueId(), $this->getId(), $this->getName(), $this->skinName, $this->skin, [$player]);
}
$pk = new AddPlayerPacket();
$pk->uuid = $this->getUniqueId();
$pk->username = $this->getName();
$pk->eid = $this->getId();
$pk->x = $this->x;
$pk->y = $this->y;
$pk->z = $this->z;
$pk->speedX = $this->motionX;
$pk->speedY = $this->motionY;
$pk->speedZ = $this->motionZ;
$pk->yaw = $this->yaw;
$pk->pitch = $this->pitch;
$pk->item = $this->getInventory()->getItemInHand();
$pk->metadata = $this->dataProperties;
$player->dataPacket($pk);
$this->inventory->sendArmorContents($player);
if(!($this instanceof Player)){
$this->server->removePlayerListData($this->getUniqueId(), [$player]);
}
}
}
public function despawnFrom(Player $player){
if(isset($this->hasSpawned[$player->getLoaderId()])){
$pk = new RemovePlayerPacket();
$pk->eid = $this->getId();
$pk->clientId = $this->getUniqueId();
$player->dataPacket($pk);
unset($this->hasSpawned[$player->getLoaderId()]);
}
}
public function close(){
if(!$this->closed){
if(!($this instanceof Player) or $this->loggedIn){
foreach($this->inventory->getViewers() as $viewer){
$viewer->removeWindow($this->inventory);
}
}
parent::close();
}
}
}
|
lgpl-3.0
|
pcolby/libqtaws
|
src/ec2/copyfpgaimageresponse.cpp
|
4221
|
/*
Copyright 2013-2021 Paul Colby
This file is part of QtAws.
QtAws is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
QtAws is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with the QtAws. If not, see <http://www.gnu.org/licenses/>.
*/
#include "copyfpgaimageresponse.h"
#include "copyfpgaimageresponse_p.h"
#include <QDebug>
#include <QNetworkReply>
#include <QXmlStreamReader>
namespace QtAws {
namespace EC2 {
/*!
* \class QtAws::EC2::CopyFpgaImageResponse
* \brief The CopyFpgaImageResponse class provides an interace for EC2 CopyFpgaImage responses.
*
* \inmodule QtAwsEC2
*
* <fullname>Amazon Elastic Compute Cloud</fullname>
*
* Amazon Elastic Compute Cloud (Amazon EC2) provides secure and resizable computing capacity in the AWS Cloud. Using
* Amazon EC2 eliminates the need to invest in hardware up front, so you can develop and deploy applications faster. Amazon
* Virtual Private Cloud (Amazon VPC) enables you to provision a logically isolated section of the AWS Cloud where you can
* launch AWS resources in a virtual network that you've defined. Amazon Elastic Block Store (Amazon EBS) provides block
* level storage volumes for use with EC2 instances. EBS volumes are highly available and reliable storage volumes that can
* be attached to any running instance and used like a hard
*
* drive>
*
* To learn more, see the following
*
* resources> <ul> <li>
*
* Amazon EC2: <a href="http://aws.amazon.com/ec2">AmazonEC2 product page</a>, <a
* href="http://aws.amazon.com/documentation/ec2">Amazon EC2 documentation</a>
*
* </p </li> <li>
*
* Amazon EBS: <a href="http://aws.amazon.com/ebs">Amazon EBS product page</a>, <a
* href="http://aws.amazon.com/documentation/ebs">Amazon EBS documentation</a>
*
* </p </li> <li>
*
* Amazon VPC: <a href="http://aws.amazon.com/vpc">Amazon VPC product page</a>, <a
* href="http://aws.amazon.com/documentation/vpc">Amazon VPC documentation</a>
*
* </p </li> <li>
*
* AWS VPN: <a href="http://aws.amazon.com/vpn">AWS VPN product page</a>, <a
* href="http://aws.amazon.com/documentation/vpn">AWS VPN documentation</a>
*
* \sa Ec2Client::copyFpgaImage
*/
/*!
* Constructs a CopyFpgaImageResponse object for \a reply to \a request, with parent \a parent.
*/
CopyFpgaImageResponse::CopyFpgaImageResponse(
const CopyFpgaImageRequest &request,
QNetworkReply * const reply,
QObject * const parent)
: Ec2Response(new CopyFpgaImageResponsePrivate(this), parent)
{
setRequest(new CopyFpgaImageRequest(request));
setReply(reply);
}
/*!
* \reimp
*/
const CopyFpgaImageRequest * CopyFpgaImageResponse::request() const
{
Q_D(const CopyFpgaImageResponse);
return static_cast<const CopyFpgaImageRequest *>(d->request);
}
/*!
* \reimp
* Parses a successful EC2 CopyFpgaImage \a response.
*/
void CopyFpgaImageResponse::parseSuccess(QIODevice &response)
{
//Q_D(CopyFpgaImageResponse);
QXmlStreamReader xml(&response);
/// @todo
}
/*!
* \class QtAws::EC2::CopyFpgaImageResponsePrivate
* \brief The CopyFpgaImageResponsePrivate class provides private implementation for CopyFpgaImageResponse.
* \internal
*
* \inmodule QtAwsEC2
*/
/*!
* Constructs a CopyFpgaImageResponsePrivate object with public implementation \a q.
*/
CopyFpgaImageResponsePrivate::CopyFpgaImageResponsePrivate(
CopyFpgaImageResponse * const q) : Ec2ResponsePrivate(q)
{
}
/*!
* Parses a EC2 CopyFpgaImage response element from \a xml.
*/
void CopyFpgaImageResponsePrivate::parseCopyFpgaImageResponse(QXmlStreamReader &xml)
{
Q_ASSERT(xml.name() == QLatin1String("CopyFpgaImageResponse"));
Q_UNUSED(xml) ///< @todo
}
} // namespace EC2
} // namespace QtAws
|
lgpl-3.0
|
advanced-online-marketing/AOM
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201802/SetTopBoxLineItemError.php
|
1066
|
<?php
namespace Google\AdsApi\Dfp\v201802;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class SetTopBoxLineItemError extends \Google\AdsApi\Dfp\v201802\ApiError
{
/**
* @var string $reason
*/
protected $reason = null;
/**
* @param string $fieldPath
* @param \Google\AdsApi\Dfp\v201802\FieldPathElement[] $fieldPathElements
* @param string $trigger
* @param string $errorString
* @param string $reason
*/
public function __construct($fieldPath = null, array $fieldPathElements = null, $trigger = null, $errorString = null, $reason = null)
{
parent::__construct($fieldPath, $fieldPathElements, $trigger, $errorString);
$this->reason = $reason;
}
/**
* @return string
*/
public function getReason()
{
return $this->reason;
}
/**
* @param string $reason
* @return \Google\AdsApi\Dfp\v201802\SetTopBoxLineItemError
*/
public function setReason($reason)
{
$this->reason = $reason;
return $this;
}
}
|
lgpl-3.0
|
dperezcabrera/jpoker
|
src/main/java/org/poker/api/game/PlayerInfo.java
|
2663
|
/*
* Copyright (C) 2016 David Pérez Cabrera <dperezcabrera@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.poker.api.game;
import net.jcip.annotations.NotThreadSafe;
import org.poker.api.core.Card;
import org.poker.api.game.TexasHoldEmUtil.PlayerState;
/**
*
* @author David Pérez Cabrera <dperezcabrera@gmail.com>
* @since 1.0.0
*/
@NotThreadSafe
public class PlayerInfo {
private String name;
private long chips;
private long bet;
private final Card[] cards = new Card[TexasHoldEmUtil.PLAYER_CARDS];
private PlayerState state;
private int errors;
public boolean isActive() {
return state.isActive();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getChips() {
return chips;
}
public void setChips(long chips) {
this.chips = chips;
}
public void addChips(long chips) {
this.chips += chips;
}
public long getBet() {
return bet;
}
public void setBet(long bet) {
this.bet = bet;
}
public Card[] getCards() {
return new Card[]{cards[0], cards[1]};
}
public void setCards(Card[] cards) {
this.cards[0] = cards[0];
this.cards[1] = cards[1];
}
public PlayerState getState() {
return state;
}
public void setState(PlayerState state) {
this.state = state;
}
public int getErrors() {
return errors;
}
public void setErrors(int errors) {
this.errors = errors;
}
public Card getCard(int index) {
return cards[index];
}
public void setCards(Card card0, Card card1) {
this.cards[0] = card0;
this.cards[1] = card1;
}
@Override
public String toString() {
return "{class:'PlayerInfo', name:'" + name + "', chips:" + chips + ", bet:" + bet + ", cards:[" + cards[0] + ", " + cards[1] + "], state:'" + state + "', errors:" + errors + '}';
}
}
|
lgpl-3.0
|
kyungtaekLIM/PSI-BLASTexB
|
src/ncbi-blast-2.5.0+/c++/include/algo/winmask/seq_masker_istat_oascii.hpp
|
4868
|
/* $Id: seq_masker_istat_oascii.hpp 462550 2015-03-19 14:07:19Z morgulis $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: Aleksandr Morgulis
*
* File Description:
* Definition for CSeqMaskerIstatOAscii class.
*
*/
#ifndef C_SEQ_MASKER_ISTAT_OASCII_H
#define C_SEQ_MASKER_ISTAT_OASCII_H
#include <corelib/ncbitype.h>
#include <corelib/ncbistr.hpp>
#include <corelib/ncbiobj.hpp>
#include <algo/winmask/seq_masker_istat.hpp>
#include <algo/winmask/seq_masker_uset_hash.hpp>
BEGIN_NCBI_SCOPE
/**
**\brief Unit counts read from an ascii file in optimized form.
**/
class NCBI_XALGOWINMASK_EXPORT CSeqMaskerIstatOAscii
: public CSeqMaskerIstat
{
public:
/**
**\brief Exceptions that CSeqMaskerIstatOAscii might throw.
**/
class Exception : public CException
{
public:
enum EErrCode
{
eStreamOpenFail, /**< File open failure. */
eBadHashParam, /**< Bad hash parameter. */
eBadParam, /**< Bad parameter. */
eFormat, /**< File does not follow the format spec. */
eAlloc /**< Allocation failure. */
};
/**
**\brief Get a description string for this exception.
**\return C-style description string
**/
virtual const char * GetErrCodeString() const;
NCBI_EXCEPTION_DEFAULT( Exception, CException );
};
/**
**\brief Object constructor.
**
** arg_threshold, arg_textend, arg_max_count, and arg_min_count, if
** non zero, override the values in the input file.
**
**\param name file name
**\param arg_threshold T_threshold
**\param arg_textend T_extend
**\param arg_max_count T_high
**\param arg_use_max_count value to use for units with count > T_high
**\param arg_min_count T_low
**\param arg_use_min_count value to use for units with count < T_low
**\param start_line number of initial lines to skip
**/
explicit CSeqMaskerIstatOAscii( const string & name,
Uint4 arg_threshold,
Uint4 arg_textend,
Uint4 arg_max_count,
Uint4 arg_use_max_count,
Uint4 arg_min_count,
Uint4 arg_use_min_count,
Uint4 start_line = 0 );
/**
**\brief Object destructor.
**/
virtual ~CSeqMaskerIstatOAscii() {}
/**
**\brief Get the value of the unit size
**\return unit size
**/
virtual Uint1 UnitSize() const { return uset.UnitSize(); }
protected:
/**
**\brief Get the count of the given unit.
**\param unit the unit to look up
**\return the count value for the unit
**/
virtual Uint4 at( Uint4 unit ) const;
/**
\brief Get the true count for an n-mer.
\param unit the n-mer value
\return n-mer count not corrected for t_low
and t_high values
**/
virtual Uint4 trueat( Uint4 unit ) const;
private:
/**\internal
**\brief The unit counts container.
**/
CSeqMaskerUsetHash uset;
};
END_NCBI_SCOPE
#endif
|
lgpl-3.0
|
jnuzh/nidama
|
taobao_sdk/top/request/UmpActivityGetRequest.php
|
783
|
<?php
/**
* TOP API: taobao.ump.activity.get request
*
* @author auto create
* @since 1.0, 2014-02-20 17:02:53
*/
class UmpActivityGetRequest
{
/**
* 活动id
**/
private $actId;
private $apiParas = array();
public function setActId($actId)
{
$this->actId = $actId;
$this->apiParas["act_id"] = $actId;
}
public function getActId()
{
return $this->actId;
}
public function getApiMethodName()
{
return "taobao.ump.activity.get";
}
public function getApiParas()
{
return $this->apiParas;
}
public function check()
{
RequestCheckUtil::checkNotNull($this->actId,"actId");
}
public function putOtherTextParam($key, $value) {
$this->apiParas[$key] = $value;
$this->$key = $value;
}
}
|
lgpl-3.0
|
bmhm/jjsonui
|
src/main/java/de/bmarwell/jjsonui/err/NoMenuSourceProvidedException.java
|
1073
|
/**
This file is part of jjsonui.
jjsonui is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
jjsonui is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with jjsonui. If not, see <http://www.gnu.org/licenses/>.
*/
package de.bmarwell.jjsonui.err;
/**
* @author bmarwell
*
*/
public class NoMenuSourceProvidedException extends Exception {
/**
* An Exception if neither URL or file has been provided.
* @param message the message to be displayed.
*/
public NoMenuSourceProvidedException(final String message) {
super(message);
}
/**
*
*/
private static final long serialVersionUID = 3800221957015905265L;
}
|
lgpl-3.0
|
advanced-online-marketing/AOM
|
vendor/googleads/googleads-php-lib/src/Google/AdsApi/Dfp/v201802/Browser.php
|
1419
|
<?php
namespace Google\AdsApi\Dfp\v201802;
/**
* This file was generated from WSDL. DO NOT EDIT.
*/
class Browser extends \Google\AdsApi\Dfp\v201802\Technology
{
/**
* @var string $majorVersion
*/
protected $majorVersion = null;
/**
* @var string $minorVersion
*/
protected $minorVersion = null;
/**
* @param int $id
* @param string $name
* @param string $majorVersion
* @param string $minorVersion
*/
public function __construct($id = null, $name = null, $majorVersion = null, $minorVersion = null)
{
parent::__construct($id, $name);
$this->majorVersion = $majorVersion;
$this->minorVersion = $minorVersion;
}
/**
* @return string
*/
public function getMajorVersion()
{
return $this->majorVersion;
}
/**
* @param string $majorVersion
* @return \Google\AdsApi\Dfp\v201802\Browser
*/
public function setMajorVersion($majorVersion)
{
$this->majorVersion = $majorVersion;
return $this;
}
/**
* @return string
*/
public function getMinorVersion()
{
return $this->minorVersion;
}
/**
* @param string $minorVersion
* @return \Google\AdsApi\Dfp\v201802\Browser
*/
public function setMinorVersion($minorVersion)
{
$this->minorVersion = $minorVersion;
return $this;
}
}
|
lgpl-3.0
|
MarkNenadov/varia
|
Ruby/ruby-museday/app/models/poem.rb
|
104
|
class Poem < ActiveRecord::Base
validates :title, :presence => true, :length => { :minimum => 2 }
end
|
lgpl-3.0
|
kingjiang/SharpDevelopLite
|
src/AddIns/Misc/SourceAnalysis/Src/CheckCurrentProjectCommand.cs
|
762
|
// <file>
// <copyright see="prj:///doc/copyright.txt"/>
// <license see="prj:///doc/license.txt"/>
// <owner name="Matt Everson" email="ti.just.me@gmail.com"/>
// <version>$Revision$</version>
// </file>
using System;
using ICSharpCode.Core;
using ICSharpCode.SharpDevelop.Project;
using ICSharpCode.SharpDevelop.Project.Commands;
namespace MattEverson.SourceAnalysis
{
public class CheckCurrentProjectCommand : BuildProject
{
public override void StartBuild()
{
BuildOptions options = new BuildOptions(BuildTarget.Rebuild, CallbackMethod);
options.TargetForDependencies = BuildTarget.Build;
options.ProjectAdditionalProperties["RunSourceAnalysis"] = "true";
BuildEngine.BuildInGui(this.ProjectToBuild, options);
}
}
}
|
lgpl-3.0
|
tweninger/nina
|
test/edu/nd/nina/traverse/DepthFirstIteratorTest.java
|
4541
|
/* ==========================================
* JGraphT : a free Java graph-theory library
* ==========================================
*
* Project Info: http://jgrapht.sourceforge.net/
* Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh)
*
* (C) Copyright 2003-2008, by Barak Naveh and Contributors.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation,
* Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/* ---------------------------
* DepthFirstIteratorTest.java
* ---------------------------
* (C) Copyright 2003-2008, by Liviu Rau and Contributors.
*
* Original Author: Liviu Rau
* Contributor(s): Barak Naveh
*
* $Id: DepthFirstIteratorTest.java 645 2008-09-30 19:44:48Z perfecthash $
*
* Changes
* -------
* 30-Jul-2003 : Initial revision (LR);
* 06-Aug-2003 : Test traversal listener & extract a shared superclass (BN);
*
*/
package edu.nd.nina.traverse;
import java.util.*;
import edu.nd.nina.*;
import edu.nd.nina.graph.*;
import edu.nd.nina.traverse.AbstractGraphIterator;
import edu.nd.nina.traverse.DepthFirstIterator;
/**
* Tests for the {@link DepthFirstIteratorTest} class.
*
* <p>NOTE: This test uses hard-coded expected ordering isn't really guaranteed
* by the specification of the algorithm. This could cause false failures if the
* traversal implementation changes.</p>
*
* @author Liviu Rau
* @since Jul 30, 2003
*/
public class DepthFirstIteratorTest
extends AbstractGraphIteratorTest
{
//~ Methods ----------------------------------------------------------------
String getExpectedStr1()
{
return "1,3,6,5,7,9,4,8,2";
}
String getExpectedStr2()
{
return "1,3,6,5,7,9,4,8,2,orphan";
}
String getExpectedFinishString()
{
return "6:4:9:2:8:7:5:3:1:orphan:";
}
AbstractGraphIterator<String, DefaultEdge> createIterator(
DirectedGraph<String, DefaultEdge> g,
String vertex)
{
AbstractGraphIterator<String, DefaultEdge> i =
new DepthFirstIterator<String, DefaultEdge>(g, vertex);
i.setCrossComponentTraversal(true);
return i;
}
/**
* See <a href="http://sf.net/projects/jgrapht">Sourceforge bug 1169182</a>
* for details.
*/
public void testBug1169182()
{
DirectedGraph<String, DefaultEdge> dg =
new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
String a = "A";
String b = "B";
String c = "C";
String d = "D";
String e = "E";
String f = "F";
String g = "G";
String h = "H";
String i = "I";
String j = "J";
String k = "K";
String l = "L";
dg.addVertex(a);
dg.addVertex(b);
dg.addVertex(c);
dg.addVertex(d);
dg.addVertex(e);
dg.addVertex(f);
dg.addVertex(g);
dg.addVertex(h);
dg.addVertex(i);
dg.addVertex(j);
dg.addVertex(k);
dg.addVertex(l);
dg.addEdge(a, b);
dg.addEdge(b, c);
dg.addEdge(c, j);
dg.addEdge(c, d);
dg.addEdge(c, e);
dg.addEdge(c, f);
dg.addEdge(c, g);
dg.addEdge(d, h);
dg.addEdge(e, h);
dg.addEdge(f, i);
dg.addEdge(g, i);
dg.addEdge(h, j);
dg.addEdge(i, c);
dg.addEdge(j, k);
dg.addEdge(k, l);
Iterator<String> dfs = new DepthFirstIterator<String, DefaultEdge>(dg);
String actual = "";
while (dfs.hasNext()) {
String v = dfs.next();
actual += v;
}
String expected = "ABCGIFEHJKLD";
assertEquals(expected, actual);
}
}
// End DepthFirstIteratorTest.java
|
lgpl-3.0
|
sefaakca/EvoSuite-Sefa
|
master/evosuite-tests/Bessj_ESTest_scaffolding.java
|
3564
|
/**
* Scaffolding file used to store all the setups needed to run
* tests automatically generated by EvoSuite
* Wed Aug 23 21:26:53 GMT 2017
*/
import org.evosuite.runtime.annotation.EvoSuiteClassExclude;
import org.junit.BeforeClass;
import org.junit.Before;
import org.junit.After;
import org.junit.AfterClass;
import org.evosuite.runtime.sandbox.Sandbox;
import org.evosuite.runtime.sandbox.Sandbox.SandboxMode;
@EvoSuiteClassExclude
public class Bessj_ESTest_scaffolding {
@org.junit.Rule
public org.evosuite.runtime.vnet.NonFunctionalRequirementRule nfr = new org.evosuite.runtime.vnet.NonFunctionalRequirementRule();
private static final java.util.Properties defaultProperties = (java.util.Properties) java.lang.System.getProperties().clone();
private org.evosuite.runtime.thread.ThreadStopper threadStopper = new org.evosuite.runtime.thread.ThreadStopper (org.evosuite.runtime.thread.KillSwitchHandler.getInstance(), 3000);
@BeforeClass
public static void initEvoSuiteFramework() {
org.evosuite.runtime.RuntimeSettings.className = "Bessj";
org.evosuite.runtime.GuiSupport.initialize();
org.evosuite.runtime.RuntimeSettings.maxNumberOfThreads = 100;
org.evosuite.runtime.RuntimeSettings.maxNumberOfIterationsPerLoop = 10000;
org.evosuite.runtime.RuntimeSettings.mockSystemIn = true;
org.evosuite.runtime.RuntimeSettings.sandboxMode = org.evosuite.runtime.sandbox.Sandbox.SandboxMode.RECOMMENDED;
org.evosuite.runtime.sandbox.Sandbox.initializeSecurityManagerForSUT();
org.evosuite.runtime.classhandling.JDKClassResetter.init();
setSystemProperties();
initializeClasses();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
}
@AfterClass
public static void clearEvoSuiteFramework(){
Sandbox.resetDefaultSecurityManager();
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
}
@Before
public void initTestCase(){
threadStopper.storeCurrentThreads();
threadStopper.startRecordingTime();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().initHandler();
org.evosuite.runtime.sandbox.Sandbox.goingToExecuteSUTCode();
setSystemProperties();
org.evosuite.runtime.GuiSupport.setHeadless();
org.evosuite.runtime.Runtime.getInstance().resetRuntime();
org.evosuite.runtime.agent.InstrumentingAgent.activate();
}
@After
public void doneWithTestCase(){
threadStopper.killAndJoinClientThreads();
org.evosuite.runtime.jvm.ShutdownHookHandler.getInstance().safeExecuteAddedHooks();
org.evosuite.runtime.classhandling.JDKClassResetter.reset();
resetClasses();
org.evosuite.runtime.sandbox.Sandbox.doneWithExecutingSUTCode();
org.evosuite.runtime.agent.InstrumentingAgent.deactivate();
org.evosuite.runtime.GuiSupport.restoreHeadlessMode();
}
public static void setSystemProperties() {
java.lang.System.setProperties((java.util.Properties) defaultProperties.clone());
java.lang.System.setProperty("file.encoding", "UTF-8");
java.lang.System.setProperty("java.awt.headless", "true");
java.lang.System.setProperty("user.country", "US");
java.lang.System.setProperty("user.language", "en");
java.lang.System.setProperty("user.timezone", "Europe/London");
}
private static void initializeClasses() {
org.evosuite.runtime.classhandling.ClassStateSupport.initializeClasses(Bessj_ESTest_scaffolding.class.getClassLoader() ,
"Bessj"
);
}
private static void resetClasses() {
}
}
|
lgpl-3.0
|
mueslo/TEA
|
databaseviewer.cpp
|
1587
|
#include "databaseviewer.h"
#include "ui_databaseviewer.h"
#include "qsqltablemodel.h"
#include "qmessagebox.h"
DatabaseViewer::DatabaseViewer(QWidget *parent) :
QDialog(parent),
ui(new Ui::DatabaseViewer)
{
ui->setupUi(this);
ui->cboxDatabase->addItem("Archived routes (rdb)");
ui->cboxDatabase->addItem("Loaded routes (adb)");
ui->cboxDatabase->addItem("Archived maps (mdb)");
connect(ui->btnQuery, SIGNAL(clicked()), this, SLOT(executeQuery()));
}
void DatabaseViewer::executeQuery()
{
QString db, table;
if (ui->cboxDatabase->currentIndex()==0) db = "rdb";
else { if (ui->cboxDatabase->currentIndex()==1) db = "adb";
else db = "mdb";
}
table = ui->edtQuery->text();
{
QSqlTableModel *model = new QSqlTableModel(this,QSqlDatabase::database(db)); //deletes the table after closing the dialog -> prevents the following error: QSqlDatabasePrivate::removeDatabase: connection 'rdb' is still in use, all queries will cease to work.
// model = new QSqlTableModel::QSqlTableModel(0,QSqlDatabase::database(db));
//model->setEditStrategy(QSqlTableModel::OnManualSubmit);
model->setEditStrategy(QSqlTableModel::OnFieldChange);
model->setTable(table);
ui->tblvResult->setModel(model);
model->select();
}
}
DatabaseViewer::~DatabaseViewer()
{
delete ui;
}
void DatabaseViewer::changeEvent(QEvent *e)
{
QDialog::changeEvent(e);
switch (e->type()) {
case QEvent::LanguageChange:
ui->retranslateUi(this);
break;
default:
break;
}
}
|
lgpl-3.0
|
Sinhika/akkamaddiAdditions2
|
src/main/java/akkamaddi/plugins/goldenglitter/GoldenGlitter.java
|
2051
|
package akkamaddi.plugins.goldenglitter;
import akkamaddi.plugins.additionslib.SubModHandler;
import alexndr.api.registry.Plugin;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
@Mod(modid = ModInfo.ID, name = ModInfo.NAME, version = ModInfo.VERSION,
acceptedMinecraftVersions=ModInfo.ACCEPTED_VERSIONS,
dependencies = ModInfo.DEPENDENCIES, updateJSON=ModInfo.VERSIONURL)
public class GoldenGlitter
{
@Mod.Instance(value = ModInfo.ID)
public static GoldenGlitter INSTANCE;
@SidedProxy(clientSide = "akkamaddi.plugins.goldenglitter.ProxyClient",
serverSide = "akkamaddi.plugins.goldenglitter.ProxyCommon")
public static ProxyCommon proxy;
public static Plugin plugin = new Plugin(ModInfo.ID, ModInfo.NAME);
/**
* Called during the PreInit phase.
* @param event FMLPreInitializationEvent
*/
@Mod.EventHandler
public void PreInit(FMLPreInitializationEvent event)
{
if (!SubModHandler.moduleEnabled(SubModHandler.MODULE_GOLDENGLITTER))
return;
proxy.PreInit(event);
} // end PreInit()
/**
* Called during the Init phase.
* @param event FMLInitializationEvent
*/
@Mod.EventHandler
public void Init(FMLInitializationEvent event)
{
if (!SubModHandler.moduleEnabled(SubModHandler.MODULE_GOLDENGLITTER))
return;
proxy.Init(event);
} // end Init()
/**
* Called during the PostInit phase.
* @param event FMLPostIntializationEvent
*/
@Mod.EventHandler
public void PostInit(FMLPostInitializationEvent event)
{
if (!SubModHandler.moduleEnabled(SubModHandler.MODULE_GOLDENGLITTER))
return;
proxy.PostInit(event);
}
} // end class
|
lgpl-3.0
|
Bang3DEngine/Bang
|
src/Engine/Factory/GameObjectFactory.cpp
|
24858
|
#include "Bang/GameObjectFactory.h"
#include "Bang/Array.tcc"
#include "Bang/Assert.h"
#include "Bang/AssetHandle.h"
#include "Bang/AudioListener.h"
#include "BangMath/Axis.h"
#include "Bang/BoxCollider.h"
#include "Bang/Camera.h"
#include "Bang/CapsuleCollider.h"
#include "Bang/GL.h"
#include "Bang/GameObject.h"
#include "Bang/GameObject.tcc"
#include "Bang/LineRenderer.h"
#include "Bang/Material.h"
#include "Bang/MaterialFactory.h"
#include "Bang/Mesh.h"
#include "Bang/MeshFactory.h"
#include "Bang/MeshRenderer.h"
#include "Bang/Physics.h"
#include "Bang/RectTransform.h"
#include "Bang/Scene.h"
#include "Bang/SphereCollider.h"
#include "Bang/TextureFactory.h"
#include "Bang/Transform.h"
#include "Bang/UIButton.h"
#include "Bang/UICanvas.h"
#include "Bang/UICheckBox.h"
#include "Bang/UIComboBox.h"
#include "Bang/UIDirLayout.h"
#include "Bang/UIDirLayoutMovableSeparator.h"
#include "Bang/UIImageRenderer.h"
#include "Bang/UIInputNumber.h"
#include "Bang/UIInputText.h"
#include "Bang/UILabel.h"
#include "Bang/UILayoutElement.h"
#include "Bang/UIList.h"
#include "Bang/UIRendererCacher.h"
#include "Bang/UIScrollArea.h"
#include "Bang/UIScrollBar.h"
#include "Bang/UIScrollPanel.h"
#include "Bang/UISlider.h"
#include "Bang/UITextRenderer.h"
#include "Bang/UITheme.h"
#include "Bang/UIToolButton.h"
#include "Bang/UITree.h"
using namespace Bang;
GameObject *GameObjectFactory::CreateGameObject(bool addTransform)
{
GameObject *go = new GameObject();
if (addTransform && !go->HasComponent<Transform>())
{
go->AddComponent<Transform>();
}
return go;
}
GameObject *GameObjectFactory::CreateUIGameObject(bool addComponents)
{
GameObject *go = new GameObject();
GameObjectFactory::CreateUIGameObjectInto(go, addComponents);
return go;
}
GameObject *GameObjectFactory::CreateGameObjectNamed(const String &name)
{
GameObject *go = GameObjectFactory::CreateGameObject(true);
go->SetName(name);
return go;
}
GameObject *GameObjectFactory::CreateUIGameObjectNamed(const String &name)
{
GameObject *go = GameObjectFactory::CreateUIGameObject(true);
go->SetName(name);
return go;
}
void GameObjectFactory::CreateUIGameObjectInto(GameObject *go, bool addComps)
{
if (addComps)
{
if (!go->HasComponent<RectTransform>())
{
go->AddComponent<RectTransform>();
}
}
}
Scene *GameObjectFactory::CreateScene(bool addTransform)
{
Scene *scene = new Scene();
if (addTransform && !scene->GetTransform())
{
scene->AddComponent<Transform>();
}
return scene;
}
Scene *GameObjectFactory::CreateUIScene()
{
Scene *scene = new Scene();
CreateUISceneInto(scene);
return scene;
}
void GameObjectFactory::CreateUISceneInto(Scene *scene)
{
Camera *cam = GameObjectFactory::CreateUICameraInto(scene);
scene->SetCamera(cam);
GameObjectFactory::CreateUIGameObjectInto(scene);
GameObjectFactory::CreateUICanvasInto(scene);
Physics::GetInstance()->UnRegisterScene(scene);
}
Scene *GameObjectFactory::CreateDefaultSceneInto(Scene *scene)
{
ASSERT(scene->GetTransform());
GameObject *cube = GameObjectFactory::CreateCubeGameObject();
cube->SetParent(scene);
GameObject *cameraGo = GameObjectFactory::CreateGameObjectNamed("Camera");
Camera *cam = GameObjectFactory::CreateDefaultCameraInto(cameraGo);
cameraGo->GetTransform()->SetPosition(Vector3(5, 4, 3));
cameraGo->GetTransform()->LookAt(Vector3::Zero());
cameraGo->SetParent(scene);
scene->SetCamera(cam);
return scene;
}
Camera *GameObjectFactory::CreateDefaultCameraInto(GameObject *go)
{
Camera *cam = go->AddComponent<Camera>();
go->AddComponent<AudioListener>();
cam->SetHDR(true);
return CreateDefaultCameraInto(cam);
}
Camera *GameObjectFactory::CreateDefaultCameraInto(Camera *cam)
{
cam->SetClearMode(CameraClearMode::SKY_BOX);
cam->SetClearColor(Color(0.5f, 0.8f, 1.0f));
cam->SetSkyBoxTexture(TextureFactory::GetDefaultSkybox());
return cam;
}
UICanvas *GameObjectFactory::CreateUICanvas()
{
GameObject *go = GameObjectFactory::CreateUIGameObject();
return GameObjectFactory::CreateUICanvasInto(go);
}
UICanvas *GameObjectFactory::CreateUICanvasInto(GameObject *go)
{
UICanvas *canvas = go->AddComponent<UICanvas>();
go->SetName("Canvas");
return canvas;
}
UIImageRenderer *GameObjectFactory::CreateUIImage(const Color &color)
{
GameObject *go = GameObjectFactory::CreateUIGameObject();
UIImageRenderer *img = go->AddComponent<UIImageRenderer>();
img->SetTint(color);
go->SetName("Image");
return img;
}
UIImageRenderer *GameObjectFactory::CreateUIImage(const Color &color,
const Vector2i &size)
{
UIImageRenderer *img = GameObjectFactory::CreateUIImage(color);
UILayoutElement *le = img->GetGameObject()->AddComponent<UILayoutElement>();
le->SetMinSize(size);
le->SetPreferredSize(size);
return img;
}
UIList *GameObjectFactory::CreateUIListInto(GameObject *go,
bool withScrollPanel)
{
return UIList::CreateInto(go, withScrollPanel);
}
UIList *GameObjectFactory::CreateUIList(bool withScrollPanel)
{
return UIList::CreateInto(
GameObjectFactory::CreateUIGameObjectNamed("List"), withScrollPanel);
}
UITree *GameObjectFactory::CreateUITreeInto(GameObject *go)
{
return UITree::CreateInto(go);
}
UITree *GameObjectFactory::CreateUITree()
{
return UITree::CreateInto(
GameObjectFactory::CreateUIGameObjectNamed("Tree"));
}
UIInputText *GameObjectFactory::CreateUIInputTextInto(GameObject *go)
{
return UIInputText::CreateInto(go);
}
UIInputText *GameObjectFactory::CreateUIInputText()
{
return GameObjectFactory::CreateUIInputTextInto(
GameObjectFactory::CreateUIGameObjectNamed("InputText"));
}
UICheckBox *GameObjectFactory::CreateUICheckBoxInto(GameObject *go)
{
return UICheckBox::CreateInto(go);
}
UICheckBox *GameObjectFactory::CreateUICheckBox()
{
return GameObjectFactory::CreateUICheckBoxInto(
GameObjectFactory::CreateUIGameObjectNamed("CheckBox"));
}
UIComboBox *GameObjectFactory::CreateUIComboBoxInto(GameObject *go)
{
return UIComboBox::CreateInto(go);
}
UIComboBox *GameObjectFactory::CreateUIComboBox()
{
return GameObjectFactory::CreateUIComboBoxInto(
GameObjectFactory::CreateUIGameObjectNamed("ComboBox"));
}
UIComboBox *GameObjectFactory::CreateUIBoolComboBoxInto(GameObject *go)
{
UIComboBox *cb = GameObjectFactory::CreateUIComboBoxInto(go);
cb->SetMultiCheck(true);
return cb;
}
UIComboBox *GameObjectFactory::CreateUIBoolComboBox()
{
return GameObjectFactory::CreateUIBoolComboBoxInto(
GameObjectFactory::CreateUIGameObjectNamed("BoolComboBox"));
}
UISlider *GameObjectFactory::CreateUISliderInto(GameObject *go,
float minValue,
float maxValue,
float step)
{
UISlider *slider = UISlider::CreateInto(go);
slider->SetMinMaxValues(minValue, maxValue);
slider->GetInputNumber()->SetStep(step);
return slider;
}
UISlider *GameObjectFactory::CreateUISlider(float minValue,
float maxValue,
float step)
{
return GameObjectFactory::CreateUISliderInto(
GameObjectFactory::CreateUIGameObjectNamed("Slider"),
minValue,
maxValue,
step);
}
UIInputNumber *GameObjectFactory::CreateUIInputNumberInto(GameObject *go)
{
return UIInputNumber::CreateInto(go);
}
UIInputNumber *GameObjectFactory::CreateUIInputNumber()
{
return GameObjectFactory::CreateUIInputNumberInto(
GameObjectFactory::CreateUIGameObjectNamed("InputNumber"));
}
UIRendererCacher *GameObjectFactory::CreateUIRendererCacherInto(GameObject *go)
{
return UIRendererCacher::CreateInto(go);
}
UIRendererCacher *GameObjectFactory::CreateUIRendererCacher()
{
return GameObjectFactory::CreateUIRendererCacherInto(
GameObjectFactory::CreateUIGameObjectNamed("UIRendererCacher"));
}
UIButton *GameObjectFactory::CreateUIButtonInto(GameObject *go)
{
return UIButton::CreateInto(go);
}
UIButton *GameObjectFactory::CreateUIButton()
{
return UIButton::CreateInto(
GameObjectFactory::CreateUIGameObjectNamed("Button"));
}
UIButton *GameObjectFactory::CreateUIButton(const String &text, Texture2D *icon)
{
const Vector2i size(15);
UIButton *btn = GameObjectFactory::CreateUIButton();
if (!text.IsEmpty())
{
btn->GetText()->SetContent(text);
}
if (icon)
{
btn->SetIcon(icon, size, (text.IsEmpty() ? 0 : 5));
}
constexpr int BigPadding = 10;
constexpr int MediumPadding = 6;
constexpr int SmallPadding = 3;
if (!text.IsEmpty() && !icon)
{
btn->GetDirLayout()->SetPaddingBot(MediumPadding);
btn->GetDirLayout()->SetPaddingTop(MediumPadding);
btn->GetDirLayout()->SetPaddingRight(BigPadding);
btn->GetDirLayout()->SetPaddingLeft(BigPadding);
}
else if (!text.IsEmpty() && icon)
{
btn->GetDirLayout()->SetPaddingBot(MediumPadding);
btn->GetDirLayout()->SetPaddingTop(MediumPadding);
btn->GetDirLayout()->SetPaddingLeft(BigPadding);
btn->GetDirLayout()->SetPaddingRight(SmallPadding);
}
else if (text.IsEmpty() && icon)
{
btn->GetDirLayout()->SetPaddingBot(SmallPadding);
btn->GetDirLayout()->SetPaddingTop(SmallPadding);
btn->GetDirLayout()->SetPaddingLeft(SmallPadding);
btn->GetDirLayout()->SetPaddingRight(SmallPadding);
}
else if (text.IsEmpty() && !icon)
{
btn->GetDirLayout()->SetPaddingBot(MediumPadding);
btn->GetDirLayout()->SetPaddingTop(MediumPadding);
btn->GetDirLayout()->SetPaddingLeft(BigPadding);
btn->GetDirLayout()->SetPaddingRight(BigPadding);
}
return btn;
}
UIToolButton *GameObjectFactory::CreateUIToolButton()
{
GameObject *go = GameObjectFactory::CreateUIGameObject();
return GameObjectFactory::CreateUIToolButtonInto(go);
}
UIToolButton *GameObjectFactory::CreateUIToolButtonInto(GameObject *go)
{
return UIToolButton::CreateInto(go);
}
UIToolButton *GameObjectFactory::CreateUIToolButton(const String &text,
Texture2D *icon)
{
const Vector2i size(15);
UIToolButton *btn = GameObjectFactory::CreateUIToolButton();
if (!text.IsEmpty())
{
btn->GetText()->SetContent(text);
}
if (icon)
{
btn->SetIcon(icon, size, (text.IsEmpty() ? 0 : 5));
}
constexpr int BigPadding = 10;
constexpr int MediumPadding = 6;
constexpr int SmallPadding = 3;
if (!text.IsEmpty() && !icon)
{
btn->GetDirLayout()->SetPaddingBot(MediumPadding);
btn->GetDirLayout()->SetPaddingTop(MediumPadding);
btn->GetDirLayout()->SetPaddingRight(BigPadding);
btn->GetDirLayout()->SetPaddingLeft(BigPadding);
}
else if (!text.IsEmpty() && icon)
{
btn->GetDirLayout()->SetPaddingBot(MediumPadding);
btn->GetDirLayout()->SetPaddingTop(MediumPadding);
btn->GetDirLayout()->SetPaddingLeft(BigPadding);
btn->GetDirLayout()->SetPaddingRight(SmallPadding);
}
else if (text.IsEmpty() && icon)
{
btn->GetDirLayout()->SetPaddingBot(SmallPadding);
btn->GetDirLayout()->SetPaddingTop(SmallPadding);
btn->GetDirLayout()->SetPaddingLeft(SmallPadding);
btn->GetDirLayout()->SetPaddingRight(SmallPadding);
}
else if (text.IsEmpty() && !icon)
{
btn->GetDirLayout()->SetPaddingBot(MediumPadding);
btn->GetDirLayout()->SetPaddingTop(MediumPadding);
btn->GetDirLayout()->SetPaddingLeft(BigPadding);
btn->GetDirLayout()->SetPaddingRight(BigPadding);
}
return btn;
}
UILabel *GameObjectFactory::CreateUILabelInto(GameObject *go)
{
return UILabel::CreateInto(go);
}
UILabel *GameObjectFactory::CreateUILabel()
{
return UILabel::CreateInto(
GameObjectFactory::CreateUIGameObjectNamed("Label"));
}
UIScrollArea *GameObjectFactory::CreateUIScrollArea()
{
return UIScrollArea::CreateInto(
GameObjectFactory::CreateUIGameObjectNamed("ScrollArea"));
}
UIScrollBar *GameObjectFactory::CreateUIScrollBarInto(GameObject *go)
{
return UIScrollBar::CreateInto(go);
}
UIScrollBar *GameObjectFactory::CreateUIScrollBar()
{
return UIScrollBar::CreateInto(
GameObjectFactory::CreateUIGameObjectNamed("ScrollBar"));
}
UIScrollPanel *GameObjectFactory::CreateUIScrollPanelInto(GameObject *go)
{
return UIScrollPanel::CreateInto(go);
}
UIScrollPanel *GameObjectFactory::CreateUIScrollPanel()
{
return GameObjectFactory::CreateUIScrollPanelInto(
GameObjectFactory::CreateUIGameObjectNamed("ScrollPanel"));
}
UIDirLayoutMovableSeparator *
GameObjectFactory::CreateUIDirLayoutMovableHSeparator()
{
UIDirLayoutMovableSeparator *sep =
GameObjectFactory::CreateUIDirLayoutMovableSeparator();
sep->SetAxis(Axis::HORIZONTAL);
return sep;
}
UIDirLayoutMovableSeparator *
GameObjectFactory::CreateUIDirLayoutMovableVSeparator()
{
UIDirLayoutMovableSeparator *sep =
GameObjectFactory::CreateUIDirLayoutMovableSeparator();
sep->SetAxis(Axis::VERTICAL);
return sep;
}
UIDirLayoutMovableSeparator *
GameObjectFactory::CreateUIDirLayoutMovableSeparator()
{
return GameObjectFactory::CreateUIDirLayoutMovableSeparatorInto(
GameObjectFactory::CreateUIGameObjectNamed("UIMovSeparator"));
}
UIDirLayoutMovableSeparator *
GameObjectFactory::CreateUIDirLayoutMovableSeparatorInto(GameObject *go)
{
return UIDirLayoutMovableSeparator::CreateInto(go);
}
UIScrollArea *GameObjectFactory::CreateUIScrollAreaInto(GameObject *go)
{
return UIScrollArea::CreateInto(go);
}
GameObject *GameObjectFactory::CreateUISpacer(LayoutSizeType sizeType,
const Vector2 &space)
{
GameObject *spacerGo =
GameObjectFactory::CreateUIGameObjectNamed("Separator");
UILayoutElement *le = spacerGo->AddComponent<UILayoutElement>();
le->SetMinSize(Vector2i(0));
le->SetPreferredSize(Vector2i(0));
le->SetFlexibleSize(Vector2(0));
if (sizeType == LayoutSizeType::MIN)
{
le->SetMinSize(Vector2i(space));
}
else if (sizeType == LayoutSizeType::PREFERRED)
{
le->SetPreferredSize(Vector2i(space));
}
else
{
le->SetFlexibleSize(Vector2(space));
}
return spacerGo;
}
GameObject *GameObjectFactory::CreateUIHSpacer(LayoutSizeType sizeType,
float spaceX)
{
GameObject *spacerGo =
GameObjectFactory::CreateUISpacer(sizeType, Vector2(spaceX, 0));
return spacerGo;
}
GameObject *GameObjectFactory::CreateUIVSpacer(LayoutSizeType sizeType,
float spaceY)
{
GameObject *spacerGo =
GameObjectFactory::CreateUISpacer(sizeType, Vector2(0, spaceY));
return spacerGo;
}
UIImageRenderer *GameObjectFactory::AddInnerShadow(GameObject *uiGo,
const Vector2i &size,
float alpha)
{
GameObject *innerShadowGo = GameObjectFactory::CreateUIGameObject();
UIImageRenderer *innerShadowImg =
innerShadowGo->AddComponent<UIImageRenderer>();
innerShadowImg->SetMode(UIImageRenderer::Mode::SLICE_9);
innerShadowImg->SetImageTexture(TextureFactory::GetInnerShadow());
innerShadowImg->SetSlice9BorderStrokePx(size);
innerShadowImg->SetTint(Color::Black().WithAlpha(alpha));
innerShadowImg->SetDepthMask(false);
// innerShadowGo->GetTransform()->TranslateLocal( Vector3(0, 0, 0.00001f) );
innerShadowGo->SetParent(uiGo);
return innerShadowImg;
}
UIImageRenderer *GameObjectFactory::AddOuterShadow(GameObject *uiGo,
const Vector2i &size,
float alpha)
{
GameObject *outerShadowGo = GameObjectFactory::CreateUIGameObject();
UIImageRenderer *outerShadowImg =
outerShadowGo->AddComponent<UIImageRenderer>();
outerShadowImg->SetMode(UIImageRenderer::Mode::SLICE_9);
outerShadowImg->SetImageTexture(TextureFactory::GetOuterShadow());
outerShadowImg->SetSlice9BorderStrokePx(size);
outerShadowImg->SetTint(Color::Black().WithAlpha(alpha));
outerShadowImg->SetDepthMask(false);
outerShadowGo->GetRectTransform()->TranslateLocal(Vector3(0, 0, 0.001f));
outerShadowGo->GetRectTransform()->SetMargins(
-size.x, -size.y, -size.x, -size.y);
outerShadowGo->SetParent(uiGo);
return outerShadowImg;
}
UIImageRenderer *GameObjectFactory::AddOuterBorder(GameObject *uiGo)
{
return GameObjectFactory::AddOuterBorder(
uiGo,
Vector2i(SCAST<int>(UITheme::GetNotFocusedBorderStroke())),
UITheme::GetNotFocusedBorderColor());
}
UIImageRenderer *GameObjectFactory::AddOuterBorder(GameObject *uiGo,
const Vector2i &size,
const Color &color)
{
GameObject *outerBorderGo = GameObjectFactory::CreateUIGameObject();
UIImageRenderer *outerBorderImg =
outerBorderGo->AddComponent<UIImageRenderer>();
outerBorderImg->SetMode(UIImageRenderer::Mode::SLICE_9);
outerBorderImg->SetImageTexture(TextureFactory::Get9SliceBorder());
outerBorderImg->SetSlice9BorderStrokePx(size);
outerBorderImg->SetTint(color);
outerBorderGo->GetRectTransform()->TranslateLocal(Vector3(0, 0, -0.00001f));
outerBorderGo->GetRectTransform()->SetMargins(
-size.x, -size.y, -size.x, -size.y);
outerBorderGo->SetParent(uiGo);
return outerBorderImg;
}
UIImageRenderer *GameObjectFactory::AddInnerBorder(GameObject *uiGo)
{
return GameObjectFactory::AddInnerBorder(
uiGo,
Vector2i(SCAST<int>(UITheme::GetNotFocusedBorderStroke())),
UITheme::GetNotFocusedBorderColor());
}
UIImageRenderer *GameObjectFactory::AddInnerBorder(GameObject *uiGo,
const Vector2i &size,
const Color &color)
{
UIImageRenderer *innerBorderImg = uiGo->AddComponent<UIImageRenderer>();
innerBorderImg->SetMode(UIImageRenderer::Mode::SLICE_9);
innerBorderImg->SetImageTexture(TextureFactory::Get9SliceBorder());
innerBorderImg->SetSlice9BorderStrokePx(size);
innerBorderImg->SetTint(color);
return innerBorderImg;
}
void GameObjectFactory::MakeBorderFocused(UIImageRenderer *border)
{
if (border)
{
border->SetTint(UITheme::GetFocusedBorderColor());
border->SetSlice9BorderStrokePx(
Vector2i(SCAST<int>(UITheme::GetFocusedBorderStroke())));
}
}
void GameObjectFactory::MakeBorderNotFocused(UIImageRenderer *border)
{
if (border)
{
border->SetTint(UITheme::GetNotFocusedBorderColor());
border->SetSlice9BorderStrokePx(
Vector2i(SCAST<int>(UITheme::GetNotFocusedBorderStroke())));
}
}
String GameObjectFactory::GetGameObjectDuplicateName(const GameObject *go)
{
String originalName = go->GetName();
String duplicateNameNumber = "";
bool isDuplicatedName = false;
for (uint i = originalName.Size() - 1; i >= 0; --i)
{
char c = originalName[i];
if (String::IsNumber(c))
{
isDuplicatedName = true;
duplicateNameNumber.Prepend(String(c));
}
else
{
isDuplicatedName = (c == '_');
break;
}
}
String duplicateName;
if (isDuplicatedName)
{
int duplicateNumber = String::ToInt(duplicateNameNumber);
duplicateName = originalName.SubString(
0, originalName.Size() - duplicateNameNumber.Size() - 2);
duplicateName += "_" + String(duplicateNumber + 1);
}
else
{
duplicateName = (originalName + "_1");
}
return duplicateName;
}
Camera *GameObjectFactory::CreateUICamera()
{
GameObject *go = GameObjectFactory::CreateGameObject();
return GameObjectFactory::CreateUICameraInto(go);
}
Camera *GameObjectFactory::CreateUICameraInto(GameObject *go)
{
Camera *cam = go->AddComponent<Camera>();
cam->SetGammaCorrection(1.0f);
cam->SetClearColor(Color::LightGray());
cam->SetHDR(false);
cam->RemoveRenderPass(RenderPass::SCENE_OPAQUE);
cam->RemoveRenderPass(RenderPass::SCENE_DECALS);
cam->RemoveRenderPass(RenderPass::SCENE_BEFORE_ADDING_LIGHTS);
cam->RemoveRenderPass(RenderPass::SCENE_AFTER_ADDING_LIGHTS);
cam->RemoveRenderPass(RenderPass::SCENE_TRANSPARENT);
cam->RemoveRenderPass(RenderPass::OVERLAY);
cam->RemoveRenderPass(RenderPass::OVERLAY_POSTPROCESS);
cam->SetRenderFlags(RenderFlag::CLEAR_COLOR |
RenderFlag::CLEAR_DEPTH_STENCIL);
return cam;
}
GameObject *GameObjectFactory::CreateUISeparator(LayoutSizeType sizeType,
const Vector2i &space,
float linePercent)
{
GameObject *sepGo =
GameObjectFactory::CreateUISpacer(sizeType, Vector2(space));
LineRenderer *lr = sepGo->AddComponent<LineRenderer>();
lr->SetMaterial(MaterialFactory::GetUIImage().Get());
lr->GetMaterial()->SetAlbedoColor(Color::Black());
lr->SetViewProjMode(GL::ViewProjMode::CANVAS);
UILayoutElement *le = sepGo->GetComponent<UILayoutElement>();
le->SetPreferredSize(Vector2i::Max(space, Vector2i::One()));
bool horizontal = (space.x == 0);
if (horizontal)
{
le->SetFlexibleSize(Vector2(99999999, 0));
lr->SetPoints(
{Vector3(-linePercent, 0, 0), Vector3(linePercent, 0, 0)});
}
else
{
le->SetFlexibleSize(Vector2(0, 99999999));
lr->SetPoints(
{Vector3(0, -linePercent, 0), Vector3(0, linePercent, 0)});
}
return sepGo;
}
GameObject *GameObjectFactory::CreateUIHSeparator(LayoutSizeType sizeType,
int spaceY,
float linePercent)
{
GameObject *sepGo = GameObjectFactory::CreateUISeparator(
sizeType, Vector2i(0, spaceY), linePercent);
return sepGo;
}
GameObject *GameObjectFactory::CreateUIVSeparator(LayoutSizeType sizeType,
int spaceX,
float linePercent)
{
GameObject *sepGo = GameObjectFactory::CreateUISeparator(
sizeType, Vector2i(spaceX, 0), linePercent);
return sepGo;
}
GameObject *GameObjectFactory::CreateGameObjectWithMesh(Mesh *m,
const String &name)
{
GameObject *go = GameObjectFactory::CreateGameObject(true);
go->SetName(name);
MeshRenderer *r = go->AddComponent<MeshRenderer>();
r->SetRenderPrimitive(GL::Primitive::TRIANGLES);
r->SetMaterial(MaterialFactory::GetDefault().Get());
r->SetMesh(m);
return go;
}
GameObject *GameObjectFactory::CreatePlaneGameObject()
{
AH<Mesh> mesh = MeshFactory::GetPlane();
GameObject *go = CreateGameObjectWithMesh(mesh.Get(), "Plane");
go->AddComponent<BoxCollider>();
return go;
}
GameObject *GameObjectFactory::CreateCubeGameObject()
{
AH<Mesh> mesh = MeshFactory::GetCube();
GameObject *go = CreateGameObjectWithMesh(mesh.Get(), "Cube");
go->AddComponent<BoxCollider>();
return go;
}
GameObject *GameObjectFactory::CreateCapsuleGameObject()
{
AH<Mesh> mesh = MeshFactory::GetCapsule();
GameObject *go = CreateGameObjectWithMesh(mesh.Get(), "Capsule");
go->AddComponent<CapsuleCollider>();
return go;
}
GameObject *GameObjectFactory::CreateCylinderGameObject()
{
AH<Mesh> mesh = MeshFactory::GetCylinder();
GameObject *go = CreateGameObjectWithMesh(mesh.Get(), "Cylinder");
BoxCollider *col = go->AddComponent<BoxCollider>();
col->SetExtents(Vector3::One());
return go;
}
GameObject *GameObjectFactory::CreateSphereGameObject()
{
AH<Mesh> mesh = MeshFactory::GetSphere();
GameObject *go = CreateGameObjectWithMesh(mesh.Get(), "Sphere");
go->AddComponent<SphereCollider>();
return go;
}
GameObject *GameObjectFactory::CreateConeGameObject()
{
AH<Mesh> mesh = MeshFactory::GetCone();
GameObject *go = CreateGameObjectWithMesh(mesh.Get(), "Cone");
go->AddComponent<BoxCollider>();
return go;
}
|
lgpl-3.0
|
Ultimaker/Cura
|
cura/Machines/Models/FirstStartMachineActionsModel.py
|
3937
|
# Copyright (c) 2019 Ultimaker B.V.
# Cura is released under the terms of the LGPLv3 or higher.
from typing import Optional, Dict, Any, TYPE_CHECKING
from PyQt5.QtCore import QObject, Qt, pyqtProperty, pyqtSignal, pyqtSlot
from UM.Qt.ListModel import ListModel
if TYPE_CHECKING:
from cura.CuraApplication import CuraApplication
class FirstStartMachineActionsModel(ListModel):
"""This model holds all first-start machine actions for the currently active machine. It has 2 roles:
- title : the title/name of the action
- content : the QObject of the QML content of the action
- action : the MachineAction object itself
"""
TitleRole = Qt.UserRole + 1
ContentRole = Qt.UserRole + 2
ActionRole = Qt.UserRole + 3
def __init__(self, application: "CuraApplication", parent: Optional[QObject] = None) -> None:
super().__init__(parent)
self.addRoleName(self.TitleRole, "title")
self.addRoleName(self.ContentRole, "content")
self.addRoleName(self.ActionRole, "action")
self._current_action_index = 0
self._application = application
self._application.initializationFinished.connect(self.initialize)
self._previous_global_stack = None
def initialize(self) -> None:
self._application.getMachineManager().globalContainerChanged.connect(self._update)
self._update()
currentActionIndexChanged = pyqtSignal()
allFinished = pyqtSignal() # Emitted when all actions have been finished.
@pyqtProperty(int, notify = currentActionIndexChanged)
def currentActionIndex(self) -> int:
return self._current_action_index
@pyqtProperty("QVariantMap", notify = currentActionIndexChanged)
def currentItem(self) -> Optional[Dict[str, Any]]:
if self._current_action_index >= self.count:
return dict()
else:
return self.getItem(self._current_action_index)
@pyqtProperty(bool, notify = currentActionIndexChanged)
def hasMoreActions(self) -> bool:
return self._current_action_index < self.count - 1
@pyqtSlot()
def goToNextAction(self) -> None:
# finish the current item
if "action" in self.currentItem:
self.currentItem["action"].setFinished()
if not self.hasMoreActions:
self.allFinished.emit()
self.reset()
return
self._current_action_index += 1
self.currentActionIndexChanged.emit()
@pyqtSlot()
def reset(self) -> None:
"""Resets the current action index to 0 so the wizard panel can show actions from the beginning."""
self._current_action_index = 0
self.currentActionIndexChanged.emit()
if self.count == 0:
self.allFinished.emit()
def _update(self) -> None:
global_stack = self._application.getMachineManager().activeMachine
if global_stack is None:
self.setItems([])
return
# Do not update if the machine has not been switched. This can cause the SettingProviders on the Machine
# Setting page to do a force update, but they can use potential outdated cached values.
if self._previous_global_stack is not None and global_stack.getId() == self._previous_global_stack.getId():
return
self._previous_global_stack = global_stack
definition_id = global_stack.definition.getId()
first_start_actions = self._application.getMachineActionManager().getFirstStartActions(definition_id)
item_list = []
for item in first_start_actions:
item_list.append({"title": item.label,
"content": item.getDisplayItem(),
"action": item,
})
item.reset()
self.setItems(item_list)
self.reset()
__all__ = ["FirstStartMachineActionsModel"]
|
lgpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.