code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
package org.geomajas.layer.geotools;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.geotools.data.AbstractDataStoreFactory;
import org.geotools.data.DataStore;
import org.geotools.data.store.ContentDataStore;
import org.geotools.data.store.ContentEntry;
import org.geotools.data.store.ContentFeatureSource;
import org.opengis.feature.type.Name;
public class DummyJdbcFactory extends AbstractDataStoreFactory implements org.geotools.data.DataStoreFactorySpi {
public class DummyJdbcDataStore extends ContentDataStore {
protected List<Name> createTypeNames() throws IOException {
return null;
}
protected ContentFeatureSource createFeatureSource(ContentEntry entry) throws IOException {
return null;
}
}
public String getDescription() {
return "DummyJdbcFactory";
}
public Param[] getParametersInfo() {
return new Param[] { new Param("testScope", Boolean.class, "Set to true for unit testing", true) };
}
public boolean canProcess(Map params) {
if (!super.canProcess(params)) {
return false; // was not in agreement with getParametersInfo
}
if (!(((String) params.get("testScope")).equalsIgnoreCase("true"))) {
return (false);
} else {
return (true);
}
}
public DataStore createDataStore(Map<String, Serializable> params) throws IOException {
return new DummyJdbcDataStore();
}
public DataStore createNewDataStore(Map<String, Serializable> params) throws IOException {
return new DummyJdbcDataStore();
}
}
| geomajas/geomajas-project-server | plugin/layer-geotools/geotools/src/test/java/org/geomajas/layer/geotools/DummyJdbcFactory.java | Java | agpl-3.0 | 1,533 |
/**
* Copyright (c) 2000-2013 Liferay, Inc. 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.
*/
package org.opencps.processmgt;
import com.liferay.portal.NoSuchModelException;
/**
* @author khoavd
*/
public class NoSuchProcessStepDossierPartException extends NoSuchModelException {
public NoSuchProcessStepDossierPartException() {
super();
}
public NoSuchProcessStepDossierPartException(String msg) {
super(msg);
}
public NoSuchProcessStepDossierPartException(String msg, Throwable cause) {
super(msg, cause);
}
public NoSuchProcessStepDossierPartException(Throwable cause) {
super(cause);
}
} | hltn/opencps | portlets/opencps-portlet/docroot/WEB-INF/service/org/opencps/processmgt/NoSuchProcessStepDossierPartException.java | Java | agpl-3.0 | 1,112 |
<?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Dojo
* @subpackage Form_Element
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
/** Zend_Dojo_Form_Element_DijitMulti */
require_once 'Zend/Dojo/Form/Element/DijitMulti.php';
/**
* RadioButton dijit
*
* @uses Zend_Dojo_Form_Element_DijitMulti
* @package Zend_Dojo
* @subpackage Form_Element
* @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id: RadioButton.php 23772 2011-02-28 21:35:29Z ralph $
*/
class Zend_Dojo_Form_Element_RadioButton extends Zend_Dojo_Form_Element_DijitMulti
{
/**
* Use RadioButton dijit view helper
* @var string
*/
public $helper = 'RadioButton';
}
| WhiteLabelReady/WhiteLabelTransfer | library/Zend/Dojo/Form/Element/RadioButton.php | PHP | agpl-3.0 | 1,413 |
/*
This file is part of the HeavenMS MapleStory Server
Copyleft (L) 2016 - 2019 RonanLana
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation version 3 as published by
the Free Software Foundation. You may not use, modify or distribute
this program under any other version of the GNU Affero General Public
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var status = -1;
function start(mode, type, selection) {
if (mode == -1) {
qm.dispose();
} else {
if(mode == 0 && type > 0) {
qm.dispose();
return;
}
if (mode == 1)
status++;
else
status--;
if (status == 0) {
qm.sendNext("We're a pack of wolves looking for our lost child. I hear you are taking care of our baby. We appreciate your kindness, but it's time to return our baby to us.", 9);
} else if (status == 1) {
qm.sendNextPrev("Werewolf is my friend, I can't just hand over a friend.", 3);
} else if (status == 2) {
qm.sendAcceptDecline("We understand, but we won't leave without our pup. Tell you what, we'll test you to see if you are worthy of raising a wolf. #rGet ready to be tested by wolves.#k");
} else if (status == 3) {
var em = qm.getEventManager("Aran_3rdmount");
if (em == null) {
qm.sendOk("Sorry, but the 3rd mount quest (Wolves) is closed.");
return;
}
else {
var em = qm.getEventManager("Aran_3rdmount");
if (!em.startInstance(qm.getPlayer())) {
qm.sendOk("There is currently someone in this map, come back later.");
} else {
qm.forceStartQuest();
}
}
} else if (status == 4) {
qm.dispose();
}
}
}
| ronancpl/MapleSolaxiaV2 | scripts/quest/21613.js | JavaScript | agpl-3.0 | 2,413 |
bpmnGatewayInclusive=function(width,_30ab){
VectorFigure.call(this);
this.stroke =1;
};
bpmnGatewayInclusive.prototype=new VectorFigure;
bpmnGatewayInclusive.prototype.type="bpmnGatewayInclusive";
bpmnGatewayInclusive.prototype.paint=function(){
VectorFigure.prototype.paint.call(this);
if(typeof workflow.zoomfactor == 'undefined')
workflow.zoomfactor = 1;
//Set the Task Limitation
if(typeof this.limitFlag == 'undefined' || this.limitFlag == false)
{
this.originalWidth = 40;
this.originalHeight = 40;
this.orgXPos = this.getX();
this.orgYPos = this.getY();
this.orgFontSize =this.fontSize;
}
this.width = this.originalWidth * workflow.zoomfactor;
this.height = this.originalHeight * workflow.zoomfactor;
var cw = this.getWidth();
var ch = this.getHeight();
var x=new Array(0,cw*0.5,cw,cw*0.5);
var y=new Array(ch*0.5,ch,ch*0.5,0);
//var x=new Array(0,this.width/2,this.width,this.width/2);
//var y=new Array(this.height/2,this.height,this.height/2,0);
var x2 = new Array();
var y2 = new Array();
for(var i=0;i<x.length;i++){
x2[i]=x[i]+4;
y2[i]=y[i]+1;
}
this.graphics.setStroke(this.stroke);
this.graphics.setColor( "#c0c0c0" );
this.graphics.fillPolygon(x2,y2);
this.graphics.setStroke(1);
this.graphics.setColor( "#ffffe5" );
this.graphics.fillPolygon(x,y);
this.graphics.setColor("#c8c865");
this.graphics.drawPolygon(x,y);
var x_cir = 15;
var y_cir = 15;
this.graphics.setColor("#c8c865");
this.graphics.drawEllipse(this.getWidth()/4,this.getHeight()/4,this.getWidth()/2,this.getHeight()/2);
this.graphics.paint();
if (this.input1 != null) {
this.input1.setPosition(0, this.height / 2);
}
if (this.input2 != null) {
this.input2.setPosition(this.width / 2, 0);
}
if (this.output1 != null) {
this.output1.setPosition(this.height / 2, this.width);
}
if (this.output2 != null) {
this.output2.setPosition(this.width, this.height / 2);
}
if (this.output3 != null) {
this.output3.setPosition(0, this.height /2 );
}
};
bpmnGatewayInclusive.prototype.setWorkflow=function(_40c5){
VectorFigure.prototype.setWorkflow.call(this,_40c5);
if(_40c5!=null){
var h2 = this.height/2;
var w2 = this.width/2;
var gatewayPortName = ['output1', 'output2', 'output3', 'input1', 'input2' ];
var gatewayPortType = ['OutputPort','OutputPort','OutputPort','InputPort','InputPort'];
var gatewayPositionX= [w2, this.width, 0 , 0, w2 ];
var gatewayPositionY= [this.width, h2, h2, h2, 0 ];
for(var i=0; i< gatewayPortName.length ; i++){
eval('this.'+gatewayPortName[i]+' = new '+gatewayPortType[i]+'()'); //Create New Port
eval('this.'+gatewayPortName[i]+'.setWorkflow(_40c5)'); //Add port to the workflow
eval('this.'+gatewayPortName[i]+'.setName("'+gatewayPortName[i]+'")'); //Set PortName
eval('this.'+gatewayPortName[i]+'.setZOrder(-1)'); //Set Z-Order of the port to -1. It will be below all the figure
eval('this.'+gatewayPortName[i]+'.setBackgroundColor(new Color(255, 255, 255))'); //Setting Background of the port to white
eval('this.'+gatewayPortName[i]+'.setColor(new Color(255, 255, 255))'); //Setting Border of the port to white
eval('this.addPort(this.'+gatewayPortName[i]+','+gatewayPositionX[i]+', '+gatewayPositionY[i]+')'); //Setting Position of the port
}
}
};
bpmnGatewayInclusive.prototype.getContextMenu=function(){
if(this.id != null){
this.workflow.handleContextMenu(this);
}
};
| carbonadona/pm | workflow/engine/templates/bpmn/GatewayInclusive.js | JavaScript | agpl-3.0 | 3,734 |
<?php
namespace Controller;
/**
* Project controller (Settings + creation/edition)
*
* @package controller
* @author Frederic Guillot
*/
class Project extends Base
{
/**
* List of projects
*
* @access public
*/
public function index()
{
if ($this->userSession->isAdmin()) {
$project_ids = $this->project->getAllIds();
}
else {
$project_ids = $this->projectPermission->getMemberProjectIds($this->userSession->getId());
}
$nb_projects = count($project_ids);
$paginator = $this->paginator
->setUrl('project', 'index')
->setMax(20)
->setOrder('name')
->setQuery($this->project->getQueryColumnStats($project_ids))
->calculate();
$this->response->html($this->template->layout('project/index', array(
'board_selector' => $this->projectPermission->getAllowedProjects($this->userSession->getId()),
'paginator' => $paginator,
'nb_projects' => $nb_projects,
'title' => t('Projects').' ('.$nb_projects.')'
)));
}
/**
* Show the project information page
*
* @access public
*/
public function show()
{
$project = $this->getProject();
$this->response->html($this->projectLayout('project/show', array(
'project' => $project,
'stats' => $this->project->getTaskStats($project['id']),
'title' => $project['name'],
)));
}
/**
* Public access management
*
* @access public
*/
public function share()
{
$project = $this->getProject();
$switch = $this->request->getStringParam('switch');
if ($switch === 'enable' || $switch === 'disable') {
$this->checkCSRFParam();
if ($this->project->{$switch.'PublicAccess'}($project['id'])) {
$this->session->flash(t('Project updated successfully.'));
} else {
$this->session->flashError(t('Unable to update this project.'));
}
$this->response->redirect('?controller=project&action=share&project_id='.$project['id']);
}
$this->response->html($this->projectLayout('project/share', array(
'project' => $project,
'title' => t('Public access'),
)));
}
/**
* Integrations page
*
* @access public
*/
public function integration()
{
$project = $this->getProject();
if ($this->request->isPost()) {
$params = $this->request->getValues();
$params += array('hipchat' => 0, 'slack' => 0, 'jabber' => 0);
$this->projectIntegration->saveParameters($project['id'], $params);
}
$values = $this->projectIntegration->getParameters($project['id']);
$values += array('hipchat_api_url' => 'https://api.hipchat.com');
$this->response->html($this->projectLayout('project/integrations', array(
'project' => $project,
'title' => t('Integrations'),
'webhook_token' => $this->config->get('webhook_token'),
'values' => $values,
'errors' => array(),
)));
}
/**
* Display a form to edit a project
*
* @access public
*/
public function edit(array $values = array(), array $errors = array())
{
$project = $this->getProject();
$this->response->html($this->projectLayout('project/edit', array(
'values' => empty($values) ? $project : $values,
'errors' => $errors,
'project' => $project,
'title' => t('Edit project')
)));
}
/**
* Validate and update a project
*
* @access public
*/
public function update()
{
$project = $this->getProject();
$values = $this->request->getValues();
if ($project['is_private'] == 1 && $this->userSession->isAdmin() && ! isset($values['is_private'])) {
$values += array('is_private' => 0);
}
list($valid, $errors) = $this->project->validateModification($values);
if ($valid) {
if ($this->project->update($values)) {
$this->session->flash(t('Project updated successfully.'));
$this->response->redirect('?controller=project&action=edit&project_id='.$project['id']);
}
else {
$this->session->flashError(t('Unable to update this project.'));
}
}
$this->edit($values, $errors);
}
/**
* Users list for the selected project
*
* @access public
*/
public function users()
{
$project = $this->getProject();
$this->response->html($this->projectLayout('project/users', array(
'project' => $project,
'users' => $this->projectPermission->getAllUsers($project['id']),
'title' => t('Edit project access list')
)));
}
/**
* Allow everybody
*
* @access public
*/
public function allowEverybody()
{
$project = $this->getProject();
$values = $this->request->getValues() + array('is_everybody_allowed' => 0);
list($valid,) = $this->projectPermission->validateProjectModification($values);
if ($valid) {
if ($this->project->update($values)) {
$this->session->flash(t('Project updated successfully.'));
}
else {
$this->session->flashError(t('Unable to update this project.'));
}
}
$this->response->redirect('?controller=project&action=users&project_id='.$project['id']);
}
/**
* Allow a specific user (admin only)
*
* @access public
*/
public function allow()
{
$values = $this->request->getValues();
list($valid,) = $this->projectPermission->validateUserModification($values);
if ($valid) {
if ($this->projectPermission->addMember($values['project_id'], $values['user_id'])) {
$this->session->flash(t('Project updated successfully.'));
}
else {
$this->session->flashError(t('Unable to update this project.'));
}
}
$this->response->redirect('?controller=project&action=users&project_id='.$values['project_id']);
}
/**
* Change the role of a project member
*
* @access public
*/
public function role()
{
$this->checkCSRFParam();
$values = array(
'project_id' => $this->request->getIntegerParam('project_id'),
'user_id' => $this->request->getIntegerParam('user_id'),
'is_owner' => $this->request->getIntegerParam('is_owner'),
);
list($valid,) = $this->projectPermission->validateUserModification($values);
if ($valid) {
if ($this->projectPermission->changeRole($values['project_id'], $values['user_id'], $values['is_owner'])) {
$this->session->flash(t('Project updated successfully.'));
}
else {
$this->session->flashError(t('Unable to update this project.'));
}
}
$this->response->redirect('?controller=project&action=users&project_id='.$values['project_id']);
}
/**
* Revoke user access (admin only)
*
* @access public
*/
public function revoke()
{
$this->checkCSRFParam();
$values = array(
'project_id' => $this->request->getIntegerParam('project_id'),
'user_id' => $this->request->getIntegerParam('user_id'),
);
list($valid,) = $this->projectPermission->validateUserModification($values);
if ($valid) {
if ($this->projectPermission->revokeMember($values['project_id'], $values['user_id'])) {
$this->session->flash(t('Project updated successfully.'));
}
else {
$this->session->flashError(t('Unable to update this project.'));
}
}
$this->response->redirect('?controller=project&action=users&project_id='.$values['project_id']);
}
/**
* Remove a project
*
* @access public
*/
public function remove()
{
$project = $this->getProject();
if ($this->request->getStringParam('remove') === 'yes') {
$this->checkCSRFParam();
if ($this->project->remove($project['id'])) {
$this->session->flash(t('Project removed successfully.'));
} else {
$this->session->flashError(t('Unable to remove this project.'));
}
$this->response->redirect('?controller=project');
}
$this->response->html($this->projectLayout('project/remove', array(
'project' => $project,
'title' => t('Remove project')
)));
}
/**
* Duplicate a project
*
* @author Antonio Rabelo
* @author Michael Lüpkes
* @access public
*/
public function duplicate()
{
$project = $this->getProject();
if ($this->request->getStringParam('duplicate') === 'yes') {
$values = array_keys($this->request->getValues());
if ($this->projectDuplication->duplicate($project['id'], $values) !== false) {
$this->session->flash(t('Project cloned successfully.'));
} else {
$this->session->flashError(t('Unable to clone this project.'));
}
$this->response->redirect('?controller=project');
}
$this->response->html($this->projectLayout('project/duplicate', array(
'project' => $project,
'title' => t('Clone this project')
)));
}
/**
* Disable a project
*
* @access public
*/
public function disable()
{
$project = $this->getProject();
if ($this->request->getStringParam('disable') === 'yes') {
$this->checkCSRFParam();
if ($this->project->disable($project['id'])) {
$this->session->flash(t('Project disabled successfully.'));
} else {
$this->session->flashError(t('Unable to disable this project.'));
}
$this->response->redirect('?controller=project&action=show&project_id='.$project['id']);
}
$this->response->html($this->projectLayout('project/disable', array(
'project' => $project,
'title' => t('Project activation')
)));
}
/**
* Enable a project
*
* @access public
*/
public function enable()
{
$project = $this->getProject();
if ($this->request->getStringParam('enable') === 'yes') {
$this->checkCSRFParam();
if ($this->project->enable($project['id'])) {
$this->session->flash(t('Project activated successfully.'));
} else {
$this->session->flashError(t('Unable to activate this project.'));
}
$this->response->redirect('?controller=project&action=show&project_id='.$project['id']);
}
$this->response->html($this->projectLayout('project/enable', array(
'project' => $project,
'title' => t('Project activation')
)));
}
/**
* Display a form to create a new project
*
* @access public
*/
public function create(array $values = array(), array $errors = array())
{
$is_private = $this->request->getIntegerParam('private', $this->userSession->isAdmin() ? 0 : 1);
$this->response->html($this->template->layout('project/new', array(
'board_selector' => $this->projectPermission->getAllowedProjects($this->userSession->getId()),
'values' => empty($values) ? array('is_private' => $is_private) : $values,
'errors' => $errors,
'is_private' => $is_private,
'title' => $is_private ? t('New private project') : t('New project'),
)));
}
/**
* Validate and save a new project
*
* @access public
*/
public function save()
{
$values = $this->request->getValues();
list($valid, $errors) = $this->project->validateCreation($values);
if ($valid) {
$project_id = $this->project->create($values, $this->userSession->getId(), true);
if ($project_id > 0) {
$this->session->flash(t('Your project have been created successfully.'));
$this->response->redirect('?controller=project&action=show&project_id='.$project_id);
}
$this->session->flashError(t('Unable to create your project.'));
}
$this->create($values, $errors);
}
}
| crwilliams/kanboard | app/Controller/Project.php | PHP | agpl-3.0 | 13,003 |
package org.bimserver.database.actions;
/******************************************************************************
* Copyright (C) 2009-2019 BIMserver.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}.
*****************************************************************************/
import java.util.Set;
import org.bimserver.BimserverDatabaseException;
import org.bimserver.database.BimserverLockConflictException;
import org.bimserver.database.DatabaseSession;
import org.bimserver.database.OldQuery;
import org.bimserver.database.query.conditions.AttributeCondition;
import org.bimserver.database.query.conditions.Condition;
import org.bimserver.database.query.conditions.IsOfTypeCondition;
import org.bimserver.database.query.conditions.Not;
import org.bimserver.database.query.literals.EnumLiteral;
import org.bimserver.models.log.AccessMethod;
import org.bimserver.models.store.ObjectState;
import org.bimserver.models.store.StorePackage;
import org.bimserver.models.store.User;
import org.bimserver.models.store.UserType;
import org.bimserver.shared.exceptions.UserException;
import org.bimserver.utils.CollectionUtils;
import org.bimserver.webservices.authorization.Authorization;
public class GetAllUsersDatabaseAction extends BimDatabaseAction<Set<User>> {
private Authorization authorization;
public GetAllUsersDatabaseAction(DatabaseSession databaseSession, AccessMethod accessMethod, Authorization authorization) {
super(databaseSession, accessMethod);
this.authorization = authorization;
}
@Override
public Set<User> execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException {
User actingUser = getUserByUoid(authorization.getUoid());
Condition condition = new IsOfTypeCondition(StorePackage.eINSTANCE.getUser());
condition = condition.and(new Not(new AttributeCondition(StorePackage.eINSTANCE.getUser_UserType(), new EnumLiteral(UserType.SYSTEM))));
if (actingUser.getUserType() != UserType.ADMIN) {
condition = condition.and(new AttributeCondition(StorePackage.eINSTANCE.getUser_State(), new EnumLiteral(ObjectState.ACTIVE)));
}
return CollectionUtils.mapToSet(getDatabaseSession().query(condition, User.class, OldQuery.getDefault()));
}
} | opensourceBIM/BIMserver | BimServer/src/org/bimserver/database/actions/GetAllUsersDatabaseAction.java | Java | agpl-3.0 | 2,879 |
package gplx.core.stores; import gplx.*; import gplx.core.*;
import gplx.core.strings.*;
public class DataRdr_ {
public static final DataRdr Null = new DataRdr_null();
public static DataRdr as_(Object obj) {return obj instanceof DataRdr ? (DataRdr)obj : null;}
public static DataRdr cast(Object obj) {try {return (DataRdr)obj;} catch(Exception exc) {throw Err_.new_type_mismatch_w_exc(exc, DataRdr.class, obj);}}
public static Object Read_1st_row_and_1st_fld(DataRdr rdr) {
try {return rdr.MoveNextPeer() ? rdr.ReadAt(0) : null;}
finally {rdr.Rls();}
}
}
class DataRdr_null implements DataRdr {
public String NameOfNode() {return To_str();} public String To_str() {return "<< NULL READER >>";}
public boolean Type_rdr() {return true;}
public Hash_adp EnvVars() {return Hash_adp_.Noop;}
public Io_url Uri() {return Io_url_.Empty;} public void Uri_set(Io_url s) {}
public boolean Parse() {return parse;} public void Parse_set(boolean v) {parse = v;} private boolean parse;
public int FieldCount() {return 0;}
public String KeyAt(int i) {return To_str();}
public Object ReadAt(int i) {return null;}
public Keyval KeyValAt(int i) {return Keyval_.new_(this.KeyAt(i), this.ReadAt(i));}
public Object Read(String name) {return null;}
public String ReadStr(String key) {return String_.Empty;} public String ReadStrOr(String key, String or) {return or;}
public byte[] ReadBryByStr(String key) {return Bry_.Empty;} public byte[] ReadBryByStrOr(String key, byte[] or) {return or;}
public byte[] ReadBry(String key) {return Bry_.Empty;} public byte[] ReadBryOr(String key, byte[] or) {return or;}
public char ReadChar(String key) {return Char_.Null;} public char ReadCharOr(String key, char or) {return or;}
public int ReadInt(String key) {return Int_.Min_value;} public int ReadIntOr(String key, int or) {return or;}
public boolean ReadBool(String key) {return false;} public boolean ReadBoolOr(String key, boolean or) {return or;}
public long ReadLong(String key) {return Long_.Min_value;} public long ReadLongOr(String key, long or) {return or;}
public double ReadDouble(String key) {return Double_.NaN;} public double ReadDoubleOr(String key, double or) {return or;}
public float ReadFloat(String key) {return Float_.NaN;} public float ReadFloatOr(String key, float or) {return or;}
public byte ReadByte(String key) {return Byte_.Min_value;} public byte ReadByteOr(String key, byte or) {return or;}
public Decimal_adp ReadDecimal(String key) {return Decimal_adp_.Zero;}public Decimal_adp ReadDecimalOr(String key, Decimal_adp or) {return or;}
public DateAdp ReadDate(String key) {return DateAdp_.MinValue;} public DateAdp ReadDateOr(String key, DateAdp or) {return or;}
public gplx.core.ios.streams.Io_stream_rdr ReadRdr(String key) {return gplx.core.ios.streams.Io_stream_rdr_.Noop;}
public boolean MoveNextPeer() {return false;}
public DataRdr Subs() {return this;}
public DataRdr Subs_byName(String name) {return this;}
public DataRdr Subs_byName_moveFirst(String name) {return this;}
public Object StoreRoot(SrlObj root, String key) {return null;}
public boolean SrlBoolOr(String key, boolean v) {return v;}
public byte SrlByteOr(String key, byte v) {return v;}
public int SrlIntOr(String key, int or) {return or;}
public long SrlLongOr(String key, long or) {return or;}
public String SrlStrOr(String key, String or) {return or;}
public DateAdp SrlDateOr(String key, DateAdp or) {return or;}
public Decimal_adp SrlDecimalOr(String key, Decimal_adp or) {return or;}
public double SrlDoubleOr(String key, double or) {return or;}
public Object SrlObjOr(String key, Object or) {return or;}
public void SrlList(String key, List_adp list, SrlObj proto, String itmKey) {}
public void TypeKey_(String v) {}
public void XtoStr_gfml(String_bldr sb) {sb.Add_str_w_crlf("NULL:;");}
public SrlMgr SrlMgr_new(Object o) {return this;}
public void Rls() {}
}
| gnosygnu/xowa_android | _100_core/src/main/java/gplx/core/stores/DataRdr_.java | Java | agpl-3.0 | 3,982 |
<?php
/**
* @author Björn Schießle <schiessle@owncloud.com>
* @author Joas Schilling <nickvergessen@owncloud.com>
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <icewind@owncloud.com>
* @author Roeland Jago Douma <roeland@famdouma.nl>
* @author Thomas Müller <thomas.mueller@tmit.eu>
* @author Vincent Petry <pvince81@owncloud.com>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OCA\Files_Sharing\API;
use OC\HintException;
class Local {
/**
* get all shares
*
* @param array $params option 'file' to limit the result to a specific file/folder
* @return \OC_OCS_Result share information
*/
public static function getAllShares($params) {
if (isset($_GET['shared_with_me']) && $_GET['shared_with_me'] !== 'false') {
return self::getFilesSharedWithMe();
}
// if a file is specified, get the share for this file
if (isset($_GET['path'])) {
if ( isset($_GET['reshares']) && $_GET['reshares'] !== 'false' ) {
$reshares = true;
} else {
$reshares = false;
}
if (isset($_GET['subfiles']) && $_GET['subfiles'] !== 'false') {
return self::getSharesFromFolder($_GET['path']);
}
return self::collectShares(self::getFileId($_GET['path']),
self::getItemType($_GET['path']),
false,
$_GET['path'],
$reshares);
}
$shares = \OCP\Share::getItemShared('file', null);
if ($shares === false) {
return new \OC_OCS_Result(null, 404, 'could not get shares');
} else {
foreach ($shares as &$share) {
if ($share['item_type'] === 'file' && isset($share['path'])) {
$share['mimetype'] = \OC_Helper::getFileNameMimeType($share['path']);
if (\OC::$server->getPreviewManager()->isMimeSupported($share['mimetype'])) {
$share['isPreviewAvailable'] = true;
}
}
if (!is_null($share['token'])) {
$share['url'] = \OC::$server->getURLGenerator()->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share['token']]);
}
}
return new \OC_OCS_Result($shares);
}
}
/**
* get share information for a given share
*
* @param array $params which contains a 'id'
* @return \OC_OCS_Result share information
*/
public static function getShare($params) {
$s = self::getShareFromId($params['id']);
return self::collectShares($s['file_source'], $s['item_type'], true, null, false, (int)$params['id']);
}
/**
* collect all share information, either of a specific share or all
* shares for a given path
*
* @param string $itemSource
* @param string $itemType
* @param bool $getSpecificShare
* @param string $path
* @param bool $reshares
* @param int $id
*
* @return \OC_OCS_Result
*/
private static function collectShares($itemSource, $itemType, $getSpecificShare = false, $path = null, $reshares = false, $id = null) {
if ($itemSource !== null) {
$shares = \OCP\Share::getItemShared($itemType, $itemSource);
$receivedFrom = \OCP\Share::getItemSharedWithBySource($itemType, $itemSource);
// if a specific share was specified only return this one
if ($getSpecificShare === true) {
foreach ($shares as $share) {
if ($share['id'] === $id) {
$shares = array('element' => $share);
break;
}
}
} else {
foreach ($shares as $key => $share) {
$shares[$key]['path'] = $path;
}
}
// include also reshares in the lists. This means that the result
// will contain every user with access to the file.
if ($reshares === true) {
$shares = self::addReshares($shares, $itemSource);
}
if ($receivedFrom) {
foreach ($shares as $key => $share) {
$shares[$key]['received_from'] = $receivedFrom['uid_owner'];
$shares[$key]['received_from_displayname'] = \OCP\User::getDisplayName($receivedFrom['uid_owner']);
}
}
} else {
$shares = null;
}
if ($shares === null || empty($shares)) {
return new \OC_OCS_Result(null, 404, 'share doesn\'t exist');
} else {
foreach ($shares as &$share) {
if (!is_null($share['token'])) {
$share['url'] = \OC::$server->getURLGenerator()->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $share['token']]);
}
}
return new \OC_OCS_Result($shares);
}
}
/**
* add reshares to a array of shares
* @param array $shares array of shares
* @param int $itemSource item source ID
* @return array new shares array which includes reshares
*/
private static function addReshares($shares, $itemSource) {
// if there are no shares than there are also no reshares
$firstShare = reset($shares);
if ($firstShare) {
$path = $firstShare['path'];
} else {
return $shares;
}
$select = '`*PREFIX*share`.`id`, `item_type`, `*PREFIX*share`.`parent`, `share_type`, `share_with`, `file_source`, `path` , `*PREFIX*share`.`permissions`, `stime`, `expiration`, `token`, `storage`, `mail_send`, `mail_send`';
$getReshares = \OCP\DB::prepare('SELECT ' . $select . ' FROM `*PREFIX*share` INNER JOIN `*PREFIX*filecache` ON `file_source` = `*PREFIX*filecache`.`fileid` WHERE `*PREFIX*share`.`file_source` = ? AND `*PREFIX*share`.`item_type` IN (\'file\', \'folder\') AND `uid_owner` != ?');
$reshares = $getReshares->execute(array($itemSource, \OCP\User::getUser()))->fetchAll();
foreach ($reshares as $key => $reshare) {
if (isset($reshare['share_with']) && $reshare['share_with'] !== '') {
$reshares[$key]['share_with_displayname'] = \OCP\User::getDisplayName($reshare['share_with']);
}
// add correct path to the result
$reshares[$key]['path'] = $path;
}
return array_merge($shares, $reshares);
}
/**
* get share from all files in a given folder (non-recursive)
* @param string $path
* @return \OC_OCS_Result
*/
private static function getSharesFromFolder($path) {
$view = new \OC\Files\View('/'.\OCP\User::getUser().'/files');
if(!$view->is_dir($path)) {
return new \OC_OCS_Result(null, 400, "not a directory");
}
$content = $view->getDirectoryContent($path);
$result = array();
foreach ($content as $file) {
// workaround because folders are named 'dir' in this context
$itemType = $file['type'] === 'file' ? 'file' : 'folder';
$share = \OCP\Share::getItemShared($itemType, $file['fileid']);
if($share) {
$receivedFrom = \OCP\Share::getItemSharedWithBySource($itemType, $file['fileid']);
reset($share);
$key = key($share);
if ($receivedFrom) {
$share[$key]['received_from'] = $receivedFrom['uid_owner'];
$share[$key]['received_from_displayname'] = \OCP\User::getDisplayName($receivedFrom['uid_owner']);
}
$result = array_merge($result, $share);
}
}
return new \OC_OCS_Result($result);
}
/**
* get files shared with the user
* @return \OC_OCS_Result
*/
private static function getFilesSharedWithMe() {
try {
$shares = \OCP\Share::getItemsSharedWith('file');
foreach ($shares as &$share) {
if ($share['item_type'] === 'file') {
$share['mimetype'] = \OC_Helper::getFileNameMimeType($share['file_target']);
if (\OC::$server->getPreviewManager()->isMimeSupported($share['mimetype'])) {
$share['isPreviewAvailable'] = true;
}
}
}
$result = new \OC_OCS_Result($shares);
} catch (\Exception $e) {
$result = new \OC_OCS_Result(null, 403, $e->getMessage());
}
return $result;
}
/**
* create a new share
* @param array $params
* @return \OC_OCS_Result
*/
public static function createShare($params) {
$path = isset($_POST['path']) ? $_POST['path'] : null;
if($path === null) {
return new \OC_OCS_Result(null, 400, "please specify a file or folder path");
}
$itemSource = self::getFileId($path);
$itemSourceName = $itemSource;
$itemType = self::getItemType($path);
$expirationDate = null;
if($itemSource === null) {
return new \OC_OCS_Result(null, 404, "wrong path, file/folder doesn't exist.");
}
$shareWith = isset($_POST['shareWith']) ? $_POST['shareWith'] : null;
$shareType = isset($_POST['shareType']) ? (int)$_POST['shareType'] : null;
switch($shareType) {
case \OCP\Share::SHARE_TYPE_REMOTE:
$shareWith = rtrim($shareWith, '/');
$itemSourceName = basename($path);
case \OCP\Share::SHARE_TYPE_USER:
case \OCP\Share::SHARE_TYPE_GROUP:
$permissions = isset($_POST['permissions']) ? (int)$_POST['permissions'] : 31;
break;
case \OCP\Share::SHARE_TYPE_LINK:
//allow password protection
$shareWith = isset($_POST['password']) ? $_POST['password'] : null;
//check public link share
$publicUploadEnabled = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_public_upload', 'yes');
if(isset($_POST['publicUpload']) && $publicUploadEnabled !== 'yes') {
return new \OC_OCS_Result(null, 403, "public upload disabled by the administrator");
}
$publicUpload = isset($_POST['publicUpload']) ? $_POST['publicUpload'] : 'false';
// read, create, update (7) if public upload is enabled or
// read (1) if public upload is disabled
$permissions = $publicUpload === 'true' ? 7 : 1;
// Get the expiration date
try {
$expirationDate = isset($_POST['expireDate']) ? self::parseDate($_POST['expireDate']) : null;
} catch (\Exception $e) {
return new \OC_OCS_Result(null, 404, 'Invalid Date. Format must be YYYY-MM-DD.');
}
break;
default:
return new \OC_OCS_Result(null, 400, "unknown share type");
}
if (($permissions & \OCP\Constants::PERMISSION_READ) === 0) {
return new \OC_OCS_Result(null, 400, 'invalid permissions');
}
try {
$token = \OCP\Share::shareItem(
$itemType,
$itemSource,
$shareType,
$shareWith,
$permissions,
$itemSourceName,
$expirationDate
);
} catch (HintException $e) {
if ($e->getCode() === 0) {
return new \OC_OCS_Result(null, 400, $e->getHint());
} else {
return new \OC_OCS_Result(null, $e->getCode(), $e->getHint());
}
} catch (\Exception $e) {
return new \OC_OCS_Result(null, 403, $e->getMessage());
}
if ($token) {
$data = array();
$data['id'] = 'unknown';
$shares = \OCP\Share::getItemShared($itemType, $itemSource);
if(is_string($token)) { //public link share
foreach ($shares as $share) {
if ($share['token'] === $token) {
$data['id'] = $share['id'];
break;
}
}
$data['url'] = \OC::$server->getURLGenerator()->linkToRouteAbsolute('files_sharing.sharecontroller.showShare', ['token' => $token]);
$data['token'] = $token;
} else {
foreach ($shares as $share) {
if ($share['share_with'] === $shareWith && $share['share_type'] === $shareType) {
$data['id'] = $share['id'];
break;
}
}
}
$data['permissions'] = $share['permissions'];
$data['expiration'] = $share['expiration'];
return new \OC_OCS_Result($data);
} else {
return new \OC_OCS_Result(null, 404, "couldn't share file");
}
}
/**
* update shares, e.g. password, permissions, etc
* @param array $params shareId 'id' and the parameter we want to update
* currently supported: permissions, password, publicUpload
* @return \OC_OCS_Result
*/
public static function updateShare($params) {
$share = self::getShareFromId($params['id']);
if(!isset($share['file_source'])) {
return new \OC_OCS_Result(null, 404, "wrong share Id, share doesn't exist.");
}
try {
if(isset($params['_put']['permissions'])) {
return self::updatePermissions($share, $params);
} elseif (isset($params['_put']['password'])) {
return self::updatePassword($params['id'], (int)$share['share_type'], $params['_put']['password']);
} elseif (isset($params['_put']['publicUpload'])) {
return self::updatePublicUpload($share, $params);
} elseif (isset($params['_put']['expireDate'])) {
return self::updateExpireDate($share, $params);
}
} catch (\Exception $e) {
return new \OC_OCS_Result(null, 400, $e->getMessage());
}
return new \OC_OCS_Result(null, 400, "Wrong or no update parameter given");
}
/**
* update permissions for a share
* @param array $share information about the share
* @param array $params contains 'permissions'
* @return \OC_OCS_Result
*/
private static function updatePermissions($share, $params) {
$itemSource = $share['item_source'];
$itemType = $share['item_type'];
$shareWith = $share['share_with'];
$shareType = $share['share_type'];
$permissions = isset($params['_put']['permissions']) ? (int)$params['_put']['permissions'] : null;
$publicUploadStatus = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_public_upload', 'yes');
$publicUploadEnabled = ($publicUploadStatus === 'yes') ? true : false;
// only change permissions for public shares if public upload is enabled
// and we want to set permissions to 1 (read only) or 7 (allow upload)
if ( (int)$shareType === \OCP\Share::SHARE_TYPE_LINK ) {
if ($publicUploadEnabled === false || ($permissions !== 7 && $permissions !== 1)) {
return new \OC_OCS_Result(null, 400, "can't change permission for public link share");
}
}
if (($permissions & \OCP\Constants::PERMISSION_READ) === 0) {
return new \OC_OCS_Result(null, 400, 'invalid permissions');
}
try {
$return = \OCP\Share::setPermissions(
$itemType,
$itemSource,
$shareType,
$shareWith,
$permissions
);
} catch (\Exception $e) {
return new \OC_OCS_Result(null, 404, $e->getMessage());
}
if ($return) {
return new \OC_OCS_Result();
} else {
return new \OC_OCS_Result(null, 404, "couldn't set permissions");
}
}
/**
* enable/disable public upload
* @param array $share information about the share
* @param array $params contains 'publicUpload' which can be 'yes' or 'no'
* @return \OC_OCS_Result
*/
private static function updatePublicUpload($share, $params) {
$publicUploadEnabled = \OC::$server->getAppConfig()->getValue('core', 'shareapi_allow_public_upload', 'yes');
if($publicUploadEnabled !== 'yes') {
return new \OC_OCS_Result(null, 403, "public upload disabled by the administrator");
}
if ($share['item_type'] !== 'folder' ||
(int)$share['share_type'] !== \OCP\Share::SHARE_TYPE_LINK ) {
return new \OC_OCS_Result(null, 400, "public upload is only possible for public shared folders");
}
// read, create, update (7) if public upload is enabled or
// read (1) if public upload is disabled
$params['_put']['permissions'] = $params['_put']['publicUpload'] === 'true' ? 7 : 1;
return self::updatePermissions($share, $params);
}
/**
* set expire date for public link share
* @param array $share information about the share
* @param array $params contains 'expireDate' which needs to be a well formated date string, e.g DD-MM-YYYY
* @return \OC_OCS_Result
*/
private static function updateExpireDate($share, $params) {
// only public links can have a expire date
if ((int)$share['share_type'] !== \OCP\Share::SHARE_TYPE_LINK ) {
return new \OC_OCS_Result(null, 400, "expire date only exists for public link shares");
}
try {
$expireDateSet = \OCP\Share::setExpirationDate($share['item_type'], $share['item_source'], $params['_put']['expireDate'], (int)$share['stime']);
$result = ($expireDateSet) ? new \OC_OCS_Result() : new \OC_OCS_Result(null, 404, "couldn't set expire date");
} catch (\Exception $e) {
$result = new \OC_OCS_Result(null, 404, $e->getMessage());
}
return $result;
}
/**
* update password for public link share
* @param int $shareId
* @param int $shareType
* @param string $password
* @return \OC_OCS_Result
*/
private static function updatePassword($shareId, $shareType, $password) {
if($shareType !== \OCP\Share::SHARE_TYPE_LINK) {
return new \OC_OCS_Result(null, 400, "password protection is only supported for public shares");
}
if($password === '') {
$password = null;
}
try {
$result = \OCP\Share::setPassword($shareId, $password);
} catch (\Exception $e) {
return new \OC_OCS_Result(null, 403, $e->getMessage());
}
if($result) {
return new \OC_OCS_Result();
}
return new \OC_OCS_Result(null, 404, "couldn't set password");
}
/**
* unshare a file/folder
* @param array $params contains the shareID 'id' which should be unshared
* @return \OC_OCS_Result
*/
public static function deleteShare($params) {
$share = self::getShareFromId($params['id']);
$fileSource = isset($share['file_source']) ? $share['file_source'] : null;
$itemType = isset($share['item_type']) ? $share['item_type'] : null;;
if($fileSource === null) {
return new \OC_OCS_Result(null, 404, "wrong share ID, share doesn't exist.");
}
$shareWith = isset($share['share_with']) ? $share['share_with'] : null;
$shareType = isset($share['share_type']) ? (int)$share['share_type'] : null;
if( $shareType === \OCP\Share::SHARE_TYPE_LINK) {
$shareWith = null;
}
try {
$return = \OCP\Share::unshare(
$itemType,
$fileSource,
$shareType,
$shareWith);
} catch (\Exception $e) {
return new \OC_OCS_Result(null, 404, $e->getMessage());
}
if ($return) {
return new \OC_OCS_Result();
} else {
$msg = "Unshare Failed";
return new \OC_OCS_Result(null, 404, $msg);
}
}
/**
* Make sure that the passed date is valid ISO 8601
* So YYYY-MM-DD
* If not throw an exception
*
* @param string $expireDate
*
* @throws \Exception
* @return \DateTime
*/
private static function parseDate($expireDate) {
if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $expireDate) === 0) {
throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
}
$date = new \DateTime($expireDate);
if ($date === false) {
throw new \Exception('Invalid date. Format must be YYYY-MM-DD');
}
return $date;
}
/**
* get file ID from a given path
* @param string $path
* @return string fileID or null
*/
private static function getFileId($path) {
$view = new \OC\Files\View('/'.\OCP\User::getUser().'/files');
$fileId = null;
$fileInfo = $view->getFileInfo($path);
if ($fileInfo) {
$fileId = $fileInfo['fileid'];
}
return $fileId;
}
/**
* get itemType
* @param string $path
* @return string type 'file', 'folder' or null of file/folder doesn't exists
*/
private static function getItemType($path) {
$view = new \OC\Files\View('/'.\OCP\User::getUser().'/files');
$itemType = null;
if ($view->is_dir($path)) {
$itemType = "folder";
} elseif ($view->is_file($path)) {
$itemType = "file";
}
return $itemType;
}
/**
* get some information from a given share
* @param int $shareID
* @return array with: item_source, share_type, share_with, item_type, permissions
*/
private static function getShareFromId($shareID) {
$sql = 'SELECT `file_source`, `item_source`, `share_type`, `share_with`, `item_type`, `permissions`, `stime` FROM `*PREFIX*share` WHERE `id` = ?';
$args = array($shareID);
$query = \OCP\DB::prepare($sql);
$result = $query->execute($args);
if (\OCP\DB::isError($result)) {
\OCP\Util::writeLog('files_sharing', \OCP\DB::getErrorMessage(), \OCP\Util::ERROR);
return null;
}
if ($share = $result->fetchRow()) {
return $share;
}
return null;
}
}
| lrytz/core | apps/files_sharing/api/local.php | PHP | agpl-3.0 | 20,004 |
class BookshelfStory < ActiveRecord::Base
belongs_to :bookshelf
belongs_to :story
validates :story_id, uniqueness: {scope: :bookshelf_id}
after_save :notify_author
def notify_author
Notification.create(event: :story_added_to_bookshelf,
subject: story,
secondary_subject: bookshelf,
user: story.user)
end
end
| noidedmedia/Fiction-Dock | app/models/bookshelf_story.rb | Ruby | agpl-3.0 | 397 |
"""
Learning Tools Interoperability (LTI) module.
Resources
---------
Theoretical background and detailed specifications of LTI can be found on:
http://www.imsglobal.org/LTI/v1p1p1/ltiIMGv1p1p1.html
This module is based on the version 1.1.1 of the LTI specifications by the
IMS Global authority. For authentication, it uses OAuth1.
When responding back to the LTI tool provider, we must issue a correct
response. Types of responses and their message payload is available at:
Table A1.2 Interpretation of the 'CodeMajor/severity' matrix.
http://www.imsglobal.org/gws/gwsv1p0/imsgws_wsdlBindv1p0.html
A resource to test the LTI protocol (PHP realization):
http://www.imsglobal.org/developers/LTI/test/v1p1/lms.php
We have also begun to add support for LTI 1.2/2.0. We will keep this
docstring in synch with what support is available. The first LTI 2.0
feature to be supported is the REST API results service, see specification
at
http://www.imsglobal.org/lti/ltiv2p0/uml/purl.imsglobal.org/vocab/lis/v2/outcomes/Result/service.html
What is supported:
------------------
1.) Display of simple LTI in iframe or a new window.
2.) Multiple LTI components on a single page.
3.) The use of multiple LTI providers per course.
4.) Use of advanced LTI component that provides back a grade.
A) LTI 1.1.1 XML endpoint
a.) The LTI provider sends back a grade to a specified URL.
b.) Currently only action "update" is supported. "Read", and "delete"
actions initially weren't required.
B) LTI 2.0 Result Service JSON REST endpoint
(http://www.imsglobal.org/lti/ltiv2p0/uml/purl.imsglobal.org/vocab/lis/v2/outcomes/Result/service.html)
a.) Discovery of all such LTI http endpoints for a course. External tools GET from this discovery
endpoint and receive URLs for interacting with individual grading units.
(see lms/djangoapps/courseware/views.py:get_course_lti_endpoints)
b.) GET, PUT and DELETE in LTI Result JSON binding
(http://www.imsglobal.org/lti/ltiv2p0/mediatype/application/vnd/ims/lis/v2/result+json/index.html)
for a provider to synchronize grades into edx-platform. Reading, Setting, and Deleteing
Numeric grades between 0 and 1 and text + basic HTML feedback comments are supported, via
GET / PUT / DELETE HTTP methods respectively
"""
import datetime
from django.utils.timezone import UTC
import logging
import oauthlib.oauth1
from oauthlib.oauth1.rfc5849 import signature
import hashlib
import base64
import urllib
import textwrap
import bleach
from lxml import etree
from webob import Response
import mock
from xml.sax.saxutils import escape
from xmodule.editing_module import MetadataOnlyEditingDescriptor
from xmodule.raw_module import EmptyDataRawDescriptor
from xmodule.x_module import XModule, module_attr
from xmodule.course_module import CourseDescriptor
from xmodule.lti_2_util import LTI20ModuleMixin, LTIError
from pkg_resources import resource_string
from xblock.core import String, Scope, List, XBlock
from xblock.fields import Boolean, Float
log = logging.getLogger(__name__)
# Make '_' a no-op so we can scrape strings
_ = lambda text: text
DOCS_ANCHOR_TAG_OPEN = (
"<a target='_blank' "
"href='http://edx.readthedocs.org/projects/ca/en/latest/exercises_tools/lti_component.html'>"
)
class LTIFields(object):
"""
Fields to define and obtain LTI tool from provider are set here,
except credentials, which should be set in course settings::
`lti_id` is id to connect tool with credentials in course settings. It should not contain :: (double semicolon)
`launch_url` is launch URL of tool.
`custom_parameters` are additional parameters to navigate to proper book and book page.
For example, for Vitalsource provider, `launch_url` should be
*https://bc-staging.vitalsource.com/books/book*,
and to get to proper book and book page, you should set custom parameters as::
vbid=put_book_id_here
book_location=page/put_page_number_here
Default non-empty URL for `launch_url` is needed due to oauthlib demand (URL scheme should be presented)::
https://github.com/idan/oauthlib/blob/master/oauthlib/oauth1/rfc5849/signature.py#L136
"""
display_name = String(
display_name=_("Display Name"),
help=_(
"Enter the name that students see for this component. "
"Analytics reports may also use the display name to identify this component."
),
scope=Scope.settings,
default="LTI",
)
lti_id = String(
display_name=_("LTI ID"),
help=_(
"Enter the LTI ID for the external LTI provider. "
"This value must be the same LTI ID that you entered in the "
"LTI Passports setting on the Advanced Settings page."
"<br />See {docs_anchor_open}the edX LTI documentation{anchor_close} for more details on this setting."
).format(
docs_anchor_open=DOCS_ANCHOR_TAG_OPEN,
anchor_close="</a>"
),
default='',
scope=Scope.settings
)
launch_url = String(
display_name=_("LTI URL"),
help=_(
"Enter the URL of the external tool that this component launches. "
"This setting is only used when Hide External Tool is set to False."
"<br />See {docs_anchor_open}the edX LTI documentation{anchor_close} for more details on this setting."
).format(
docs_anchor_open=DOCS_ANCHOR_TAG_OPEN,
anchor_close="</a>"
),
default='http://www.example.com',
scope=Scope.settings)
custom_parameters = List(
display_name=_("Custom Parameters"),
help=_(
"Add the key/value pair for any custom parameters, such as the page your e-book should open to or "
"the background color for this component."
"<br />See {docs_anchor_open}the edX LTI documentation{anchor_close} for more details on this setting."
).format(
docs_anchor_open=DOCS_ANCHOR_TAG_OPEN,
anchor_close="</a>"
),
scope=Scope.settings)
open_in_a_new_page = Boolean(
display_name=_("Open in New Page"),
help=_(
"Select True if you want students to click a link that opens the LTI tool in a new window. "
"Select False if you want the LTI content to open in an IFrame in the current page. "
"This setting is only used when Hide External Tool is set to False. "
),
default=True,
scope=Scope.settings
)
has_score = Boolean(
display_name=_("Scored"),
help=_(
"Select True if this component will receive a numerical score from the external LTI system."
),
default=False,
scope=Scope.settings
)
weight = Float(
display_name=_("Weight"),
help=_(
"Enter the number of points possible for this component. "
"The default value is 1.0. "
"This setting is only used when Scored is set to True."
),
default=1.0,
scope=Scope.settings,
values={"min": 0},
)
module_score = Float(
help=_("The score kept in the xblock KVS -- duplicate of the published score in django DB"),
default=None,
scope=Scope.user_state
)
score_comment = String(
help=_("Comment as returned from grader, LTI2.0 spec"),
default="",
scope=Scope.user_state
)
hide_launch = Boolean(
display_name=_("Hide External Tool"),
help=_(
"Select True if you want to use this component as a placeholder for syncing with an external grading "
"system rather than launch an external tool. "
"This setting hides the Launch button and any IFrames for this component."
),
default=False,
scope=Scope.settings
)
# Users will be presented with a message indicating that their e-mail/username would be sent to a third
# party application. When "Open in New Page" is not selected, the tool automatically appears without any user action.
ask_to_send_username = Boolean(
display_name=_("Request user's username"),
# Translators: This is used to request the user's username for a third party service.
# Usernames can only be requested if "Open in New Page" is set to True.
help=_(
"Select True to request the user's username. You must also set Open in New Page to True to get the user's information."
),
default=False,
scope=Scope.settings
)
ask_to_send_email = Boolean(
display_name=_("Request user's email"),
# Translators: This is used to request the user's email for a third party service.
# Emails can only be requested if "Open in New Page" is set to True.
help=_(
"Select True to request the user's email address. You must also set Open in New Page to True to get the user's information."
),
default=False,
scope=Scope.settings
)
description = String(
display_name=_("LTI Application Information"),
help=_(
"Enter a description of the third party application. If requesting username and/or email, use this text box to inform users "
"why their username and/or email will be forwarded to a third party application."
),
default="",
scope=Scope.settings
)
button_text = String(
display_name=_("Button Text"),
help=_(
"Enter the text on the button used to launch the third party application."
),
default="",
scope=Scope.settings
)
accept_grades_past_due = Boolean(
display_name=_("Accept grades past deadline"),
help=_("Select True to allow third party systems to post grades past the deadline."),
default=True,
scope=Scope.settings
)
class LTIModule(LTIFields, LTI20ModuleMixin, XModule):
"""
Module provides LTI integration to course.
Except usual Xmodule structure it proceeds with OAuth signing.
How it works::
1. Get credentials from course settings.
2. There is minimal set of parameters need to be signed (presented for Vitalsource)::
user_id
oauth_callback
lis_outcome_service_url
lis_result_sourcedid
launch_presentation_return_url
lti_message_type
lti_version
roles
*+ all custom parameters*
These parameters should be encoded and signed by *OAuth1* together with
`launch_url` and *POST* request type.
3. Signing proceeds with client key/secret pair obtained from course settings.
That pair should be obtained from LTI provider and set into course settings by course author.
After that signature and other OAuth data are generated.
OAuth data which is generated after signing is usual::
oauth_callback
oauth_nonce
oauth_consumer_key
oauth_signature_method
oauth_timestamp
oauth_version
4. All that data is passed to form and sent to LTI provider server by browser via
autosubmit via JavaScript.
Form example::
<form
action="${launch_url}"
name="ltiLaunchForm-${element_id}"
class="ltiLaunchForm"
method="post"
target="ltiLaunchFrame-${element_id}"
encType="application/x-www-form-urlencoded"
>
<input name="launch_presentation_return_url" value="" />
<input name="lis_outcome_service_url" value="" />
<input name="lis_result_sourcedid" value="" />
<input name="lti_message_type" value="basic-lti-launch-request" />
<input name="lti_version" value="LTI-1p0" />
<input name="oauth_callback" value="about:blank" />
<input name="oauth_consumer_key" value="${oauth_consumer_key}" />
<input name="oauth_nonce" value="${oauth_nonce}" />
<input name="oauth_signature_method" value="HMAC-SHA1" />
<input name="oauth_timestamp" value="${oauth_timestamp}" />
<input name="oauth_version" value="1.0" />
<input name="user_id" value="${user_id}" />
<input name="role" value="student" />
<input name="oauth_signature" value="${oauth_signature}" />
<input name="custom_1" value="${custom_param_1_value}" />
<input name="custom_2" value="${custom_param_2_value}" />
<input name="custom_..." value="${custom_param_..._value}" />
<input type="submit" value="Press to Launch" />
</form>
5. LTI provider has same secret key and it signs data string via *OAuth1* and compares signatures.
If signatures are correct, LTI provider redirects iframe source to LTI tool web page,
and LTI tool is rendered to iframe inside course.
Otherwise error message from LTI provider is generated.
"""
js = {
'js': [
resource_string(__name__, 'js/src/lti/lti.js')
]
}
css = {'scss': [resource_string(__name__, 'css/lti/lti.scss')]}
js_module_name = "LTI"
def get_input_fields(self):
# LTI provides a list of default parameters that might be passed as
# part of the POST data. These parameters should not be prefixed.
# Likewise, The creator of an LTI link can add custom key/value parameters
# to a launch which are to be included with the launch of the LTI link.
# In this case, we will automatically add `custom_` prefix before this parameters.
# See http://www.imsglobal.org/LTI/v1p1p1/ltiIMGv1p1p1.html#_Toc316828520
PARAMETERS = [
"lti_message_type",
"lti_version",
"resource_link_title",
"resource_link_description",
"user_image",
"lis_person_name_given",
"lis_person_name_family",
"lis_person_name_full",
"lis_person_contact_email_primary",
"lis_person_sourcedid",
"role_scope_mentor",
"context_type",
"context_title",
"context_label",
"launch_presentation_locale",
"launch_presentation_document_target",
"launch_presentation_css_url",
"launch_presentation_width",
"launch_presentation_height",
"launch_presentation_return_url",
"tool_consumer_info_product_family_code",
"tool_consumer_info_version",
"tool_consumer_instance_guid",
"tool_consumer_instance_name",
"tool_consumer_instance_description",
"tool_consumer_instance_url",
"tool_consumer_instance_contact_email",
]
client_key, client_secret = self.get_client_key_secret()
# parsing custom parameters to dict
custom_parameters = {}
for custom_parameter in self.custom_parameters:
try:
param_name, param_value = [p.strip() for p in custom_parameter.split('=', 1)]
except ValueError:
_ = self.runtime.service(self, "i18n").ugettext
msg = _('Could not parse custom parameter: {custom_parameter}. Should be "x=y" string.').format(
custom_parameter="{0!r}".format(custom_parameter)
)
raise LTIError(msg)
# LTI specs: 'custom_' should be prepended before each custom parameter, as pointed in link above.
if param_name not in PARAMETERS:
param_name = 'custom_' + param_name
custom_parameters[unicode(param_name)] = unicode(param_value)
return self.oauth_params(
custom_parameters,
client_key,
client_secret,
)
def get_context(self):
"""
Returns a context.
"""
# use bleach defaults. see https://github.com/jsocol/bleach/blob/master/bleach/__init__.py
# ALLOWED_TAGS are
# ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li', 'ol', 'strong', 'ul']
#
# ALLOWED_ATTRIBUTES are
# 'a': ['href', 'title'],
# 'abbr': ['title'],
# 'acronym': ['title'],
#
# This lets all plaintext through.
sanitized_comment = bleach.clean(self.score_comment)
return {
'input_fields': self.get_input_fields(),
# These parameters do not participate in OAuth signing.
'launch_url': self.launch_url.strip(),
'element_id': self.location.html_id(),
'element_class': self.category,
'open_in_a_new_page': self.open_in_a_new_page,
'display_name': self.display_name,
'form_url': self.runtime.handler_url(self, 'preview_handler').rstrip('/?'),
'hide_launch': self.hide_launch,
'has_score': self.has_score,
'weight': self.weight,
'module_score': self.module_score,
'comment': sanitized_comment,
'description': self.description,
'ask_to_send_username': self.ask_to_send_username,
'ask_to_send_email': self.ask_to_send_email,
'button_text': self.button_text,
'accept_grades_past_due': self.accept_grades_past_due,
}
def get_html(self):
"""
Renders parameters to template.
"""
return self.system.render_template('lti.html', self.get_context())
@XBlock.handler
def preview_handler(self, _, __):
"""
This is called to get context with new oauth params to iframe.
"""
template = self.system.render_template('lti_form.html', self.get_context())
return Response(template, content_type='text/html')
def get_user_id(self):
user_id = self.runtime.anonymous_student_id
assert user_id is not None
return unicode(urllib.quote(user_id))
def get_outcome_service_url(self, service_name="grade_handler"):
"""
Return URL for storing grades.
To test LTI on sandbox we must use http scheme.
While testing locally and on Jenkins, mock_lti_server use http.referer
to obtain scheme, so it is ok to have http(s) anyway.
The scheme logic is handled in lms/lib/xblock/runtime.py
"""
return self.runtime.handler_url(self, service_name, thirdparty=True).rstrip('/?')
def get_resource_link_id(self):
"""
This is an opaque unique identifier that the TC guarantees will be unique
within the TC for every placement of the link.
If the tool / activity is placed multiple times in the same context,
each of those placements will be distinct.
This value will also change if the item is exported from one system or
context and imported into another system or context.
This parameter is required.
Example: u'edx.org-i4x-2-3-lti-31de800015cf4afb973356dbe81496df'
Hostname, edx.org,
makes resource_link_id change on import to another system.
Last part of location, location.name - 31de800015cf4afb973356dbe81496df,
is random hash, updated by course_id,
this makes resource_link_id unique inside single course.
First part of location is tag-org-course-category, i4x-2-3-lti.
Location.name itself does not change on import to another course,
but org and course_id change.
So together with org and course_id in a form of
i4x-2-3-lti-31de800015cf4afb973356dbe81496df this part of resource_link_id:
makes resource_link_id to be unique among courses inside same system.
"""
return unicode(urllib.quote("{}-{}".format(self.system.hostname, self.location.html_id())))
def get_lis_result_sourcedid(self):
"""
This field contains an identifier that indicates the LIS Result Identifier (if any)
associated with this launch. This field identifies a unique row and column within the
TC gradebook. This field is unique for every combination of context_id / resource_link_id / user_id.
This value may change for a particular resource_link_id / user_id from one launch to the next.
The TP should only retain the most recent value for this field for a particular resource_link_id / user_id.
This field is generally optional, but is required for grading.
"""
return "{context}:{resource_link}:{user_id}".format(
context=urllib.quote(self.context_id),
resource_link=self.get_resource_link_id(),
user_id=self.get_user_id()
)
def get_course(self):
"""
Return course by course id.
"""
return self.descriptor.runtime.modulestore.get_course(self.course_id)
@property
def context_id(self):
"""
Return context_id.
context_id is an opaque identifier that uniquely identifies the context (e.g., a course)
that contains the link being launched.
"""
return self.course_id.to_deprecated_string()
@property
def role(self):
"""
Get system user role and convert it to LTI role.
"""
roles = {
'student': u'Student',
'staff': u'Administrator',
'instructor': u'Instructor',
}
return roles.get(self.system.get_user_role(), u'Student')
def oauth_params(self, custom_parameters, client_key, client_secret):
"""
Signs request and returns signature and OAuth parameters.
`custom_paramters` is dict of parsed `custom_parameter` field
`client_key` and `client_secret` are LTI tool credentials.
Also *anonymous student id* is passed to template and therefore to LTI provider.
"""
client = oauthlib.oauth1.Client(
client_key=unicode(client_key),
client_secret=unicode(client_secret)
)
# Must have parameters for correct signing from LTI:
body = {
u'user_id': self.get_user_id(),
u'oauth_callback': u'about:blank',
u'launch_presentation_return_url': '',
u'lti_message_type': u'basic-lti-launch-request',
u'lti_version': 'LTI-1p0',
u'roles': self.role,
# Parameters required for grading:
u'resource_link_id': self.get_resource_link_id(),
u'lis_result_sourcedid': self.get_lis_result_sourcedid(),
u'context_id': self.context_id,
}
if self.has_score:
body.update({
u'lis_outcome_service_url': self.get_outcome_service_url()
})
self.user_email = ""
self.user_username = ""
# Username and email can't be sent in studio mode, because the user object is not defined.
# To test functionality test in LMS
if callable(self.runtime.get_real_user):
real_user_object = self.runtime.get_real_user(self.runtime.anonymous_student_id)
try:
self.user_email = real_user_object.email
except AttributeError:
self.user_email = ""
try:
self.user_username = real_user_object.username
except AttributeError:
self.user_username = ""
if self.open_in_a_new_page:
if self.ask_to_send_username and self.user_username:
body["lis_person_sourcedid"] = self.user_username
if self.ask_to_send_email and self.user_email:
body["lis_person_contact_email_primary"] = self.user_email
# Appending custom parameter for signing.
body.update(custom_parameters)
headers = {
# This is needed for body encoding:
'Content-Type': 'application/x-www-form-urlencoded',
}
try:
__, headers, __ = client.sign(
unicode(self.launch_url.strip()),
http_method=u'POST',
body=body,
headers=headers)
except ValueError: # Scheme not in url.
# https://github.com/idan/oauthlib/blob/master/oauthlib/oauth1/rfc5849/signature.py#L136
# Stubbing headers for now:
headers = {
u'Content-Type': u'application/x-www-form-urlencoded',
u'Authorization': u'OAuth oauth_nonce="80966668944732164491378916897", \
oauth_timestamp="1378916897", oauth_version="1.0", oauth_signature_method="HMAC-SHA1", \
oauth_consumer_key="", oauth_signature="frVp4JuvT1mVXlxktiAUjQ7%2F1cw%3D"'}
params = headers['Authorization']
# Parse headers to pass to template as part of context:
params = dict([param.strip().replace('"', '').split('=') for param in params.split(',')])
params[u'oauth_nonce'] = params[u'OAuth oauth_nonce']
del params[u'OAuth oauth_nonce']
# oauthlib encodes signature with
# 'Content-Type': 'application/x-www-form-urlencoded'
# so '='' becomes '%3D'.
# We send form via browser, so browser will encode it again,
# So we need to decode signature back:
params[u'oauth_signature'] = urllib.unquote(params[u'oauth_signature']).decode('utf8')
# Add LTI parameters to OAuth parameters for sending in form.
params.update(body)
return params
def max_score(self):
return self.weight if self.has_score else None
@XBlock.handler
def grade_handler(self, request, suffix): # pylint: disable=unused-argument
"""
This is called by courseware.module_render, to handle an AJAX call.
Used only for grading. Returns XML response.
Example of request body from LTI provider::
<?xml version = "1.0" encoding = "UTF-8"?>
<imsx_POXEnvelopeRequest xmlns = "some_link (may be not required)">
<imsx_POXHeader>
<imsx_POXRequestHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>528243ba5241b</imsx_messageIdentifier>
</imsx_POXRequestHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>
<replaceResultRequest>
<resultRecord>
<sourcedGUID>
<sourcedId>feb-123-456-2929::28883</sourcedId>
</sourcedGUID>
<result>
<resultScore>
<language>en-us</language>
<textString>0.4</textString>
</resultScore>
</result>
</resultRecord>
</replaceResultRequest>
</imsx_POXBody>
</imsx_POXEnvelopeRequest>
Example of correct/incorrect answer XML body:: see response_xml_template.
"""
response_xml_template = textwrap.dedent("""\
<?xml version="1.0" encoding="UTF-8"?>
<imsx_POXEnvelopeResponse xmlns = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0">
<imsx_POXHeader>
<imsx_POXResponseHeaderInfo>
<imsx_version>V1.0</imsx_version>
<imsx_messageIdentifier>{imsx_messageIdentifier}</imsx_messageIdentifier>
<imsx_statusInfo>
<imsx_codeMajor>{imsx_codeMajor}</imsx_codeMajor>
<imsx_severity>status</imsx_severity>
<imsx_description>{imsx_description}</imsx_description>
<imsx_messageRefIdentifier>
</imsx_messageRefIdentifier>
</imsx_statusInfo>
</imsx_POXResponseHeaderInfo>
</imsx_POXHeader>
<imsx_POXBody>{response}</imsx_POXBody>
</imsx_POXEnvelopeResponse>
""")
# Returns when `action` is unsupported.
# Supported actions:
# - replaceResultRequest.
unsupported_values = {
'imsx_codeMajor': 'unsupported',
'imsx_description': 'Target does not support the requested operation.',
'imsx_messageIdentifier': 'unknown',
'response': ''
}
# Returns if:
# - past due grades are not accepted and grade is past due
# - score is out of range
# - can't parse response from TP;
# - can't verify OAuth signing or OAuth signing is incorrect.
failure_values = {
'imsx_codeMajor': 'failure',
'imsx_description': 'The request has failed.',
'imsx_messageIdentifier': 'unknown',
'response': ''
}
if not self.accept_grades_past_due and self.is_past_due():
failure_values['imsx_description'] = "Grade is past due"
return Response(response_xml_template.format(**failure_values), content_type="application/xml")
try:
imsx_messageIdentifier, sourcedId, score, action = self.parse_grade_xml_body(request.body)
except Exception as e:
error_message = "Request body XML parsing error: " + escape(e.message)
log.debug("[LTI]: " + error_message)
failure_values['imsx_description'] = error_message
return Response(response_xml_template.format(**failure_values), content_type="application/xml")
# Verify OAuth signing.
try:
self.verify_oauth_body_sign(request)
except (ValueError, LTIError) as e:
failure_values['imsx_messageIdentifier'] = escape(imsx_messageIdentifier)
error_message = "OAuth verification error: " + escape(e.message)
failure_values['imsx_description'] = error_message
log.debug("[LTI]: " + error_message)
return Response(response_xml_template.format(**failure_values), content_type="application/xml")
real_user = self.system.get_real_user(urllib.unquote(sourcedId.split(':')[-1]))
if not real_user: # that means we can't save to database, as we do not have real user id.
failure_values['imsx_messageIdentifier'] = escape(imsx_messageIdentifier)
failure_values['imsx_description'] = "User not found."
return Response(response_xml_template.format(**failure_values), content_type="application/xml")
if action == 'replaceResultRequest':
self.set_user_module_score(real_user, score, self.max_score())
values = {
'imsx_codeMajor': 'success',
'imsx_description': 'Score for {sourced_id} is now {score}'.format(sourced_id=sourcedId, score=score),
'imsx_messageIdentifier': escape(imsx_messageIdentifier),
'response': '<replaceResultResponse/>'
}
log.debug("[LTI]: Grade is saved.")
return Response(response_xml_template.format(**values), content_type="application/xml")
unsupported_values['imsx_messageIdentifier'] = escape(imsx_messageIdentifier)
log.debug("[LTI]: Incorrect action.")
return Response(response_xml_template.format(**unsupported_values), content_type='application/xml')
@classmethod
def parse_grade_xml_body(cls, body):
"""
Parses XML from request.body and returns parsed data
XML body should contain nsmap with namespace, that is specified in LTI specs.
Returns tuple: imsx_messageIdentifier, sourcedId, score, action
Raises Exception if can't parse.
"""
lti_spec_namespace = "http://www.imsglobal.org/services/ltiv1p1/xsd/imsoms_v1p0"
namespaces = {'def': lti_spec_namespace}
data = body.strip().encode('utf-8')
parser = etree.XMLParser(ns_clean=True, recover=True, encoding='utf-8')
root = etree.fromstring(data, parser=parser)
imsx_messageIdentifier = root.xpath("//def:imsx_messageIdentifier", namespaces=namespaces)[0].text or ''
sourcedId = root.xpath("//def:sourcedId", namespaces=namespaces)[0].text
score = root.xpath("//def:textString", namespaces=namespaces)[0].text
action = root.xpath("//def:imsx_POXBody", namespaces=namespaces)[0].getchildren()[0].tag.replace('{' + lti_spec_namespace + '}', '')
# Raise exception if score is not float or not in range 0.0-1.0 regarding spec.
score = float(score)
if not 0 <= score <= 1:
raise LTIError('score value outside the permitted range of 0-1.')
return imsx_messageIdentifier, sourcedId, score, action
def verify_oauth_body_sign(self, request, content_type='application/x-www-form-urlencoded'):
"""
Verify grade request from LTI provider using OAuth body signing.
Uses http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html::
This specification extends the OAuth signature to include integrity checks on HTTP request bodies
with content types other than application/x-www-form-urlencoded.
Arguments:
request: DjangoWebobRequest.
Raises:
LTIError if request is incorrect.
"""
client_key, client_secret = self.get_client_key_secret()
headers = {
'Authorization': unicode(request.headers.get('Authorization')),
'Content-Type': content_type,
}
sha1 = hashlib.sha1()
sha1.update(request.body)
oauth_body_hash = base64.b64encode(sha1.digest())
oauth_params = signature.collect_parameters(headers=headers, exclude_oauth_signature=False)
oauth_headers = dict(oauth_params)
oauth_signature = oauth_headers.pop('oauth_signature')
mock_request_lti_1 = mock.Mock(
uri=unicode(urllib.unquote(self.get_outcome_service_url())),
http_method=unicode(request.method),
params=oauth_headers.items(),
signature=oauth_signature
)
mock_request_lti_2 = mock.Mock(
uri=unicode(urllib.unquote(request.url)),
http_method=unicode(request.method),
params=oauth_headers.items(),
signature=oauth_signature
)
if oauth_body_hash != oauth_headers.get('oauth_body_hash'):
log.error(
"OAuth body hash verification failed, provided: {}, "
"calculated: {}, for url: {}, body is: {}".format(
oauth_headers.get('oauth_body_hash'),
oauth_body_hash,
self.get_outcome_service_url(),
request.body
)
)
raise LTIError("OAuth body hash verification is failed.")
if (not signature.verify_hmac_sha1(mock_request_lti_1, client_secret) and not
signature.verify_hmac_sha1(mock_request_lti_2, client_secret)):
log.error("OAuth signature verification failed, for "
"headers:{} url:{} method:{}".format(
oauth_headers,
self.get_outcome_service_url(),
unicode(request.method)
))
raise LTIError("OAuth signature verification has failed.")
def get_client_key_secret(self):
"""
Obtains client_key and client_secret credentials from current course.
"""
course = self.get_course()
for lti_passport in course.lti_passports:
try:
lti_id, key, secret = [i.strip() for i in lti_passport.split(':')]
except ValueError:
_ = self.runtime.service(self, "i18n").ugettext
msg = _('Could not parse LTI passport: {lti_passport}. Should be "id:key:secret" string.').format(
lti_passport='{0!r}'.format(lti_passport)
)
raise LTIError(msg)
if lti_id == self.lti_id.strip():
return key, secret
return '', ''
def is_past_due(self):
"""
Is it now past this problem's due date, including grace period?
"""
due_date = self.due # pylint: disable=no-member
if self.graceperiod is not None and due_date: # pylint: disable=no-member
close_date = due_date + self.graceperiod # pylint: disable=no-member
else:
close_date = due_date
return close_date is not None and datetime.datetime.now(UTC()) > close_date
class LTIDescriptor(LTIFields, MetadataOnlyEditingDescriptor, EmptyDataRawDescriptor):
"""
Descriptor for LTI Xmodule.
"""
module_class = LTIModule
grade_handler = module_attr('grade_handler')
preview_handler = module_attr('preview_handler')
lti_2_0_result_rest_handler = module_attr('lti_2_0_result_rest_handler')
clear_user_module_score = module_attr('clear_user_module_score')
get_outcome_service_url = module_attr('get_outcome_service_url')
| mtlchun/edx | common/lib/xmodule/xmodule/lti_module.py | Python | agpl-3.0 | 37,531 |
from datetime import datetime, date
import pytest
from pytz import UTC
from uber.config import c
from uber.models import Attendee, Session
from uber.site_sections import summary
@pytest.fixture
def birthdays():
dates = [
date(1964, 12, 30),
date(1964, 12, 31),
date(1964, 1, 1),
date(1964, 1, 2),
date(1964, 1, 9),
date(1964, 1, 10),
date(1964, 1, 11),
date(1964, 1, 12),
date(1964, 1, 30),
date(1964, 1, 31),
date(1964, 2, 1),
date(1964, 2, 2),
date(1964, 2, 27),
date(1964, 2, 28),
date(1964, 2, 29),
date(1964, 3, 1),
date(1964, 3, 2)]
attendees = []
for d in dates:
attendees.append(Attendee(
placeholder=True,
first_name='Born on',
last_name=d.strftime('%B %-d, %Y'),
ribbon=c.VOLUNTEER_RIBBON,
staffing=True,
birthdate=d))
ids = []
with Session() as session:
session.bulk_insert(attendees)
ids = [a.id for a in attendees]
yield ids
with Session() as session:
session.query(Attendee).filter(Attendee.id.in_(ids)).delete(
synchronize_session=False)
class TestBirthdayCalendar(object):
@pytest.mark.parametrize('year', [None, 2027, 2028])
def test_attendee_birthday_calendar(
self,
admin_attendee,
year,
birthdays,
monkeypatch):
if year:
assert str(year)
response = summary.Root().attendee_birthday_calendar(year=year)
else:
assert str(datetime.now(UTC).year)
response = summary.Root().attendee_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (17 + 1) # Extra line for the header
@pytest.mark.parametrize('epoch,eschaton,expected', [
(datetime(2018, 1, 10), datetime(2018, 1, 11), 2), # Normal dates
(datetime(2017, 12, 31), datetime(2018, 1, 1), 2), # Crossing the year
(datetime(2018, 1, 31), datetime(2018, 2, 1), 2), # Crossing the month
(datetime(2018, 2, 28), datetime(2018, 3, 1), 3), # Leap day
(datetime(2018, 1, 1), datetime(2018, 3, 4), 15), # Multi-month
(datetime(2017, 12, 28), datetime(2018, 3, 4), 17), # Everybody
])
def test_event_birthday_calendar(
self,
admin_attendee,
epoch,
eschaton,
expected,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', epoch)
monkeypatch.setattr(c, 'ESCHATON', eschaton)
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
lines = response.strip().split('\n')
assert len(lines) == (expected + 1) # Extra line for the header
def test_event_birthday_calendar_correct_birthday_years(
self,
admin_attendee,
birthdays,
monkeypatch):
monkeypatch.setattr(c, 'EPOCH', datetime(2017, 12, 31))
monkeypatch.setattr(c, 'ESCHATON', datetime(2018, 1, 1))
response = summary.Root().event_birthday_calendar()
if isinstance(response, bytes):
response = response.decode('utf-8')
assert '"Born on December 31, 1964\'s Birthday",2017-12-31' in response
assert '"Born on January 1, 1964\'s Birthday",2018-01-01' in response
lines = response.strip().split('\n')
assert len(lines) == (2 + 1) # Extra line for the header
| magfest/ubersystem | tests/uber/site_sections/test_summary.py | Python | agpl-3.0 | 3,732 |
/*
* Copyright (c) 2013-2016 John Connor (BM-NC49AxAjcqVcF5jNPu85Rb8MJ2d9JqZt)
*
* This file is part of vcash.
*
* vcash is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cassert>
#include <iostream>
#include <stdexcept>
#include <sstream>
#include <coin/address.hpp>
#include <coin/base58.hpp>
#include <coin/big_number.hpp>
#include <coin/hd_ecdsa.hpp>
#include <coin/hd_keychain.hpp>
#include <coin/logger.hpp>
using namespace coin;
std::uint32_t hd_keychain::g_private_version = private_version;
std::uint32_t hd_keychain::g_public_version = public_version;
/**
* The curve order.
*/
static const big_number g_curve_order(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"
);
hd_keychain::hd_keychain()
{
// ...
}
hd_keychain::hd_keychain(
const std::vector<std::uint8_t> & key,
const std::vector<std::uint8_t> & chain_code,
const std::uint32_t & child_num, const std::uint32_t & parent_fingerprint,
const std::uint32_t & depth
)
: m_depth(depth)
, m_parent_fingerprint(parent_fingerprint)
, m_child_count(child_num)
, m_chain_code(chain_code)
, m_key(key)
{
if (m_chain_code.size() != 32)
{
throw std::runtime_error("Invalid chain code.");
}
if (m_key.size() == 32)
{
big_number n;
n.set_vector_no_reverse(m_key);
if (n >= g_curve_order || n.is_zero())
{
throw std::runtime_error("Invalid key.");
}
std::vector<std::uint8_t> private_key;
private_key.push_back(0x00);
private_key.insert(private_key.end(), m_key.begin(), m_key.end());
m_key = private_key;
}
else if (m_key.size() == 33)
{
try
{
hd_ecdsa::point K(m_key);
}
catch (...)
{
throw std::runtime_error("Invalid key.");
}
}
else
{
throw std::runtime_error("Invalid key.");
}
m_version = is_private() ? g_private_version : g_public_version;
update_public_key();
m_is_valid = true;
}
hd_keychain::hd_keychain(const std::vector<std::uint8_t> & extkey)
{
if (extkey.size() != 78)
{
throw std::runtime_error("Invalid extended key length.");
}
m_version =
((std::uint32_t)extkey[0] << 24) |
((std::uint32_t)extkey[1] << 16) |
((std::uint32_t)extkey[2] << 8) |
(std::uint32_t)extkey[3]
;
m_depth = extkey[4];
m_parent_fingerprint =
((std::uint32_t)extkey[5] << 24) |
((std::uint32_t)extkey[6] << 16) |
((std::uint32_t)extkey[7] << 8) |
(std::uint32_t)extkey[8]
;
m_child_count =
((std::uint32_t)extkey[9] << 24) |
((std::uint32_t)extkey[10] << 16) |
((uint32_t)extkey[11] << 8) |
(uint32_t)extkey[12]
;
m_chain_code.assign(extkey.begin() + 13, extkey.begin() + 45);
m_key.assign(extkey.begin() + 45, extkey.begin() + 78);
update_public_key();
m_is_valid = true;
}
hd_keychain::hd_keychain(const hd_keychain & other)
{
m_is_valid = other.m_is_valid;
if (m_is_valid == true)
{
m_version = other.m_version;
m_depth = other.m_depth;
m_parent_fingerprint = other.m_parent_fingerprint;
m_child_count = other.m_child_count;
m_chain_code = other.m_chain_code;
m_key = other.m_key;
update_public_key();
}
}
hd_keychain & hd_keychain::operator = (const hd_keychain & rhs)
{
m_is_valid = rhs.m_is_valid;
if (m_is_valid == true)
{
m_version = rhs.m_version;
m_depth = rhs.m_depth;
m_parent_fingerprint = rhs.m_parent_fingerprint;
m_child_count = rhs.m_child_count;
m_chain_code = rhs.m_chain_code;
m_key = rhs.m_key;
update_public_key();
}
return *this;
}
bool hd_keychain::operator == (const hd_keychain & rhs) const
{
return
m_is_valid && rhs.m_is_valid && m_version == rhs.m_version &&
m_depth == rhs.m_depth &&
m_parent_fingerprint == rhs.m_parent_fingerprint &&
m_child_count == rhs.m_child_count &&
m_chain_code == rhs.m_chain_code && m_key == rhs.m_key
;
}
bool hd_keychain::operator != (const hd_keychain & rhs) const
{
return !(*this == rhs);
}
void hd_keychain::set_is_valid(const bool & val)
{
m_is_valid = val;
}
const bool hd_keychain::is_valid() const
{
return m_is_valid;
}
const bool hd_keychain::is_private() const
{
return m_key.size() == 33 && m_key[0] == 0x00;
}
const std::vector<std::uint8_t> hd_keychain::extended_key() const
{
std::vector<std::uint8_t> ret;
ret.push_back((std::uint32_t)m_version >> 24);
ret.push_back(((std::uint32_t)m_version >> 16) & 0xff);
ret.push_back(((std::uint32_t)m_version >> 8) & 0xff);
ret.push_back((std::uint32_t)m_version & 0xff);
ret.push_back(m_depth);
ret.push_back((std::uint32_t)m_parent_fingerprint >> 24);
ret.push_back(((std::uint32_t)m_parent_fingerprint >> 16) & 0xff);
ret.push_back(((std::uint32_t)m_parent_fingerprint >> 8) & 0xff);
ret.push_back((std::uint32_t)m_parent_fingerprint & 0xff);
ret.push_back((std::uint32_t)m_child_count >> 24);
ret.push_back(((std::uint32_t)m_child_count >> 16) & 0xff);
ret.push_back(((std::uint32_t)m_child_count >> 8) & 0xff);
ret.push_back((std::uint32_t)m_child_count & 0xff);
ret.insert(ret.end(), m_chain_code.begin(), m_chain_code.end());
ret.insert(ret.end(), m_key.begin(), m_key.end());
return ret;
}
void hd_keychain::set_version(const std::uint32_t & val)
{
m_version = val;
}
const std::uint32_t & hd_keychain::version() const
{
return m_version;
}
void hd_keychain::set_depth(const std::uint8_t & val)
{
m_depth = val;
}
const std::uint8_t & hd_keychain::depth() const
{
return m_depth;
}
void hd_keychain::set_parent_fingerprint(const std::uint32_t & val)
{
m_parent_fingerprint = val;
}
const std::uint32_t & hd_keychain::parent_fingerprint() const
{
return m_parent_fingerprint;
}
void hd_keychain::set_child_count(const std::uint32_t & val)
{
m_child_count = val;
}
const std::uint32_t & hd_keychain::child_count() const
{
return m_child_count;
}
void hd_keychain::set_chain_code(const std::vector<std::uint8_t> & val)
{
m_chain_code = val;
}
const std::vector<std::uint8_t> & hd_keychain::chain_code() const
{
return m_chain_code;
}
void hd_keychain::set_key(const std::vector<std::uint8_t> & val)
{
m_key = val;
}
const std::vector<std::uint8_t> & hd_keychain::key() const
{
return m_key;
}
std::vector<std::uint8_t> hd_keychain::privkey() const
{
if (is_private() == true)
{
return std::vector<std::uint8_t> (m_key.begin() + 1, m_key.end());
}
return std::vector<std::uint8_t> ();
}
void hd_keychain::set_pubkey(const std::vector<std::uint8_t> & val)
{
m_pubkey = val;
}
const std::vector<std::uint8_t> & hd_keychain::pubkey() const
{
return m_pubkey;
}
std::vector<std::uint8_t> hd_keychain::uncompressed_pubkey() const
{
hd_ecdsa::key k;
k.set_public_key(m_pubkey);
return k.get_public_key(false);
}
std::vector<std::uint8_t> hd_keychain::get_hash() const
{
auto digest = hash::sha256_ripemd160(&m_pubkey[0], m_pubkey.size());
return std::vector<std::uint8_t> (&digest[0], &digest[0] + digest.size());
}
std::uint32_t hd_keychain::fingerprint() const
{
auto digest = get_hash();
return
(std::uint32_t)digest[0] << 24 | (std::uint32_t)digest[1] << 16 |
(std::uint32_t)digest[2] << 8 | (std::uint32_t)digest[3]
;
}
std::vector<std::uint8_t> hd_keychain::full_hash() const
{
std::vector<std::uint8_t> data(m_pubkey);
data.insert(data.end(), m_chain_code.begin(), m_chain_code.end());
auto digest = hash::sha256_ripemd160(&data[0], data.size());
return std::vector<std::uint8_t> (&digest[0], &digest[0] + digest.size());
}
hd_keychain hd_keychain::get_public() const
{
if (m_is_valid == false)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
hd_keychain ret;
ret.set_is_valid(m_is_valid);
ret.set_version(g_public_version);
ret.set_depth(m_depth);
ret.set_parent_fingerprint(m_parent_fingerprint);
ret.set_child_count(m_child_count);
ret.set_chain_code(m_chain_code);
ret.set_key(m_pubkey);
ret.set_pubkey(m_pubkey);
return ret;
}
hd_keychain hd_keychain::get_child(const std::uint32_t & index) const
{
if (m_is_valid == false)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
bool priv_derivation = 0x80000000 & index;
if (is_private() == false && priv_derivation)
{
throw std::runtime_error(
std::string(__FUNCTION__) +
": tried to derive private key on public key."
);
}
hd_keychain ret;
ret.set_is_valid(false);
std::vector<std::uint8_t> data;
data.insert(
data.end(), (priv_derivation ? m_key : m_pubkey).begin(),
(priv_derivation ? m_key : m_pubkey).end()
);
data.push_back(index >> 24);
data.push_back((index >> 16) & 0xff);
data.push_back((index >> 8) & 0xff);
data.push_back(index & 0xff);
auto digest = crypto::hmac_sha512(m_chain_code, data);
std::vector<std::uint8_t> l32(digest.begin(), digest.begin() + 32);
big_number i_l;
i_l.set_vector_no_reverse(l32);
auto foo1 = i_l.get_hex();
auto foo2 = g_curve_order.get_hex();
if (i_l >= g_curve_order)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
if (is_private() == true)
{
big_number k;
k.set_vector_no_reverse(m_key);
k += i_l;
k %= g_curve_order;
if (k.is_zero() == true)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
auto child_key = k.get_vector_no_reverse();
std::vector<std::uint8_t> padded_key(33 - child_key.size(), 0);
padded_key.insert(
padded_key.end(), child_key.begin(), child_key.end()
);
ret.set_key(padded_key);
ret.update_public_key();
}
else
{
hd_ecdsa::point point_k;
point_k.set_bytes(m_pubkey);
point_k.generator_mul(l32);
if (point_k.is_at_infinity())
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
ret.set_key(point_k.bytes());
ret.set_pubkey(point_k.bytes());
}
ret.set_version(m_version);
ret.set_depth(m_depth + 1);
ret.set_parent_fingerprint(fingerprint());
ret.set_child_count(index);
ret.m_chain_code.assign(digest.begin() + 32, digest.end());
ret.set_is_valid(true);
return ret;
}
hd_keychain hd_keychain::get_child(const std::string & path) const
{
if (path.size() == 0)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
std::vector<uint32_t> paths;
std::size_t i = 0;
std::uint64_t n = 0;
while (i < path.size())
{
char c = path[i];
if (c >= '0' && c <= '9')
{
n *= 10;
n += (std::uint32_t)(c - '0');
if (n >= 0x80000000)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
i++;
if (i >= path.size())
{
paths.push_back((std::uint32_t)n);
}
}
else if (c == '\'')
{
if (i + 1 < path.size())
{
if (
(i + 2 >= path.size()) || (path[i + 1] != '/') ||
(path[i + 2] < '0') || (path[i + 2] > '9')
)
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
}
n |= 0x80000000;
paths.push_back((std::uint32_t)n);
n = 0;
i += 2;
}
else if (c == '/')
{
if (i + 1 >= path.size() || path[i + 1] < '0' || path[i + 1] > '9')
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
paths.push_back((std::uint32_t)n);
n = 0;
i++;
}
else
{
throw std::runtime_error(
std::string(__FUNCTION__) + ": invalid hd_keychain"
);
}
}
hd_keychain ret(*this);
for (auto i : paths)
{
ret = ret.get_child(i);
}
return ret;
}
hd_keychain hd_keychain::get_child_node(
const std::uint32_t & index, const bool & private_derivation
) const
{
std::uint32_t mask = private_derivation ? 0x80000000ull : 0x00000000ull;
return get_child(mask).get_child(index);
}
std::vector<std::uint8_t> hd_keychain::get_private_signing_key(
const std::uint32_t & index
) const
{
assert(index != 0);
return get_child(index).privkey();
}
std::vector<std::uint8_t> hd_keychain::get_public_signing_key(
const std::uint32_t & index, const bool & compressed
) const
{
assert(index != 0);
return
compressed ? get_child(index).pubkey() :
get_child(index).uncompressed_pubkey()
;
}
void hd_keychain::set_versions(
const std::uint32_t & private_version,
const std::uint32_t & public_version
)
{
g_private_version = private_version;
g_public_version = public_version;
}
std::string hd_keychain::to_string() const
{
std::stringstream ss;
ss << "hd_keychain: " << std::endl;
ss << "\tversion: " << std::hex << m_version << std::endl;
ss << "\tdepth: " << static_cast<std::int32_t> (depth()) << std::endl;
ss << "\tparent_fingerprint: " << m_parent_fingerprint << std::endl;
ss << "\tchild_num: " << m_child_count << std::endl;
ss << "\tchain_code: " << utility::hex_string(m_chain_code) << std::endl;
ss << "\tkey: " << utility::hex_string(m_key) << std::endl;
ss << "\thash: " << utility::hex_string(get_hash()) << std::endl;
return ss.str();
}
void hd_keychain::update_public_key()
{
if (is_private() == true)
{
hd_ecdsa::key key_curve;
key_curve.set_private_key(
std::vector<std::uint8_t> (m_key.begin() + 1, m_key.end())
);
m_pubkey = key_curve.get_public_key();
}
else
{
m_pubkey = m_key;
}
}
inline std::uint32_t test_p(const std::uint32_t & i)
{
return 0x80000000 | i;
}
inline bool test_is_p(const std::uint32_t & i)
{
return 0x80000000 & i;
}
std::string test_s(const std::uint32_t & i)
{
std::stringstream ss;
ss << (0x7fffffff & i);
if (test_is_p(i))
{
ss << "'";
}
return ss.str();
}
void test_show_key(const hd_keychain & keychain)
{
auto extended_key = keychain.extended_key();
base58 b58;
b58.set_data(
constants::test_net ? 111 : 0,
reinterpret_cast<char *> (&extended_key[0]), extended_key.size()
);
std::cout <<
" * ext " << (keychain.is_private() ? "prv" : "pub") << ": " <<
b58.to_string(false) <<
std::endl;
}
void test_show_step(
const std::string & chainname, const hd_keychain & public_hd_keychain,
const hd_keychain & private_hd_keychain
)
{
std::cout << "* [" << chainname << "]" << std::endl;
test_show_key(public_hd_keychain);
test_show_key(private_hd_keychain);
}
int hd_keychain::run_test()
{
#if 1
const std::vector<std::uint8_t> seed =
utility::from_hex("000102030405060708090a0b0c0d0e0f")
;
const std::uint32_t chain[] =
{
test_p(0), 1, test_p(2), 2, 1000000000
};
#else
const std::vector<std::uint8_t> seed =
utility::from_hex("fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab"
"7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754"
"514e4b484542")
;
const std::uint32_t chain[] =
{
0, test_p(2147483647), 1, test_p(2147483646), 2
};
#endif
const auto chain_length = sizeof(chain) / sizeof(std::uint32_t);
try
{
hd_keychain::set_versions(0x0488ADE4, 0x0488B21E);
std::cout << "Seed: " << utility::hex_string(seed) << std::endl;
hd_keychain::seed hd_seed(seed);
auto k = hd_seed.get_master_key();
auto c = hd_seed.get_master_chain_code();
std::stringstream chainname;
chainname << "Chain m";
hd_keychain prv(k, c);
hd_keychain pub = prv.get_public();
test_show_step(chainname.str(), pub, prv);
hd_keychain parentpub;
for (auto k = 0; k < chain_length; k++)
{
chainname << "/" << test_s(chain[k]);
if (test_is_p(chain[k]) == false)
{
parentpub = pub;
}
prv = prv.get_child(chain[k]);
assert(prv.is_valid());
pub = prv.get_public();
assert(pub.is_valid());
if (test_is_p(chain[k]) == false)
{
auto parentpubChild = parentpub.get_child(chain[k]);
assert(pub == parentpubChild);
}
test_show_step(chainname.str(), pub, prv);
}
return 0;
}
catch (const std::exception & e)
{
std::cout << "Error: " << e.what() << std::endl;
}
return 0;
}
| xCoreDev/vanillacoin | src/hd_keychain.cpp | C++ | agpl-3.0 | 19,176 |
from django.template import Library, Node, TemplateSyntaxError, Variable
from django.conf import settings
from django.core import urlresolvers
import hashlib
import re
register = Library()
class ViewNode(Node):
def __init__(self, parser, token):
self.args = []
self.kwargs = {}
tokens = token.split_contents()
if len(tokens) < 2:
raise TemplateSyntaxError("%r tag requires one or more arguments" % token.contents.split()[0])
tag_name = tokens.pop(0)
self.url_or_view = tokens.pop(0)
for token in tokens:
equals = token.find("=")
if equals == -1:
self.args.append(token)
else:
self.kwargs[str(token[:equals])] = token[equals + 1:]
def render(self, context):
print('render view tag...')
if 'request' not in context:
return ""
request = context['request']
# get the url for the view
url = Variable(self.url_or_view).resolve(context)
if not settings.USE_AJAX_REQUESTS:
# do not load the whole template, just the content, like an ajax request
#request.is_ajax = True # not needed since the jQuery.get() is implying this
urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
resolver = urlresolvers.RegexURLResolver(r'^/', urlconf)
# get the view function
view, args, kwargs = resolver.resolve(url)
try:
if callable(view):
ret = view(context['request'], *args, **kwargs).render()
return ret.rendered_content
raise Exception("%r is not callable" % view)
except:
if settings.TEMPLATE_DEBUG:
raise
else:
print('return js code for jquery')
return """<div id="%(div_id)s">loading ...</div>
<script>
$.get( "%(url)s", function( data ) {
$( "#%(div_id)s" ).html( data );
});
</script>""" % {'div_id': url.replace("/", ""), 'url': url}
return ""
register.tag('view', ViewNode)
| meymarce/overlord | overlord/templatetags/view_tag.py | Python | agpl-3.0 | 2,130 |
import { clone } from 'lodash';
export class SqlPartDef {
type: string;
style: string;
label: string;
params: any[];
defaultParams: any[];
wrapOpen: string;
wrapClose: string;
separator: string;
constructor(options: any) {
this.type = options.type;
if (options.label) {
this.label = options.label;
} else {
this.label = this.type[0].toUpperCase() + this.type.substring(1) + ':';
}
this.style = options.style;
if (this.style === 'function') {
this.wrapOpen = '(';
this.wrapClose = ')';
this.separator = ', ';
} else {
this.wrapOpen = ' ';
this.wrapClose = ' ';
this.separator = ' ';
}
this.params = options.params;
this.defaultParams = options.defaultParams;
}
}
export class SqlPart {
part: any;
def: SqlPartDef;
params: any[];
label: string;
name: string;
datatype: string;
constructor(part: any, def: any) {
this.part = part;
this.def = def;
if (!this.def) {
throw { message: 'Could not find sql part ' + part.type };
}
this.datatype = part.datatype;
if (part.name) {
this.name = part.name;
this.label = def.label + ' ' + part.name;
} else {
this.name = '';
this.label = def.label;
}
part.params = part.params || clone(this.def.defaultParams);
this.params = part.params;
}
updateParam(strValue: string, index: number) {
// handle optional parameters
if (strValue === '' && this.def.params[index].optional) {
this.params.splice(index, 1);
} else {
this.params[index] = strValue;
}
this.part.params = this.params;
}
}
| grafana/grafana | public/app/angular/components/sql_part/sql_part.ts | TypeScript | agpl-3.0 | 1,657 |
###########################################################################
# Concurrent WSGI server - webserver3h.py #
# #
# Tested with Python 2.7.9 on Ubuntu 14.04 & Mac OS X #
###########################################################################
import errno
import os
import signal
import socket
import StringIO
import sys
def grim_reaper(signum, frame):
while True:
try:
pid, status = os.waitpid(
-1, # Wait for any child process
os.WNOHANG # Do not block and return EWOULDBLOCK error
)
print(
'Child {pid} terminated with status {status}'
'\n'.format(pid=pid, status=status)
)
except OSError:
return
if pid == 0: # no more zombies
return
class WSGIServer(object):
address_family = socket.AF_INET
socket_type = socket.SOCK_STREAM
request_queue_size = 1024
def __init__(self, server_address):
# Create a listening socket
self.listen_socket = listen_socket = socket.socket(
self.address_family,
self.socket_type
)
# Allow to reuse the same address
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# Bind
listen_socket.bind(server_address)
# Activate
listen_socket.listen(self.request_queue_size)
# Get server host name and port
host, port = self.listen_socket.getsockname()[:2]
self.server_name = socket.getfqdn(host)
self.server_port = port
# Return headers set by Web framework/Web application
self.headers_set = []
def set_app(self, application):
self.application = application
def serve_forever(self):
listen_socket = self.listen_socket
while True:
try:
self.client_connection, client_address = listen_socket.accept()
except IOError as e:
code, msg = e.args
# restart 'accept' if it was interrupted
if code == errno.EINTR:
continue
else:
raise
pid = os.fork()
if pid == 0: # child
listen_socket.close() # close child copy
# Handle one request and close the client connection.
self.handle_one_request()
os._exit(0)
else: # parent
self.client_connection.close() # close parent copy
def handle_one_request(self):
self.request_data = request_data = self.client_connection.recv(1024)
# Print formatted request data a la 'curl -v'
print(''.join(
'< {line}\n'.format(line=line)
for line in request_data.splitlines()
))
self.parse_request(request_data)
# Construct environment dictionary using request data
env = self.get_environ()
# It's time to call our application callable and get
# back a result that will become HTTP response body
result = self.application(env, self.start_response)
# Construct a response and send it back to the client
self.finish_response(result)
def parse_request(self, text):
request_line = text.splitlines()[0]
request_line = request_line.rstrip('\r\n')
# Break down the request line into components
(self.request_method, # GET
self.path, # /hello
self.request_version # HTTP/1.1
) = request_line.split()
def get_environ(self):
env = {}
# The following code snippet does not follow PEP8 conventions
# but it's formatted the way it is for demonstration purposes
# to emphasize the required variables and their values
#
# Required WSGI variables
env['wsgi.version'] = (1, 0)
env['wsgi.url_scheme'] = 'http'
env['wsgi.input'] = StringIO.StringIO(self.request_data)
env['wsgi.errors'] = sys.stderr
env['wsgi.multithread'] = False
env['wsgi.multiprocess'] = False
env['wsgi.run_once'] = False
# Required CGI variables
env['REQUEST_METHOD'] = self.request_method # GET
env['PATH_INFO'] = self.path # /hello
env['SERVER_NAME'] = self.server_name # localhost
env['SERVER_PORT'] = str(self.server_port) # 8888
return env
def start_response(self, status, response_headers, exc_info=None):
# Add necessary server headers
server_headers = [
('Date', 'Tue, 31 Mar 2015 12:54:48 GMT'),
('Server', 'WSGIServer 0.2'),
]
self.headers_set = [status, response_headers + server_headers]
# To adhere to WSGI specification the start_response must return
# a 'write' callable. We simplicity's sake we'll ignore that detail
# for now.
# return self.finish_response
def finish_response(self, result):
try:
status, response_headers = self.headers_set
response = 'HTTP/1.1 {status}\r\n'.format(status=status)
for header in response_headers:
response += '{0}: {1}\r\n'.format(*header)
response += '\r\n'
for data in result:
response += data
# Print formatted response data a la 'curl -v'
print(''.join(
'> {line}\n'.format(line=line)
for line in response.splitlines()
))
self.client_connection.sendall(response)
finally:
self.client_connection.close()
SERVER_ADDRESS = (HOST, PORT) = '', 8888
def make_server(server_address, application):
signal.signal(signal.SIGCHLD, grim_reaper)
server = WSGIServer(server_address)
server.set_app(application)
return server
if __name__ == '__main__':
if len(sys.argv) < 2:
sys.exit('Provide a WSGI application object as module:callable')
app_path = sys.argv[1]
module, application = app_path.split(':')
module = __import__(module)
application = getattr(module, application)
httpd = make_server(SERVER_ADDRESS, application)
print('WSGIServer: Serving HTTP on port {port} ...\n'.format(port=PORT))
httpd.serve_forever()
| hamishcunningham/fishy-wifi | wegrow-cloudside/elf-data-collector/webserver4/server-again.py | Python | agpl-3.0 | 6,539 |
# Copyright (C) 2018 - TODAY, Pavlov Media
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from . import models
from . import wizards
| OCA/contract | agreement_legal/__init__.py | Python | agpl-3.0 | 151 |
/*
This file is part of Archivematica.
Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
Archivematica 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.
Archivematica 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 Archivematica. If not, see <http://www.gnu.org/licenses/>.
*/
var enableElements = function(cssSelectors) {
for (var index in cssSelectors) {
$(cssSelectors[index]).removeAttr('disabled');
}
};
var disableElements = function(cssSelectors) {
for (var index in cssSelectors) {
$(cssSelectors[index]).attr('disabled', 'disabled');
}
};
function setupBacklogBrowser() {
var backlogBrowserEntryClickHandler = function(event) {
if (typeof event.data != 'undefined') {
var explorer = event.data.self.container
, explorerId = explorer.id
var entryEl = this
, entryId = $(this).attr('id')
, borderCssSpec = '1px solid red';
if (explorer.selectedEntryId == entryId) {
// un-highlight selected entry
$(entryEl).css('border', '');
// remove selected entry
explorer.selectedEntryId = undefined;
} else {
// remove highlighting of existing entries
$('#' + explorerId).find('.backbone-file-explorer-entry').css('border', '');
// highlight selected entry
$(entryEl).css('border', borderCssSpec);
// change selected entry
explorer.selectedEntryId = entryId;
// enable/disable arrange panel action buttons
if (explorer.id == 'originals') {
enableOrDisableOriginalsPanelActionButtons(explorer);
}
// enable/disable arrange panel action buttons
if (explorer.id == 'arrange') {
enableOrDisableArrangePanelActionButtons(explorer);
}
}
}
}
function enableOrDisableOriginalsPanelActionButtons(originals) {
var selectedType = originals.getTypeForCssId(originals.selectedEntryId);
// enable/disable hide button
if (typeof originals.selectedEntryId !== 'undefined') {
enableElements(['#originals_hide_button']);
} else {
disableElements(['#originals_hide_button']);
}
// enable/disable buttons for actions that only work with files
if (typeof originals.selectedEntryId !== 'undefined' && selectedType == 'file') {
enableElements(['#open_originals_file_button']);
} else {
disableElements(['#open_originals_file_button']);
}
}
function enableOrDisableArrangePanelActionButtons(arrange) {
var selectedType = arrange.getTypeForCssId(arrange.selectedEntryId);
// enable/disable delete button
if (typeof arrange.selectedEntryId !== 'undefined') {
enableElements(['#arrange_delete_button']);
} else {
disableElements(['#arrange_delete_button']);
}
// enable/disable create SIP button
if (selectedType == 'directory') {
enableElements(['#arrange_create_sip_button']);
} else {
disableElements(['#arrange_create_sip_button']);
}
// enable/disable metadata button
if (typeof arrange.selectedEntryId !== 'undefined') {
enableElements(['#arrange_edit_metadata_button']);
} else {
disableElements(['#arrange_edit_metadata_button']);
}
// enable/disable create directory button
// (if nothing is selected, it'll create in top level)
if (typeof arrange.selectedEntryId === 'undefined' || selectedType == 'directory') {
enableElements(['#arrange_create_directory_button']);
} else {
disableElements(['#arrange_create_directory_button']);
}
}
function moveHandler(move) {
// don't allow moving anything into the originals directory
if (move.self.id == 'originals') {
move.self.alert('Error', "You can't copy into the originals directory.");
return;
}
if (!move.allowed) {
move.self.alert('Error', "You can't move a directory into its subdirectory.");
return;
}
// move.self is the arrange browser
move.self.busy();
// determine whether a move or copy should be performed
var source,
actionUrlPath = '/filesystem/copy_to_arrange/',
arrangeDir = '/'+Base64.decode(move.self.structure.name);
// do a move if drag and drop occurs within the arrange pane
if (
move.droppedPath.indexOf(arrangeDir) == 0
&& move.containerPath.indexOf(arrangeDir) == 0
) {
// arrange -> arrange
source = move.self.getByPath(move.droppedPath)
} else {
// originals -> arrange
// TODO don't use global if possible
source = originals.getByPath(move.droppedPath)
}
var destination = move.self.getByPath(move.containerPath);
// Add trailing / to directories
if (source.type() == 'directory') {
move.droppedPath+='/'
}
if (typeof destination == 'undefined') {
// Moving into the parent directory arrange/
// Error if source is a file
if (source.type() != 'directory') {
move.self.alert('Error', "Files must go in a SIP, not the parent directory.");
}
move.containerPath = arrangeDir+'/'
} else if (destination.type() == 'directory') {
move.containerPath+='/'
} else if (destination.type() == 'file') {
move.containerPath = move.containerPath.match(/.*\//)[0];
}
$.post(
actionUrlPath,
{
filepath: Base64.encode(move.droppedPath),
destination: Base64.encode(move.containerPath)
},
function(result) {
if (result.error == undefined) {
move.self.idle();
move.self.render();
$('#search_submit').click(); // Fetches from backlog again and renders it
} else {
alert(result.message);
move.self.idle();
}
}
);
}
var originals = new FileExplorer({
el: $('#originals'),
levelTemplate: $('#template-dir-level').html(),
entryTemplate: $('#template-dir-entry').html(),
entryClickHandler: backlogBrowserEntryClickHandler,
nameClickHandler: backlogBrowserEntryClickHandler,
// Data will be populated by backlog.js when a search is conducted
});
originals.structure = {
'name': Base64.encode('originals'),
'parent': '',
'children': []
};
originals.itemsPerPage = 10;
originals.moveHandler = moveHandler;
originals.options.actionHandlers = [];
originals.render();
enableOrDisableOriginalsPanelActionButtons(originals);
var arrange = new FileExplorer({
el: $('#arrange'),
levelTemplate: $('#template-dir-level').html(),
entryTemplate: $('#template-dir-entry').html(),
entryClickHandler: backlogBrowserEntryClickHandler,
nameClickHandler: backlogBrowserEntryClickHandler,
ajaxDeleteUrl: '/filesystem/delete/arrange/',
ajaxChildDataUrl: '/filesystem/contents/arrange/'
});
arrange.structure = {
'name': Base64.encode('arrange'),
'parent': '',
'children': []
};
arrange.itemsPerPage = 10;
arrange.options.actionHandlers = [];
arrange.moveHandler = moveHandler;
arrange.render();
enableOrDisableArrangePanelActionButtons(arrange);
// search results widget
var originals_search_results = new fileBrowser.EntryList({
el: $('#originals_search_results'),
moveHandler: moveHandler,
levelTemplate: $('#template-dir-level').html(),
entryTemplate: $('#template-dir-entry').html(),
itemsPerPage: 20
});
return {
'originals': originals,
'arrange': arrange
};
}
// spawn browsers
var originals_browser,
arrange_browser;
$(document).ready(function() {
// Monkey-patch entry toggling logic to allow auto-search of backlog
(function(originalToggleDirectoryLogic) {
var backlogSearched = false;
fileBrowser.EntryView.prototype.toggleDirectory = function($el) {
var result = originalToggleDirectoryLogic.apply(this, arguments);
// if toggling in the original panels, check to see if backlog entries have been
// added to it yet and, if not, perform search
if (this.container.id == 'originals' &&
this.container.structure.children.length == 0 &&
backlogSearched == false
) {
backlogSearched = true;
$('#search_submit').click();
}
return result;
};
})(fileBrowser.EntryView.prototype.toggleDirectory);
var browsers = setupBacklogBrowser();
originals_browser = browsers['originals'];
arrange_browser = browsers['arrange'];
originals_browser.display_data = function(data) {
// Accept and display data from an external source
// Assumes it is properly formatted already
this.structure.children = data;
// Open top level folder
this.openFolder($('#'+this.id+'__'+Base64.decode(this.structure.name)))
this.render();
}
$('#arrange_edit_metadata_button').click(function() {
// if metadata button isn't disabled, execute
if (typeof $('#arrange_edit_metadata_button').attr('disabled') === 'undefined') {
if (typeof arrange_browser.selectedEntryId === 'undefined') {
arrange_browser.alert('Edit metadata', 'Please select a directory or file to edit.');
return;
}
var path = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId);
directoryMetadataForm.show(path, function(levelOfDescription) {
var entry = arrange_browser.getByPath(path);
entry.set({'levelOfDescription': levelOfDescription});
arrange_browser.render();
});
}
});
$('#arrange_create_directory_button').click(function() {
// if create directory button isn't disabled, execute
if (typeof $('#arrange_create_directory_button').attr('disabled') === 'undefined') {
var selectedType = arrange_browser.getTypeForCssId(arrange_browser.selectedEntryId);
if (selectedType != 'directory' && typeof arrange_browser.selectedEntryId !== 'undefined') {
arrange_browser.alert('Create Directory', "You can't create a directory in a file.");
} else {
var path = prompt('Name of new directory?');
if (path) {
var path_root = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId) || '/' + Base64.decode(arrange_browser.structure.name)
, relative_path = path_root + '/' + path;
$.ajax({
url: '/filesystem/create_directory_within_arrange/',
type: 'POST',
async: false,
cache: false,
data: {
path: Base64.encode(relative_path)
},
success: function(results) {
arrange_browser.dirView.model.addDir({'name': path});
arrange_browser.render();
},
error: function(results) {
originals_browser.alert('Error', results.message);
}
});
}
}
}
});
$('#arrange_delete_button').click(function() {
if (typeof arrange_browser.selectedEntryId === 'undefined') {
arrange_browser.alert('Delete', 'Please select a directory or file to delete.');
return;
}
var path = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId)
, type = arrange_browser.getTypeForCssId(arrange_browser.selectedEntryId);
arrange_browser.confirm(
'Delete',
'Are you sure you want to delete this directory or file?',
function() {
if( type == 'directory') {
path += '/'
}
arrange_browser.deleteEntry(path, type);
arrange_browser.selectedEntryId = undefined;
$('#search_submit').click();
}
);
});
// Hide the selected object
$('#originals_hide_button').click(function () {
// Have to hide all its children too or weird behaviour
$('#' + originals_browser.selectedEntryId).next().hide();
$('#' + originals_browser.selectedEntryId).hide();
});
// create SIP button functionality
$('#arrange_create_sip_button').click(function() {
// if create SIP button isn't disabled, execute
if (typeof $('#arrange_create_sip_button').attr('disabled') === 'undefined') {
if (typeof arrange_browser.selectedEntryId === 'undefined') {
arrange_browser.alert('Create SIP', 'Please select a directory before creating a SIP.');
return
}
var entryDiv = $('#' + arrange_browser.selectedEntryId)
, path = arrange_browser.getPathForCssId(arrange_browser.selectedEntryId)
, entryObject = arrange_browser.getByPath(path)
if (entryObject.type() != 'directory') {
arrange_browser.alert('Create SIP', 'SIPs can only be created from directories, not files.')
return
}
arrange_browser.confirm(
'Create SIP',
'Are you sure you want to create a SIP?',
function() {
$('.activity-indicator').show();
$.post(
'/filesystem/copy_from_arrange/',
{filepath: Base64.encode(path+'/')},
function(result) {
$('.activity-indicator').hide();
var title = (result.error) ? 'Error' : ''
arrange_browser.alert(
title,
result.message
)
if (!result.error) {
$(entryDiv).next().hide()
$(entryDiv).hide()
}
}
)
}
)
}
});
var createOpenHandler = function(buttonCssSelector, browser) {
return function() {
// if view button isn't disabled, execute
if (typeof $(buttonCssSelector).attr('disabled') === 'undefined') {
if (typeof browser.selectedEntryId === 'undefined') {
browser.alert('Error', 'Please specifiy a file to view.');
} else {
var entryDiv = $('#' + browser.selectedEntryId)
, path = browser.getPathForCssId(browser.selectedEntryId)
, type = browser.getTypeForCssId(browser.selectedEntryId);
if (type == 'directory') {
browser.alert('Error', 'Please specifiy a file to view.');
} else {
window.open(
'/filesystem/download_ss/?filepath=' + encodeURIComponent(Base64.encode(path)),
'_blank'
);
}
}
}
};
};
// open originals file button functionality
$('#open_originals_file_button').click(createOpenHandler('#open_originals_file_button', originals_browser));
});
| sevein/archivematica | src/dashboard/src/media/js/ingest/ingest_file_browser.js | JavaScript | agpl-3.0 | 14,811 |
/* This file is part of VoltDB.
* Copyright (C) 2008-2013 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
/**
* Specifies whether the system should be run on the native C++
* backend for VoltDB, or if the system should use a JDBC
* wrapper around HSQLDB.
*
* HSQLDB is pure java, making the system very portable, and it
* supports a wide range of SQL. On the other hand, it's not as
* fast and only supports a single partition. It's best used
* for testing.
*
*/
public enum BackendTarget {
NATIVE_EE_JNI("jni", false),
NATIVE_EE_IPC("ipc", true),
NATIVE_EE_VALGRIND_IPC("valgrind_ipc", true),
HSQLDB_BACKEND("hsqldb", false),
NONE("none", false);
private BackendTarget(String display, boolean isIPC) { this.display = display; this.isIPC = isIPC; }
public final String display;
public final boolean isIPC;
}
| kobronson/cs-voltdb | src/frontend/org/voltdb/BackendTarget.java | Java | agpl-3.0 | 1,505 |
# -*- coding: utf-8 -*-
{
'name': "Better validation for Attendance",
'summary': """
Short (1 phrase/line) summary of the module's purpose, used as
subtitle on modules listing or apps.openerp.com""",
'description': """
Long description of module's purpose
""",
'author': "Jörn Mankiewicz",
'website': "http://www.yourcompany.com",
# Categories can be used to filter modules in modules listing
# Check https://github.com/odoo/odoo/blob/master/openerp/addons/base/module/module_data.xml
# for the full list
'category': 'Uncategorized',
'version': '8.0.0.1',
# any module necessary for this one to work correctly
'depends': ['base','hr_attendance','hr_timesheet_improvement'],
# always loaded
'data': [
# 'security/ir.model.access.csv',
'views/hr_attendance.xml',
],
# only loaded in demonstration mode
'demo': [
'demo.xml',
],
}
| jmankiewicz/odooAddons | hr_attendance_new_check/__openerp__.py | Python | agpl-3.0 | 958 |
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2011. (c) 2011.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
* $Revision: 5 $
*
************************************************************************
*/
package ca.nrc.cadc.ac.admin;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NameClassPair;
import javax.naming.NameParser;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* A Simple JNDI context.
*/
public class ContextImpl implements Context
{
private final static ConcurrentMap<String,Object> POOL_MAP =
new ConcurrentHashMap<>(1);
@Override
public Object lookup(String name) throws NamingException
{
return POOL_MAP.get(name);
}
@Override
public void bind(String name, Object value) throws NamingException
{
POOL_MAP.put(name, value);
}
@Override
public Object addToEnvironment(String arg0, Object arg1)
throws NamingException
{
return null;
}
@Override
public void bind(Name arg0, Object arg1) throws NamingException
{
}
@Override
public void close() throws NamingException
{
}
@Override
public Name composeName(Name arg0, Name arg1) throws NamingException
{
return null;
}
@Override
public String composeName(String arg0, String arg1)
throws NamingException
{
return null;
}
@Override
public Context createSubcontext(Name arg0) throws NamingException
{
// TODO Auto-generated method stub
return null;
}
@Override
public Context createSubcontext(String arg0) throws NamingException
{
return null;
}
@Override
public void destroySubcontext(Name arg0) throws NamingException
{
}
@Override
public void destroySubcontext(String arg0) throws NamingException
{
// TODO Auto-generated method stub
}
@Override
public Hashtable<?, ?> getEnvironment() throws NamingException
{
return null;
}
@Override
public String getNameInNamespace() throws NamingException
{
return null;
}
@Override
public NameParser getNameParser(Name arg0) throws NamingException
{
return null;
}
@Override
public NameParser getNameParser(String arg0) throws NamingException
{
return null;
}
@Override
public NamingEnumeration<NameClassPair> list(Name arg0)
throws NamingException
{
return null;
}
@Override
public NamingEnumeration<NameClassPair> list(String arg0)
throws NamingException
{
// TODO Auto-generated method stub
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(Name arg0)
throws NamingException
{
return null;
}
@Override
public NamingEnumeration<Binding> listBindings(String arg0)
throws NamingException
{
return null;
}
@Override
public Object lookup(Name arg0) throws NamingException
{
// TODO Auto-generated method stub
return null;
}
@Override
public Object lookupLink(Name arg0) throws NamingException
{
return null;
}
@Override
public Object lookupLink(String arg0) throws NamingException
{
return null;
}
@Override
public void rebind(Name arg0, Object arg1) throws NamingException
{
}
@Override
public void rebind(String arg0, Object arg1) throws NamingException
{
}
@Override
public Object removeFromEnvironment(String arg0) throws NamingException
{
return null;
}
@Override
public void rename(Name arg0, Name arg1) throws NamingException
{
}
@Override
public void rename(String arg0, String arg1) throws NamingException
{
}
@Override
public void unbind(Name arg0) throws NamingException
{
}
@Override
public void unbind(String arg0) throws NamingException
{
}
} | opencadc/ac | cadc-access-control-admin/src/main/java/ca/nrc/cadc/ac/admin/ContextImpl.java | Java | agpl-3.0 | 7,999 |
package jlib.datastream.intraprocess;
import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import jlib.datastream.ezio.LineReaderObject;
import jlib.events.Command;
import jlib.utils.e.event.DuplicateCommandException;
import jlib.utils.e.oop.NonUniqueIdentifierException;
/**
* Background Daemon thread that reads user input into the console in a non-blocking daemon thread and takes actions depending on user input.
*
* Commands and command identifiers must be unique. Case sensitivity param cannot be changed after construction. Commands have arguments passed as an Object[] of Strings.
* Input source cannot be changed and commands cannot be added after the daemon is started
*
* @author J-Dierberger
*/
public class BackgroundDaemon<T extends LineReaderObject & Closeable> implements Closeable{
private ArrayList<Command> commands;
private final boolean caseSensitive;
private T reader;
private Thread daemon;
private boolean daemonStarted;
private boolean daemonClosed;
/**
* Create a BackgroundDaemon with the given case-sensitivity param and the given Commands.
*
* @param caseSensitive If Command input is case sensitive.
* @param inputSource The source of input the daemon reads from.
* @param commands The list of Commands this daemon can execute.
*/
public BackgroundDaemon(boolean caseSensitive, T inputSource, Command...commands){
this.caseSensitive = caseSensitive;
ArrayList<String> commandNames = new ArrayList<String>();
// Check for no duplicate names.
for(int i = 0; i < commands.length; i++){
if(!caseSensitive && commandNames.contains(commands[i].getName())){
throw new NonUniqueIdentifierException("Duplicate command "+commands[i].getName());
}else if(caseSensitive && commandNames.contains(commands[i].getName().toLowerCase())){
throw new NonUniqueIdentifierException("Duplicate command "+commands[i].getName().toLowerCase());
}else{
String name = commands[i].getName();
name = _caseCorrect(name);
commandNames.add(name);
}
}
// If we pass the loop without throwing exceptions then we have a valid list of commands.
this.commands = new ArrayList<Command>();
for(Command c : commands){
this.commands.add(c);
}
daemonStarted = false;
daemonClosed = false;
reader = inputSource;
}
/**
* Create a BackgroundDaemon with the given case-sensitivity param.
*
* @param caseSensitive If Command input is case sensitive.
* @param inputSource The source of input the daemon reads from.
*/
public BackgroundDaemon(boolean caseSensitive, T inputSource){
this(caseSensitive, inputSource, new Command[]{});
}
/**
* Create a BackgroundDaemon with the given list of executable Commands. Case sensitivity turned off by default. This cannot be changed after construction.
*
* @param commands The list of Commands this daemon can execute.
* @param inputSource The source of input the daemon reads from.
*/
public BackgroundDaemon(Command[] commands, T inputSource){
this(false, inputSource, new Command[]{});
}
/**
* Create a BackgroundDaemon with the given input source to read from. Case sensitivity is turned off by default. This cannot be changed after construction.
*
* @param inputSource The source of input the daemon reads from.
*/
public BackgroundDaemon(T inputSource){
this(false, inputSource, new Command[]{});
}
/**
* Start the daemon thread.
*/
public void start(){
daemon = new Thread(){
@Override
public void run(){
while(true){
try{
String in = reader.readLine();
String[] fullCommand = in.split(",");
String inputComm = fullCommand[0];
String[] args = new String[fullCommand.length-1];
for(int i = 1; i < fullCommand.length; i++){
args[i-1] = fullCommand[i].trim();
}
inputComm = _caseCorrect(inputComm);
for(Command c : commands){
String commName = c.getName();
commName = _caseCorrect(commName);
if(inputComm.equals(commName)){
c.execute((Object[])args);
break;
}
}
}catch(Throwable e){
e.printStackTrace();
}
}
}
};
daemon.setDaemon(true);
daemon.start();
daemonStarted = true;
}
/**
* Set the input source of the daemon.
*
* @param T The object to read input from. Reads line-by-line.
*/
public void setLineReaderObject(T inputSource){
_checkStarted();
reader = inputSource;
}
/**
* Add a Command to the list of Commands this daemon can execute.
*
* @param c The Command to add.
*/
public void addCommand(Command c){
_checkStarted();
if(commands.contains(c)){
throw new DuplicateCommandException("Command already exists in this daemon's list of commands.");
}
String commName = c.getName();
commName = _caseCorrect(commName);
for(Command comm : commands){
String cName = comm.getName();
cName = _caseCorrect(cName);
if(commName.equals(cName)){
throw new NonUniqueIdentifierException("Duplicate command "+cName);
}
}
commands.add(c);
}
/**
* Remove the given Command from the list of Commands this daemon can execute.
*
* @param c The Command to remove.
*/
public void removeCommand(Command c){
_checkStarted();
commands.remove(c);
}
/**
* Stop the daemon thread.
*
* @throws IOException If closing fails.
*/
public void close() throws IOException{
_checkClosed();
reader.close();
daemon.interrupt();
daemonClosed = true;
}
/**
* Check if the daemon was started.
*
* @return If the daemon was started.
*/
public boolean started(){
return daemonStarted;
}
/**
* Check if the daemon is alive.
*
* @return If the daemon thread is still alive.
*/
public boolean isAlive(){
return daemon.isAlive();
}
/**
* Check if the daemon is closed.
*
* @return If the daemon is closed.
*/
public boolean isClosed(){
return daemonClosed;
}
private void _checkStarted(){
if(daemonStarted){
throw new IllegalStateException("Illegal modification attempted; daemon already started.");
}
}
private void _checkClosed(){
if(!daemonStarted){
throw new IllegalStateException("Daemon not started; cannot close.");
}else if(daemonClosed){
throw new IllegalStateException("Daemon already closed; cannot close again.");
}
}
private String _caseCorrect(String s){
if(!caseSensitive){
return s.toLowerCase();
}else{
return s;
}
}
}
| JDierberger1/JDierberger | src/jlib/datastream/intraprocess/BackgroundDaemon.java | Java | agpl-3.0 | 6,700 |
/*
* This file is part of SerialPundit.
*
* Copyright (C) 2014-2020, Rishi Gupta. All rights reserved.
*
* The SerialPundit is DUAL LICENSED. It is made available under the terms of the GNU Affero
* General Public License (AGPL) v3.0 for non-commercial use and under the terms of a commercial
* license for commercial use of this software.
*
* The SerialPundit 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.
*/
package com.serialpundit.usb;
import java.io.IOException;
import com.serialpundit.core.SerialComException;
import com.serialpundit.core.SerialComPlatform;
import com.serialpundit.core.SerialComSystemProperty;
import com.serialpundit.usb.ISerialComUSBHotPlugListener;
import com.serialpundit.usb.internal.SerialComUSBJNIBridge;
/**
* <p>Encapsulates USB related operations and values.</p>
*
* <p>An end product may be based on dedicated USB-UART bridge IC for providing serial over USB or
* may use general purpose microcontroller like PIC18F4550 from Microchip technology Inc. and
* program appropriate firmware (USB CDC) into it to provide UART communication over USB port.</p>
*
* <p>[1] If your USB-UART converter based design is not working, consider not connecting USB connector
* shield directly to ground. Further, double check if termination resistors in D+/D- lines are
* really required or not.</p>
*
* @author Rishi Gupta
*/
public final class SerialComUSB {
/** <p>Value indicating all vendors (vendor neutral operation).</p>*/
public static final int V_ALL = 0x0000;
/** <p>Value indicating vendor - Future technology devices international, Ltd. It manufactures FT232
* USB-UART bridge IC.</p>*/
public static final int V_FTDI = 0x0403;
/** <p>Value indicating vendor - Silicon Laboratories. It manufactures CP2102 USB-UART bridge IC.</p>*/
public static final int V_SLABS = 0x10C4;
/** <p>Value indicating vendor - Microchip technology Inc. It manufactures MCP2200 USB-UART bridge IC.</p>*/
public static final int V_MCHIP = 0x04D8;
/** <p>Value indicating vendor - Prolific technology Inc. It manufactures PL2303 USB-UART bridge IC.</p>*/
public static final int V_PL = 0x067B;
/** <p>Value indicating vendor - Exar corporation. It manufactures XR21V1410 USB-UART bridge IC.</p>*/
public static final int V_EXAR = 0x04E2;
/** <p>Value indicating vendor - Atmel corporation. It manufactures AT90USxxx and other processors which
* can be used as USB-UART bridge.</p>*/
public static final int V_ATML = 0x03EB;
/** <p>Value indicating vendor - MosChip semiconductor. It manufactures MCS7810 USB-UART bridge IC.</p>*/
public static final int V_MOSCHP = 0x9710;
/** <p>Value indicating vendor - Cypress semiconductor corporation. It manufactures CY7C65213 USB-UART
* bridge IC.</p>*/
public static final int V_CYPRS = 0x04B4;
/** <p>Value indicating vendor - Texas instruments, Inc. It manufactures TUSB3410 USB-UART bridge IC.</p>*/
public static final int V_TI = 0x0451;
/** <p>Value indicating vendor - WinChipHead. It manufactures CH340 USB-UART bridge IC.</p>*/
public static final int V_WCH = 0x4348;
/** <p>Value indicating vendor - QinHeng electronics. It manufactures HL-340 converter product.</p>*/
public static final int V_QHE = 0x1A86;
/** <p>Value indicating vendor - NXP semiconductors. It manufactures LPC134x series of microcontrollers.</p>*/
public static final int V_NXP = 0x1FC9;
/** <p>Value indicating vendor - Renesas electronics (NEC electronics). It manufactures μPD78F0730
* microcontroller which can be used as USB-UART converter.</p>*/
public static final int V_RNSAS = 0x0409;
/** <p>The value indicating that the USB device can have any vendor id and product id. </p>*/
public static final int DEV_ANY = 0x00;
/** <p>The value indicating that a USB device has been added into system. </p>*/
public static final int DEV_ADDED = 0x01;
/** <p>The value indicating that a USB device has been removed from system. </p>*/
public static final int DEV_REMOVED = 0x02;
// private stuff
private SerialComPlatform mSerialComPlatform;
private final SerialComSystemProperty mSerialComSystemProperty;
private final Object lockB = new Object();
private static int osType = SerialComPlatform.OS_UNKNOWN;
private static int cpuArch = SerialComPlatform.ARCH_UNKNOWN;
private static int abiType = SerialComPlatform.ABI_UNKNOWN;
private static final Object lockA = new Object();
private static SerialComUSBJNIBridge mUSBJNIBridge;
/**
* <p>Allocates a new SerialComUSB object and load/link native libraries if required.</p>
*
* @param libDirectory absolute path of directory to be used for native library extraction.
* @param loadedLibName library name without extension (do not append .so, .dll or .dylib etc.).
* @throws IOException if native libraries are not found or can not be loaded/linked. If
* appropriate files/directories can not be read or written, If native library can not
* be initialized.
*/
public SerialComUSB(String libDirectory, String loadedLibName) throws IOException {
mSerialComSystemProperty = new SerialComSystemProperty();
synchronized(lockA) {
if(osType <= 0) {
mSerialComPlatform = new SerialComPlatform(mSerialComSystemProperty);
osType = mSerialComPlatform.getOSType();
if(osType == SerialComPlatform.OS_UNKNOWN) {
throw new SerialComException("Could not identify operating system. Please report to us your environemnt so that we can add support for it !");
}
cpuArch = mSerialComPlatform.getCPUArch(osType);
if(cpuArch == SerialComPlatform.ARCH_UNKNOWN) {
throw new SerialComException("Could not identify CPU architecture. Please report to us your environemnt so that we can add support for it !");
}
if((cpuArch == SerialComPlatform.ARCH_ARMV7) || (cpuArch == SerialComPlatform.ARCH_ARMV6) || (cpuArch == SerialComPlatform.ARCH_ARMV5)) {
if(osType == SerialComPlatform.OS_LINUX) {
abiType = mSerialComPlatform.getABIType();
}
}
}
if(mUSBJNIBridge == null) {
mUSBJNIBridge = new SerialComUSBJNIBridge();
SerialComUSBJNIBridge.loadNativeLibrary(libDirectory, loadedLibName, mSerialComSystemProperty, osType, cpuArch, abiType);
mUSBJNIBridge.initNativeLib();
}
}
}
/**
* <p>Returns an array of SerialComUSBdevice class objects containing information about all the USB devices
* found by this library. Application can call various methods on SerialComUSBdevice object to get specific
* information like vendor id and product id etc. The GUI applications may display a dialogue box asking
* user to connect the end product if the desired product is still not connected to system.</p>
*
* <p>The USB vendor id, USB product id, serial number, product name and manufacturer information is
* encapsulated in the object of class SerialComUSBdevice returned.</p>
*
* <p>Some USB-UART chip manufactures may give some unique USB PID(s) to end product manufactures at minimal
* or no cost. Applications written for these end products may be interested in finding devices only from the
* USB-UART chip manufacturer. For example, an application built for finger print scanner based on FT232 IC
* will like to list only those devices whose VID matches VID of FTDI. Then further application may verify
* PID by calling methods on the USBDevice object. For this purpose argument vendorFilter may be used.</p>
*
* @param vendorFilter vendor whose devices should be listed (one of the constants SerialComUSB.V_xxxxx or
* any valid USB VID).
* @return list of the USB devices with information about them or empty array if no device matching given
* criteria found.
* @throws SerialComException if an I/O error occurs.
* @throws IllegalArgumentException if vendorFilter is negative or invalid number.
*/
public SerialComUSBdevice[] listUSBdevicesWithInfo(int vendorFilter) throws SerialComException {
int i = 0;
int numOfDevices = 0;
SerialComUSBdevice[] usbDevicesFound = null;
if((vendorFilter < 0) || (vendorFilter > 0XFFFF)) {
throw new IllegalArgumentException("Argument vendorFilter can not be negative or greater than 0xFFFF !");
}
String[] usbDevicesInfo = mUSBJNIBridge.listUSBdevicesWithInfo(vendorFilter);
if(usbDevicesInfo != null) {
if(usbDevicesInfo.length < 4) {
return new SerialComUSBdevice[] { };
}
numOfDevices = usbDevicesInfo.length / 6;
usbDevicesFound = new SerialComUSBdevice[numOfDevices];
for(int x=0; x<numOfDevices; x++) {
usbDevicesFound[x] = new SerialComUSBdevice(usbDevicesInfo[i], usbDevicesInfo[i+1], usbDevicesInfo[i+2],
usbDevicesInfo[i+3], usbDevicesInfo[i+4], usbDevicesInfo[i+5]);
i = i + 6;
}
return usbDevicesFound;
}else {
throw new SerialComException("Could not find USB devices. Please retry !");
}
}
/**
* <p>This registers a listener who will be invoked whenever a USB device has been plugged or
* un-plugged in system. This method can be used to write auto discovery applications for example
* when a hardware USB device is added to system, application can automatically detect, identify
* it and launches an appropriate service.</p>
*
* <p>This API can be used for detecting both USB-HID and USB-CDC devices. Essentially this API is
* USB interface agnostic; meaning it would invoke listener for matching USB device irresepective of
* functionality offered by the USB device.</p>
*
* <p>Application must implement ISerialComUSBHotPlugListener interface and override onUSBHotPlugEvent method.
* The event value SerialComUSB.DEV_ADDED indicates USB device has been added to the system. The event
* value SerialComUSB.DEV_REMOVED indicates USB device has been removed from system.</p>
*
* <p>Application can specify the usb device for which callback should be called based on USB VID and
* USB PID. If the value of filterVID is specified however the value of filterPID is constant SerialComUSB.DEV_ANY,
* then callback will be called for USB device which matches given VID and its PID can have any value.
* If the value of filterPID is specified however the value of filterVID is constant SerialComUSB.DEV_ANY,
* then callback will be called for USB device which matches given PID and its VID can have any value.</p>
*
* <p>If both filterVID and filterPID are set to SerialComUSB.DEV_ANY, then callback will be called for
* every USB device. Further in listener, USBVID will be 0, if SerialComUSB.DEV_ANY was passed to registerUSBHotPlugEventListener
* for filterVID argument. USBPID will be 0, if SerialComUSB.DEV_ANY was passed to registerUSBHotPlugEventListener for filterPID
* and serialNumber will be empty string if null was passed to registerUSBHotPlugEventListener for serialNumber argument.</p>
*
* <p>If the application do not know the USB attributes like the VID/PID/Serial of the device use listUSBdevicesWithInfo()
* along with hot plug listener. For example; call listUSBdevicesWithInfo(SerialComUSB.V_ALL) and create and arraylist
* to know what all USB devices are present in system and register this hotplug listener. Now whenever a USB device
* is attached to system, listener will be called. From with this listener call listUSBdevicesWithInfo(SerialComUSB.V_ALL)
* and create arraylist again. Compare these two list to find information about newly added device and take next
* appropriate step<p>
*
* @param hotPlugListener object of class which implements ISerialComUSBHotPlugListener interface.
* @param filterVID USB vendor ID to match.
* @param filterPID USB product ID to match.
* @param serialNumber serial number of USB device (case insensitive, optional, can be null) to match.
* @return opaque handle on success that should be passed to unregisterUSBHotPlugEventListener method
* for unregistering this listener.
* @throws SerialComException if registration fails due to some reason.
* @throws IllegalArgumentException if hotPlugListener is null or if USB VID or USB PID are invalid numbers.
*/
public int registerUSBHotPlugEventListener(final ISerialComUSBHotPlugListener hotPlugListener,
int filterVID, int filterPID, String serialNumber) throws SerialComException {
int opaqueHandle = 0;
if(hotPlugListener == null) {
throw new IllegalArgumentException("Argument hotPlugListener can not be null !");
}
if((filterVID < 0) || (filterPID < 0) || (filterVID > 0XFFFF) || (filterPID > 0XFFFF)) {
throw new IllegalArgumentException("USB VID or PID can not be negative number(s) or greater than 0xFFFF !");
}
synchronized(lockB) {
opaqueHandle = mUSBJNIBridge.registerUSBHotPlugEventListener(hotPlugListener, filterVID, filterPID, serialNumber);
if(opaqueHandle < 0) {
throw new SerialComException("Could not register USB device hotplug listener. Please retry !");
}
}
return opaqueHandle;
}
/**
* <p>This unregisters listener and terminate native thread used for monitoring specified USB device
* insertion or removal.</p>
*
* @param opaqueHandle handle returned by registerUSBHotPlugEventListener method for this listener.
* @return true on success.
* @throws SerialComException if un-registration fails due to some reason.
* @throws IllegalArgumentException if argument opaqueHandle is negative.
*/
public boolean unregisterUSBHotPlugEventListener(final int opaqueHandle) throws SerialComException {
int ret = 0;
if(opaqueHandle < 0) {
throw new IllegalArgumentException("Argument opaqueHandle can not be negative !");
}
synchronized(lockB) {
ret = mUSBJNIBridge.unregisterUSBHotPlugEventListener(opaqueHandle);
if(ret < 0) {
throw new SerialComException("Could not un-register USB device hotplug listener. Please retry !");
}
}
return true;
}
/**
* <p>Gives COM port (COMxx/ttySx) of a connected USB-UART device (CDC/ACM Interface) assigned by operating
* system.</p>
*
* <p>Assume a bar code scanner using FTDI chip FT232R is to be used by application at point of sale.
* First we need to know whether it is connect to system or not. This can be done using
* listUSBdevicesWithInfo() or by using USB hot plug listener depending upon application design.</p>
*
* <p>Once it is known that the device is connected to system, we application need to open it. For this,
* application needs to know the COM port number or device node corresponding to the scanner. It is for
* this purpose this method can be used.</p>
*
* <p>Another use case of this API is to align application design with true spirit of USB hot plugging
* in operating system. When a USB-UART device is connected, OS may assign different COM port number or
* device node to the same device depending upon system scenario. Generally we need to write custom udev
* rules so that device node will be same. Using this API this limitation can be overcome.
*
* <p>The reason why this method returns array instead of string is that two or more USB-UART converters
* connected to system might have exactly same USB attributes. So this will list COM ports assigned to all
* of them.<p>
*
* @param usbVidToMatch USB vendor id of the device to match.
* @param usbPidToMatch USB product id of the device to match.
* @param serialNumber USB serial number (case insensitive, optional) of device to match or null if not
* to be matched.
* @return list of COM port(s) (device node) for given USB device or empty array if no COM port is assigned.
* @throws SerialComException if an I/O error occurs.
* @throws IllegalArgumentException if usbVidToMatch or usbPidToMatch is negative or or invalid number.
*/
public String[] findComPortFromUSBAttributes(int usbVidToMatch, int usbPidToMatch, final String serialNumber) throws SerialComException {
if((usbVidToMatch < 0) || (usbVidToMatch > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbVidToMatch can not be negative or greater than 0xFFFF !");
}
if((usbPidToMatch < 0) || (usbPidToMatch > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbPidToMatch can not be negative or greater than 0xFFFF !");
}
String serialNum = null;
if(serialNumber != null) {
serialNum = serialNumber.toLowerCase();
}
String[] comPortsInfo = mUSBJNIBridge.findComPortFromUSBAttribute(usbVidToMatch, usbPidToMatch, serialNum);
if(comPortsInfo == null) {
throw new SerialComException("Could not find COM port for given device. Please retry !");
}
return comPortsInfo;
}
/**
* <p>Gets the USB device firmware revision number as reported by USB device descriptor in its
* device descriptor using bcdDevice field.</p>
*
* <p>Application can get this firmware revision number and can self adopt to a particular hardware
* device. For example if a particular feature is present in firmware version 1.00 than application
* create a button in GUI, however for revision 1.11 it creates a different button in GUI window.</p>
*
* <p>Embedded system device vendors sometimes use bcdDevice value to indicate the 'embedded bootloader'
* version so that the firmware image flash loader program can identify the bootloader in use and use the
* appropriate protocol to flash firmware in flash memory. Typically, USB Device Firmware Upgrade (DFU)
* which is an official USB device class specification of the USB Implementers Forum is used.</p>
*
* <p>On custom hardware the RTS and DTR pins of USB-UART device can be used to control GPIO or boot mode
* pins to enter a particular boot mode. For example, open the host serial port, make DTR low and RTS high
* and then reset microcontroller board. The microcontroller will see levels at its boot pins and will
* enter into a particular boot mode.</p>
*
* @param usbvid USB vendor ID to match.
* @param usbpid USB product ID to match.
* @param serialNumber serial number of USB device (case insensitive, optional) to match.
* @return firmware number revision string on success.
* @throws SerialComException if an I/O error occurs.
*/
public String[] getFirmwareRevisionNumber(int usbvid, int usbpid, String serialNumber) throws SerialComException {
if((usbvid < 0) || (usbvid > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbvid can not be negative or greater than 0xFFFF !");
}
if((usbpid < 0) || (usbpid > 0XFFFF)) {
throw new IllegalArgumentException("Argument usbpid can not be negative or greater than 0xFFFF !");
}
String serial = null;
if(serialNumber != null) {
serial = serialNumber.trim().toLowerCase();
}
String[] bcdCodedRevNumber = mUSBJNIBridge.getFirmwareRevisionNumber(usbvid, usbpid, serial);
if(bcdCodedRevNumber == null) {
throw new SerialComException("Could not get the bcdDevice field of USB device descriptor. Please retry !");
}
String[] fwver = new String[bcdCodedRevNumber.length];
int firmwareRevisionNum;
for(int x=0; x < bcdCodedRevNumber.length; x++) {
firmwareRevisionNum = Integer.parseInt(bcdCodedRevNumber[x]);
fwver[x] = String.format("%x.%02x", (firmwareRevisionNum & 0xFF00) >> 8, firmwareRevisionNum & 0x00FF);
}
return fwver;
}
/**
* <p>Read all the power management related information about a particular USB device. The returned
* instance of SerialComUSBPowerInfo class contains information about auto suspend, selective suspend,
* current power status etc.</p>
*
*
* @param comPort serial port name/path (COMxx, /dev/ttyUSBx) which is associated with a particular
* USB CDC/ACM interface in the USB device to be analyzed for power management.
* @return an instance of SerialComUSBPowerInfo class containing operating system and device specific
* information about power management or null if given COM port does not belong to a USB
* device.
* @throws SerialComException if an I/O error occurs.
*/
public SerialComUSBPowerInfo getCDCUSBDevPowerInfo(String comPort) throws SerialComException {
if(comPort == null) {
throw new IllegalArgumentException("Argument comPort can not be null !");
}
String portNameVal = comPort.trim();
if(portNameVal.length() == 0) {
throw new IllegalArgumentException("Argument comPort can not be empty string !");
}
String[] usbPowerInfo = mUSBJNIBridge.getCDCUSBDevPowerInfo(portNameVal);
if(usbPowerInfo != null) {
if(usbPowerInfo.length > 2) {
return new SerialComUSBPowerInfo(usbPowerInfo[0], usbPowerInfo[1], usbPowerInfo[2],
usbPowerInfo[3], usbPowerInfo[4], usbPowerInfo[5]);
}
}else {
throw new SerialComException("Could not find USB devices. Please retry !");
}
return null;
}
/**
* <p>Sets the latency timer value for FTDI devices. When using FTDI USB-UART devices, optimal values
* of latency timer and read/write block size may be required to obtain optimal data throughput.</p>
*
* <p>Note that built-in drivers in Linux kernel image may not allow changing timer values as it may have
* been hard-coded. Drivers supplied by FTDI at their website should be used if changing latency timer
* values is required by application.</p>
*
* @return true on success.
* @throws SerialComException if an I/O error occurs.
*/
public boolean setLatencyTimer(String comPort, byte timerValue) throws SerialComException {
int ret = mUSBJNIBridge.setLatencyTimer(comPort, timerValue);
if(ret < 0) {
throw new SerialComException("Could not set the latency timer value. Please retry !");
}
return true;
}
/**
* <p>Gets the current latency timer value for FTDI devices.</p>
*
* @return current latency timer value.
* @throws SerialComException if an I/O error occurs.
*/
public int getLatencyTimer(String comPort) throws SerialComException {
int value = mUSBJNIBridge.getLatencyTimer(comPort);
if(value < 0) {
throw new SerialComException("Could not get the latency timer value. Please retry !");
}
return value;
}
/**
* <p>Checks whether a particular USB device identified by vendor id, product id and serial number is
* connected to the system or not. The connection information is obtained from the operating system.</p>
*
* @param vendorID USB-IF vendor ID of the USB device to match.
* @param productID product ID of the USB device to match.
* @param serialNumber USB device's serial number (case insensitive, optional). If not required it can be null.
* @return true is device is connected otherwise false.
* @throws SerialComException if an I/O error occurs.
* @throws IllegalArgumentException if productID or vendorID is negative or invalid.
*/
public boolean isUSBDevConnected(int vendorID, int productID, String serialNumber) throws SerialComException {
if((vendorID < 0) || (vendorID > 0XFFFF)) {
throw new IllegalArgumentException("Argument vendorID can not be negative or greater than 0xFFFF !");
}
if((productID < 0) || (productID > 0XFFFF)) {
throw new IllegalArgumentException("Argument productID can not be negative or greater than 0xFFFF !");
}
int ret = mUSBJNIBridge.isUSBDevConnected(vendorID, productID, serialNumber);
if(ret < 0) {
throw new SerialComException("Unknown error occurred !");
}else if(ret == 1) {
return true;
}
return false;
}
/**
* <p>Returns an instance of class SerialComUSBHID for HID over USB operations.</p>
*
* @return an instance of SerialComUSBHID.
* @throws SerialComException if operation can not be completed successfully.
*/
public SerialComUSBHID getUSBHIDTransportInstance() throws SerialComException {
return new SerialComUSBHID(mUSBJNIBridge);
}
}
| RishiGupta12/serial-communication-manager | modules/usb/src/com/serialpundit/usb/SerialComUSB.java | Java | agpl-3.0 | 25,769 |
import os
import time
import sys
FOLDERPATH = sys.argv[1]
#os.chdir(FOLDERPATH)
walk = os.walk(FOLDERPATH)
FSEVENT = "delete"
for item in walk:
FILEPATHPREFIX = item[0] + "\\"
for song in item[2]:
if song.endswith(".mp3"):
FILEPATH = "%s%s" % (FILEPATHPREFIX, song)
os.system('python script.py "' + song + '" "' + FILEPATH + '" "' + FSEVENT + '"') | collaj/MusicServer | scripts/test_script_delete.py | Python | agpl-3.0 | 404 |
<?php
/**
* OpenEyes.
*
* (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
* (C) OpenEyes Foundation, 2011-2013
* This file is part of OpenEyes.
* OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.openeyes.org.uk
*
* @author OpenEyes <info@openeyes.org.uk>
* @copyright Copyright (c) 2011-2013, OpenEyes Foundation
* @license http://www.gnu.org/licenses/agpl-3.0.html The GNU Affero General Public License V3.0
*/
namespace OEModule\OphCiExamination\models;
/**
* This is the model class for table "ophciexamination_dilation_drugs".
*
* @property int $id
* @property string $name
*/
class OphCiExamination_Dilation_Drugs extends \BaseActiveRecordVersioned
{
/**
* Returns the static model of the specified AR class.
*
* @return OphCiExamination_Dilation_Drugs the static model class
*/
public static function model($className = __CLASS__)
{
return parent::model($className);
}
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'ophciexamination_dilation_drugs';
}
/**
* @return array validation rules for model attributes.
*/
public function rules()
{
return array(
array('name', 'required'),
array('id, name, display_order', 'safe', 'on' => 'search'),
);
}
/**
* @return array relational rules.
*/
public function relations()
{
return array();
}
/**
* Retrieves a list of models based on the current search/filter conditions.
*
* @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
*/
public function search()
{
$criteria = new \CDbCriteria();
$criteria->compare('id', $this->id, true);
$criteria->compare('name', $this->name, true);
return new \CActiveDataProvider(get_class($this), array(
'criteria' => $criteria,
));
}
}
| FiviumAustralia/OpenEyes | protected/modules/OphCiExamination/models/OphCiExamination_Dilation_Drugs.php | PHP | agpl-3.0 | 2,664 |
import SPELLS from 'common/SPELLS/index';
/*
* Fields:
* int: spell scales with Intellect
* crit: spell scales with (is able to or procced from) Critical Strike
* hasteHpm: spell does more healing due to Haste, e.g. HoTs that gain more ticks
* hasteHpct: spell can be cast more frequently due to Haste, basically any spell except for non haste scaling CDs
* mastery: spell is boosted by Mastery
* masteryStack: spell's HoT counts as a Mastery Stack
* vers: spell scales with Versatility
* multiplier: spell scales with whatever procs it, should be ignored for purpose of weights and for 'total healing' number
* ignored: spell should be ignored for purpose of stat weights
*/
// This only works with actual healing events; casts are not recognized.
export default {
[SPELLS.LEECH.id]: { // procs a percent of all your healing, so we ignore for weights and total healing
multiplier: true,
},
[SPELLS.XAVARICS_MAGNUM_OPUS.id]: { // Prydaz
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.HEALTHSTONE.id]: {
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: true, // confirmed
},
[SPELLS.COASTAL_HEALING_POTION.id]: {
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.MARK_OF_THE_ANCIENT_PRIESTESS.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/zxXDd7CJFbLQpHGM/#fight=12&source=3&type=summary
[SPELLS.RESOUNDING_PROTECTION_ABSORB.id]: { // General Azerite Power
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.IMPASSIVE_VISAGE_HEAL.id]: {
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.VAMPIRIC_SPEED_HEAL.id]: { // General(?) Azerite trait
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.STALWART_PROTECTOR.id]: { // General Paladin Azerite Power
int: false,
crit: false,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.REJUVENATING_TIDES.id]: { // Darkmoon Deck: Tides
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
[SPELLS.TOUCH_OF_THE_VOODOO.id]: { // Revitalizing Voodoo Totem
int: false,
crit: true,
hasteHpct: false,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/zxXDd7CJFbLQpHGM/#fight=12&source=3
[SPELLS.CONCENTRATED_MENDING_HEALING.id]: { // Healing Azerite Power
int: false,
crit: true,
hasteHpm: true,
mastery: true, // TODO: Re-evaluate, going on word of mouth and I have my doubts
vers: true,
},
// https://www.warcraftlogs.com/reports/cXnPABVbLjk68qyM#fight=6&type=healing&source=10
271682: { // Harmonious Chord - Lady Waycrest's Music Box (trinket)
int: false,
crit: true,
hasteHpct: false,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/cXnPABVbLjk68qyM#fight=6&type=healing&source=10&ability=267537&view=events
267537: { // Coastal Surge (Weapon enchant)
int: false,
crit: true,
hasteHpct: false,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/axKCmGyfgXFw6QVL/#fight=28&source=156
[SPELLS.BLESSED_PORTENTS_HEAL.id]: { // General Azerite Power
int: false,
crit: true,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/axKCmGyfgXFw6QVL/#fight=28&source=156
[SPELLS.BRACING_CHILL_HEAL.id]: { // General Azerite Power
int: false,
crit: true,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/fKaZdyWcQYAwTtz2/#fight=4&source=9&type=healing&options=8
[SPELLS.AZERITE_FORTIFICATION.id]: { // General Azerite Power
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/fKaZdyWcQYAwTtz2/#fight=4&source=9&type=healing&options=8
[SPELLS.AZERITE_VEINS.id]: { // General Azerite Power
int: false,
crit: true,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/fKaZdyWcQYAwTtz2/#fight=4&source=9&type=healing&options=8
[SPELLS.SAVIOR.id]: { // General Azerite Power
int: false,
crit: true,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/LpM43CgfYQ9ntXyz/#fight=4&source=3
[SPELLS.LASER_MATRIX_HEAL.id]: { // General Azerite trait
int: false,
crit: true,
hasteHpm: true,
mastery: false,
vers: true,
},
// https://www.warcraftlogs.com/reports/LpM43CgfYQ9ntXyz/#fight=4&source=3
[SPELLS.MUTATING_ANTIBODY.id]: { // Inoculating Extract
int: false,
crit: true,
hasteHpct: false,
mastery: false,
vers: true,
},
};
| FaideWW/WoWAnalyzer | src/parser/shared/modules/features/SpellInfo.js | JavaScript | agpl-3.0 | 5,070 |
/**
* @author Anakeen
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License
*/
// Utility function to add an event listener
function addEvent(o,e,f){
if (o.addEventListener){ o.addEventListener(e,f,true); return true; }
else if (o.attachEvent){ return o.attachEvent("on"+e,f); }
else { return false; }
}
// Utility function to send an event
// o the object
// en the event name : mouseup, mouseodwn
function sendEvent(o,en) {
if (o) {
if( document.createEvent ) {
// var ne=document.createEvent("HTMLEvents");
var ne;
if ((en.indexOf('mouse') > -1)||(en.indexOf('click') > -1)) ne=document.createEvent("MouseEvents");
else ne=document.createEvent("HTMLEvents");
ne.initEvent(en,true,true);
o.dispatchEvent(ne);
}
else {
try {
o.fireEvent( "on"+en );
}
catch (ex) {
;
}
}
}
}
Ext.fdl.Document = Ext.extend(Ext.Panel, {
document: null,
context: null,
mode: 'view',
forceExt: false,
forceClassic: false,
displayToolbar: true,
displaynotes: true,
notes: [],
layout: 'fit',
toString: function(){
return 'Ext.fdl.Document';
},
initComponent: function(){
if(!this.document){
console.log('Ext.fdl.Document is not provided a document.');
}
this.context = this.document.context;
if(this.displayToolbar){
this.tbar = new Ext.Toolbar({
enableOverflow: true,
hidden: true,
height: 28
});
}
Ext.fdl.Document.superclass.initComponent.call(this);
this.on({
afterrender: {
fn: function(){
this.switchMode(this.mode);
var o = this;
(function(){
o.viewNotes();
}).defer(1000);
fdldoc = this.document;
(function(){
fdldoc.addUserTag({
tag: 'VIEWED'
});
}).defer(1000);
},
scope: this
}
});
},
setDocument: function(document){
this.document = document ;
},
reload: function(){
this.switchMode(this.mode);
},
switchMode: function(mode){
var me = this ;
if (this.showMask) {
this.showMask();
}
this.removeAll();
switch (mode) {
case 'view':
if ((this.document.getProperty('generateVersion') == 3 && !this.forceClassic)|| this.forceExt) {
var dcv = this.document.getDefaultConsultationView();
var subPanel = new Ext.fdl.SubDocument({
document: this.document,
config: this.config
});
subPanel.on('close',function(){
this.fireEvent('close',this);
},this);
subPanel.switchMode = function(mode){
me.switchMode(mode);
};
if (dcv) {
if (!eval('window.' + dcv.extwidget)) {
// Dynamically add Javascript file
this.includeJS(dcv.extsrc);
}
// Override document with extended behaviours
Ext.apply(subPanel, eval('window.' + dcv.extwidget));
}
else {
Ext.apply(subPanel, Ext.fdl.DocumentDefaultView);
}
this.add(subPanel);
subPanel.on('afterrender',function(){
subPanel.display();
});
}
else {
this.renderViewClassic();
}
break;
case 'edit':
case 'create':
//var dev = this.document.getDefaultEditionView();
if ((this.document.getProperty('generateVersion') == 3 && !this.forceClassic) || this.forceExt) {
var dev = this.document.getDefaultEditionView();
var subPanel = new Ext.fdl.SubDocument({
document: this.document,
mode: mode,
config: this.config
});
subPanel.on('close',function(){
this.fireEvent('close',this);
},this);
subPanel.switchMode = function(mode){
me.switchMode(mode);
};
if (dev) {
if (!eval('window.' + dev.extwidget)) {
// Dynamically add Javascript file
this.includeJS(dev.extsrc);
}
// Override document with extended behaviours
Ext.apply(subPanel, eval('window.' + dev.extwidget));
}
else {
Ext.apply(subPanel, Ext.fdl.DocumentDefaultEdit);
}
this.add(subPanel);
subPanel.on('afterrender',function(){
subPanel.display();
});
}
else {
this.renderEditClassic();
}
break;
default:
break;
};
this.mode = mode;
// Do layout will not work on render. It must not be called first time.
if (this.firstLayout) {
this.doLayout();
}
this.firstLayout = true;
if (this.hideMask) {
this.hideMask();
}
},
generateMenu: function(panel,menu,mediaObject){
var me = this ;
//console.log('GENERATE MENU',panel,menu,mediaObject.dom);
//panel.getTopToolbar().removeAll();
menu.removeAll();
var documentMenu = mediaObject.dom.contentWindow.documentMenu;
//console.log('DOCUMENT MENU',documentMenu);
var documentId = (mediaObject.dom.contentWindow.document.getElementsByName('document-id').length > 0) ? mediaObject.dom.contentWindow.document.getElementsByName('document-id')[0].content : '' ;
//console.log('DOCUMENT ID', documentId);
var document = this.context.getDocument({
id: documentId,
useCache:true,
latest: false
});
if(document && document.id){
this.setDocument(document);
//console.log('DOCUMENT',documentId,me.document.getTitle());
//me.publish('modifydocument',me.document);
}
for(var name in documentMenu){
var menuObject = documentMenu[name];
var menuItem = Ext.fdl.MenuManager.getMenuItem(menuObject,{
widgetDocument:me,
documentId:documentId,
panel: panel,
mediaObject: mediaObject,
context: this.context,
menu: menu
});
console.log('MENU ITEM',menuItem);
menu.add(menuItem);
}
menu.add(new Ext.Toolbar.Fill());
var toolbarStatus = me.documentToolbarStatus();
for (var i = 0; i < toolbarStatus.length; i++) {
if (toolbarStatus[i]) {
menu.add(toolbarStatus[i]);
}
}
menu.doLayout();
menu.show();
mediaObject.dom.contentWindow.displaySaveForce = function(){
if (mediaObject.dom.contentWindow.documentMenu.saveforce) {
mediaObject.dom.contentWindow.documentMenu.saveforce.visibility = 1 ;
me.generateMenu(panel,menu,mediaObject);
}
};
},
// If this function returns a string, confirm when closing this document displaying this string.
// This method is used in Ext.fdl.Window to check if document can be closed with ou without confirm.
closeConfirm: function(){
if(this.mediaObject){
try {
if(this.mediaObject.dom.contentWindow.beforeUnload){
var beforeUnload = this.mediaObject.dom.contentWindow.beforeUnload();
return beforeUnload ;
}
} catch(exception) {
}
}
return false;
},
renderViewClassic: function(){
//console.log('RENDER VIEW CLASSIC DOCUMENT ID',this.document.id);
var me = this ;
if(!this.config){
this.config = {};
}
if(!this.config.targetRelation){
//this.config.targetRelation = 'Ext.fdl.Document.prototype.publish("opendocument",null,%V%,"view")';
}
console.log('CONFIG',this.config);
delete this.config.opener ;
var sconf='';
if (this.config && this.document.context) sconf=JSON.stringify(this.config);
//console.log(this.config);
//console.log(JSON.stringify(this.config));
if(this.config.url){
var url = this.config.url ;
url = url.replace(new RegExp("(action=FDL_CARD)","i"),"action=VIEWEXTDOC");
//url = this.document.context.url + url ;
console.log('Calculated URL',url);
} else {
url = this.document.context.url + '?app=FDL&action=VIEWEXTDOC&id=' + this.document.getProperty('id') + '&extconfig='+encodeURI(sconf);
}
var mediaPanel = new Ext.ux.MediaPanel({
style: 'height:100%;',
bodyStyle: 'height:100%;',
border: false,
autoScroll: false,
mediaCfg: {
mediaType: 'HTM',
url: url
},
listeners : {
mediaload : function(panel,mediaObject){
me.mediaObject = mediaObject;
var menu = me.getTopToolbar();
console.log('MEDIA OBJECT',mediaObject);
me.generateMenu(panel,menu,mediaObject);
addEvent(mediaObject.dom,'load',function(){
var menu = me.getTopToolbar();
console.log('MEDIA OBJECT',mediaObject);
me.generateMenu(panel,menu,mediaObject);
});
}
}
});
this.add(mediaPanel);
this.doLayout();
},
renderEditClassic: function(){
var me = this ;
if(!this.config){
this.config = {};
}
if(this.config.url){
var url = this.config.url ;
url = url.replace(new RegExp("(app=GENERIC)","i"),"app=FDL");
url = url.replace(new RegExp("(action=GENERIC_EDIT)","i"),"action=EDITEXTDOC");
//url = this.document.context.url + url ;
console.log('Calculated URL',url);
} else {
var url = this.document.context.url + '?app=FDL&action=EDITEXTDOC&classid=' + this.document.getProperty('fromid') + '&id=' + this.document.getProperty('id');
}
var mediaPanel = new Ext.ux.MediaPanel({
style: 'height:100%;',
bodyStyle: 'height:100%;',
border: false,
autoScroll: false,
mediaCfg: {
mediaType: 'HTM',
url: url
},
listeners : {
mediaload : function(panel,mediaObject){
me.mediaObject = mediaObject;
var menu = me.getTopToolbar();
console.log('MEDIA OBJECT(1)',mediaObject);
me.generateMenu(panel,menu,mediaObject);
addEvent(mediaObject.dom,'load',function(){
var menu = me.getTopToolbar();
console.log('MEDIA OBJECT(2)',mediaObject);
me.generateMenu(panel,menu,mediaObject);
});
}
}
});
this.add(mediaPanel);
this.doLayout();
},
displayUrl: function(url,target,config){
this.publish('openurl',url,target,config);
},
addNote: function(){
var note = this.document.context.createDocument({
familyId: 'SIMPLENOTE',
mode: 'view'
});
if (note) {
note.setValue('note_pasteid', this.document.getProperty('initid'));
note.setValue('note_width', 200);
note.setValue('note_height', 200);
note.setValue('note_top', 50);
note.setValue('note_left', 50);
note.save();
this.document.reload();
var nid=note.getProperty('initid');
this.viewNotes();
var wnid = this.notes[nid];
if (wnid) {
var p = wnid.items.itemAt(0);
//console.log("note",p);
setTimeout(function(){
p.items.itemAt(0).items.itemAt(0).setVisible(false);
p.items.itemAt(0).items.itemAt(1).setVisible(true);
p.items.itemAt(0).items.itemAt(2).setVisible(true);
p.items.itemAt(0).items.itemAt(3).setVisible(true);
p.items.itemAt(0).items.itemAt(1).focus();
}, 1000);
}
}
},
viewNotes: function(config){
var noteids = this.document.getProperty('postitid');
if (noteids.length > 0) {
for (var i = 0; i < noteids.length; i++) {
if (noteids[i] > 0) {
var note;
if (!this.notes[noteids[i]]) {
note = this.document.context.getDocument({
id: noteids[i]
});
var wd = new Ext.fdl.Document({
style: 'padding:0px;margin:0px;',
bodyStyle: 'padding:0px;margin:0px;',
document: note,
anchor: '100% 100%',
displayToolbar: false,
listeners: {close: function (panel) {
panel.ownerCt.close();
}}
});
this.notes[noteids[i]] = wd;
}
else {
note = this.notes[noteids[i]].document;
}
if (note.isAlive()) {
var color = 'yellow';
var nocolor = note.getValue('note_color');
if (nocolor)
color = nocolor;
var x = parseInt(note.getValue('note_left'));
var y = parseInt(note.getValue('note_top'));
if ((!this.notes[noteids[i]].window) || (this.notes[noteids[i]].window.getWidth() == 0)) {
var notewin = new Ext.Window({
layout: 'fit',
cls: 'x-fdl-note',
style: 'padding:0px;margin:0px;background-color:' + color,
title: note.getTitle(),
closeAction: 'hide',
width: parseInt(note.getValue('note_width')),
height: parseInt(note.getValue('note_height')),
resizable: true,
note: note,
tools: [{
id: 'close',
qtip: 'Cacher la note',
// hidden:true,
handler: function(event, toolEl, panel){
panel.setVisible(false);
}
}],
plain: true,
renderTo: this.body,
constrain: true,
items: [this.notes[note.id]],
x: x,
y: y,
listeners: {
move: function(o){
if (this.note && (this.note.getProperty('owner') == this.note.context.getUser().id)) {
var xy = o.getPosition(true);
if ((o.getWidth() > 0) && (xy[0] > 0)) {
this.note.setValue('note_width', o.getWidth());
this.note.setValue('note_height', o.getHeight());
this.note.setValue('note_left', xy[0]);
this.note.setValue('note_top', xy[1]);
this.note.save();
}
}
},
close: function(o){
}
}
});
this.notes[noteids[i]].window = notewin;
notewin.show();
}
else {
if (config && config.undisplay)
this.notes[noteids[i]].window.setVisible(false);
else
this.notes[noteids[i]].window.setVisible(true);
}
}
}
}
}
},
includeJS: function(url){
console.log('Include JS', url);
if (window.XMLHttpRequest) {
var XHR = new XMLHttpRequest();
}
else {
var XHR = new ActiveXObject("Microsoft.XMLHTTP");
}
if (XHR) {
XHR.open("GET", (this.document.context.url + url), false);
XHR.send(null);
eval(XHR.responseText);
}
else {
return false;
}
},
detailSearch: function(){
return new Ext.fdl.DSearch({
document: this.document,
hidden: true,
border: false
});
},
documentToolbarStatus: function(){
// If document is in creation mode, no toolbar status to display
if(!this.document.id){
return false ;
}
var u = this.document.context.getUser();
var info = u.getInfo();
var statestatus = null;
var statestatustext = '';
if(this.document.getProperty('version')){
console.log('VERSION',this.document.getProperty('version'));
statestatustext = 'version ' + this.document.getProperty('version')+' ';
}
if (this.document.hasWorkflow()){
if(this.document.isFixed()) {
statestatustext += '<i>' + '<span style="padding-left:10px;margin-right:3px;background-color:' + this.document.getColorState() + '"> </span>' + this.document.getLocalisedState() + '</i>';
} else {
if (this.document.getActivityState()) {
statestatustext += '<i>' + this.document.getActivityState() + '</i>';
} else {
statestatustext += '<i>' + this.document.getLocalisedState() + '</i>';
}
}
}
if(statestatustext){
statestatus = new Ext.Toolbar.TextItem(statestatustext);
}
var lockstatus = null;
if (this.document.getProperty('locked') > 0) {
if (this.document.getProperty('locked') == info['id']) {
lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Verrouillé par ' + this.document.getProperty('locker') + '" src="' + this.document.context.url + 'FDL/Images/greenlock.png" style="height:16px" />');
}
else {
lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Vérrouillé par ' + this.document.getProperty('locker') + '" src="' + this.document.context.url + 'FDL/Images/redlock.png" style="height:16px" />');
}
}
var readstatus = null;
if (this.document.getProperty('locked') == -1) {
readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Figé" src="' + this.document.context.url + 'FDL/Images/readfixed.png" style="height:16px" />');
}
else
if (!this.document.canEdit()) {
readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Lecture seule" src="' + this.document.context.url + 'FDL/Images/readonly.png" style="height:16px" />');
}
var postitstatus = null;
if (this.document.getProperty('postitid').length > 0) {
//console.log(this.document.getProperty('postitid'));
postitstatus = new Ext.Button({
tooltip: 'Afficher/Cacher les notes',
text: 'Notes',
icon: this.document.context.url + 'Images/simplenote16.png',
scope: this,
handler: function(b, e){
this.displaynotes = (!this.displaynotes);
this.viewNotes({
undisplay: (!this.displaynotes)
});
}
});
}
// TODO Correct the icon path
var allocatedstatus = null;
if (this.document.getProperty('allocated')) {
var an = this.document.getProperty('allocatedname');
var aimg = this.document.context.url + "Images/allocatedred16.png";
if (this.document.getProperty('allocated') == this.document.context.getUser().id) {
aimg = this.document.context.url + "Images/allocatedgreen16.png";
}
allocatedstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Affecté à ' + an + '" src="' + aimg + '" style="height:16px" />');
}
return [statestatus,lockstatus, readstatus, postitstatus, allocatedstatus];
}
});
Ext.reg('fdl-document', Ext.fdl.Document);
Ext.fdl.SubDocument = Ext.extend(Ext.form.FormPanel, {
document: null,
context: null,
mode: 'view',
// Force Ext default rendering, ignoring generateVersion property
forceExt: false,
displayToolbar: true,
border: false,
bodyStyle: 'overflow-y:auto; padding: 0px;',
//frame: true,
autoHeight: false,
layout: 'form',
method: 'POST',
enctype: 'multipart/form-data',
fileUpload: true,
initComponent: function(){
if(!this.document){
console.log('Ext.fdl.Document is not provided a document.');
}
this.context = this.document.context;
Ext.fdl.SubDocument.superclass.initComponent.call(this);
},
close: function(){
console.log('DOCUMENT CLOSE');
this.fireEvent('close',this);
},
getHtmlValue: function(attrid, tag){
var as = this.document.getAttributes();
var ht = '';
for (var aid in as) {
oa = as[aid];
if (oa.parentId == attrid && oa.getValue) {
if (oa.getValue() != '')
ht += '<' + tag + '>' + oa.getLabel() + ' : ' + oa.getValue() + '</' + tag + '>';
}
}
return ht;
},
applyLink: function(attrid){
var me = this;
if (attrid) {
var text = me.document.getValue(attrid) || '';
var reg = new RegExp("", "ig");
reg.compile("\\[ADOC ([0-9]*)\\]", "ig");
var getLink = function(str, id){
var value = me.document.getValue(id);
var display = me.document.getDisplayValue(id);
return "<a class='docid' oncontextmenu='window.Fdl.ApplicationManager.displayDocument(" + value + ");return false;' href='javascript:window.Fdl.ApplicationManager.displayDocument(" + value + ");'> " +
// me.context.getDocument({
// id: id
// }).getTitle() +
display +
"</a>";
};
text = text.replace(reg, getLink);
}
return text;
},
orderAttribute: function(){
if (!this.ordered) {
function sortAttribute(attr1, attr2){
return attr1.rank - attr2.rank;
};
function giveRank(type){
for (var i = 0; i < ordered.length; i++) {
if (ordered[i].type == type) {
for (var j = 0; j < ordered.length; j++) {
if ((ordered[i].id == ordered[j].parentId) && (ordered[i].rank > ordered[j].rank || ordered[i].rank == 0)) {
ordered[i].rank = ordered[j].rank;
}
}
}
}
};
var ordered = new Array();
var as = this.document.getAttributes();
for (var aid in as) {
ordered.push(as[aid]);
}
//ordered = ordered.slice(); // Makes an independant copy of attribute array
// Each structuring attribute is given its children lowest rank
giveRank('array');
giveRank('frame');
giveRank('tab');
ordered.sort(sortAttribute);
this.ordered = ordered;
}
return this.ordered;
},
documentToolbarButton: function(){
var button = new Ext.Button({
text: 'Document',
menu: [{
xtype: 'menuitem',
text: this.context._("eui::ToEdit"),
scope: this,
handler: function(){
this.switchMode('edit');
},
disabled: !this.document.canEdit()
}, {
xtype: 'menuitem',
text: 'Verrouiller',
scope: this,
handler: function(){
this.document.lock();
Ext.Info.msg(this.document.getTitle(), "Verrouillage");
this.switchMode(this.mode);
},
disabled: !this.document.canEdit(),
hidden: (this.document.getProperty('locked') > 0 || this.document.getProperty('locked') == -1)
}, {
xtype: 'menuitem',
text: 'Déverrouiller',
scope: this,
handler: function(){
this.document.unlock();
Ext.Info.msg(this.document.getTitle(), "Déverrouillage");
this.switchMode(this.mode);
},
disabled: !this.document.canEdit(),
hidden: (this.document.getProperty('locked') == 0 || this.document.getProperty('locked') == -1)
}, {
xtype: 'menuitem',
text: 'Actualiser',
scope: this,
handler: function(){
this.document.reload();
this.switchMode(this.mode);
}
}, {
xtype: 'menuitem',
text: 'Supprimer',
scope: this,
handler: function(){
this.document.remove();
updateDesktop();
this.ownerCt.destroy();
}
}, {
xtype: 'menuitem',
text: 'Historique',
scope: this,
handler: function(){
var histowin = Ext.fdl.viewDocumentHistory(this.document);
histowin.show();
}
}, {
xtype: 'menuitem',
text: 'Ajouter une note',
scope: this,
handler: function(){
var nid = this.addNote();
this.viewNotes();
var wnid = this.notes[nid];
if (wnid) {
var p = wnid.items.itemAt(0);
setTimeout(function(){
p.items.itemAt(0).setVisible(false);
p.items.itemAt(1).setVisible(true);
p.items.itemAt(2).setVisible(true);
p.items.itemAt(3).setVisible(true);
p.items.itemAt(1).focus();
}, 1000);
}
},
hidden: (this.document.getProperty('locked') == -1)
}, {
xtype: 'menuitem',
text: 'Affecter un utilisateur',
scope: this,
handler: function(){
var o = this;
//console.log(o);
var oa = new Fdl.RelationAttribute({
relationFamilyId: 'IUSER'
});
console.log('THISDOCUMENT', this.document, oa);
oa._family = this.document;
//console.log(oa);
var wu = new Ext.fdl.DocId({
attribute: oa
});
var toolbar = new Ext.Toolbar({
scope: this,
items: [{
xtype: 'button',
text: 'Affecter',
scope: this,
handler: function(){
var uid = wu.getValue();
if (uid) {
if (this.document.allocate({
userId: uid
})) {
this.switchMode(this.mode);
}
else {
Ext.Msg.alert(Fdl.getLastErrorMessage());
}
w.close();
}
}
}, {
xtype: 'button',
scope: this,
text: 'Enlever l\'affectation',
handler: function(){
if (this.document.unallocate()) {
this.switchMode(this.mode);
}
else {
Ext.Msg.alert(Fdl.getLastErrorMessage());
}
w.close();
}
}, {
xtype: 'button',
text: 'Annuler',
handler: function(){
w.close();
}
}]
});
var w = new Ext.Window({
constrain: true,
renderTo: o.ownerCt.body,
title: 'Affecter un utilisateur',
bbar: toolbar,
items: [wu]
});
// var f = new Ext.FormPanel({
// items: [wu, toolbar]
// });
// w.add(f);
w.show();
(function(){
wu.focus();
}).defer(1000);
},
disabled: !this.document.canEdit()
}, {
xtype: 'menuitem',
text: 'Enregistrer une version',
scope: this,
handler: function(){
Ext.Msg.prompt('Version', 'Entrer le nom de la version', function(btn, text){
if (btn == 'ok') {
// Fdl.ApplicationManager.closeDocument(this.document.id);
var previousId = this.document.id;
// Add Revision change document id ...
this.document.addRevision({
version: text,
volatileVersion: true
});
// ... so we need to notify a document
//Fdl.ApplicationManager.notifyDocument(this.document, previousId);
// this.switchMode(this.mode);
// this.doLayout();
}
}, this);
},
disabled: !this.document.canEdit(),
hidden:(this.document.getProperty('doctype')!='F')
}]
});
return button;
},
cycleToolbarButton: function(){
if (this.document.hasWorkflow()) {
var menu = Array();
var fs = this.document.getFollowingStates();
for (var i = 0; i < fs.length; i++) {
menu.push({
xtype: 'menuitem',
text: fs[i].transition ? Ext.util.Format.capitalize(fs[i].transitionLabel) : "Passer à l'état : " + fs[i].label,
style: 'background-color:' + fs[i].color + ';',
scope: this,
to_state: fs[i].state,
handler: function(b, e){
var previousId = this.document.id;
if (this.document.changeState({
state: b.to_state
})) {
Fdl.ApplicationManager.notifyDocument(this.document, previousId);
Ext.Info.msg(this.document.getTitle(), "Changement d'état");
}
else {
// Error during state change
}
// this.switchMode(this.mode);
// this.doLayout();
}
});
}
menu.push({
xtype: 'menuitem',
text: 'Voir le graphe',
scope: this,
handler: function(){
var wid = this.document.getProperty('wid');
new Ext.Window({
title: 'Cycle pour ' + this.document.getTitle(),
resizable: true,
width: 800,
height: 400,
border: false,
items: [new Ext.ux.MediaPanel({
mediaCfg: {
mediaType: 'HTM',
url: '/?app=FDL&action=WORKFLOW_GRAPH&id=' + wid,
width: '100%',
height: '100%'
}
})]
}).show();
}
});
var button = new Ext.Button({
text: 'Cycle',
menu: menu
});
return button;
}
return null;
},
documentToolbarStatus: function(){
var u = this.document.context.getUser();
var info = u.getInfo();
var lockstatus = null;
if (this.document.getProperty('locked') > 0) {
if (this.document.getProperty('locked') == info['id']) {
lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Verrouillé par ' + this.document.getProperty('locker') + '" src="FDL/Images/greenlock.png" style="height:16px" />');
}
else {
lockstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Vérrouillé par ' + this.document.getProperty('locker') + '" src="FDL/Images/redlock.png" style="height:16px" />');
}
}
var readstatus = null;
if (this.document.getProperty('locked') == -1) {
readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Figé" src="FDL/Images/readfixed.png" style="height:16px" />');
}
else
if (!this.document.canEdit()) {
readstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Lecture seule" src="FDL/Images/readonly.png" style="height:16px" />');
}
var postitstatus = null;
if (this.document.getProperty('postitid').length > 0) {
//console.log(this.document.getProperty('postitid'));
postitstatus = new Ext.Button({
tooltip: 'Afficher/Cacher les notes',
text: 'Notes',
icon: 'Images/simplenote16.png',
scope: this,
handler: function(b, e){
this.displaynotes = (!this.displaynotes);
this.viewNotes({
undisplay: (!this.displaynotes)
});
}
});
}
// TODO Correct the icon path
var allocatedstatus = null;
if (this.document.getProperty('allocated')) {
var an = this.document.getProperty('allocatedname');
var aimg = "Images/allocatedred16.png";
if (this.document.getProperty('allocated') == this.document.context.getUser().id) {
aimg = "Images/allocatedgreen16.png";
}
allocatedstatus = new Ext.Toolbar.TextItem('<img ext:qtip="Affecté à ' + an + '" src="' + aimg + '" style="height:16px" />');
}
return [lockstatus, readstatus, postitstatus, allocatedstatus];
},
adminToolbarButton: function(){
var button = new Ext.Button({
text: 'Administration',
menu: [{
xtype: 'menuitem',
text: 'Famille',
scope: this,
handler: function(b, e){
Fdl.ApplicationManager.displayFamily(this.document.getProperty('fromid'));
}
}, {
xtype: 'menuitem',
text: 'Modifier le Cycle',
scope: this,
handler: function(b, e){
Fdl.ApplicationManager.displayCycleEditor(this.document.getProperty('wid'));
}
}, {
xtype: 'menuitem',
text: 'Administrer le Cycle',
scope: this,
handler: function(b, e){
Fdl.ApplicationManager.displayDocument(this.document.getProperty('wid'), 'edit');
}
}, {
xtype: 'menuitem',
text: 'Propriétés',
handler: function(b, e){
Ext.Msg.alert('Propriétés', 'Pas encore disponible.');
}
}]
});
return button;
},
renderToolbar: function(){
if (!this.displayToolbar) {
return false;
}
var toolbar = new Ext.Toolbar({
style: 'margin-bottom:10px;'
});
toolbar.add(this.documentToolbarButton());
// Add cycle toolbar button if applicable
var cycleToolbarButton = this.cycleToolbarButton();
if (cycleToolbarButton) {
toolbar.add(cycleToolbarButton);
}
// toolbar.add(this.adminToolbarButton());
toolbar.add(new Ext.Toolbar.Fill());
var toolbarStatus = this.documentToolbarStatus();
for (var i = 0; i < toolbarStatus.length; i++) {
if (toolbarStatus[i]) {
toolbar.add(toolbarStatus[i]);
}
}
return toolbar;
},
/**
*
* @param {Object} attrid
* @param {Object} config (display : if true returns widget even if value is empty)
*/
getExtValue: function(attrid, config){
if ((config && config.display) || this.alwaysDisplay) {
var display = true;
}
if ((config && config.hideHeader)) {
var hideHeader = true;
}
var attr = this.document.getAttribute(attrid);
if (!attr) {
return null;
}
var ordered = this.orderAttribute();
// Handle Visibility
switch (attr.getVisibility()) {
case 'W':
case 'R':
case 'S':
break;
case 'O':
case 'H':
case 'I':
return null;
break;
case 'U':
//For array, prevents add and delete of rows
break;
}
switch (attr.type) {
case 'menu':
case 'action':
return new Ext.Button({
text: attr.getLabel(),
handler: this.handleAction
});
break;
case 'text':
case 'longtext':
case 'date':
case 'integer':
case 'int':
case 'double':
case 'money':
if (this.document.getValue(attr.id) || display) {
return new Ext.fdl.DisplayField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id)
});
}
else {
return null;
}
break;
case 'htmltext':
if (this.document.getValue(attr.id) || display) {
return new Ext.fdl.DisplayField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.applyLink(attr.id)
});
}
else {
return null;
}
break;
case 'time':
if (this.document.getValue(attr.id) || display) {
return new Ext.form.TimeField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
disabled: true
});
}
else {
return null;
}
break;
case 'timestamp':
if (this.document.getValue(attr.id) || display) {
return new Ext.ux.form.DateTime({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
disabled: true
});
}
else {
return null;
}
break;
case 'password':
if (this.document.getValue(attr.id) || display) {
return new Ext.form.TextField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
inputType: 'password',
value: this.document.getValue(attr.id),
disabled: true
});
}
else {
return null;
}
break;
case 'image':
// return new Ext.form.FileUploadField({
// fieldLabel: attr.getLabel(),
// buttonCfg: {
// text: '',
// iconCls: 'upload-icon'
// },
// disabled: true
// });
return null;
break;
case 'color':
// return new Ext.form.ColorField({
// fieldLabel: attr.getLabel()
// })
////console.log('Attribute not represented : ' + attr.type);
return null;
break;
case 'frame':
var frame = new Ext.form.FieldSet({
title: Ext.util.Format.capitalize(attr.getLabel()),
autoHeight: true,
collapsible: true,
width: 'auto',
labelWidth: 150,
style: 'margin:10px;',
bodyStyle: 'padding-left:40px;width:auto;'
});
var empty = true;
for (var i = 0; i < ordered.length; i++) {
var curAttr = ordered[i];
if (curAttr.parentId == attr.id) {
var extValue = this.getExtValue(curAttr.id);
if (extValue != null) {
frame.add(extValue);
empty = false;
}
}
}
if (!empty || display) {
return frame;
}
else {
return null;
}
break;
case 'tab':
var tab = new Ext.Panel({
title: Ext.util.Format.capitalize(attr.getLabel()),
autoHeight: true,
autoWidth: true,
width: 'auto',
layout: 'form',
border: false,
defaults: {
//width: 'auto',
// as we use deferredRender:false we mustn't
// render tabs into display:none containers
hideMode: 'offsets'
}
});
var empty = true;
for (var i = 0; i < ordered.length; i++) {
var curAttr = ordered[i];
if (curAttr.parentId == attr.id) {
var extValue = this.getExtValue(curAttr.id);
if (extValue != null) {
tab.add(extValue);
empty = false;
}
}
}
if (!empty || display) {
return tab;
}
else {
return null;
}
break;
case 'array':
var elements = attr.getElements();
var fields = new Array();
for (var i = 0; i < elements.length; i++) {
fields.push(elements[i].id);
}
//console.log('VALUES',this.document.getValues(attr.id));
//var values = attr.getArrayValues()
var values = this.document.getValue(attr.id) || [];
if (values.length == 0 && !display) {
return null;
}
for (var i = 0; i < elements.length; i++) {
// Transform docid into links
if (elements[i].type == 'docid') {
for (var j = 0; j < values.length; j++) {
if (values[j][elements[i].id]) {
values[j][elements[i].id] = "<a class='docid' " +
'href="javascript:window.Fdl.ApplicationManager.displayDocument(' +
values[j][elements[i].id] +
');"' +
'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' +
values[j][elements[i].id] +
');return false;">' +
elements[i].getTitle()[j] +
"</a>";
}
else {
values[j][elements[i].id] = '';
}
}
}
// Transform enum with correct label
if (elements[i].type == 'enum') {
for (var j = 0; j < values.length; j++) {
values[j][elements[i].id] = elements[i].getEnumLabel({
key: values[j][elements[i].id]
});
}
}
}
var store = new Ext.data.JsonStore({
fields: fields,
data: values
});
var columns = [];
for (var i = 0; i < ordered.length; i++) {
var curAttr = ordered[i];
if (curAttr.parentId == attr.id) {
// Handle Visibility
switch (curAttr.getVisibility()) {
case 'W':
case 'R':
case 'S':
columns.push({
header: Ext.util.Format.capitalize(curAttr.getLabel()),
dataIndex: curAttr.id
});
break;
case 'O':
case 'H':
case 'I':
break;
case 'U':
//For array, prevents add and delete of rows
break;
}
}
}
var array = new Ext.grid.GridPanel({
title: Ext.util.Format.capitalize(attr.getLabel()),
autoHeight: true,
collapsible: true,
titleCollapse: true,
viewConfig: {
forceFit: true,
autoFill: true
},
animCollapse: false,
disableSelection: true,
store: store,
columns: columns,
style: 'margin-bottom:10px;',
header: !hideHeader,
border: false
});
return array;
break;
case 'enum':
//console.log('Attribute not represented : ' + attr.type);
return null;
break;
case 'docid':
if (this.document.getValue(attr.id) || display) {
if (attr.getOption('multiple') != 'yes') {
return new Ext.fdl.DisplayField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: "<a class='docid' " +
'href="javascript:window.Fdl.ApplicationManager.displayDocument(' +
this.document.getValue(attr.id) +
');"' +
'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' +
this.document.getValue(attr.id) +
');return false;">' +
(this.document.getDisplayValue(attr.id) || '') +
"</a>"
});
}
else {
var values = this.document.getValue(attr.id);
var displays = this.document.getDisplayValue(attr.id);
console.log('Attribute', values, displays);
var fieldValue = '';
for (var i = 0; i < values.length; i++) {
fieldValue += "<a class='docid' " +
'href="javascript:window.Fdl.ApplicationManager.displayDocument(' +
values[i] +
');"' +
'oncontextmenu="window.Fdl.ApplicationManager.displayDocument(' +
values[i] +
');return false;">' +
displays[i] +
"</a><br/>";
}
return new Ext.fdl.DisplayField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: fieldValue
});
}
}
else {
return null;
}
break;
case 'file':
if (this.document.getValue(attr.id) || display) {
return new Ext.fdl.DisplayField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: '<a class="docid" ' +
'href="' +
this.document.getDisplayValue(attr.id, {
url: true,
inline: false
}) +
'" >' +
this.document.getDisplayValue(attr.id) +
"</a>"
});
}
else {
return null;
}
break;
default:
//console.log('Attribute not represented : ' + attr.type);
return null;
break;
}
},
getHeader: function(){
return new Ext.Panel({
html: ""
/*
html: '<img src=' +
this.document.getIcon({
width: 48
}) +
' style="float:left;padding:0px 5px 5px 0px;" />' +
"<p style='font-size:12;'>" +
this.document.getProperty('fromtitle') +
'</p>' +
'<h1 style="display:inline;font-size:14;text-transform: uppercase;">' +
(this.document.getProperty('id') ? this.document.getTitle() : ('Création ' + this.document.getProperty('fromtitle'))) +
'</h1>' +
'<span style="padding-left:10px">' +
(this.document.getProperty('version') ? (' Version ' + this.document.getProperty('version')) : '') +
'</span>' +
(this.document.hasWorkflow() ?
"<p><i style='border-style:none none solid none;border-width:2px;border-color:" +
this.document.getColorState() +
"'>" +
(this.document.isFixed() ? ('(' + this.document.getLocalisedState() + ') ') : '') )+
"<b>" +
(this.document.getActivityState() ? Ext.util.Format.capitalize(this.document.getActivityState()) : '') +
"</b>" +
'</i></p>'*/
});
},
/**
* Get Ext default input component for a given id.
* @param {Object} attrid
* @param {Object} inArray
* @param {Object} rank
* @param {Object} defaultValue
* @param {Object} empty
*/
getExtInput: function(attrid, inArray, rank, defaultValue, empty){
var attr = this.document.getAttribute(attrid);
if (!attr) {
return null;
}
//var name = inArray ? attr.id + '[]' : attr.id;
var name = attr.id;
var ordered = this.orderAttribute();
// Handle Visibility
switch (attr.getVisibility()) {
case 'W':
case 'O':
break;
case 'R':
case 'H':
case 'I':
return null;
break;
case 'S':
//Viewable in edit mode but not editable
var disabled = true;
break;
case 'U':
//For array, prevents add and delete of rows
break;
}
switch (attr.type) {
case 'menu':
// return new Ext.Button({
// text: Ext.util.Format.capitalize(attr.getLabel()),
// handler: this.handleAction
// });
break;
case 'text':
return new Ext.fdl.Text({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null,
name: name,
allowBlank: !attr.needed,
disabled: disabled
});
break;
case 'longtext':
return new Ext.fdl.LongText({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null,
name: name,
allowBlank: !attr.needed,
disabled: disabled
});
break;
case 'htmltext':
return new Ext.fdl.HtmlText({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
name: name,
disabled: disabled
});
break;
case 'int':
case 'integer':
return new Ext.fdl.Integer({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
name: name,
allowBlank: !attr.needed,
disabled: disabled
});
break;
case 'double':
return new Ext.fdl.Double({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
name: name,
allowBlank: !attr.needed,
disabled: disabled
});
break;
case 'money':
return new Ext.fdl.Money({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
name: name,
allowBlank: !attr.needed,
disabled: disabled
});
break;
case 'date':
return new Ext.fdl.Date({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
altFormats: 'd-j-Y|d-m-Y',
format: 'd/m/Y',
value: !empty ? (rank != undefined ? this.document.getValue(attr.id)[rank] : this.document.getValue(attr.id)) : null,
name: name,
disabled: disabled
});
break;
case 'time':
return new Ext.form.TimeField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
value: this.document.getValue(attr.id),
name: name,
disabled: disabled
});
break;
case 'timestamp':
return new Ext.ux.form.DateTime({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
name: name,
disabled: disabled
});
break;
case 'password':
return new Ext.form.TextField({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
inputType: 'password',
value: this.document.getValue(attr.id),
name: name,
disabled: disabled
});
break;
case 'image':
return new Ext.fdl.Image({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
name: name,
value: attr.getFileName()
});
break;
case 'file':
return new Ext.fdl.File({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
name: name,
value: attr.getFileName()
});
break;
case 'color':
return new Ext.fdl.Color({
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
name: name
});
break;
case 'frame':
var frame = new Ext.form.FieldSet({
title: Ext.util.Format.capitalize(attr.getLabel()),
autoHeight: true,
autoWidth: true,
collapsible: true,
labelWidth: 150,
//width: 'auto',
style: 'margin:10px;',
//bodyStyle: 'padding-left:40px;width:auto;'
bodyStyle: 'padding-left:20px;',
anchor: '100%'
});
for (var i = 0; i < ordered.length; i++) {
var curAttr = ordered[i];
if (curAttr.parentId == attr.id) {
var ext_input = this.getExtInput(curAttr.id);
if (ext_input != null) {
frame.add(ext_input);
}
}
}
return frame;
break;
case 'tab':
var tab = new Ext.Panel({
title: Ext.util.Format.capitalize(attr.getLabel()),
autoHeight: true,
autoWidth: true,
//frame: true,
layout: 'form',
border: false,
defaults: { // as we use deferredRender:false we mustn't
// render tabs into display:none containers
//hideMode: 'offsets'
}
});
var empty = true;
for (var i = 0; i < ordered.length; i++) {
var curAttr = ordered[i];
if (curAttr.parentId == attr.id) {
tab.add(this.getExtInput(curAttr.id));
empty = false;
}
}
if (!empty) {
return tab;
}
else {
return null;
}
break;
// Improvement for using RowEditor with array
/* case 'array':
var elements = attr.getElements();
var values = attr.getArrayValues();
var docWidget = this;
var columns = [new Ext.grid.RowNumberer()];
var fields = [];
for (var i = 0; i < elements.length; i++) {
var attr = this.document.getAttribute(elements[i].id);
var col = Ext.apply({},{
editor: this.getExtInput(elements[i].id, true, null, null, true),
header: attr.getLabel(),
dataIndex: elements[i].id,
hideable: false,
viewCfg: {
autoFill: true,
forceFit: true
}
});
//should be a method
switch(attr.type){
case 'docid':
var renderer = attr.getTitle.createDelegate(attr);
//this is not the good renderer
//the good one would only be fdl.getTitle
//that does not exists currently
break;
default:
var renderer = null;
break;
}
if(renderer){
Ext.apply(col, {
renderer: renderer
});
}
//EO method
var field = Ext.apply({},{
name: elements[i].id
})
columns.push(col);
fields.push(field);
}
var store = new Ext.data.Store({
reader: new Ext.data.JsonReader({
fields: fields
}),
data: values
})
// not forget to include ext/examples/ux/RowEditor.js
//maybe work on roweditor about last row...
var editor = new Ext.ux.RowEditor({
saveText: 'Update'
});
//var arrayPanel = new Ext.grid.EditorGridPanel({ //only gridpanel if using roweditor!
var arrayPanel = new Ext.grid.GridPanel({
title: Ext.util.Format.capitalize(attr.getLabel()),
frame: true,
plugins:[editor],
collapsible: true,
titleCollapse: true,
animCollapse: false,
style: 'margin-bottom:10px;',
columns: columns,
store: store,
autoHeight: true,
autoScroll: true,
bbar: [{
ref: '../addBtn',
iconCls: 'icon-row-add',
text: 'Add row',
handler: function(){
var e = new store.recordType();
editor.stopEditing();
store.insert(0, e);
arrayPanel.getView().refresh();
arrayPanel.getSelectionModel().selectRow(0);
editor.startEditing(0);
}
},{
ref: '../removeBtn',
iconCls: 'icon-row-delete',
text: 'Remove row',
disabled: true,
handler: function(){
editor.stopEditing();
var s = arrayPanel.getSelectionModel().getSelections();
for(var i = 0, r; r = s[i]; i++){
store.remove(r);
}
}
}]
});
arrayPanel.getSelectionModel().on('selectionchange', function(sm){
arrayPanel.removeBtn.setDisabled(sm.getCount() < 1);
});
return arrayPanel;
break;
*/
case 'array':
var elements = attr.getElements();
var fields = new Array();
for (var i = 0; i < elements.length; i++) {
fields.push(elements[i].id);
}
//var values = attr.getArrayValues();
var values = this.document.getValue(attr.id) || [];
var docWidget = this;
var columns = 0;
for (var i = 0; i < elements.length; i++) {
// Handle Visibility
switch (elements[i].getVisibility()) {
case 'W':
case 'O':
columns++;
break;
}
}
var arrayPanel = new Ext.Panel({
title: Ext.util.Format.capitalize(attr.getLabel()),
frame: true,
collapsible: true,
titleCollapse: true,
animCollapse: false,
style: 'margin-bottom:10px;',
layout: 'table',
layoutConfig: {
columns: columns
},
bbar: [{
text: 'Ajouter',
tooltip: 'Ajouter',
scope: docWidget,
handler: function(){
// For each columnPanel child
// Add one row of editor widget
var elements = attr.getElements();
for (var i = 0; i < elements.length; i++) {
switch (elements[i].getVisibility()) {
case 'W':
case 'O':
var editorWidget = this.getExtInput(elements[i].id, true, null, null, true);
arrayPanel.add(editorWidget);
break;
}
}
arrayPanel.doLayout();
}
}]
});
for (var i = 0; i < elements.length; i++) {
// Handle Visibility
switch (elements[i].getVisibility()) {
case 'W':
case 'O':
switch (elements[i].type) {
case 'enum':
if (attr.getOption('eformat') == 'bool') {
var width = 60;
}
else {
var width = 120;
}
break;
case 'docid':
var width = 200;
break;
case 'date':
var width = 110;
break;
default:
var width = 100;
break;
}
var columnPanel = new Ext.Panel({
title: Ext.util.Format.capitalize(elements[i].getLabel()),
width: width,
style: 'overflow:auto;',
bodyStyle: 'text-align:center;margin-top:3px;',
frame: false,
layout: 'form',
hideLabels: true
});
arrayPanel.add(columnPanel);
break;
}
}
for (var j = 0; j < values.length; j++) {
for (var i = 0; i < elements.length; i++) {
switch (elements[i].getVisibility()) {
case 'W':
case 'O':
var editorWidget = this.getExtInput(elements[i].id, true, j, values[j][elements[i].id]);
arrayPanel.add(editorWidget);
}
}
}
return arrayPanel;
break;
case 'enum':
// var label = attr.getEnumLabel({
// key: this.document.getValue(attr.id)[rank]
// });
//
// if (attr.getOption('eformat') == 'bool') {
//
// return new Ext.ux.form.XCheckbox({
// fieldLabel: inArray ? ' ' : Ext.util.Format.capitalize(attr.getLabel()),
// //boxLabel: inArray ? '' : Ext.util.Format.capitalize(attr.getLabel()) ,
// checked: this.document.getValue(attr.id)[rank] == 'yes' ? true : false,
// submitOnValue: 'yes',
// submitOffValue: 'no',
// name: name,
// style: inArray ? 'margin:auto;' : ''
// });
//
// }
// else {
//
// var items = attr.getEnumItems();
//
// return new Ext.form.ComboBox({
//
// fieldLabel: inArray ? ' ' : Ext.util.Format.capitalize(attr.getLabel()),
//
// valueField: 'key',
// displayField: 'label',
//
// width: 150,
//
// // Required to give simple select behaviour
// //emptyText: '--Famille--',
// editable: false,
// forceSelection: true,
// disableKeyFilter: true,
// triggerAction: 'all',
// mode: 'local',
//
// value: items[0].key,
//
// store: new Ext.data.JsonStore({
// data: items,
// fields: ['key', 'label']
// })
//
// });
//
// }
break;
case 'docid':
if (attr.getOption('multiple') == 'yes') {
return new Ext.fdl.MultiDocId({
attribute: attr,
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
docIdList: this.document.getValue(attr.id),
docTitleList: this.document.getValue(attr.id + '_title')
});
}
else {
return new Ext.fdl.DocId({
attribute: attr,
fieldLabel: Ext.util.Format.capitalize(attr.getLabel()),
//value: this.document.getValue(attr.id),
value: !empty ? (rank != null ? this.document.getDisplayValue(attr.id)[rank] : this.document.getDisplayValue(attr.id)) : null,
//name: attr.id,
hiddenName: name,
hiddenValue: !empty ? (defaultValue != null ? defaultValue : this.document.getValue(attr.id)) : null,
allowBlank: !attr.needed,
disabled: disabled
});
}
break;
default:
console.log('Attribute not represented : ' + attr.type);
return null;
break;
}
}
});
| Eric-Brison/dynacase-core | Zone/Ui/widget-document.js | JavaScript | agpl-3.0 | 80,977 |
<?php
namespace App\Http\Controllers;
use enshrined\svgSanitize\Sanitizer;
use App\Helpers\Helper;
use App\Http\Requests\ImageUploadRequest;
use App\Http\Requests\SettingsSamlRequest;
use App\Http\Requests\SetupUserRequest;
use App\Models\Setting;
use App\Models\User;
use App\Notifications\FirstAdminNotification;
use App\Notifications\MailTest;
use Artisan;
use Auth;
use Crypt;
use DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Image;
use Input;
use Redirect;
use Response;
/**
* This controller handles all actions related to Settings for
* the Snipe-IT Asset Management application.
*
* @version v1.0
*/
class SettingsController extends Controller
{
/**
* Checks to see whether or not the database has a migrations table
* and a user, otherwise display the setup view.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupIndex()
{
$start_settings['php_version_min'] = false;
if (version_compare(PHP_VERSION, config('app.min_php'), '<')) {
return response('<center><h1>This software requires PHP version ' . config('app.min_php') . ' or greater. This server is running ' . PHP_VERSION . '. </h1><h2>Please upgrade PHP on this server and try again. </h2></center>', 500);
}
try {
$conn = DB::select('select 2 + 2');
$start_settings['db_conn'] = true;
$start_settings['db_name'] = DB::connection()->getDatabaseName();
$start_settings['db_error'] = null;
} catch (\PDOException $e) {
$start_settings['db_conn'] = false;
$start_settings['db_name'] = config('database.connections.mysql.database');
$start_settings['db_error'] = $e->getMessage();
}
$protocol = array_key_exists('HTTPS', $_SERVER) && ('on' == $_SERVER['HTTPS']) ? 'https://' : 'http://';
$host = array_key_exists('SERVER_NAME', $_SERVER) ? $_SERVER['SERVER_NAME'] : null;
$port = array_key_exists('SERVER_PORT', $_SERVER) ? $_SERVER['SERVER_PORT'] : null;
if (('http://' === $protocol && '80' != $port) || ('https://' === $protocol && '443' != $port)) {
$host .= ':' . $port;
}
$pageURL = $protocol . $host . $_SERVER['REQUEST_URI'];
$start_settings['url_valid'] = (url('/') . '/setup' === $pageURL);
$start_settings['url_config'] = url('/');
$start_settings['real_url'] = $pageURL;
$start_settings['php_version_min'] = true;
// Curl the .env file to make sure it's not accessible via a browser
$ch = curl_init($protocol . $host . '/.env');
curl_setopt($ch, CURLOPT_HEADER, true); // we want headers
curl_setopt($ch, CURLOPT_NOBODY, true); // we don't need body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if (404 == $httpcode || 403 == $httpcode || 0 == $httpcode) {
$start_settings['env_exposed'] = false;
} else {
$start_settings['env_exposed'] = true;
}
if (\App::Environment('production') && (true == config('app.debug'))) {
$start_settings['debug_exposed'] = true;
} else {
$start_settings['debug_exposed'] = false;
}
$environment = app()->environment();
if ('production' != $environment) {
$start_settings['env'] = $environment;
$start_settings['prod'] = false;
} else {
$start_settings['env'] = $environment;
$start_settings['prod'] = true;
}
if (function_exists('posix_getpwuid')) { // Probably Linux
$owner = posix_getpwuid(fileowner($_SERVER['SCRIPT_FILENAME']));
$start_settings['owner'] = $owner['name'];
} else { // Windows
// TODO: Is there a way of knowing if a windows user has elevated permissions
// This just gets the user name, which likely isn't 'root'
// $start_settings['owner'] = getenv('USERNAME');
$start_settings['owner'] = '';
}
if (('root' === $start_settings['owner']) || ('0' === $start_settings['owner'])) {
$start_settings['owner_is_admin'] = true;
} else {
$start_settings['owner_is_admin'] = false;
}
if ((is_writable(storage_path()))
&& (is_writable(storage_path() . '/framework'))
&& (is_writable(storage_path() . '/framework/cache'))
&& (is_writable(storage_path() . '/framework/sessions'))
&& (is_writable(storage_path() . '/framework/views'))
&& (is_writable(storage_path() . '/logs'))
) {
$start_settings['writable'] = true;
} else {
$start_settings['writable'] = false;
}
$start_settings['gd'] = extension_loaded('gd');
return view('setup/index')
->with('step', 1)
->with('start_settings', $start_settings)
->with('section', 'Pre-Flight Check');
}
/**
* Save the first admin user from Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return Redirect
*/
public function postSaveFirstAdmin(SetupUserRequest $request)
{
$user = new User();
$user->first_name = $data['first_name'] = $request->input('first_name');
$user->last_name = $request->input('last_name');
$user->email = $data['email'] = $request->input('email');
$user->activated = 1;
$permissions = ['superuser' => 1];
$user->permissions = json_encode($permissions);
$user->username = $data['username'] = $request->input('username');
$user->password = bcrypt($request->input('password'));
$data['password'] = $request->input('password');
$settings = new Setting();
$settings->full_multiple_companies_support = $request->input('full_multiple_companies_support', 0);
$settings->site_name = $request->input('site_name');
$settings->alert_email = $request->input('email');
$settings->alerts_enabled = 1;
$settings->pwd_secure_min = 10;
$settings->brand = 1;
$settings->locale = $request->input('locale', 'en');
$settings->default_currency = $request->input('default_currency', 'USD');
$settings->user_id = 1;
$settings->email_domain = $request->input('email_domain');
$settings->email_format = $request->input('email_format');
$settings->next_auto_tag_base = 1;
$settings->auto_increment_assets = $request->input('auto_increment_assets', 0);
$settings->auto_increment_prefix = $request->input('auto_increment_prefix');
if ((! $user->isValid()) || (! $settings->isValid())) {
return redirect()->back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors());
} else {
$user->save();
Auth::login($user, true);
$settings->save();
if ('1' == Input::get('email_creds')) {
$data = [];
$data['email'] = $user->email;
$data['username'] = $user->username;
$data['first_name'] = $user->first_name;
$data['last_name'] = $user->last_name;
$data['password'] = $request->input('password');
$user->notify(new FirstAdminNotification($data));
}
return redirect()->route('setup.done');
}
}
/**
* Return the admin user creation form in Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupUser()
{
return view('setup/user')
->with('step', 3)
->with('section', 'Create a User');
}
/**
* Return the view that tells the user that the Setup is done.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupDone()
{
return view('setup/done')
->with('step', 4)
->with('section', 'Done!');
}
/**
* Migrate the database tables, and return the output
* to a view for Setup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function getSetupMigrate()
{
Artisan::call('migrate', ['--force' => true]);
if ((! file_exists(storage_path() . '/oauth-private.key')) || (! file_exists(storage_path() . '/oauth-public.key'))) {
Artisan::call('migrate', ['--path' => 'vendor/laravel/passport/database/migrations', '--force' => true]);
Artisan::call('passport:install');
}
return view('setup/migrate')
->with('output', 'Databases installed!')
->with('step', 2)
->with('section', 'Create Database Tables');
}
/**
* Return a view that shows some of the key settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function index()
{
$settings = Setting::getSettings();
return view('settings/index', compact('settings'));
}
/**
* Return the admin settings page.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getEdit()
{
$setting = Setting::getSettings();
return view('settings/general', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getSettings()
{
$setting = Setting::getSettings();
return view('settings/general', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postSettings(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->modellist_displays = '';
if (($request->filled('show_in_model_list')) && (count($request->input('show_in_model_list')) > 0))
{
$setting->modellist_displays = implode(',', $request->input('show_in_model_list'));
}
$setting->full_multiple_companies_support = $request->input('full_multiple_companies_support', '0');
$setting->unique_serial = $request->input('unique_serial', '0');
$setting->show_images_in_email = $request->input('show_images_in_email', '0');
$setting->show_archived_in_list = $request->input('show_archived_in_list', '0');
$setting->dashboard_message = $request->input('dashboard_message');
$setting->email_domain = $request->input('email_domain');
$setting->email_format = $request->input('email_format');
$setting->username_format = $request->input('username_format');
$setting->require_accept_signature = $request->input('require_accept_signature');
$setting->show_assigned_assets = $request->input('show_assigned_assets', '0');
if (! config('app.lock_passwords')) {
$setting->login_note = $request->input('login_note');
}
$setting->default_eula_text = $request->input('default_eula_text');
$setting->thumbnail_max_h = $request->input('thumbnail_max_h');
$setting->privacy_policy_link = $request->input('privacy_policy_link');
$setting->depreciation_method = $request->input('depreciation_method');
if ('' != Input::get('per_page')) {
$setting->per_page = $request->input('per_page');
} else {
$setting->per_page = 200;
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getBranding()
{
$setting = Setting::getSettings();
return view('settings.branding', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postBranding(ImageUploadRequest $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->brand = $request->input('brand', '1');
$setting->header_color = $request->input('header_color');
$setting->support_footer = $request->input('support_footer');
$setting->version_footer = $request->input('version_footer');
$setting->footer_text = $request->input('footer_text');
$setting->skin = $request->input('skin');
$setting->show_url_in_emails = $request->input('show_url_in_emails', '0');
$setting->logo_print_assets = $request->input('logo_print_assets', '0');
// Only allow the site name and CSS to be changed if lock_passwords is false
// Because public demos make people act like dicks
if (! config('app.lock_passwords')) {
$setting->site_name = $request->input('site_name');
$setting->custom_css = $request->input('custom_css');
}
if ($request->hasFile('logo')) {
$image = $request->file('logo');
$ext = $image->getClientOriginalExtension();
$setting->logo = $file_name = 'logo-.'.date('Y-m-d').'.'. $ext;
if ('svg' != $image->getClientOriginalExtension()) {
$upload = Image::make($image->getRealPath())->resize(null, 150, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($file_name, (string) $upload->encode());
// Remove Current image if exists
if (($setting->logo) && (file_exists($file_name))) {
Storage::disk('public')->delete($file_name);
}
} elseif ('1' == $request->input('clear_logo')) {
Storage::disk('public')->delete($setting->logo);
$setting->logo = null;
$setting->brand = 1;
}
if ($request->hasFile('email_logo')) {
$email_image = $email_upload = $request->file('email_logo');
$email_ext = $email_image->getClientOriginalExtension();
$setting->email_logo = $email_file_name = 'email_logo.' . $email_ext;
if ('svg' != $email_image->getClientOriginalExtension()) {
$email_upload = Image::make($email_image->getRealPath())->resize(null, 100, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($email_file_name, (string) $email_upload->encode());
// Remove Current image if exists
if (($setting->email_logo) && (file_exists($email_file_name))) {
Storage::disk('public')->delete($email_file_name);
}
} elseif ('1' == $request->input('clear_email_logo')) {
Storage::disk('public')->delete($setting->email_logo);
$setting->email_logo = null;
// If they are uploading an image, validate it and upload it
}
// If the user wants to clear the label logo...
if ($request->hasFile('label_logo')) {
$image = $request->file('label_logo');
$ext = $image->getClientOriginalExtension();
$setting->label_logo = $label_file_name = 'label_logo.' . $ext;
if ('svg' != $image->getClientOriginalExtension()) {
$upload = Image::make($image->getRealPath())->resize(null, 100, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
}
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($label_file_name, (string) $upload->encode());
// Remove Current image if exists
if (($setting->label_logo) && (file_exists($label_file_name))) {
Storage::disk('public')->delete($label_file_name);
}
} elseif ('1' == $request->input('clear_label_logo')) {
Storage::disk('public')->delete($setting->label_logo);
$setting->label_logo = null;
// If they are uploading an image, validate it and upload it
}
// If the user wants to clear the favicon...
if ($request->hasFile('favicon')) {
$favicon_image = $favicon_upload = $request->file('favicon');
$favicon_ext = $favicon_image->getClientOriginalExtension();
$setting->favicon = $favicon_file_name = 'favicon-uploaded.' . $favicon_ext;
if (('ico' != $favicon_image->getClientOriginalExtension()) && ('svg' != $favicon_image->getClientOriginalExtension())) {
$favicon_upload = Image::make($favicon_image->getRealPath())->resize(null, 36, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
});
// This requires a string instead of an object, so we use ($string)
Storage::disk('public')->put($favicon_file_name, (string) $favicon_upload->encode());
} else {
Storage::disk('public')->put($favicon_file_name, file_get_contents($request->file('favicon')));
}
// Remove Current image if exists
if (($setting->favicon) && (file_exists($favicon_file_name))) {
Storage::disk('public')->delete($favicon_file_name);
}
} elseif ('1' == $request->input('clear_favicon')) {
Storage::disk('public')->delete($setting->clear_favicon);
$setting->favicon = null;
// If they are uploading an image, validate it and upload it
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getSecurity()
{
$setting = Setting::getSettings();
return view('settings.security', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postSecurity(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
if (! config('app.lock_passwords')) {
if ('' == $request->input('two_factor_enabled')) {
$setting->two_factor_enabled = null;
} else {
$setting->two_factor_enabled = $request->input('two_factor_enabled');
}
// remote user login
$setting->login_remote_user_enabled = (int) $request->input('login_remote_user_enabled');
$setting->login_common_disabled = (int) $request->input('login_common_disabled');
$setting->login_remote_user_custom_logout_url = $request->input('login_remote_user_custom_logout_url');
$setting->login_remote_user_header_name = $request->input('login_remote_user_header_name');
}
$setting->pwd_secure_uncommon = (int) $request->input('pwd_secure_uncommon');
$setting->pwd_secure_min = (int) $request->input('pwd_secure_min');
$setting->pwd_secure_complexity = '';
if ($request->filled('pwd_secure_complexity')) {
$setting->pwd_secure_complexity = implode('|', $request->input('pwd_secure_complexity'));
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getLocalization()
{
$setting = Setting::getSettings();
return view('settings.localization', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postLocalization(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
if (! config('app.lock_passwords')) {
$setting->locale = $request->input('locale', 'en');
}
$setting->default_currency = $request->input('default_currency', '$');
$setting->date_display_format = $request->input('date_display_format');
$setting->time_display_format = $request->input('time_display_format');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getAlerts()
{
$setting = Setting::getSettings();
return view('settings.alerts', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postAlerts(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$alert_email = rtrim($request->input('alert_email'), ',');
$alert_email = trim($alert_email);
$admin_cc_email = rtrim($request->input('admin_cc_email'), ',');
$admin_cc_email = trim($admin_cc_email);
$setting->alert_email = $alert_email;
$setting->admin_cc_email = $admin_cc_email;
$setting->alerts_enabled = $request->input('alerts_enabled', '0');
$setting->alert_interval = $request->input('alert_interval');
$setting->alert_threshold = $request->input('alert_threshold');
$setting->audit_interval = $request->input('audit_interval');
$setting->audit_warning_days = $request->input('audit_warning_days');
$setting->show_alerts_in_menu = $request->input('show_alerts_in_menu', '0');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getSlack()
{
$setting = Setting::getSettings();
return view('settings.slack', compact('setting'));
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postSlack(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$validatedData = $request->validate([
'slack_channel' => 'regex:/(?<!\w)#\w+/|required_with:slack_endpoint|nullable',
]);
if ($validatedData) {
$setting->slack_endpoint = $request->input('slack_endpoint');
$setting->slack_channel = $request->input('slack_channel');
$setting->slack_botname = $request->input('slack_botname');
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getAssetTags()
{
$setting = Setting::getSettings();
return view('settings.asset_tags', compact('setting'));
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postAssetTags(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->auto_increment_prefix = $request->input('auto_increment_prefix');
$setting->auto_increment_assets = $request->input('auto_increment_assets', '0');
$setting->zerofill_count = $request->input('zerofill_count');
$setting->next_auto_tag_base = $request->input('next_auto_tag_base');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function getBarcodes()
{
$setting = Setting::getSettings();
$is_gd_installed = extension_loaded('gd');
return view('settings.barcodes', compact('setting'))->with('is_gd_installed', $is_gd_installed);
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.0]
*
* @return View
*/
public function postBarcodes(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->qr_code = $request->input('qr_code', '0');
$setting->alt_barcode = $request->input('alt_barcode');
$setting->alt_barcode_enabled = $request->input('alt_barcode_enabled', '0');
$setting->barcode_type = $request->input('barcode_type');
$setting->qr_text = $request->input('qr_text');
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getPhpInfo()
{
if (true === config('app.debug')) {
return view('settings.phpinfo');
}
return redirect()->route('settings.index')
->with('error', 'PHP syetem debugging information is only available when debug is enabled in your .env file.');
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getLabels()
{
$setting = Setting::getSettings();
return view('settings.labels', compact('setting'));
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function postLabels(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->labels_per_page = $request->input('labels_per_page');
$setting->labels_width = $request->input('labels_width');
$setting->labels_height = $request->input('labels_height');
$setting->labels_pmargin_left = $request->input('labels_pmargin_left');
$setting->labels_pmargin_right = $request->input('labels_pmargin_right');
$setting->labels_pmargin_top = $request->input('labels_pmargin_top');
$setting->labels_pmargin_bottom = $request->input('labels_pmargin_bottom');
$setting->labels_display_bgutter = $request->input('labels_display_bgutter');
$setting->labels_display_sgutter = $request->input('labels_display_sgutter');
$setting->labels_fontsize = $request->input('labels_fontsize');
$setting->labels_pagewidth = $request->input('labels_pagewidth');
$setting->labels_pageheight = $request->input('labels_pageheight');
$setting->labels_display_company_name = $request->input('labels_display_company_name', '0');
$setting->labels_display_company_name = $request->input('labels_display_company_name', '0');
if ($request->filled('labels_display_name')) {
$setting->labels_display_name = 1;
} else {
$setting->labels_display_name = 0;
}
if ($request->filled('labels_display_serial')) {
$setting->labels_display_serial = 1;
} else {
$setting->labels_display_serial = 0;
}
if ($request->filled('labels_display_tag')) {
$setting->labels_display_tag = 1;
} else {
$setting->labels_display_tag = 0;
}
if ($request->filled('labels_display_tag')) {
$setting->labels_display_tag = 1;
} else {
$setting->labels_display_tag = 0;
}
if ($request->filled('labels_display_model')) {
$setting->labels_display_model = 1;
} else {
$setting->labels_display_model = 0;
}
if ($setting->save()) {
return redirect()->route('settings.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getLdapSettings()
{
$setting = Setting::getSettings();
return view('settings.ldap', compact('setting'));
}
/**
* Saves settings from form.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function postLdapSettings(Request $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->ldap_enabled = $request->input('ldap_enabled', '0');
$setting->ldap_server = $request->input('ldap_server');
$setting->ldap_server_cert_ignore = $request->input('ldap_server_cert_ignore', false);
$setting->ldap_uname = $request->input('ldap_uname');
if ($request->input('ldap_pword') !== '') {
$setting->ldap_pword = Crypt::encrypt($request->input('ldap_pword'));
}
$setting->ldap_basedn = $request->input('ldap_basedn');
$setting->ldap_filter = $request->input('ldap_filter');
$setting->ldap_username_field = $request->input('ldap_username_field');
$setting->ldap_lname_field = $request->input('ldap_lname_field');
$setting->ldap_fname_field = $request->input('ldap_fname_field');
$setting->ldap_auth_filter_query = $request->input('ldap_auth_filter_query');
$setting->ldap_version = $request->input('ldap_version');
$setting->ldap_active_flag = $request->input('ldap_active_flag');
$setting->ldap_emp_num = $request->input('ldap_emp_num');
$setting->ldap_email = $request->input('ldap_email');
$setting->ad_domain = $request->input('ad_domain');
$setting->is_ad = $request->input('is_ad', '0');
$setting->ldap_tls = $request->input('ldap_tls', '0');
$setting->ldap_pw_sync = $request->input('ldap_pw_sync', '0');
$setting->custom_forgot_pass_url = $request->input('custom_forgot_pass_url');
if ($setting->save()) {
return redirect()->route('settings.ldap.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Return a form to allow a super admin to update settings.
*
* @author Johnson Yi <jyi.dev@outlook.com>
*
* @since v5.0.0
*
* @return View
*/
public function getSamlSettings()
{
$setting = Setting::getSettings();
return view('settings.saml', compact('setting'));
}
/**
* Saves settings from form.
*
* @author Johnson Yi <jyi.dev@outlook.com>
*
* @since v5.0.0
*
* @return View
*/
public function postSamlSettings(SettingsSamlRequest $request)
{
if (is_null($setting = Setting::getSettings())) {
return redirect()->to('admin')->with('error', trans('admin/settings/message.update.error'));
}
$setting->saml_enabled = $request->input('saml_enabled', '0');
$setting->saml_idp_metadata = $request->input('saml_idp_metadata');
$setting->saml_attr_mapping_username = $request->input('saml_attr_mapping_username');
$setting->saml_forcelogin = $request->input('saml_forcelogin', '0');
$setting->saml_slo = $request->input('saml_slo', '0');
if (!empty($request->input('saml_sp_privatekey'))) {
$setting->saml_sp_x509cert = $request->input('saml_sp_x509cert');
$setting->saml_sp_privatekey = $request->input('saml_sp_privatekey');
}
$setting->saml_custom_settings = $request->input('saml_custom_settings');
if ($setting->save()) {
return redirect()->route('settings.saml.index')
->with('success', trans('admin/settings/message.update.success'));
}
return redirect()->back()->withInput()->withErrors($setting->getErrors());
}
/**
* Show the listing of backups.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return View
*/
public function getBackups()
{
$path = storage_path() . '/app/' . config('backup.backup.name');
$path = 'backups';
$backup_files = Storage::files($path);
$files = [];
if (count($backup_files) > 0) {
for ($f = 0; $f < count($backup_files); ++$f) {
$files[] = [
'filename' => basename($backup_files[$f]),
'filesize' => Setting::fileSizeConvert(Storage::size($backup_files[$f])),
'modified' => Storage::lastModified($backup_files[$f]),
];
}
}
return view('settings/backups', compact('path', 'files'));
}
/**
* Process the backup.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return Redirect
*/
public function postBackups()
{
if (! config('app.lock_passwords')) {
Artisan::call('backup:run');
$output = Artisan::output();
// Backup completed
if (! preg_match('/failed/', $output)) {
return redirect()->route('settings.backups.index')
->with('success', trans('admin/settings/message.backup.generated'));
}
$formatted_output = str_replace('Backup completed!', '', $output);
$output_split = explode('...', $formatted_output);
if (array_key_exists(2, $output_split)) {
return redirect()->route('settings.backups.index')->with('error', $output_split[2]);
}
return redirect()->route('settings.backups.index')->with('error', $formatted_output);
}
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
/**
* Download the backup file.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return Redirect
*/
public function downloadFile($filename = null)
{
if (! config('app.lock_passwords')) {
if (Storage::exists($filename)) {
return Response::download(Storage::url('') . e($filename));
} else {
// Redirect to the backup page
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
}
} else {
// Redirect to the backup page
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
}
/**
* Delete the backup file.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v1.8]
*
* @return View
*/
public function deleteFile($filename = null)
{
if (! config('app.lock_passwords')) {
$path = 'backups';
if (Storage::exists($path . '/' . $filename)) {
try {
Storage::delete($path . '/' . $filename);
return redirect()->route('settings.backups.index')->with('success', trans('admin/settings/message.backup.file_deleted'));
} catch (\Exception $e) {
\Log::debug($e);
}
} else {
return redirect()->route('settings.backups.index')->with('error', trans('admin/settings/message.backup.file_not_found'));
}
} else {
return redirect()->route('settings.backups.index')->with('error', trans('general.feature_disabled'));
}
}
/**
* Return a form to allow a super admin to update settings.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function getPurge()
{
return view('settings.purge-form');
}
/**
* Purges soft-deletes.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return View
*/
public function postPurge()
{
if (! config('app.lock_passwords')) {
if ('DELETE' == Input::get('confirm_purge')) {
// Run a backup immediately before processing
Artisan::call('backup:run');
Artisan::call('snipeit:purge', ['--force' => 'true', '--no-interaction' => true]);
$output = Artisan::output();
return view('settings/purge')
->with('output', $output)->with('success', trans('admin/settings/message.purge.success'));
} else {
return redirect()->back()->with('error', trans('admin/settings/message.purge.validation_failed'));
}
} else {
return redirect()->back()->with('error', trans('general.feature_disabled'));
}
}
/**
* Returns a page with the API token generation interface.
*
* We created a controller method for this because closures aren't allowed
* in the routes file if you want to be able to cache the routes.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v4.0]
*
* @return View
*/
public function api()
{
return view('settings.api');
}
/**
* Test the email configuration.
*
* @author [A. Gianotto] [<snipe@snipe.net>]
*
* @since [v3.0]
*
* @return Redirect
*/
public function ajaxTestEmail()
{
try {
(new User())->forceFill([
'name' => config('mail.from.name'),
'email' => config('mail.from.address'),
])->notify(new MailTest());
return response()->json(Helper::formatStandardApiResponse('success', null, 'Maiol sent!'));
} catch (Exception $e) {
return response()->json(Helper::formatStandardApiResponse('success', null, $e->getMessage()));
}
}
public function getLoginAttempts()
{
return view('settings.logins');
}
} | ppavlov28/snipe-it | app/Http/Controllers/SettingsController.php | PHP | agpl-3.0 | 44,314 |
/* ************************************************************************
qooxdoo - the new era of web development
http://qooxdoo.org
Copyright:
2004-2009 1&1 Internet AG, Germany, http://www.1und1.de
License:
LGPL: http://www.gnu.org/licenses/lgpl.html
EPL: http://www.eclipse.org/org/documents/epl-v10.php
See the LICENSE file in the project's top-level directory for details.
Authors:
* Martin Wittemann (martinwittemann)
************************************************************************ */
/**
* <h2>Form Controller</h2>
*
* *General idea*
*
* The form controller is responsible for connecting a form with a model. If no
* model is given, a model can be created. This created model will fit exactly
* to the given form and can be used for serialization. All the connections
* between the form items and the model are handled by an internal
* {@link qx.data.controller.Object}.
*
* *Features*
*
* * Connect a form to a model (bidirectional)
* * Create a model for a given form
*
* *Usage*
*
* The controller only works if both a controller and a model are set.
* Creating a model will automatically set the created model.
*
* *Cross reference*
*
* * If you want to bind single values, use {@link qx.data.controller.Object}
* * If you want to bind a list like widget, use {@link qx.data.controller.List}
* * If you want to bind a tree widget, use {@link qx.data.controller.Tree}
*/
qx.Class.define("qx.data.controller.Form",
{
extend : qx.core.Object,
/**
* @param model {qx.core.Object | null} The model to bind the target to. The
* given object will be set as {@link #model} property.
* @param target {qx.ui.form.Form | null} The form which contains the form
* items. The given form will be set as {@link #target} property.
* @param selfUpdate {Boolean?false} If set to true, you need to call the
* {@link #updateModel} method to get the data in the form to the model.
* Otherwise, the data will be synced automatically on every change of
* the form.
*/
construct : function(model, target, selfUpdate)
{
this.base(arguments);
this._selfUpdate = !!selfUpdate;
this.__bindingOptions = {};
if (model != null) {
this.setModel(model);
}
if (target != null) {
this.setTarget(target);
}
},
properties :
{
/** Data object containing the data which should be shown in the target. */
model :
{
check: "qx.core.Object",
apply: "_applyModel",
event: "changeModel",
nullable: true,
dereference: true
},
/** The target widget which should show the data. */
target :
{
check: "qx.ui.form.Form",
apply: "_applyTarget",
event: "changeTarget",
nullable: true,
init: null,
dereference: true
}
},
members :
{
__objectController : null,
__bindingOptions : null,
/**
* The form controller uses for setting up the bindings the fundamental
* binding layer, the {@link qx.data.SingleValueBinding}. To achieve a
* binding in both directions, two bindings are neede. With this method,
* you have the opportunity to set the options used for the bindings.
*
* @param name {String} The name of the form item for which the options
* should be used.
* @param model2target {Map} Options map used for the binding from model
* to target. The possible options can be found in the
* {@link qx.data.SingleValueBinding} class.
* @param target2model {Map} Options map used for the binding from target
* to model. The possible options can be found in the
* {@link qx.data.SingleValueBinding} class.
*/
addBindingOptions : function(name, model2target, target2model)
{
this.__bindingOptions[name] = [model2target, target2model];
// return if not both, model and target are given
if (this.getModel() == null || this.getTarget() == null) {
return;
}
// renew the affected binding
var item = this.getTarget().getItems()[name];
var targetProperty =
this.__isModelSelectable(item) ? "modelSelection[0]" : "value";
// remove the binding
this.__objectController.removeTarget(item, targetProperty, name);
// set up the new binding with the options
this.__objectController.addTarget(
item, targetProperty, name, !this._selfUpdate, model2target, target2model
);
},
/**
* Creates and sets a model using the {@link qx.data.marshal.Json} object.
* Remember that this method can only work if the form is set. The created
* model will fit exactly that form. Changing the form or adding an item to
* the form will need a new model creation.
*
* @param includeBubbleEvents {Boolean} Whether the model should support
* the bubbling of change events or not.
* @return {qx.core.Object} The created model.
*/
createModel : function(includeBubbleEvents) {
var target = this.getTarget();
// throw an error if no target is set
if (target == null) {
throw new Error("No target is set.");
}
var items = target.getItems();
var data = {};
for (var name in items) {
var names = name.split(".");
var currentData = data;
for (var i = 0; i < names.length; i++) {
// if its the last item
if (i + 1 == names.length) {
// check if the target is a selection
var clazz = items[name].constructor;
var itemValue = null;
if (qx.Class.hasInterface(clazz, qx.ui.core.ISingleSelection)) {
// use the first element of the selection because passed to the
// marshaler (and its single selection anyway) [BUG #3541]
itemValue = items[name].getModelSelection().getItem(0) || null;
} else {
itemValue = items[name].getValue();
}
// call the converter if available [BUG #4382]
if (this.__bindingOptions[name] && this.__bindingOptions[name][1]) {
itemValue = this.__bindingOptions[name][1].converter(itemValue);
}
currentData[names[i]] = itemValue;
} else {
// if its not the last element, check if the object exists
if (!currentData[names[i]]) {
currentData[names[i]] = {};
}
currentData = currentData[names[i]];
}
}
}
var model = qx.data.marshal.Json.createModel(data, includeBubbleEvents);
this.setModel(model);
return model;
},
/**
* Responsible for synching the data from entered in the form to the model.
* Please keep in mind that this method only works if you create the form
* with <code>selfUpdate</code> set to true. Otherwise, this method will
* do nothing because updates will be synched automatically on every
* change.
*/
updateModel: function(){
// only do stuff if self update is enabled and a model or target is set
if (!this._selfUpdate || !this.getModel() || !this.getTarget()) {
return;
}
var items = this.getTarget().getItems();
for (var name in items) {
var item = items[name];
var sourceProperty =
this.__isModelSelectable(item) ? "modelSelection[0]" : "value";
var options = this.__bindingOptions[name];
options = options && this.__bindingOptions[name][1];
qx.data.SingleValueBinding.updateTarget(
item, sourceProperty, this.getModel(), name, options
);
}
},
// apply method
_applyTarget : function(value, old) {
// if an old target is given, remove the binding
if (old != null) {
this.__tearDownBinding(old);
}
// do nothing if no target is set
if (this.getModel() == null) {
return;
}
// target and model are available
if (value != null) {
this.__setUpBinding();
}
},
// apply method
_applyModel : function(value, old) {
// first, get rid off all bindings (avoids whong data population)
if (this.__objectController != null) {
var items = this.getTarget().getItems();
for (var name in items) {
var item = items[name];
var targetProperty =
this.__isModelSelectable(item) ? "modelSelection[0]" : "value";
this.__objectController.removeTarget(item, targetProperty, name);
}
}
// set the model of the object controller if available
if (this.__objectController != null) {
this.__objectController.setModel(value);
}
// do nothing is no target is set
if (this.getTarget() == null) {
return;
}
// model and target are available
if (value != null) {
this.__setUpBinding();
}
},
/**
* Internal helper for setting up the bindings using
* {@link qx.data.controller.Object#addTarget}. All bindings are set
* up bidirectional.
*/
__setUpBinding : function() {
// create the object controller
if (this.__objectController == null) {
this.__objectController = new qx.data.controller.Object(this.getModel());
}
// get the form items
var items = this.getTarget().getItems();
// connect all items
for (var name in items) {
var item = items[name];
var targetProperty =
this.__isModelSelectable(item) ? "modelSelection[0]" : "value";
var options = this.__bindingOptions[name];
// try to bind all given items in the form
try {
if (options == null) {
this.__objectController.addTarget(item, targetProperty, name, !this._selfUpdate);
} else {
this.__objectController.addTarget(
item, targetProperty, name, !this._selfUpdate, options[0], options[1]
);
}
// ignore not working items
} catch (ex) {
if (qx.core.Environment.get("qx.debug")) {
this.warn("Could not bind property " + name + " of " + this.getModel());
}
}
}
},
/**
* Internal helper for removing all set up bindings using
* {@link qx.data.controller.Object#removeTarget}.
*
* @param oldTarget {qx.ui.form.Form} The form which has been removed.
*/
__tearDownBinding : function(oldTarget) {
// do nothing if the object controller has not been created
if (this.__objectController == null) {
return;
}
// get the items
var items = oldTarget.getItems();
// disconnect all items
for (var name in items) {
var item = items[name];
var targetProperty =
this.__isModelSelectable(item) ? "modelSelection[0]" : "value";
this.__objectController.removeTarget(item, targetProperty, name);
}
},
/**
* Returns whether the given item implements
* {@link qx.ui.core.ISingleSelection} and
* {@link qx.ui.form.IModelSelection}.
*
* @param item {qx.ui.form.IForm} The form item to check.
*
* @return {true} true, if given item fits.
*/
__isModelSelectable : function(item) {
return qx.Class.hasInterface(item.constructor, qx.ui.core.ISingleSelection) &&
qx.Class.hasInterface(item.constructor, qx.ui.form.IModelSelection);
}
},
/*
*****************************************************************************
DESTRUCTOR
*****************************************************************************
*/
destruct : function() {
// dispose the object controller because the bindings need to be removed
if (this.__objectController) {
this.__objectController.dispose();
}
}
});
| Seldaiendil/meyeOS | devtools/qooxdoo-1.5-sdk/framework/source/class/qx/data/controller/Form.js | JavaScript | agpl-3.0 | 11,935 |
<?php
namespace BioSounds\Security;
use Exception;
class Session
{
/**
* @throws Exception
*/
public function startSecureSession()
{
$session_name = 'biosounds_session';
$secure = false;
$httpOnly = true;
// Forces sessions to only use cookies.
if (!ini_set('session.use_only_cookies', 1)) {
error_log('Session: error when setting cookies.');
throw new Exception('There was a problem with your session. Please contact the administrator.');
}
// Gets current cookies params.
$cookieParams = session_get_cookie_params();
session_set_cookie_params(1800, $cookieParams['path'], $cookieParams['domain'], $secure, $httpOnly);
//No cache for avoiding back button 'document expired' problem
header("Cache-Control: no cache");
session_cache_limiter("private, must-revalidate");
// Sets the session name to the one set above.
session_name($session_name);
session_start();
if (!isset($_SESSION['regenerate_timeout'])) {
session_regenerate_id(true);
$_SESSION['regenerate_timeout'] = time();
}
// Regenerate session ID every five minutes:
if ($_SESSION['regenerate_timeout'] < time() - 300) {
session_regenerate_id(true);
$_SESSION['regenerate_timeout'] = time();
}
}
}
| nperezg/biosounds | src/src/BioSounds/Security/Session.php | PHP | agpl-3.0 | 1,424 |
# coding=utf-8
# Copyright (c) 2001, Canal TP and/or its affiliates. All rights reserved.
#
# This file is part of Navitia,
# the software to build cool stuff with public transport.
#
# Hope you'll enjoy and contribute to this project,
# powered by Canal TP (www.canaltp.fr).
# Help us simplify mobility and open public transport:
# a non ending quest to the responsive locomotion way of traveling!
#
# LICENCE: This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Stay tuned using
# twitter @navitia
# [matrix] channel #navitia:matrix.org (https://app.element.io/#/room/#navitia:matrix.org)
# https://groups.google.com/d/forum/navitia
# www.navitia.io
from tests.mock_navitia import navitia_response
response = navitia_response.NavitiaResponse()
response.queries = [
"vehicle_journeys/?filter=vehicle_journey.has_code(source, Code-orders)&since=20120615T120000Z&until=20120615T190000Z&data_freshness=base_schedule&depth=2"
# resquest time is UTC -> 12:00 is 8:00 local in Sherbrooke
]
response.response_code = 200
response.json_response = """
{
"disruptions": [],
"feed_publishers": [
{
"id": "builder",
"license": "ODBL",
"name": "departure board",
"url": "www.canaltp.fr"
}
],
"links": [
],
"pagination": {
"items_on_page": 1,
"items_per_page": 25,
"start_page": 0,
"total_result": 1
},
"vehicle_journeys": [
{
"calendars": [
{
"active_periods": [
{
"begin": "20120615",
"end": "20130615"
}
],
"week_pattern": {
"friday": true,
"monday": false,
"saturday": false,
"sunday": false,
"thursday": false,
"tuesday": false,
"wednesday": false
}
}
],
"disruptions": [],
"id": "R:vj1",
"name": "R:vj1",
"stop_times": [
{
"arrival_time": "100000",
"departure_time": "100000",
"utc_arrival_time": "140000",
"utc_departure_time": "140000",
"headsign": "R:vj1",
"journey_pattern_point": {
"id": "journey_pattern_point:14"
},
"stop_point": {
"codes": [
{
"type": "source",
"value": "Code-StopR1"
}
],
"coord": {
"lat": "0",
"lon": "0"
},
"equipments": [
"has_wheelchair_boarding",
"has_bike_accepted"
],
"id": "StopR1",
"label": "StopR1",
"links": [],
"name": "StopR1",
"stop_area": {
"coord": {
"lat": "0",
"lon": "0"
},
"id": "StopR1",
"label": "StopR1",
"links": [],
"name": "StopR1",
"timezone": "America/Montreal"
}
}
},
{
"arrival_time": "101000",
"departure_time": "101000",
"utc_arrival_time": "140100",
"utc_departure_time": "140100",
"headsign": "R:vj1",
"journey_pattern_point": {
"id": "journey_pattern_point:15"
},
"stop_point": {
"codes": [
{
"type": "source",
"value": "Code-StopR2"
}
],
"coord": {
"lat": "0",
"lon": "0"
},
"equipments": [
"has_wheelchair_boarding",
"has_bike_accepted"
],
"id": "StopR2",
"label": "StopR2",
"links": [],
"name": "StopR2",
"stop_area": {
"coord": {
"lat": "0",
"lon": "0"
},
"id": "StopR2",
"label": "StopR2",
"links": [],
"name": "StopR2",
"timezone": "America/Montreal"
}
}
},
{
"arrival_time": "102000",
"departure_time": "102000",
"utc_arrival_time": "140200",
"utc_departure_time": "140200",
"headsign": "R:vj1",
"journey_pattern_point": {
"id": "journey_pattern_point:16"
},
"stop_point": {
"codes": [
{
"type": "source",
"value": "Code-StopR3"
}
],
"coord": {
"lat": "0",
"lon": "0"
},
"equipments": [
"has_wheelchair_boarding",
"has_bike_accepted"
],
"id": "StopR3",
"label": "StopR3",
"links": [],
"name": "StopR3",
"stop_area": {
"coord": {
"lat": "0",
"lon": "0"
},
"id": "StopR3",
"label": "StopR3",
"links": [],
"name": "StopR3",
"timezone": "America/Montreal"
}
}
},
{
"arrival_time": "103000",
"departure_time": "103000",
"utc_arrival_time": "140300",
"utc_departure_time": "140300",
"headsign": "R:vj1",
"journey_pattern_point": {
"id": "journey_pattern_point:17"
},
"stop_point": {
"codes": [
{
"type": "source",
"value": "Code-StopR4"
}
],
"coord": {
"lat": "0",
"lon": "0"
},
"equipments": [
"has_wheelchair_boarding",
"has_bike_accepted"
],
"id": "StopR4",
"label": "StopR4",
"links": [],
"name": "StopR4",
"stop_area": {
"coord": {
"lat": "0",
"lon": "0"
},
"id": "StopR4",
"label": "StopR4",
"links": [],
"name": "StopR4",
"timezone": "America/Montreal"
}
}
},
{
"arrival_time": "104000",
"departure_time": "104000",
"utc_arrival_time": "140400",
"utc_departure_time": "140400",
"headsign": "R:vj1",
"journey_pattern_point": {
"id": "journey_pattern_point:17"
},
"stop_point": {
"codes": [
{
"type": "source",
"value": "Code-StopR5"
}
],
"coord": {
"lat": "0",
"lon": "0"
},
"equipments": [
"has_wheelchair_boarding",
"has_bike_accepted"
],
"id": "StopR5",
"label": "StopR5",
"links": [],
"name": "StopR5",
"stop_area": {
"coord": {
"lat": "0",
"lon": "0"
},
"id": "StopR5",
"label": "StopR5",
"links": [],
"name": "StopR5",
"timezone": "America/Montreal"
}
}
},
{
"arrival_time": "105000",
"departure_time": "105000",
"utc_arrival_time": "140500",
"utc_departure_time": "140500",
"headsign": "R:vj1",
"journey_pattern_point": {
"id": "journey_pattern_point:17"
},
"stop_point": {
"codes": [
{
"type": "source",
"value": "Code-StopR6"
}
],
"coord": {
"lat": "0",
"lon": "0"
},
"equipments": [
"has_wheelchair_boarding",
"has_bike_accepted"
],
"id": "StopR6",
"label": "StopR6",
"links": [],
"name": "StopR6",
"stop_area": {
"coord": {
"lat": "0",
"lon": "0"
},
"id": "StopR6",
"label": "StopR6",
"links": [],
"name": "StopR6",
"timezone": "America/Montreal"
}
}
}
],
"trip": {
"id": "R:vj1",
"name": "R:vj1"
},
"validity_pattern": {
"beginning_date": "20120614",
"days": "100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010000001000000100000010"
}
}
]
}
"""
| CanalTP/kirin | tests/mock_navitia/vj_bad_order.py | Python | agpl-3.0 | 13,166 |
import SPELLS from 'common/SPELLS';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import TalentStatisticBox from 'parser/ui/TalentStatisticBox';
import React from 'react';
const DEATHSTRIKE_COST = 40;
class Heartbreaker extends Analyzer {
rpGains = [];
hsCasts = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.HEARTBREAKER_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.HEART_STRIKE), this.onCast);
this.addEventListener(Events.energize.spell(SPELLS.HEARTBREAKER), this.onEnergize);
}
onCast(event) {
this.hsCasts += 1;
}
onEnergize(event) {
if (event.resourceChangeType !== RESOURCE_TYPES.RUNIC_POWER.id) {
return;
}
this.rpGains.push(event.resourceChange);
}
get totalRPGained() {
return this.rpGains.reduce((a, b) => a + b, 0);
}
get averageHearStrikeHits() {
return (this.rpGains.length / this.hsCasts).toFixed(2);
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.HEARTBREAKER_TALENT.id}
position={STATISTIC_ORDER.OPTIONAL(1)}
value={this.totalRPGained}
label="Runic Power gained"
tooltip={
<>
Resulting in about {Math.floor(this.totalRPGained / DEATHSTRIKE_COST)} extra Death
Strikes.
<br />
Your Heart Strike hit on average {this.averageHearStrikeHits} targets.
</>
}
/>
);
}
}
export default Heartbreaker;
| anom0ly/WoWAnalyzer | analysis/deathknightblood/src/modules/talents/Heartbreaker.js | JavaScript | agpl-3.0 | 1,692 |
using System;
using ImGui;
using ImGui.Rendering.Composition;
namespace ImGui.Rendering
{
internal partial class DrawingContent
{
public bool ReadRecord(out DrawLineCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawLine)
{
return false;
}
DrawLineCommand* data = (DrawLineCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawRectangleCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawRectangle)
{
return false;
}
DrawRectangleCommand* data = (DrawRectangleCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawRoundedRectangleCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawRoundedRectangle)
{
return false;
}
DrawRoundedRectangleCommand* data = (DrawRoundedRectangleCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawEllipseCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*)pCur;
if (pCurRecord->Type != RecordType.DrawRoundedRectangle)
{
return false;
}
DrawEllipseCommand* data = (DrawEllipseCommand*)(pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawGeometryCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawGeometry)
{
return false;
}
DrawGeometryCommand* data = (DrawGeometryCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawImageCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawImage)
{
return false;
}
DrawImageCommand* data = (DrawImageCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawSlicedImageCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawSlicedImage)
{
return false;
}
DrawSlicedImageCommand* data = (DrawSlicedImageCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawGlyphRunCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawGlyphRun)
{
return false;
}
DrawGlyphRunCommand* data = (DrawGlyphRunCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out DrawTextCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*) pCur;
if (pCurRecord->Type != RecordType.DrawText)
{
return false;
}
DrawTextCommand* data = (DrawTextCommand*) (pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out PushClipCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*)pCur;
if (pCurRecord->Type != RecordType.DrawGlyphRun)
{
return false;
}
PushClipCommand* data = (PushClipCommand*)(pCur + sizeof(RecordHeader));
record = *data;
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadRecord(out PopCommand record)
{
record = default;
unsafe
{
fixed (byte* pByte = this.buffer)
{
// This pointer points to the current read point in the
// instruction stream.
byte* pCur = pByte;
// This points to the first byte past the end of the
// instruction stream (i.e. when to stop)
byte* pEndOfInstructions = pByte + this.currentReadOffset;
if ((pCur >= pEndOfInstructions)) //reach end
{
return false;
}
RecordHeader* pCurRecord = (RecordHeader*)pCur;
if (pCurRecord->Type != RecordType.Pop)
{
return false;
}
//pop command consumes no space
this.currentReadOffset += pCurRecord->Size;
return true;
}
}
}
public bool ReadDependentResource<T>(uint index, out T resource) where T:class
{
if (index >= this.dependentResources.Count)
{
resource = null;
return false;
}
resource = (T)this.dependentResources[(int)index-1];
return true;
}
private int currentReadOffset;
}
} | zwcloud/ImGui | src/ImGui/Rendering/DrawingContent.Read.cs | C# | agpl-3.0 | 13,920 |
package com.x.bbs.assemble.control.jaxrs.replyinfo.exception;
import com.x.base.core.project.exception.PromptException;
public class ExceptionReplySubjectIdEmpty extends PromptException {
private static final long serialVersionUID = 1859164370743532895L;
public ExceptionReplySubjectIdEmpty() {
super("主题ID为空,无法继续查询操作。" );
}
}
| o2oa/o2oa | o2server/x_bbs_assemble_control/src/main/java/com/x/bbs/assemble/control/jaxrs/replyinfo/exception/ExceptionReplySubjectIdEmpty.java | Java | agpl-3.0 | 364 |
####################################################################################################
# Copyright (C) 2016 by Ingo Keller, Katrin Lohan #
# <brutusthetschiepel@gmail.com> #
# #
# This file is part of pyJD (Python/Yarp Tools for the JD robot). #
# #
# pyJD is free software: you can redistribute it and/or modify it under the terms of the #
# GNU Affero General Public License as published by the Free Software Foundation, either #
# version 3 of the License, or (at your option) any later version. #
# #
# pyJD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; #
# without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. #
# See the GNU Affero General Public License for more details. #
# #
# You should have received a copy of the GNU Affero General Public License #
# along with pyJD. If not, see <http://www.gnu.org/licenses/>. #
####################################################################################################
import argparse
import socket
import time
import yarp
EMSG_YARP_NOT_FOUND = "Could not connect to the yarp server. Try running 'yarp detect'."
EMSG_ROBOT_NOT_FOUND = 'Could not connect to the robot at %s:%s'
class EZModule(yarp.RFModule):
""" The EZBModule class provides a base class for developing modules for the JD robot.
"""
# Default IP Address and Port for the JD Humanoid Robot.
TCP_IP = '192.168.1.1'
TCP_PORT = 23
# Existing motor ID's are D0-D9, D12-D14 and D16-D18 there are more limits
LIMITS = [ (30, 180),
(70, 170),
(0, 170),
(0, 170),
(0, 60),
(0, 180),
(0, 90),
(0, 60),
(0, 180),
(0, 180),
(0, 180),
(0, 160),
(0, 180),
(0, 130),
(0, 180),
(0, 160),
(0, 180),
(50, 130),
(0, 180),
(0, 180),
(0, 180) ]
def __init__(self, ip, port, prefix):
yarp.RFModule.__init__(self)
self.ip = ip
self.port = int(port)
self.prefix = prefix
# self.last_pos = [-1] * len(EZModule.LIMITS)
def configure(self, rf):
name = self.__class__.__name__
if self.prefix:
name = self.prefix + '/' + name
self.setName(name)
# RPC Port
self.rpc_port = yarp.RpcServer()
# name settings
port_name = '/%s/%s' % (name, 'rpc')
if not self.rpc_port.open(port_name):
raise RuntimeError, EMSG_YARP_NOT_FOUND
self.attach_rpc_server(self.rpc_port)
return True
def interruptModule(self):
self.rpc_port.interrupt()
for x in dir(self):
if x.endswith('Port') and 'interrupt' in dir(getattr(self, x)):
getattr(self, x).interrupt()
return True
def close(self):
self.rpc_port.close()
for x in dir(self):
if x.endswith('Port') and 'close' in dir(getattr(self, x)):
getattr(self, x).close()
return True
def getPeriod(self):
return 0.1
def updateModule(self):
# XXX: I do not know why we need that, but if method is empty the module gets stuck
time.sleep(0.000001)
return True
def createInputPort(self, name, mode = 'unbuffered'):
""" This method returns an input port.
@param obj - the object that the port is created for
@param name - if a name is provided it gets appended to the modules name
@param buffered - if buffered is True a buffered port will be used otherwise not;
default is True.
@result port
"""
return self.__createPort(name + ':i', None, mode)
def __createPort(self, name, target = None, mode = 'unbuffered'):
""" This method returns a port object.
@param name - yarp name for the port
@param obj - object for which the port is created
@param buffered - if buffered is True a buffered port will be used otherwise not;
default is True.
@result port
"""
# create port
if mode == 'buffered':
port = yarp.BufferedPortBottle()
elif mode == 'rpcclient':
port = yarp.RpcClient()
elif mode == 'rpcserver':
port = yarp.RpcServer()
else:
port = yarp.Port()
# build port name
port_name = ['']
# prefix handling
if hasattr(self, 'prefix') and self.prefix:
port_name.append(self.prefix)
port_name.append(self.__class__.__name__)
port_name.append(name)
# open port
if not port.open('/'.join(port_name)):
raise RuntimeError, EMSG_YARP_NOT_FOUND
# add output if given
if target:
port.addOutput(target)
if hasattr(self, '_ports'):
self._ports.append(port)
return port
def createOutputPort(self, name, target = None, mode = 'unbuffered'):
""" This method returns an output port.
@param obj - the object that the port is created for
@param name - if a name is provided it gets appended to the modules name
@param buffered - if buffered is True a buffered port will be used otherwise not;
default is True.
@result port
"""
return self.__createPort(name + ':o', target, mode)
####################################################################################################
#
# Default methods for running the modules standalone
#
####################################################################################################
def createArgParser():
""" This method creates a base argument parser.
@return Argument Parser object
"""
parser = argparse.ArgumentParser(description='Create a JDModule to control the JD robot.')
parser.add_argument( '-i', '--ip',
dest = 'ip',
default = str(EZModule.TCP_IP),
help = 'IP address for the JD robot.')
parser.add_argument( '-p', '--port',
dest = 'port',
default = str(EZModule.TCP_PORT),
help = 'Port for the JD robot')
parser.add_argument( '-n', '--name',
dest = 'name',
default = '',
help = 'Name prefix for Yarp port names')
return parser.parse_args()
def main(module_cls):
""" This is a main method to run a module from command line.
@param module_cls - an EZModule based class that can be started as a standalone module.
"""
args = createArgParser()
yarp.Network.init()
resource_finder = yarp.ResourceFinder()
resource_finder.setVerbose(True)
# resource_finder.configure(argc,argv);
module = module_cls(args.ip, args.port, args.name)
module.runModule(resource_finder)
yarp.Network.fini()
| BrutusTT/pyJD | pyJD/EZModule.py | Python | agpl-3.0 | 8,093 |
<?php
/**
* Centurion
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@centurion-project.org so we can send you a copy immediately.
*
* @category Centurion
* @package Centurion_Application
* @subpackage Resource
* @copyright Copyright (c) 2008-2011 Octave & Octave (http://www.octaveoctave.com)
* @license http://centurion-project.org/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @category Centurion
* @package Centurion_Application
* @subpackage Resource
* @copyright Copyright (c) 2008-2011 Octave & Octave (http://www.octaveoctave.com)
* @license http://centurion-project.org/license/new-bsd New BSD License
* @author Florent Messa <florent.messa@gmail.com>
*/
class Centurion_Application_Resource_Exception extends Zend_Application_Resource_Exception
{
}
| Sparfel/iTop-s-Portal | library/Centurion/Application/Resource/Exception.php | PHP | agpl-3.0 | 1,059 |
/*
MiracleGrue - Model Generator for toolpathing. <http://www.grue.makerbot.com>
Copyright (C) 2011 Far McKon <Far@makerbot.com>, Hugo Boyer (hugo@makerbot.com)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
*/
#include <map>
#include <set>
#include "shrinky.h"
#include "log.h"
namespace mgl {
using namespace std;
void lengthCheck(const std::vector<Segment2Type> &segments, const char *msg) {
for (unsigned int i = 0; i < segments.size(); i++) {
const Segment2Type &seg = segments[i];
Scalar l = seg.length();
// Log::often() << msg << " seg[" << i << "] = " << seg << " l=" << l << endl;
if (!(l > 0)) {
Log::info() << "Z";
stringstream ss;
ss << msg << " Zero length: segment[" << i << "] = " << seg << endl;
ScadDebugFile::segment3(ss, "", "segments", segments, 0, 0.1);
ShrinkyException mixup(ss.str().c_str());
throw mixup;
}
}
}
void connectivityCheck(const std::vector<Segment2Type> &segments,
Scalar tol) {
for (unsigned int i = 0; i < segments.size(); i++) {
unsigned int prevId = i == 0 ? segments.size() - 1 : i - 1;
const Segment2Type &prevSeg = segments[prevId];
Segment2Type seg = segments[i];
if (!prevSeg.b.tequals(seg.a, tol)) {
Point2Type dist = prevSeg.b - seg.a;
stringstream ss;
ss << "Connectivity error: segment[" << prevId << "] = " << prevSeg << endl;
ss << " and segment[" << i << "] = " << seg << endl;
ss << " segment[" << prevId << "] length = " << prevSeg.length() << endl;
ss << " segment[" << i << "] length = " << seg.length() << endl;
ss << " Distance between segments " << dist.magnitude();
ss << endl;
Log::info() << "C";
// Log::often() << "|" << dist.magnitude() << "|" << prevSeg.length() << "|" << seg.length() << "|";
ScadDebugFile::segment3(ss, "", "segments", segments, 0, 0.1);
ShrinkyException mixup(ss.str().c_str());
throw mixup;
}
}
}
void createConvexList(const std::vector<Segment2Type> &segments, std::vector<bool> &convex) {
Scalar tol = 0.3;
for (size_t id = 0; id < segments.size(); id++) {
size_t prevId = id == 0 ? segments.size() - 1 : id - 1;
const Segment2Type &seg = segments[id];
const Segment2Type &prevSeg = segments[prevId];
const Point2Type & i = prevSeg.a;
const Point2Type & j = seg.a;
const Point2Type & j2 = prevSeg.b;
const Point2Type & k = seg.b;
bool isSameSame = j.tequals(j2, tol);
if (!isSameSame) {
stringstream ss;
ss << endl << "CONNECTIVITY ERROR" << endl;
ss << "Segment id: " << id << ", prevId: " << prevId << endl;
ss << "i: " << i << endl;
ss << "j: " << j << endl;
ss << "j2: " << j2 << endl;
ss << "k: " << k << endl;
Point2Type d = j2 - j;
Scalar distance = d.magnitude();
ss << "distance " << distance << endl;
ss << "SameSame " << isSameSame << endl;
Log::info() << "_C_";
ShrinkyException mixup(ss.str().c_str());
throw mixup;
}
bool vertex = convexVertex(i, j, k);
convex.push_back(vertex);
}
}
void segmentsDiagnostic(const char* title, const std::vector<Segment2Type> &segments) {
Log::info() << endl << title << endl;
Log::info() << "id\tconvex\tlength\tdistance\tangle\ta, b" << endl;
for (size_t id = 0; id < segments.size(); id++) {
const Segment2Type &seg = segments[id];
size_t prevId = id == 0 ? segments.size() - 1 : id - 1;
const Segment2Type &prevSeg = segments[prevId];
const Point2Type & i = prevSeg.a;
const Point2Type & j = seg.a;
const Point2Type & j2 = prevSeg.b;
const Point2Type & k = seg.b;
Point2Type d = j2 - j;
Scalar distance = d.magnitude();
Scalar length = seg.squaredLength();
Scalar angle = d.angleFromPoint2s(i, j, k);
bool vertex = convexVertex(i, j, k);
Log::info() << id << "\t" << vertex << "\t" << length << ",\t" << distance << ",\t" << angle << "\t" << seg.a << ", " << seg.b << "\t" << endl;
}
}
Point2Type getInsetDirection(const Segment2Type &seg) {
Point3Type v(seg.b.x - seg.a.x, seg.b.y - seg.a.y, 0);
Point3Type up(0, 0, 1);
Point3Type inset = v.crossProduct(up);
inset.normalise();
Point2Type inset2(inset.x, inset.y);
return inset2;
}
Segment2Type elongateAndPrelongate(const Segment2Type &s, Scalar dist) {
Segment2Type segment(s);
Point2Type l = segment.b - segment.a;
l.normalise();
l *= dist;
segment.b += l;
segment.a -= l;
return segment;
}
void insetSegments(const std::vector<Segment2Type> &segments, Scalar d,
std::vector<Segment2Type> &insets) {
assert(insets.size() == 0);
for (size_t i = 0; i < segments.size(); i++) {
Segment2Type seg = segments[i];
Point2Type inset = getInsetDirection(seg);
inset *= d;
seg.a += inset;
seg.b += inset;
insets.push_back(seg);
}
assert(insets.size() == segments.size());
}
string segment3(const Segment2Type &s, Scalar z) {
stringstream ss;
ss << "[[" << s.a[0] << ", " << s.a[1] << ", " << z << "], [" << s.b[0] << ", " << s.b[1] << ", " << z << "]]";
return ss.str();
}
void trimConvexSegments(const std::vector<Segment2Type> & rawInsets,
const std::vector<bool> &convex,
std::vector<Segment2Type> & segments) {
assert(segments.size() == 0);
segments = rawInsets;
for (unsigned int i = 0; i < segments.size(); i++) {
unsigned int prevId = i == 0 ? segments.size() - 1 : i - 1;
Segment2Type ¤tSegment = segments[i];
Segment2Type &previousSegment = segments[prevId];
if (convex[i]) {
Point2Type intersection;
bool trimmed = segmentSegmentIntersection(previousSegment, currentSegment, intersection);
if (trimmed) {
previousSegment.b = intersection;
currentSegment.a = intersection;
} else {
stringstream ss;
ss << "Trim ERROR: segment " << i << endl;
ss << "segments = [ " << segment3(previousSegment, 0) << " , " << segment3(currentSegment, 0) << " ]; " << endl;
ss << "color([0,0.5,0,1])loop_segments3(segments, false);" << endl;
ShrinkyException mixup(ss.str().c_str());
// throw mixup;
}
}
}
}
void AddReflexSegments(const std::vector<Segment2Type> &segments,
const std::vector<Segment2Type> &trimmedInsets,
const std::vector<bool> &convexVertices,
std::vector<Segment2Type> &newSegments) {
assert(newSegments.size() == 0);
newSegments.reserve(segments.size() * 2);
for (unsigned int i = 0; i < segments.size(); i++) {
unsigned int prevId = i == 0 ? segments.size() - 1 : i - 1;
if (!convexVertices[i]) {
// Point2Type center = segments[i].a;
Point2Type start = trimmedInsets[prevId].b;
Point2Type end = trimmedInsets[i].a;
Segment2Type straight(start, end);
newSegments.push_back(straight);
}
newSegments.push_back(trimmedInsets[i]);
}
}
void removeShortSegments(const std::vector<Segment2Type> &segments,
Scalar cutoffLength,
std::vector<Segment2Type> &shorts) {
shorts.reserve(segments.size()); // worst case
assert(cutoffLength > 0);
Scalar cutoffLength2 = cutoffLength * cutoffLength;
for (unsigned int i = 0; i < segments.size(); i++) {
const Segment2Type &seg = segments[i];
Scalar length2 = seg.squaredLength();
if (length2 > cutoffLength2) {
shorts.push_back(seg);
}
}
}
void Shrinky::openScadFile(const char *scadFileName) {
if (scadFileName) {
fscad.open(scadFileName);
std::ostream & out = fscad.getOut();
out << "module loop_segments3(segments, ball=true)" << endl;
out << "{" << endl;
out << " if(ball) corner (x=segments[0][0][0], y=segments[0][0][1], z=segments[0][0][2], diameter=0.25, faces=12, thickness_over_width=1);" << endl;
out << " for(seg = segments)" << endl;
out << " {" << endl;
out << " tube(x1=seg[0][0], y1=seg[0][1], z1=seg[0][2], x2=seg[1][0], y2=seg[1][1], z2=seg[1][2] , diameter1=0.1, diameter2=0.05, faces=4, thickness_over_width=1);" << endl;
out << " }" << endl;
out << "}" << endl;
fscad.writeHeader();
}
}
Shrinky::Shrinky(const char *scadFileName)
: scadFileName(scadFileName), scadZ(0), color(1), counter(0), dz(0) {
openScadFile(scadFileName);
}
bool attachSegments(Segment2Type &first, Segment2Type &second, Scalar elongation) {
// LineSegment2 s0 = elongateAndPrelongate(first, elongation); // elongate(first, elongation);
// LineSegment2 s1 = elongateAndPrelongate(second, elongation); //prelongate(second, elongation);
Segment2Type s0 = first.elongate(elongation);
Segment2Type s1 = second.prelongate(elongation);
Point2Type intersection;
bool trimmed = segmentSegmentIntersection(s0, s1, intersection);
if (trimmed) {
first.b = intersection;
second.a = intersection;
return true;
}
return false;
}
//
// Calculates altitude in terms of the sides
// http://en.wikipedia.org/wiki/Altitude_(triangle)
//
// @inputs: the length of 3 triangle sides
// @returns the altitude from side a
Scalar triangleAltitude(Scalar a, Scalar b, Scalar c) {
Scalar s = 0.5 * (a + b + c);
Scalar h = 2 * SCALAR_SQRT(s * (s - a)*(s - b)*(s - c)) / a;
return h;
}
// an edged has collapsed when its 2 bisectors intersect
// at an altitude that is lower than the inset distance
bool edgeCollapse(const Segment2Type& segment,
const Point2Type& bisector0,
const Point2Type& bisector1,
Scalar elongation,
Scalar &collapseDistance) {
// segment is the base of the triangle
// from which we want the altitude
Segment2Type bisectorSegment0;
bisectorSegment0.a = segment.a;
bisectorSegment0.b = segment.a + bisector0;
Segment2Type bisectorSegment1;
bisectorSegment1.a = segment.b + bisector1;
bisectorSegment1.b = segment.b;
Segment2Type s0 = bisectorSegment0.elongate(elongation);
Segment2Type s1 = bisectorSegment1.prelongate(elongation);
Point2Type intersection;
bool attached = segmentSegmentIntersection(s0, s1, intersection);
if (attached) {
// the triangle is made from
Point2Type edge0 = segment.a - intersection;
Point2Type edge1 = segment.b - intersection;
Scalar a, b, c;
a = segment.length();
b = edge0.magnitude();
c = edge1.magnitude();
collapseDistance = triangleAltitude(a, b, c);
if (collapseDistance < 0) {
assert(0);
}
return true;
}
return false;
}
void outMap(const std::multimap<Scalar, unsigned int> &collapsingSegments) {
Log::info() << "collapse distance\tsegment id" << endl;
Log::info() << "--------------------------------" << endl;
for (std::multimap<Scalar, unsigned int>::const_iterator it = collapsingSegments.begin();
it != collapsingSegments.end(); it++) {
const std::pair<Scalar, unsigned int>& seg = *it;
Log::info() << "\t" << seg.first << ",\t" << seg.second << endl;
}
}
Scalar removeFirstCollapsedSegments(const std::vector<Segment2Type> &originalSegments,
const std::vector<Point2Type> &bisectors,
Scalar insetDist,
std::vector<Segment2Type> &relevantSegments) {
Scalar elongation = 100;
assert(relevantSegments.size() == 0);
relevantSegments.reserve(originalSegments.size());
//Log::often() << "NB of segments:" << originalSegments.size() << endl;
multimap<Scalar, unsigned int> collapsingSegments;
// Log::often() << endl << "removeFirstCollapsedSegments:: looking for collapses" << endl;
std::vector<Segment2Type> segments = originalSegments;
for (unsigned int i = 0; i < segments.size(); i++) {
unsigned int nextId = i == segments.size() - 1 ? 0 : i + 1;
//const LineSegment2 &nextSeg = segments[nextId];
const Point2Type &nextBisector = bisectors[nextId];
const Segment2Type ¤tSegment = segments[i];
const Point2Type ¤tBisector = bisectors[i];
Scalar collapseDistance;
// check
//Log::often() << "segment[" << i << "] = " << currentSegment << endl;
bool collapsed = edgeCollapse(currentSegment,
currentBisector,
nextBisector,
elongation,
collapseDistance);
if (collapsed) {
//Log::often() << " ** segment " << i << " ,collapse distance " << collapseDistance << endl;
if (collapseDistance < insetDist) {
// shortestCollapseDistance = collapseDistance;
collapsingSegments.insert(std::pair<Scalar, unsigned int>(collapseDistance, i));
}
}
}
if (collapsingSegments.empty()) {
// no problem... inset all the way!
for (unsigned int i = 0; i < segments.size(); i++) {
relevantSegments.push_back(segments[i]);
}
return insetDist;
}
// otherwise...
std::multimap<Scalar, unsigned int>::iterator collapserator = collapsingSegments.begin();
Scalar collapseDistance = (*collapserator).first;
//Log::often() << "COLLAPSED ID " << firstCollapse << endl;
std::set<unsigned int> toRemove;
// Log::often() << "removeFirstCollapsedSegments:: who to remove" << endl;
bool done = false;
do {
Scalar d = (*collapserator).first;
unsigned int segmentId = (*collapserator).second;
//Log::often() << " " << d << ": Removing collapsed segment[" << segmentId <<"]=" << segments[segmentId] << endl;
toRemove.insert(segmentId);
collapserator++;
if (collapserator == collapsingSegments.end()) {
done = true;
}
if (d > collapseDistance) {
// Log::often() << "d(" << d << ") > collapseDistance (" << collapseDistance << endl;
done = true;
}
} while (!done);
//Log::often() << "removeFirstCollapsedSegments:: making new list" << endl;
for (unsigned int i = 0; i < segments.size(); i++) {
if (toRemove.find(i) == toRemove.end()) {
relevantSegments.push_back(segments[i]);
}
}
return collapseDistance;
}
// True if the 3 points are collinear
bool collinear(const Point2Type &a, const Point2Type &b, const Point2Type &c, Scalar tol) {
Scalar dot = ((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - c[0]) * (b[1] - a[1]));
bool r = tequals(dot, 0, tol);
return r;
}
void elongateAndTrimSegments(const std::vector<Segment2Type> & longSegments,
Scalar elongation,
std::vector<Segment2Type> &segments) {
Scalar tol = 1e-6;
segments = longSegments;
for (unsigned int i = 0; i < segments.size(); i++) {
unsigned int prevId = i == 0 ? segments.size() - 1 : i - 1;
Segment2Type &previousSegment = segments[prevId];
Segment2Type ¤tSegment = segments[i];
//Log::often() << "prev: seg[" << prevId << "] = " << previousSegment << endl;
//Log::often() << "cur: seg[" << i << "] = " << currentSegment << endl;
if (previousSegment.b.tequals(currentSegment.a, tol)) {
// the job is already done.. segments are attached,
// nothing to see
// Log::often() << "already attached" << endl;
continue;
}
if (previousSegment.length() == 0) {
Log::info() << "X";
continue;
}
if (currentSegment.length() == 0) {
Log::info() << "Y";
continue;
}
bool attached = attachSegments(previousSegment, currentSegment, elongation);
if (!attached) {
Log::info() << "!";
Point2Type m = (previousSegment.a + currentSegment.b) * 0.5;
previousSegment.b = m;
currentSegment.a = m;
}
// Log::often() << "attach point " << currentSegment.a << endl;
//Log::often() << endl;
}
}
void createBisectors(const std::vector<Segment2Type>& segments,
Scalar tol,
std::vector<Point2Type> &motorCycles) {
for (unsigned int i = 0; i < segments.size(); i++) {
unsigned int prevId = i == 0 ? segments.size() - 1 : i - 1;
const Segment2Type &prevSeg = segments[prevId];
const Segment2Type &seg = segments[i];
Point2Type prevInset = getInsetDirection(prevSeg);
Point2Type inset = getInsetDirection(seg);
Point2Type bisector = inset;
// if points are disjoint, do not combine both insets
if (prevSeg.b.tequals(seg.a, tol)) {
bisector += prevInset;
} else {
//
// ok... maybe this is a bit drastic and we could combine the biesctors
// this author needs to make up his mind about non closed polygon support
//
Point2Type dist = prevSeg.b - seg.a;
stringstream ss;
ss << "This is not a closed polygon. segment[" << prevId << "].b = " << prevSeg.b;
ss << " and segment[" << i << "].a = " << seg.a << " are distant by " << dist.magnitude();
ss << endl;
ScadDebugFile::segment3(ss, "", "segments", segments, 0, 0.1);
Log::info() << "O";
ShrinkyException mixup(ss.str().c_str());
throw mixup;
// assert(0);
}
if (bisector.squaredMagnitude() == 0) {
stringstream ss;
ss << "Null bisector at segment [" << i << "] position=" << seg.a << endl;
ss << " previous_inset=" << prevInset << " inset=" << inset;
Log::info() << "N";
ShrinkyException mixup(ss.str().c_str());
throw mixup;
}
bisector.normalise();
motorCycles.push_back(bisector);
}
}
void Shrinky::writeScadBisectors(const std::vector<Point2Type> & bisectors, const std::vector<Segment2Type> & originalSegments) {
if (scadFileName) {
std::vector<Segment2Type> motorCycleTraces;
for (size_t i = 0; i < bisectors.size(); i++) {
Point2Type a = originalSegments[i].a;
Point2Type dir = bisectors[i];
dir *= 2;
Point2Type b = a + dir;
Segment2Type s(a, b);
motorCycleTraces.push_back(s);
}
scadZ = fscad.writeSegments3("bisectors_", "color([0.75,0.5,0.2,1])loop_segments3", motorCycleTraces, scadZ, dz, this->counter);
}
}
void Shrinky::writeScadSegments(const char* segNames,
const char* prefix,
const std::vector<Segment2Type> & segments) {
if (scadFileName) {
string funcName = prefix;
funcName += "loop_segments3";
scadZ = fscad.writeSegments3(segNames, funcName.c_str(), segments, scadZ, dz, this->counter);
}
}
void Shrinky::inset(const std::vector<Segment2Type>& originalSegments,
Scalar insetDist,
std::vector<Segment2Type> &finalInsets) {
bool writePartialSteps = true;
int count = originalSegments.size();
if (count < 2) {
assert(0);
}
assert(finalInsets.size() == 0);
finalInsets.reserve(originalSegments.size());
Scalar tol = 1e-6; // for continuity testing and distance to go
Scalar distanceToGo = insetDist;
std::vector<Segment2Type> initialSegs = originalSegments;
bool done = false;
while (!done) {
connectivityCheck(initialSegs, tol);
//Log::often() << " ** distance to go: " << distanceToGo << endl;
finalInsets.clear();
Scalar distanceGone = insetStep(initialSegs, distanceToGo, tol, writePartialSteps, finalInsets);
distanceToGo -= distanceGone;
if (tequals(distanceToGo, 0, tol)) {
done = true;
return;
}
if (finalInsets.size() > 2) {
initialSegs = finalInsets;
} else {
return;
}
}
}
void removeZeroLengthSegments(const std::vector<Segment2Type> &inputSegments, std::vector<Segment2Type> &segments, Scalar tol) {
assert(inputSegments.size() > 0);
segments.reserve(inputSegments.size());
// deep copy
for (unsigned int i = 0; i < inputSegments.size(); i++) {
const Segment2Type &seg = inputSegments[i];
if (tequals(seg.squaredLength(), 0, tol)) {
continue;
}
segments.push_back(seg);
}
}
Scalar Shrinky::insetStep(const std::vector<Segment2Type>& originalSegments,
Scalar insetDist,
Scalar continuityTolerance,
bool, // writePartialStep,
std::vector<Segment2Type> &finalInsets) {
Scalar tol = 1e-6;
// magic numbers
Scalar elongation = insetDist * 100; // continuityTolerance * 5;
unsigned int segmentCount = originalSegments.size();
assert(segmentCount > 0);
assert(finalInsets.size() == 0);
assert(&originalSegments != &finalInsets);
if (segmentCount < 2) {
stringstream ss;
ss << "1 line segment is not enough to create a closed polygon";
assert(0);
ShrinkyException mixup(ss.str().c_str());
throw mixup;
}
bool dumpSteps = false;
if (dumpSteps)segmentsDiagnostic("originalSegments", originalSegments);
Scalar insetStepDistance = insetDist;
try {
if (scadFileName) {
// OpenScad
// Scalar dz = 0.1;
stringstream coloredOutline;
// Scalar color = (1.0 * i)/(shells-1);
int color = 0;
coloredOutline << "color([" << color << "," << color << "," << 1 - color << " ,1])";
Scalar dzBefore = scadZ;
writeScadSegments("outlines_", coloredOutline.str().c_str(), originalSegments);
// trick to get the bisector in place
scadZ = dzBefore;
}
std::vector<Segment2Type> relevantSegments;
if (originalSegments.size() > 2) {
//Log::often() << "...BISECTING..." << endl;
std::vector<Point2Type> bisectors;
createBisectors(originalSegments, continuityTolerance, bisectors);
writeScadBisectors(bisectors, originalSegments);
//Log::often() << "...COLLAPSING..." << endl;
insetStepDistance = removeFirstCollapsedSegments(originalSegments, bisectors, insetDist, relevantSegments);
if (dumpSteps) segmentsDiagnostic("relevantSegments", relevantSegments);
writeScadSegments("relevants_", "color([0.5,0.5,0,1])", relevantSegments);
}
std::vector<Segment2Type> insets;
unsigned int relevantCount = relevantSegments.size();
if (relevantCount > 2) {
//Log::often() << "...INSETTING..." << endl;
insetSegments(relevantSegments, insetStepDistance, insets);
if (dumpSteps) segmentsDiagnostic("Insets", insets);
writeScadSegments("raw_insets_", "color([1,0,0.4,1])", insets);
lengthCheck(insets, "insets");
}
std::vector<Segment2Type> connected;
if (insets.size() > 2) {
//Log::often() << "...ATTACHING..." << endl;
elongateAndTrimSegments(insets, elongation, connected);
writeScadSegments("connected_", "color([0.25,0.25,0.25,1])", connected);
// lengthCheck(finalInsets, "finalInsets");
}
if (connected.size() > 2) {
removeZeroLengthSegments(connected, finalInsets, tol);
writeScadSegments("final_insets_", "color([0.5,0.5,0.5,1])", connected);
}
} catch (ShrinkyException &mixup) {
Log::info() << mixup.error << endl;
// Log::often() << "ABORT MISSION!!! " << insetStepDistance << ": " << mixup.error << endl;
// this is a lie... but we want to break the loop
insetStepDistance = insetDist;
throw;
}
this->counter++;
return insetStepDistance;
}
void Shrinky::closeScadFile() {
if (scadFileName) {
std::ostream & out = fscad.getOut();
int shells = counter;
fscad.writeMinMax("draw_outlines", "outlines_", shells);
fscad.writeMinMax("draw_bisectors", "bisectors_", shells);
fscad.writeMinMax("draw_raw_insets", "raw_insets_", shells);
//fscad.writeMinMax("draw_trimmed_insets", "trimmed_insets_", shells);
fscad.writeMinMax("draw_relevants", "relevants_", shells);
fscad.writeMinMax("draw_final_insets", "final_insets_", shells);
out << "min=0;" << endl;
out << "max=" << shells - 1 << ";" << std::endl;
out << std::endl;
out << "draw_outlines(min, max);" << std::endl;
out << "draw_bisectors(min, max);" << std::endl;
out << "draw_relevants(min, max);" << std::endl;
out << "draw_raw_insets(min, max);" << std::endl;
out << "draw_final_insets(min, max);" << std::endl;
out << endl;
out << "// s = [\"segs.push_back(TriangleSegment2(Point2Type(%s+x, %s+y), Point2Type(%s+x, %s+y)));\" %(x[0][0], x[0][1], x[1][0], x[1][1]) for x in segments]" << std::endl;
out << "// print '\\n'.join(s) " << endl;
fscad.close();
}
}
Shrinky::~Shrinky() {
closeScadFile();
}
void createShells(const SegmentVector & outlinesSegments,
const std::vector<Scalar> &insetDistances,
unsigned int sliceId,
const char *scadFile,
bool writeDebugScadFiles,
std::vector<SegmentVector> & insetsForLoops)
{
assert(insetsForLoops.size() == 0);
unsigned int nbOfShells = insetDistances.size();
// dbgs__( "outlineSegmentCount " << outlineSegmentCount)
for (unsigned int outlineId = 0; outlineId < outlinesSegments.size(); outlineId++) {
const std::vector<Segment2Type> &outlineLoop = outlinesSegments[outlineId];
assert(outlineLoop.size() > 0);
insetsForLoops.push_back(SegmentVector());
assert(insetsForLoops.size() == outlineId + 1);
SegmentVector &insetTable = *insetsForLoops.rbegin(); // inset curves for a single loop
insetTable.reserve(nbOfShells);
for (unsigned int shellId = 0; shellId < nbOfShells; shellId++) {
insetTable.push_back(std::vector<Segment2Type > ());
}
//unsigned int segmentCountBefore =0;
//unsigned int segmentCountAfter =0;
unsigned int currentShellIdForErrorReporting = 0;
try {
Shrinky shrinky;
const vector<Segment2Type> *previousInsets = &outlineLoop;
for (unsigned int shellId = 0; shellId < nbOfShells; shellId++) {
currentShellIdForErrorReporting = shellId;
Scalar insetDistance = insetDistances[shellId];
std::vector<Segment2Type> &insets = insetTable[shellId];
if ((*previousInsets).size() > 2) {
shrinky.inset(*previousInsets, insetDistance, insets);
previousInsets = &insets;
}
}
} catch (ShrinkyException &messup) {
if (writeDebugScadFiles) {
static int counter = 0;
Log::info() << endl;
Log::info() << "----- ------ ERROR " << counter << " ------ ------" << endl;
Log::info() << "sliceId: " << sliceId << endl;
Log::info() << "loopId : " << outlineId << endl;
Log::info() << "shellId: " << currentShellIdForErrorReporting << endl;
stringstream ss;
ss << "_slice_" << sliceId << "_loop_" << outlineId << ".scad";
MyComputer myComputer;
string loopScadFile = myComputer.fileSystem.ChangeExtension(scadFile, ss.str().c_str());
Shrinky shriker(loopScadFile.c_str());
shriker.dz = 0.1;
try {
std::ostream &scad = shriker.fscad.getOut();
scad << "/*" << endl;
scad << messup.error;
scad << endl << "*/" << endl;
vector<Segment2Type> previousInsets = outlineLoop;
Log::info() << "Creating file: " << loopScadFile << endl;
Log::info() << " Number of points " << (int) previousInsets.size() << endl;
ScadDebugFile::segment3(cout, "", "segments", previousInsets, 0, 0.1);
std::vector<Segment2Type> insets;
for (unsigned int shellId = 0; shellId < nbOfShells; shellId++) {
Scalar insetDistance = insetDistances[shellId];
shriker.inset(previousInsets, insetDistance, insets);
previousInsets = insets;
insets.clear(); // discard...
}
} catch (ShrinkyException &) // the same excpetion is thrown again
{
Log::info() << "saving " << endl;
}
Log::info() << "--- --- ERROR " << counter << " END --- ----" << endl;
counter++;
}
}
}
}
//// creates shells from the segments table
////
void createShellsForSliceUsingShrinky(const SegmentVector & outlinesSegments,
const std::vector<Scalar> &insetDistances,
unsigned int sliceId,
const char *scadFile,
std::vector<SegmentVector> & insetsForLoops)
{
assert(insetsForLoops.size() == 0);
unsigned int nbOfShells = insetDistances.size();
for (unsigned int shellId = 0; shellId < nbOfShells; shellId++) {
insetsForLoops.push_back(SegmentVector());
SegmentVector ¤tShellTable = *insetsForLoops.rbegin();
for (unsigned int outlineId = 0; outlineId < outlinesSegments.size(); outlineId++) {
try {
Shrinky shrinky;
currentShellTable.push_back(std::vector<Segment2Type > ());
std::vector<Segment2Type> &outlineShell = *currentShellTable.rbegin();
Scalar dist = insetDistances[shellId];
const SegmentVector *pInputs = NULL;
if (shellId == 0) {
pInputs = &outlinesSegments;
} else {
pInputs = &insetsForLoops[shellId - 1];
}
const SegmentVector &inputTable = *pInputs;
const std::vector<Segment2Type> & inputSegments = inputTable[outlineId];
if (inputSegments.size() > 2) {
shrinky.inset(inputSegments, dist, outlineShell);
}
} catch (ShrinkyException &messup) {
if (scadFile != 0x00) {
static int counter = 0;
Log::info() << endl;
Log::info() << "----- ------ ERROR " << counter << " ------ ------" << endl;
Log::info() << "sliceId: " << sliceId << endl;
Log::info() << "loopId : " << outlineId << endl;
Log::info() << "shellId: " << shellId << endl;
stringstream ss;
ss << "_slice_" << sliceId << "_loop_" << outlineId << ".scad";
MyComputer myComputer;
string loopScadFile = myComputer.fileSystem.ChangeExtension(scadFile, ss.str().c_str());
Shrinky shriker(loopScadFile.c_str());
shriker.dz = 0.1;
try {
Shrinky shrinky;
currentShellTable.push_back(std::vector<Segment2Type > ());
std::vector<Segment2Type> &outlineShell = *currentShellTable.rbegin();
Scalar dist = insetDistances[shellId];
if (shellId == 0) {
const SegmentVector &inputTable = outlinesSegments;
const std::vector<Segment2Type> & inputSegments = inputTable[outlineId];
shrinky.inset(inputSegments, dist, outlineShell);
} else {
const SegmentVector &inputTable = insetsForLoops[shellId - 1];
const std::vector<Segment2Type> & inputSegments = inputTable[outlineId];
shrinky.inset(inputSegments, dist, outlineShell);
}
} catch (ShrinkyException &) // the same excpetion is thrown again
{
Log::info() << "saving " << endl;
}
Log::info() << "--- --- ERROR " << counter << " END --- ----" << endl;
counter++;
}
}
}
}
}
}
| makerbot/Miracle-Grue | src/mgl/shrinky.cc | C++ | agpl-3.0 | 33,552 |
# -*- coding: utf-8 -*-
require 'rails_helper'
RSpec.describe CfThreads::InvisibleController, type: :controller do
include InvisibleHelper
before(:each) do
@forum = create(:write_forum)
@user = create(:user)
@messages = [create(:message, forum: @forum),
create(:message, forum: @forum),
create(:message, forum: @forum)]
@threads = @messages.map(&:thread).reverse # default sort order is descending
sign_in @user
end
describe 'GET #list_invisible_threads' do
it 'assigns a list of invisible threads to @threads' do
@threads.each do |thread|
mark_invisible(@user, thread)
end
get :list_invisible_threads
expect(assigns(:threads)).to eq(@threads)
end
end
describe 'POST #hide_thread' do
it 'hides a thread' do
expect do
post :hide_thread, params: thread_params_from_slug(@threads.first)
end.to change {
CfThread
.joins('INNER JOIN invisible_threads iv ON iv.thread_id = threads.thread_id')
.where('iv.user_id = ?', @user.user_id)
.count
}.by(1)
end
end
describe 'POST #unhide_thread' do
it 'unhides a thread' do
mark_invisible(@user, @threads.first)
expect do
post :unhide_thread, params: thread_params_from_slug(@threads.first)
end.to change {
CfThread
.joins('INNER JOIN invisible_threads iv ON iv.thread_id = threads.thread_id')
.where('iv.user_id = ?', @user.user_id).count
}.by(-1)
end
end
end
# eof
| CountOrlok/cforum | spec/controllers/cf_threads/invisible_controller_spec.rb | Ruby | agpl-3.0 | 1,562 |
import os
from xbrowse_server import xbrowse_controls
from django.core.management.base import BaseCommand
from xbrowse_server.base.models import Project, Individual, VCFFile
from xbrowse_server import sample_management
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('args', nargs='*')
parser.add_argument('--indiv-id')
parser.add_argument('--cohort-id')
parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one")
parser.add_argument('--load', action="store_true", help="Whether to also load the VCF data, and not just add record its path in the meta-data tables")
def handle(self, *args, **options):
project_id = args[0]
project = Project.objects.get(project_id=project_id)
vcf_file_path = os.path.abspath(args[1])
vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0]
if options.get('clear'):
for individual in project.individual_set.all():
individual.vcf_files.clear()
if options.get('indiv_id'):
individual = Individual.objects.get(
project=project,
indiv_id=options.get('indiv_id')
)
sample_management.add_vcf_file_to_individual(individual, vcf_file)
else:
sample_management.add_vcf_file_to_project(project, vcf_file)
if options.get('load'):
print("Loading VCF into project store")
xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path])
print("Loading VCF datastore")
xbrowse_controls.load_project_datastore(project_id, vcf_files=[vcf_file_path])
| macarthur-lab/xbrowse | xbrowse_server/base/management/commands/add_vcf_to_project.py | Python | agpl-3.0 | 1,768 |
/*
* ################################################################
*
* ProActive Parallel Suite(TM): The Java(TM) library for
* Parallel, Distributed, Multi-Core Computing for
* Enterprise Grids & Clouds
*
* Copyright (C) 1997-2012 INRIA/University of
* Nice-Sophia Antipolis/ActiveEon
* Contact: proactive@ow2.org or contact@activeeon.com
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License
* as published by the Free Software Foundation; version 3 of
* the License.
*
* 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
* Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero 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
*
* If needed, contact us to obtain a release under GPL Version 2 or 3
* or a different license than the AGPL.
*
* Initial developer(s): The ProActive Team
* http://proactive.inria.fr/team_members.htm
* Contributor(s):
*
* ################################################################
* $$PROACTIVE_INITIAL_DEV$$
*/
package org.objectweb.proactive.extensions.mixedlocation;
import java.io.IOException;
import java.security.AccessControlException;
import java.security.PublicKey;
import org.objectweb.proactive.core.ProActiveException;
import org.objectweb.proactive.core.ProActiveRuntimeException;
import org.objectweb.proactive.core.UniqueID;
import org.objectweb.proactive.core.body.UniversalBody;
import org.objectweb.proactive.core.body.ft.internalmsg.FTMessage;
import org.objectweb.proactive.core.body.reply.Reply;
import org.objectweb.proactive.core.body.request.Request;
import org.objectweb.proactive.core.component.request.Shortcut;
import org.objectweb.proactive.core.gc.GCMessage;
import org.objectweb.proactive.core.gc.GCResponse;
import org.objectweb.proactive.core.security.PolicyServer;
import org.objectweb.proactive.core.security.ProActiveSecurityManager;
import org.objectweb.proactive.core.security.SecurityContext;
import org.objectweb.proactive.core.security.TypedCertificate;
import org.objectweb.proactive.core.security.crypto.KeyExchangeException;
import org.objectweb.proactive.core.security.crypto.SessionException;
import org.objectweb.proactive.core.security.exceptions.RenegotiateSessionException;
import org.objectweb.proactive.core.security.exceptions.SecurityNotAvailableException;
import org.objectweb.proactive.core.security.securityentity.Entities;
import org.objectweb.proactive.core.security.securityentity.Entity;
public class UniversalBodyWrapper implements UniversalBody, Runnable {
/**
*
*/
protected UniversalBody wrappedBody;
protected long time;
protected UniqueID id;
protected boolean stop;
protected long creationTime;
//protected Thread t ;
/**
* Create a time-limited wrapper around a UniversalBody
* @param body the wrapped UniversalBody
* @param time the life expectancy of this wrapper in milliseconds
*/
public UniversalBodyWrapper(UniversalBody body, long time) {
this.wrappedBody = body;
this.time = time;
this.creationTime = System.currentTimeMillis();
// t =new Thread(this);
this.id = this.wrappedBody.getID();
// t.start();
}
public int receiveRequest(Request request) throws IOException, RenegotiateSessionException {
// System.out.println("UniversalBodyWrapper.receiveRequest");
if (this.wrappedBody == null) {
throw new IOException();
}
//the forwarder should be dead
if (System.currentTimeMillis() > (this.creationTime + this.time)) {
// this.updateServer();
// this.wrappedBody = null;
// t.start();
// System.gc();
throw new IOException();
} else {
try {
return this.wrappedBody.receiveRequest(request);
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
// this.stop();
}
public int receiveReply(Reply r) throws IOException {
return this.wrappedBody.receiveReply(r);
}
public String getNodeURL() {
return this.wrappedBody.getNodeURL();
}
public UniqueID getID() {
return this.id;
}
public void updateLocation(UniqueID id, UniversalBody body) throws IOException {
this.wrappedBody.updateLocation(id, body);
}
public UniversalBody getRemoteAdapter() {
return this.wrappedBody.getRemoteAdapter();
}
public String getReifiedClassName() {
return this.wrappedBody.getReifiedClassName();
}
public void enableAC() throws java.io.IOException {
this.wrappedBody.enableAC();
}
public void disableAC() throws java.io.IOException {
this.wrappedBody.disableAC();
}
protected void updateServer() {
// System.out.println("UniversalBodyWrapper.updateServer");
// LocationServer server = LocationServerFactory.getLocationServer();
// try {
// server.updateLocation(id, this.wrappedBody);
// } catch (Exception e) {
// System.out.println("XXXX Error XXXX");
// // e.printStackTrace();
// }
}
//protected synchronized void stop() {
// this.stop=true;
// this.notifyAll();
//}
//
//protected synchronized void waitForStop(long time) {
// if (!this.stop) {
// try {
// wait(time);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
//
//}
public void run() {
// System.out.println("UniversalBodyWrapper.run life expectancy " + time);
try {
// Thread.currentThread().sleep(time);
// this.waitForStop(time);
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println("UniversalBodyWrapper.run end of life...");
this.updateServer();
this.wrappedBody = null;
// System.gc();
}
// SECURITY
public void terminateSession(long sessionID) throws java.io.IOException, SecurityNotAvailableException {
this.wrappedBody.terminateSession(sessionID);
}
public TypedCertificate getCertificate() throws java.io.IOException, SecurityNotAvailableException {
return this.wrappedBody.getCertificate();
}
public long startNewSession(long distantSessionID, SecurityContext policy,
TypedCertificate distantCertificate) throws IOException, SecurityNotAvailableException,
SessionException {
return this.wrappedBody.startNewSession(distantSessionID, policy, distantCertificate);
}
public PublicKey getPublicKey() throws java.io.IOException, SecurityNotAvailableException {
return this.wrappedBody.getPublicKey();
}
public byte[] randomValue(long sessionID, byte[] cl_rand) throws IOException,
SecurityNotAvailableException, RenegotiateSessionException {
return this.wrappedBody.randomValue(sessionID, cl_rand);
}
public byte[] publicKeyExchange(long sessionID, byte[] sig_code) throws IOException,
SecurityNotAvailableException, RenegotiateSessionException, KeyExchangeException {
return this.wrappedBody.publicKeyExchange(sessionID, sig_code);
}
public byte[][] secretKeyExchange(long sessionID, byte[] tmp, byte[] tmp1, byte[] tmp2, byte[] tmp3,
byte[] tmp4) throws IOException, SecurityNotAvailableException, RenegotiateSessionException {
return this.wrappedBody.secretKeyExchange(sessionID, tmp, tmp1, tmp2, tmp3, tmp4);
}
// /* (non-Javadoc)
// * @see org.objectweb.proactive.core.body.UniversalBody#getCertificateEncoded()
// */
// public byte[] getCertificateEncoded()
// throws IOException, SecurityNotAvailableException {
// return this.wrappedBody.getCertificateEncoded();
// }
/* (non-Javadoc)
* @see org.objectweb.proactive.core.body.UniversalBody#getPolicy(org.objectweb.proactive.ext.security.SecurityContext)
*/
public SecurityContext getPolicy(Entities local, Entities distant) throws SecurityNotAvailableException,
IOException {
return this.wrappedBody.getPolicy(local, distant);
}
public Entities getEntities() throws SecurityNotAvailableException, IOException {
return this.wrappedBody.getEntities();
}
/**
* @see org.objectweb.proactive.core.body.UniversalBody#receiveFTMessage(org.objectweb.proactive.core.body.ft.internalmsg.FTMessage)
*/
public Object receiveFTMessage(FTMessage ev) throws IOException {
return this.wrappedBody.receiveFTMessage(ev);
}
public GCResponse receiveGCMessage(GCMessage msg) throws IOException {
return this.wrappedBody.receiveGCMessage(msg);
}
public void setRegistered(boolean registered) throws IOException {
this.wrappedBody.setRegistered(registered);
}
public void createShortcut(Shortcut shortcut) throws IOException {
// TODO implement
throw new ProActiveRuntimeException("create shortcut method not implemented yet");
}
public String registerByName(String name, boolean rebind) throws IOException, ProActiveException {
return this.wrappedBody.registerByName(name, rebind);
}
public String registerByName(String name, boolean rebind, String protocol) throws IOException,
ProActiveException {
return this.wrappedBody.registerByName(name, rebind, protocol);
}
public ProActiveSecurityManager getProActiveSecurityManager(Entity user)
throws SecurityNotAvailableException, AccessControlException, IOException {
return this.wrappedBody.getProActiveSecurityManager(user);
}
public void setProActiveSecurityManager(Entity user, PolicyServer policyServer)
throws SecurityNotAvailableException, AccessControlException, IOException {
this.wrappedBody.setProActiveSecurityManager(user, policyServer);
}
public String getUrl() {
return this.wrappedBody.getUrl();
}
}
| acontes/programming | src/Extensions/org/objectweb/proactive/extensions/mixedlocation/UniversalBodyWrapper.java | Java | agpl-3.0 | 10,651 |
var clover = new Object();
// JSON: {classes : [{name, id, sl, el, methods : [{sl, el}, ...]}, ...]}
clover.pageData = {"classes":[{"el":46,"id":86762,"methods":[{"el":38,"sc":2,"sl":36}],"name":"AbstractEigenvectorModel","sl":32}]}
// JSON: {test_ID : {"methods": [ID1, ID2, ID3...], "name" : "testXXX() void"}, ...};
clover.testTargets = {}
// JSON: { lines : [{tests : [testid1, testid2, testid3, ...]}, ...]};
clover.srcFileLines = [[], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], [], []]
| cm-is-dog/rapidminer-studio-core | report/html/com/rapidminer/operator/features/transformation/AbstractEigenvectorModel.js | JavaScript | agpl-3.0 | 629 |
# -*- coding: utf-8 -*-
"""
Class_LabExperimBased provides functionalities for data handling of data obtained in lab experiments in the field of (waste)water treatment.
Copyright (C) 2016 Chaim De Mulder
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see http://www.gnu.org/licenses/.
"""
import sys
#import os
#from os import listdir
#import pandas as pd
#import scipy as sp
#import numpy as np
#import datetime as dt
import matplotlib.pyplot as plt #plotten in python
import warnings as wn
from wwdata.Class_HydroData import HydroData
class LabExperimBased(HydroData):
"""
Superclass for a HydroData object, expanding the functionalities with
specific functions for data gathered is lab experiments.
Attributes
----------
timedata_column : str
name of the column containing the time data
data_type : str
type of the data provided
experiment_tag : str
A tag identifying the experiment; can be a date or a code used by
the producer/owner of the data.
time_unit : str
The time unit in which the time data is given
units : array
The units of the variables in the columns
"""
def __init__(self,data,timedata_column='index',data_type='NAT',
experiment_tag='No tag given',time_unit=None):
"""
initialisation of a LabExperimBased object, based on a previously defined
HydroData object.
"""
HydroData.__init__(self,data,timedata_column=timedata_column,data_type=data_type,
experiment_tag=experiment_tag,time_unit=time_unit)
def hours(self,time_column='index'):
"""
calculates the hours from the relative values
Parameters
----------
time_column : string
column containing the relative time values; default to index
"""
if time_column == 'index':
self.data['index']=self.time.values
self.data['h']= (self.data['indexes'])*24 + self.data['indexes'].shift(1)
self.data['h'].fillna(0,inplace=True)
self.data.drop('index', axis=1, inplace=True)
else:
self.data['h']= (self.data[time_column])*24 + self.data[time_column].shift(1)
self.data['h'].fillna(0,inplace=True)
def add_conc(self,column_name,x,y,new_name='default'):
"""
calculates the concentration values of the given column and adds them as
a new column to the DataFrame.
Parameters
----------
column_name : str
column with values
x : int
...
y : int
...
new_name : str
name of the new column, default to 'column_name + mg/L'
"""
if new_name == 'default':
new_name = column_name + ' ' + 'mg/L'
self.data[new_name] = self.data[column_name].values*x*y
## Instead of this function: define a dataframe/dict with conversion or
## concentration factors, so that you can have a function that automatically
## converts all parameters in the frame to concentrations
def check_ph(self,ph_column='pH',thresh=0.4):
"""
gives the maximal change in pH
Parameters
----------
ph_column : str
column with pH-values, default to 'pH'
threshold : int
threshold value for warning, default to '0.4'
"""
dph = self.data[ph_column].max()-self.data[ph_column].min()
if dph > thresh:
wn.warn('Strong change in pH during experiment!')
else:
self.delta_ph = dph
def in_out(self,columns):
"""
(start_values-end_values)
Parameters
----------
columns : array of strings
"""
inv=0
outv=0
indexes= self.time.values
for column in columns:
inv += self.data[column][indexes[0]]
for column in columns:
outv += self.data[column][indexes[-1]]
in_out = inv-outv
return in_out
def removal(self,columns):
"""
total removal of nitrogen
(1-(end_values/start_values))
Parameters
----------
columns : array of strings
"""
inv=0
outv=0
indexes= self.time.values
for column in columns:
inv += self.data[column][indexes[0]]
for column in columns:
outv += self.data[column][indexes[-1]]
removal = 1-(outv/inv)
return removal
def calc_slope(self,columns,time_column='h'):
"""
calculates the slope of the selected columns
Parameters
----------
columns : array of strings
columns to calculate the slope for
time_column : str
time used for calculation; default to 'h'
"""
for column in columns:
self.data[column + " " +'slope'] = (self.data[column].shift(1)-self.data[column])\
/(self.data[time_column]-self.data[time_column].shift(1))
def plot(self,columns,time_column='index'):
"""
calculates the slope of the selected columns
Parameters
----------
columns : array of strings
columns to plot
time_column : str
time used for calculation; default to 'h'
"""
fig = plt.figure(figsize=(10,6))
ax = fig.add_subplot(111)
if time_column=='index':
for column in columns:
ax.plot(self.time,self.data[column],marker='o')
else:
for column in columns:
ax.plot(self.data[time_column],self.data[column],marker='o')
ax.legend()
return fig,ax
#######################################
def _print_removed_output(original,new,type_):
"""
function printing the output of functions that remove datapoints.
Parameters
----------
original : int
original length of the dataset
new : int
length of the new dataset
type_ : str
'removed' or 'dropped'
"""
print('Original dataset:',original,'datapoints')
print('New dataset:',new,'datapoints')
print(original-new,'datapoints ',type_)
def _log_removed_output(log_file,original,new,type_):
"""
function writing the output of functions that remove datapoints to a log file.
Parameters
----------
log_file : str
string containing the directory to the log file to be written out
original : int
original length of the dataset
new : int
length of the new dataset
type_ : str
'removed' or 'dropped'
"""
log_file = open(log_file,'a')
log_file.write(str('\nOriginal dataset: '+str(original)+' datapoints; new dataset: '+
str(new)+' datapoints'+str(original-new)+' datapoints ',type_))
log_file.close()
| cdemulde/wwdata | wwdata/Class_LabExperimBased.py | Python | agpl-3.0 | 7,474 |
<?php
/**
* OpenEyes.
*
* (C) Moorfields Eye Hospital NHS Foundation Trust, 2008-2011
* (C) OpenEyes Foundation, 2011-2012
* This file is part of OpenEyes.
* OpenEyes is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
* OpenEyes is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License along with OpenEyes in a file titled COPYING. If not, see <http://www.gnu.org/licenses/>.
*
* @link http://www.openeyes.org.uk
*
* @author OpenEyes <info@openeyes.org.uk>
* @copyright Copyright (c) 2011-2012, OpenEyes Foundation
* @license http://www.gnu.org/licenses/agpl-3.0.html The GNU Affero General Public License V3.0
*/
class OphInVisualfields_Pattern extends BaseActiveRecordVersioned
{
/**
* @return string the associated database table name
*/
public function tableName()
{
return 'ophinvisualfields_pattern';
}
}
| FiviumAustralia/OpenEyes | protected/modules/OphInVisualfields/models/OphInVisualfields_Pattern.php | PHP | agpl-3.0 | 1,288 |
<?php
/*
* Copyright (C) 2009 Nouweo
*
* Nouweo is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
function count_all_mbr($where='')
{
$where_clause = ( strlen( $where ) > 0 ) ? ' WHERE ' . $where . ' ' : '';
$query = Nw::$DB->query('SELECT COUNT(*) as count FROM '.Nw::$prefix_table.'members'.$where_clause) OR Nw::$DB->trigger(__LINE__, __FILE__);
$dn = $query->fetch_assoc();
$query->free();
return $dn['count'];
}
| nephthys/Nouweo_PHP | inc/lib/users/count_all_mbr.php | PHP | agpl-3.0 | 1,064 |
'use strict';
angular.module('impactApp')
.controller('PartenairesEditCtrl', function($scope, $state, partenaire) {
$scope.partenaire = partenaire;
$scope.update = function() {
$scope.partenaire.$save(function() {
$state.go('^', {}, {reload: true});
});
};
$scope.delete = function() {
$scope.partenaire.$delete(function() {
$state.go('^', {}, {reload: true});
});
};
});
| sgmap/impact | client/app/dashboard/users/partenaires/edit.controller.js | JavaScript | agpl-3.0 | 439 |
import { State, Selector, Action, StateContext } from '@ngxs/store';
import { Injectable } from '@angular/core';
import { DetttagliTipologieService } from '../../../../core/service/dettagli-tipologie/dettagli-tipologie.service';
import { TriageService } from '../../../../core/service/triage/triage.service';
import {
GetDettagliTipologieByCodTipologia,
ClearDettagliTipologie,
SetDettaglioTipologiaTriageChiamata,
SetTipologiaTriageChiamata,
SetTriageChiamata,
ClearTipologiaTriageChiamata,
ClearDettaglioTipologiaTriageChiamata,
ClearTriageChiamata, StartLoadingTriageChiamata, StopLoadingTriageChiamata
} from '../../actions/triage-modal/triage-modal.actions';
import { GetDettaglioTipologiaByCodTipologiaDto } from '../../../interface/dto/dettagli-tipologie/dettaglio-tipologia-dto.interface';
import { DettaglioTipologia } from '../../../interface/dettaglio-tipologia.interface';
import { TreeviewItem } from 'ngx-treeview';
import { ItemTriageData } from '../../../interface/item-triage-data.interface';
import { PosInterface } from '../../../interface/pos.interface';
import { StartLoadingDettagliTipologia, StopLoadingDettagliTipologia } from '../../../../features/home/store/actions/form-richiesta/scheda-telefonata.actions';
export interface TriageChiamataModalStateModel {
dettagliTipologia: DettaglioTipologia[];
codTipologiaSelezionata: number;
codDettaglioTipologiaSelezionato: number;
triage: TreeviewItem;
triageData: ItemTriageData[];
idTriage: string;
pos: PosInterface[];
loadingTriageChiamata: boolean;
}
export const TriageChiamataModalStateDefaults: TriageChiamataModalStateModel = {
dettagliTipologia: undefined,
codTipologiaSelezionata: undefined,
codDettaglioTipologiaSelezionato: undefined,
triage: undefined,
triageData: undefined,
idTriage: undefined,
pos: undefined,
loadingTriageChiamata: undefined
};
@Injectable()
@State<TriageChiamataModalStateModel>({
name: 'triageChiamataModal',
defaults: TriageChiamataModalStateDefaults
})
export class TriageChiamataModalState {
constructor(private detttagliTipologieService: DetttagliTipologieService,
private triageService: TriageService) {
}
@Selector()
static dettagliTipologia(state: TriageChiamataModalStateModel): DettaglioTipologia[] {
return state.dettagliTipologia;
}
@Selector()
static triage(state: TriageChiamataModalStateModel): TreeviewItem {
return state.triage;
}
@Selector()
static triageData(state: TriageChiamataModalStateModel): ItemTriageData[] {
return state.triageData;
}
@Selector()
static loadingTriageChiamata(state: TriageChiamataModalStateModel): boolean {
return state.loadingTriageChiamata;
}
@Action(GetDettagliTipologieByCodTipologia)
getDettagliTipologieByCodTipologia({ patchState, dispatch }: StateContext<TriageChiamataModalStateModel>, action: GetDettagliTipologieByCodTipologia): void {
dispatch(new StartLoadingTriageChiamata());
dispatch(new StartLoadingDettagliTipologia());
this.detttagliTipologieService.getDettaglioTipologiaByCodTipologia(action.codTipologia).subscribe((response: GetDettaglioTipologiaByCodTipologiaDto) => {
patchState({
dettagliTipologia: response.listaDettaglioTipologie
});
dispatch(new StopLoadingTriageChiamata());
dispatch(new StopLoadingDettagliTipologia());
});
}
@Action(ClearDettagliTipologie)
clearDettagliTipologie({ patchState }: StateContext<TriageChiamataModalStateModel>): void {
patchState({
dettagliTipologia: TriageChiamataModalStateDefaults.dettagliTipologia
});
}
@Action(SetTipologiaTriageChiamata)
setTipologiaTriageChiamata({ patchState }: StateContext<TriageChiamataModalStateModel>, action: SetTipologiaTriageChiamata): void {
patchState({
codTipologiaSelezionata: action.codTipologia
});
}
@Action(ClearTipologiaTriageChiamata)
clearTipologiaTriageChiamata({ patchState }: StateContext<TriageChiamataModalStateModel>): void {
patchState({
codTipologiaSelezionata: TriageChiamataModalStateDefaults.codTipologiaSelezionata
});
}
@Action(SetDettaglioTipologiaTriageChiamata)
setDettaglioTipologiaTriageChiamata({patchState, dispatch }: StateContext<TriageChiamataModalStateModel>, action: SetDettaglioTipologiaTriageChiamata): void {
patchState({
codDettaglioTipologiaSelezionato: action.codDettaglioTipologia,
pos: action.pos
});
dispatch(new SetTriageChiamata());
}
@Action(ClearDettaglioTipologiaTriageChiamata)
clearDettaglioTipologiaTriageChiamata({ patchState }: StateContext<TriageChiamataModalStateModel>): void {
patchState({
codDettaglioTipologiaSelezionato: TriageChiamataModalStateDefaults.codDettaglioTipologiaSelezionato
});
}
@Action(SetTriageChiamata)
setTriageChiamata({ getState, patchState, dispatch }: StateContext<TriageChiamataModalStateModel>): void {
const state = getState();
const codTipologiaSelezionata = state.codTipologiaSelezionata;
const codDettaglioTipologiaSelezionata = state.codDettaglioTipologiaSelezionato;
dispatch(new StartLoadingTriageChiamata());
this.triageService.get(codTipologiaSelezionata, codDettaglioTipologiaSelezionata).subscribe((res: { triage: { id: string, data: TreeviewItem }, triageData: ItemTriageData[] }) => {
patchState({
idTriage: res?.triage?.id,
triage: res?.triage?.data,
triageData: res?.triageData
});
dispatch(new StopLoadingTriageChiamata());
});
}
@Action(ClearTriageChiamata)
clearTriageChiamata({ patchState }: StateContext<TriageChiamataModalStateModel>): void {
patchState({
idTriage: TriageChiamataModalStateDefaults.idTriage,
triage: TriageChiamataModalStateDefaults.triage,
triageData: TriageChiamataModalStateDefaults.triageData,
pos: TriageChiamataModalStateDefaults.pos
});
}
@Action(StartLoadingTriageChiamata)
startLoadingTriageChiamata({ patchState }: StateContext<TriageChiamataModalStateModel>): void {
patchState({
loadingTriageChiamata: true
});
}
@Action(StopLoadingTriageChiamata)
stopLoadingTriageChiamata({ patchState }: StateContext<TriageChiamataModalStateModel>): void {
patchState({
loadingTriageChiamata: false
});
}
}
| vvfosprojects/sovvf | src/frontend/launcherComponent/src/app/shared/store/states/triage-chiamata-modal/triage-chiamata-modal.state.ts | TypeScript | agpl-3.0 | 6,729 |
/*
*
* Copyright 2015 IK4-Tekniker All Rights Reserved
*
* This file is part of Health Questionnaire SE at FISTAR https://www.fi-star.eu/
*
* Health Questionnaire SE is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Health Questionnaire SE is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Health Questionnaire SE. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* patricia.casla at tekniker dot es
*
* Author: Ignacio Lazaro Llorente
*/
package es.tekniker.framework.ktek.entity;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/*
* Class used as input parameter on login service
*/
@XmlRootElement(name = "KtekLoginEntity")
@XmlType(
namespace = "http://es.tekniker.framework.ktek",
propOrder = {"reference", "password", "coordinates"})
public class KtekLoginEntity implements Serializable{
private String reference;
private String password;
private KtekLoginCoordinatesEntity[] coordinates;
public boolean isRequiredDataDefined(){
boolean boolOK=true;
if(reference.equals(""))
boolOK=false;
if(password.equals(""))
boolOK=false;
if(coordinates == null)
boolOK=false;
if(coordinates.length !=3)
boolOK=false;
if(coordinates[0].getLetter()==null && coordinates[0].getLetter().equals(""))
boolOK=false;
if(coordinates[0].getValue()==null && coordinates[0].getValue().equals(""))
boolOK=false;
if(coordinates[1].getLetter()==null && coordinates[1].getLetter().equals(""))
boolOK=false;
if(coordinates[1].getValue()==null && coordinates[1].getValue().equals(""))
boolOK=false;
if(coordinates[2].getLetter()==null && coordinates[2].getLetter().equals(""))
boolOK=false;
if(coordinates[2].getValue()==null && coordinates[2].getValue().equals(""))
boolOK=false;
return boolOK;
}
/**
* @return the reference
*/
public String getReference() {
return reference;
}
/**
* @param reference the reference to set
*/
public void setReference(String reference) {
this.reference = reference;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
/**
* @return the coordinates
*/
public KtekLoginCoordinatesEntity[] getCoordinates() {
return coordinates;
}
/**
* @param coordinates the coordinates to set
*/
public void setCoordinates(KtekLoginCoordinatesEntity[] coordinates) {
this.coordinates = coordinates;
}
public String toString(){
String sData="reference:" + reference + " password:" + password ;
return sData;
}
}
| ik4tekniker/FISTAR-Health-Questionnaire-SE | HQSE_code/HQSE_WebServices_Code_BETA/commons.mng.bo/src/main/java/es/tekniker/framework/ktek/entity/KtekLoginEntity.java | Java | agpl-3.0 | 3,255 |
class CardsFromMunAnalyzer
def self.analyze(data)
return {} if data.nil? || data.empty?
{
name: data["name"],
lists: data["lists"].map { |list| {name: list["name"], id: list["id"]} },
cards: data["cards"].map { |card| {name: card["name"], id: card["id"], due: card["due"]} }
}
end
end | nschmidtg/simpla | utils/analyzers/cards_from_mun_analyzer.rb | Ruby | agpl-3.0 | 319 |
'use strict';
const _ = require('underscore');
const Handlebars = require('handlebars');
const moment = require('moment');
const VPREmulatorModel = require('./vprEmulatorModel');
const toFMDateTime = require('../vdmUtils').toFMDateTime;
class VPRPatientEmulator extends VPREmulatorModel {
template() {
return [
"<results version='{{vprDataVersion}}' timeZone='-0500' >",
"<demographics total='{{total}}' >",
'<patient>',
"<bid value='{{bid}}' />",
"<dob value='{{toDate dateOfBirth}}' />",
'{{{getFacilities}}}',
"<familyName value='{{toFamilyName name}}' />",
"<fullName value='{{name}}' />",
"<gender value='{{toGender sex}}' />",
"<givenNames value='{{toGivenName name}}' />",
"<id value='{{patientId}}' />",
"<inpatient value='{{getInpatient}}' />",
"<lrdfn value='{{getLrdfn}}' />",
"<sc value='{{sc}}' />",
"<ssn value='{{socialSecurityNumber}}' />",
"<veteran value='{{veteran}}' />",
'</patient>',
'</demographics>',
'</results>',
];
}
compileTemplate(mvdmForm) {
Handlebars.registerHelper('toDate', date => toFMDateTime(date.value));
Handlebars.registerHelper('toFamilyName', name => name.substring(0, name.indexOf(',')));
Handlebars.registerHelper('toGender', (sex) => {
const map = {
MALE: 'M',
FEMALE: 'F',
};
return map[sex];
});
Handlebars.registerHelper('toGivenName', name => name.substring(name.indexOf(',') + 1, name.length));
Handlebars.registerHelper('getInpatient', () => {
if (mvdmForm.currentAdmission) {
return 'true';
}
return 'false';
});
Handlebars.registerHelper('getLrdfn', () => {
if (_.has(mvdmForm, 'laboratoryReference')) {
return mvdmForm.laboratoryReference.id.split('-')[1];
}
return 0;
});
Handlebars.registerHelper('getFacilities', () => {
/*
* Facilities visited by the Patient
*
* In the general case there may be many facilities (MPI can be called). For an
* isolate VISTA, there will be at most one, this VISTA.
*
* TODO: replace with a Javascript Utility or a computed property in Patient
*/
const dateStr = moment().format('YYYY-MM-DD');
return `${'<facilities>' +
"<facility code='050' name='SOFTWARE SERVICE' latestDate='"}${toFMDateTime(dateStr)}' domain='FOIA.DOMAIN.EXT' />` +
'</facilities>';
});
mvdmForm.bid = `C${mvdmForm.socialSecurityNumber.substring(5, 9)}`;
mvdmForm.patientId = mvdmForm.id.replace('2-', '');
mvdmForm.sc = mvdmForm.isServiceConnected ? 1 : 0;
mvdmForm.veteran = mvdmForm.isVeteran ? 1 : 0;
const temp = Handlebars.compile(this.template().join(''));
const res = temp(mvdmForm);
return res;
}
getOnePatientDetail(res) {
if (res === 'error') {
return `<results version='${this.vprDataVersion}' timeZone='-0500' ><demographics total='0' ></demographics></results>`;
}
res.vprDataVersion = this.vprDataVersion;
res.total = 1;
const result = this.compileTemplate(res);
return result.replace(/"/g, '\'');
}
toReturnValue(invokeResult) {
return this.getOnePatientDetail(invokeResult);
}
transformIEN(ien) {
return `2-${ien}`;
}
}
module.exports = VPRPatientEmulator;
| vistadataproject/MVDM | vprEmulator/vprEmulatorPatientModel.js | JavaScript | agpl-3.0 | 3,784 |
from common.log import logUtils as log
from constants import clientPackets
from constants import serverPackets
def handle(userToken, packetData):
# get token data
username = userToken.username
# Read packet data
packetData = clientPackets.setAwayMessage(packetData)
# Set token away message
userToken.awayMessage = packetData["awayMessage"]
# Send private message from fokabot
if packetData["awayMessage"] == "":
fokaMessage = "Your away message has been reset"
else:
fokaMessage = "Your away message is now: {}".format(packetData["awayMessage"])
userToken.enqueue(serverPackets.sendMessage("FokaBot", username, fokaMessage))
log.info("{} has changed their away message to: {}".format(username, packetData["awayMessage"]))
| osuripple/pep.py | events/setAwayMessageEvent.py | Python | agpl-3.0 | 743 |
<?php
$this->load_template('header.php');
?>
<div id="settings">
<div id="settings_left">
<div class="ttl" style="margin-right:12px;"><div class="ttl2"><h3><?= $this->lang('settings_menu_title') ?></h3></div></div>
<div class="sidenav">
<a href="<?= $C->SITE_URL ?>settings/profile"><?= $this->lang('settings_menu_profile') ?></a>
<a href="<?= $C->SITE_URL ?>settings/contacts"><?= $this->lang('settings_menu_contacts') ?></a>
<a href="<?= $C->SITE_URL ?>settings/avatar"><?= $this->lang('settings_menu_avatar') ?></a>
<a href="<?= $C->SITE_URL ?>settings/password"><?= $this->lang('settings_menu_password') ?></a>
<a href="<?= $C->SITE_URL ?>settings/email"><?= $this->lang('settings_menu_email') ?></a>
<a href="<?= $C->SITE_URL ?>settings/system"><?= $this->lang('settings_menu_system') ?></a>
<a href="<?= $C->SITE_URL ?>settings/notifications"><?= $this->lang('settings_menu_notif') ?></a>
<?php if( function_exists('curl_init') ) { ?>
<a href="<?= $C->SITE_URL ?>settings/rssfeeds"><?= $this->lang('settings_menu_rssfeeds') ?></a>
<?php } ?>
<a href="<?= $C->SITE_URL ?>settings/delaccount" class="onsidenav"><?= $this->lang('settings_menu_delaccount') ?></a>
</div>
</div>
<div id="settings_right">
<div class="ttl">
<div class="ttl2">
<h3><?= $this->lang('settings_delaccount_ttl2') ?></h3>
</div>
</div>
<?php if($D->error) { ?>
<?= errorbox($this->lang('st_delaccount_error'), $this->lang($D->errmsg), TRUE, 'margin-top:5px;margin-bottom:5px;') ?>
<?php } ?>
<div class="greygrad" style="margin-top:5px;">
<div class="greygrad2">
<div class="greygrad3">
<?= $this->lang('st_delaccount_description') ?>
<form method="post" name="delaccount" onsubmit="return confirm('<?= htmlspecialchars($this->lang('st_delaccount_confirm')) ?>');" action="<?= $C->SITE_URL ?>settings/delaccount" autocomplete="off">
<table id="setform" cellspacing="5" style="margin-top:5px;">
<tr>
<td class="setparam"><?= $this->lang('st_delaccount_password') ?></td>
<td><input type="password" name="userpass" value="" autocomplete="off" class="setinp" /></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="<?= $this->lang('st_delaccount_submit') ?>" style="padding:4px; font-weight:bold;"/></td>
</tr>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
<?php
$this->load_template('footer.php');
?> | Opentronix/Opentronix | upload/themes/default/html/settings_delaccount.php | PHP | agpl-3.0 | 2,687 |
/*
Copyright (c) 2003-2017, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'specialchar', 'de-ch', {
options: 'Sonderzeichenoptionen',
title: 'Sonderzeichen auswählen',
toolbar: 'Sonderzeichen einfügen'
} );
| afshinnj/php-mvc | assets/framework/ckeditor/plugins/specialchar/lang/de-ch.js | JavaScript | agpl-3.0 | 319 |
<?php
if(!$app->isEnabled('events')){
return;
}
$class_event = 'MapasCulturais\Entities\Event';
$num_events = $this->getNumEvents();
$num_verified_events = $this->getNumVerifiedEvents();
$event_linguagens = array_values($app->getRegisteredTaxonomy($class_event, 'linguagem')->restrictedTerms);
sort($event_linguagens);
$event_img_attributes = 'class="random-feature no-image"';
$event = $this->getOneVerifiedEntity($class_event);
if($event && $img_url = $this->getEntityFeaturedImageUrl($event)){
$event_img_attributes = 'class="random-feature" style="background-image: url(' . $img_url . ');"';
}
$url_search_events = $this->searchEventsUrl;
?>
<article id="home-events" class="js-page-menu-item home-entity clearfix">
<div class="box">
<h1><span class="icon icon-event"></span> Eventos</h1>
<div class="clearfix">
<div class="statistics">
<div class="statistic"><?php echo $num_events ?></div>
<div class="statistic-label">eventos agendados</div>
</div>
<div class="statistics">
<div class="statistic"><?php echo $num_verified_events ?></div>
<div class="statistic-label">eventos da <?php $this->dict('home: abbreviation'); ?></div>
</div>
</div>
<p><?php $this->dict('home: events') ?></p>
<h4>Encontre eventos por</h4>
<ul class="abas clearfix">
<li class="active"><a href="#event-terms">Linguagem</a></li>
</ul>
<div id="event-terms" class="tag-box">
<div>
<?php foreach ($event_linguagens as $i => $t): ?>
<a class="tag" href="<?php echo $app->createUrl('site', 'search') ?>##(event:(linguagens:!(<?php echo $i ?>)),global:(enabled:(event:!t),filterEntity:event))"><?php echo $t ?></a>
<?php endforeach; ?>
</div>
</div>
</div>
<div class="box">
<?php if($event): ?>
<a href="<?php echo $event->singleUrl ?>">
<div <?php echo $event_img_attributes;?>>
<div class="feature-content">
<h3>destaque</h3>
<h2><?php echo $event->name ?></h2>
<p><?php echo $event->shortDescription ?></p>
</div>
</div>
</a>
<?php endif; ?>
<a class="btn btn-accent btn-large add" href="<?php echo $app->createUrl('event', 'create') ?>">Adicionar evento</a>
<a class="btn btn-accent btn-large" href="<?php echo $url_search_events ?>">Ver tudo</a>
</div>
</article> | tuliolages/mapasculturais | src/protected/application/themes/BaseV1/layouts/parts/home-events.php | PHP | agpl-3.0 | 2,629 |
package com.codingbat;
public final class String2 {
/*
* http://codingbat.com/prob/p165312
*
* Given a string, return a string where for every char in the original,
* there are two chars.
*
* doubleChar("The") → "TThhee"
*
* doubleChar("AAbb") → "AAAAbbbb"
*
* doubleChar("Hi-There") → "HHii--TThheerree"
*/
public String doubleChar(String str) {
return null;
}
/*
* http://codingbat.com/prob/p147448
*
* Return the number of times that the string "hi" appears anywhere in the
* given string.
*
* countHi("abc hi ho") → 1
*
* countHi("ABChi hi") → 2
*
* countHi("hihi") → 2
*/
public int countHi(String str) {
return 0;
}
/*
* http://codingbat.com/prob/p111624
*
* Return true if the string "cat" and "dog" appear the same number of times
* in the given string.
*
* catDog("catdog") → true
*
* catDog("catcat") → false
*
* catDog("1cat1cadodog") → true
*/
public boolean catDog(String str) {
return false;
}
/*
* http://codingbat.com/prob/p123614
*
* Return the number of times that the string "code" appears anywhere in the
* given string, except we'll accept any letter for the 'd', so "cope" and
* "cooe" count.
*
* countCode("aaacodebbb") → 1
*
* countCode("codexxcode") → 2
*
* countCode("cozexxcope") → 2
*/
public int countCode(String str) {
return 0;
}
/*
* http://codingbat.com/prob/p126880
*
* Given two strings, return true if either of the strings appears at the
* very end of the other string, ignoring upper/lower case differences (in
* other words, the computation should not be "case sensitive"). Note:
* str.toLowerCase() returns the lowercase version of a string.
*
* endOther("Hiabc", "abc") → true
*
* endOther("AbC", "HiaBc") → true
*
* endOther("abc", "abXabc") → true
*/
public boolean endOther(String a, String b) {
return false;
}
/*
* http://codingbat.com/prob/p136594
*
* Return true if the given string contains an appearance of "xyz" where the
* xyz is not directly preceeded by a period (.). So "xxyz" counts but
* "x.xyz" does not.
*
* xyzThere("abcxyz") → true
*
* xyzThere("abc.xyz") → false
*
* xyzThere("xyz.abc") → true
*/
public boolean xyzThere(String str) {
return false;
}
/*
* http://codingbat.com/prob/p175762
*
* Return true if the given string contains a "bob" string, but where the
* middle 'o' char can be any char.
*
* bobThere("abcbob") → true
*
* bobThere("b9b") → true
*
* bobThere("bac") → false
*/
public boolean bobThere(String str) {
return false;
}
/*
* http://codingbat.com/prob/p134250
*
* We'll say that a String is xy-balanced if for all the 'x' chars in the
* string, there exists a 'y' char somewhere later in the string. So "xxy"
* is balanced, but "xyx" is not. One 'y' can balance multiple 'x's. Return
* true if the given string is xy-balanced.
*
* xyBalance("aaxbby") → true
*
* xyBalance("aaxbb") → false
*
* xyBalance("yaaxbb") → false
*/
public boolean xyBalance(String str) {
return false;
}
/*
* http://codingbat.com/prob/p125185
*
* Given two strings, A and B, create a bigger string made of the first char
* of A, the first char of B, the second char of A, the second char of B,
* and so on. Any leftover chars go at the end of the result.
*
* mixString("abc", "xyz") → "axbycz"
*
* mixString("Hi", "There") → "HTihere"
*
* mixString("xxxx", "There") → "xTxhxexre"
*/
public String mixString(String a, String b) {
return null;
}
/*
* http://codingbat.com/prob/p152339
*
* Given a string and an int N, return a string made of N repetitions of the
* last N characters of the string. You may assume that N is between 0 and
* the length of the string, inclusive.
*
* repeatEnd("Hello", 3) → "llollollo"
*
* repeatEnd("Hello", 2) → "lolo"
*
* repeatEnd("Hello", 1) → "o"
*/
public String repeatEnd(String str, int n) {
return null;
}
/*
* http://codingbat.com/prob/p128796
*
* Given a string and an int n, return a string made of the first n
* characters of the string, followed by the first n-1 characters of the
* string, and so on. You may assume that n is between 0 and the length of
* the string, inclusive (i.e. n >= 0 and n <= str.length()).
*
* repeatFront("Chocolate", 4) → "ChocChoChC"
*
* repeatFront("Chocolate", 3) → "ChoChC"
*
* repeatFront("Ice Cream", 2) → "IcI"
*/
public String repeatFront(String str, int n) {
return null;
}
/*
* http://codingbat.com/prob/p109637
*
* Given two strings, word and a separator, return a big string made of
* count occurences of the word, separated by the separator string.
*
* repeatSeparator("Word", "X", 3) → "WordXWordXWord"
*
* repeatSeparator("This", "And", 2) → "ThisAndThis"
*
* repeatSeparator("This", "And", 1) → "This"
*/
public String repeatSeparator(String word, String sep, int count) {
return null;
}
/*
* http://codingbat.com/prob/p136417
*
* Given a string, consider the prefix string made of the first N chars of
* the string. Does that prefix string appear somewhere else in the string?
* Assume that the string is not empty and that N is in the range
* 1..str.length().
*
* prefixAgai("abXYabc", 1) → true
*
* prefixAgain("abXYabc", 2) → true
*
* prefixAgain("abXYabc", 3) → false
*/
public boolean prefixAgain(String str, int n) {
return false;
}
/*
* http://codingbat.com/prob/p159772
*
* Given a string, does "xyz" appear in the middle of the string? To define
* middle, we'll say that the number of chars to the left and right of the
* "xyz" must differ by at most one. This problem is harder than it looks.
*
* xyzMiddle("AAxyzBB") → true
*
* xyzMiddle("AxyzBB") → true
*
* xyzMiddle("AxyzBBB") → false
*/
public boolean xyzMiddle(String str) {
return false;
}
/*
* http://codingbat.com/prob/p129952
*
* A sandwich is two pieces of bread with something in between. Return the
* string that is between the first and last appearance of "bread" in the
* given string, or return the empty string "" if there are not two pieces
* of bread.
*
* getSandwich("breadjambread") → "jam"
*
* getSandwich("xxbreadjambreadyy") → "jam"
*
* getSandwich("xxbreadyy") → ""
*/
public String getSandwich(String str) {
return null;
}
/*
* http://codingbat.com/prob/p194491
*
* Returns true if for every '*' (star) in the string, if there are chars
* both immediately before and after the star, they are the same.
*
* sameStarChar("xy*yzz") → true
*
* sameStarChar("xy*zzz") → false
*
* sameStarChar("*xa*az") → true
*/
public boolean sameStarChar(String str) {
return false;
}
/*
* http://codingbat.com/prob/p180759
*
* Look for patterns like "zip" and "zap" in the string -- length-3,
* starting with 'z' and ending with 'p'. Return a string where for all such
* words, the middle letter is gone, so "zipXzap" yields "zpXzp".
*
* zipZap("zipXzap") → "zpXzp"
*
* zipZap("zopzop") → "zpzp"
*
* zipZap("zzzopzop") → "zzzpzp"
*/
public String zipZap(String str) {
return null;
}
/*
* http://codingbat.com/prob/p139564
*
* Return a version of the given string, where for every star (*) in the
* string the star and the chars immediately to its left and right are gone.
* So "ab*cd" yields "ad" and "ab**cd" also yields "ad".
*
* starOut("ab*cd") → "ad"
*
* starOut("ab**cd") → "ad"
*
* starOut("sm*eilly") → "silly"
*/
public String starOut(String str) {
return null;
}
/*
* http://codingbat.com/prob/p170829
*
* Given a string and a non-empty word string, return a version of the
* original String where all chars have been replaced by pluses ("+"),
* except for appearances of the word string which are preserved unchanged.
*
* plusOut("12xy34", "xy") → "++xy++"
*
* plusOut("12xy34", "1") → "1+++++"
*
* plusOut("12xy34xyabcxy", "xy") → "++xy++xy+++xy"
*/
public String plusOut(String str, String word) {
return null;
}
/*
* http://codingbat.com/prob/p147538
*
* Given a string and a non-empty word string, return a string made of each
* char just before and just after every appearance of the word in the
* string. Ignore cases where there is no char before or after the word, and
* a char may be included twice if it is between two words.
*
* wordEnds("abcXY123XYijk", "XY") → "c13i"
*
* wordEnds("XY123XY", "XY") → "13"
*
* wordEnds("XY1XY", "XY") → "11"
*/
public String wordEnds(String str, String word) {
return null;
}
}
| perzyje/prog-training-oct2012 | day15/src/main/java/com/codingbat/String2.java | Java | agpl-3.0 | 8,849 |
<?php
/*
* jQuery File Upload Plugin PHP Example 5.7
* https://github.com/blueimp/jQuery-File-Upload
*
* Copyright 2010, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
*/
error_reporting(E_ALL | E_STRICT);
//require('upload.class.php');
//$upload_handler = new UploadHandler($options = array('image_versions' => array()));
header('Pragma: no-cache');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Content-Disposition: inline; filename="files.json"');
header('X-Content-Type-Options: nosniff');
header('Access-Control-Allow-Origin: *');
//header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE');
header('Access-Control-Allow-Methods: OPTIONS, POST');
header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size');
function validate($uploaded_file, $file, $error, $index) {
if ($error) {
$file->error = $error;
return false;
}
if (!$file->name) {
$file->error = 'missingFileName';
return false;
}
/* if (!preg_match($this->options['accept_file_types'], $file->name)) {
$file->error = 'acceptFileTypes';
return false;
} */
/* if ($uploaded_file && is_uploaded_file($uploaded_file)) {
$file_size = filesize($uploaded_file);
} else {
$file_size = $_SERVER['CONTENT_LENGTH'];
}
if ($this->options['max_file_size'] && (
$file_size > $this->options['max_file_size'] ||
$file->size > $this->options['max_file_size'])
) {
$file->error = 'maxFileSize';
return false;
}
if ($this->options['min_file_size'] &&
$file_size < $this->options['min_file_size']) {
$file->error = 'minFileSize';
return false;
}
if (is_int($this->options['max_number_of_files']) && (
count($this->get_file_objects()) >= $this->options['max_number_of_files'])
) {
$file->error = 'maxNumberOfFiles';
return false;
}
list($img_width, $img_height) = @getimagesize($uploaded_file);
if (is_int($img_width)) {
if ($this->options['max_width'] && $img_width > $this->options['max_width'] ||
$this->options['max_height'] && $img_height > $this->options['max_height']) {
$file->error = 'maxResolution';
return false;
}
if ($this->options['min_width'] && $img_width < $this->options['min_width'] ||
$this->options['min_height'] && $img_height < $this->options['min_height']) {
$file->error = 'minResolution';
return false;
}
} */
return true;
}
function handle_form_data($file, $index) {
// Handle form data, e.g. $_REQUEST['description'][$index]
}
function trim_file_name($name, $type, $index) {
// Remove path information and dots around the filename, to prevent uploading
// into different directories or replacing hidden system files.
// Also remove control characters and spaces (\x00..\x20) around the filename:
$file_name = trim(basename(stripslashes($name)), ".\x00..\x20");
// Add missing file extension for known image types:
if (strpos($file_name, '.') === false &&
preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
$file_name .= '.' . $matches[1];
}
return $file_name;
}
function handle_file_upload($uploaded_file, $name, $size, $type, $error, $index = null) {
$file = new stdClass();
$file->name = trim_file_name($name, $type, $index);
$file->size = intval($size);
$file->type = $type;
if (validate($uploaded_file, $file, $error, $index)) {
handle_form_data($file, $index);
// !!
$file_path = dirname($_SERVER['SCRIPT_FILENAME']).'/files/' . $file->name;
clearstatcache();
if ($uploaded_file && is_uploaded_file($uploaded_file)) {
// multipart/formdata uploads (POST method uploads)
move_uploaded_file($uploaded_file, $file_path);
} else {
// Non-multipart uploads (PUT method support)
file_put_contents(
$file_path, fopen('php://input', 'r'), $append_file ? FILE_APPEND : 0
);
}
$file_size = filesize($file_path);
if ($file_size === $file->size) {
} else {
unlink($file_path);
$file->error = 'abort';
}
$file->size = $file_size;
}
return $file;
}
$options['param_name'] = "files";
switch ($_SERVER['REQUEST_METHOD']) {
case 'OPTIONS':
break;
/* case 'HEAD':
case 'GET':
$upload_handler->get();
break; */
case 'POST': {
$upload = isset($_FILES[$options['param_name']]) ?
$_FILES[$options['param_name']] : null;
$info = array();
if ($upload && is_array($upload['tmp_name'])) {
// param_name is an array identifier like "files[]",
// $_FILES is a multi-dimensional array:
foreach ($upload['tmp_name'] as $index => $value) {
$info[] = handle_file_upload(
$upload['tmp_name'][$index], isset($_SERVER['HTTP_X_FILE_NAME']) ?
$_SERVER['HTTP_X_FILE_NAME'] : $upload['name'][$index], isset($_SERVER['HTTP_X_FILE_SIZE']) ?
$_SERVER['HTTP_X_FILE_SIZE'] : $upload['size'][$index], isset($_SERVER['HTTP_X_FILE_TYPE']) ?
$_SERVER['HTTP_X_FILE_TYPE'] : $upload['type'][$index], $upload['error'][$index], $index
);
}
} elseif ($upload || isset($_SERVER['HTTP_X_FILE_NAME'])) {
// param_name is a single object identifier like "file",
// $_FILES is a one-dimensional array:
$info[] = handle_file_upload(
isset($upload['tmp_name']) ? $upload['tmp_name'] : null, isset($_SERVER['HTTP_X_FILE_NAME']) ?
$_SERVER['HTTP_X_FILE_NAME'] : (isset($upload['name']) ?
$upload['name'] : null), isset($_SERVER['HTTP_X_FILE_SIZE']) ?
$_SERVER['HTTP_X_FILE_SIZE'] : (isset($upload['size']) ?
$upload['size'] : null), isset($_SERVER['HTTP_X_FILE_TYPE']) ?
$_SERVER['HTTP_X_FILE_TYPE'] : (isset($upload['type']) ?
$upload['type'] : null), isset($upload['error']) ? $upload['error'] : null
);
}
header('Vary: Accept');
$json = json_encode($info);
$redirect = isset($_REQUEST['redirect']) ?
stripslashes($_REQUEST['redirect']) : null;
if ($redirect) {
header('Location: ' . sprintf($redirect, rawurlencode($json)));
return;
}
if (isset($_SERVER['HTTP_ACCEPT']) &&
(strpos($_SERVER['HTTP_ACCEPT'], 'application/json') !== false)) {
header('Content-type: application/json');
} else {
header('Content-type: text/plain');
}
echo $json;
}
break;
/* case 'DELETE':
$upload_handler->delete();
break; */
default:
header('HTTP/1.1 405 Method Not Allowed');
}
| iesoretania/atica.old | server/upload/index.php | PHP | agpl-3.0 | 7,441 |
"""course_discovery URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')
Including another URLconf
1. Add an import: from blog import urls as blog_urls
2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))
"""
import os
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.auth.views import logout
from django.core.urlresolvers import reverse_lazy
from django.views.generic import RedirectView
from course_discovery.apps.core import views as core_views
admin.autodiscover()
# pylint: disable=invalid-name
# Always login via edX OpenID Connect
login = RedirectView.as_view(url=reverse_lazy('social:begin', args=['edx-oidc']), permanent=False, query_string=True)
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api/', include('course_discovery.apps.api.urls', namespace='api')),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^auto_auth/$', core_views.AutoAuth.as_view(), name='auto_auth'),
url(r'^health/$', core_views.health, name='health'),
url(r'^login/$', login, name='login'),
url(r'^logout/$', logout, name='logout'),
url('', include('social.apps.django_app.urls', namespace='social')),
]
if settings.DEBUG and os.environ.get('ENABLE_DJANGO_TOOLBAR', False): # pragma: no cover
import debug_toolbar # pylint: disable=import-error
urlpatterns.append(url(r'^__debug__/', include(debug_toolbar.urls)))
| cpennington/course-discovery | course_discovery/urls.py | Python | agpl-3.0 | 1,899 |
/**
* This file is part of agora-gui-admin.
* Copyright (C) 2015-2016 Agora Voting SL <agora@agoravoting.com>
* agora-gui-admin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License.
* agora-gui-admin is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with agora-gui-admin. If not, see <http://www.gnu.org/licenses/>.
**/
angular.module('avAdmin')
.controller(
'AddCsvModal',
function($scope, $modalInstance, election, ConfigService, Plugins)
{
$scope.election = election;
$scope.textarea = "";
$scope.helpurl = ConfigService.helpUrl;
$scope.ok = function () {
$modalInstance.close($("#csv-textarea").val());
};
// if there's a parent election, add those fields at the end of the example
if ($scope.election.children_election_info)
{
$scope.childrenElections = _.map(
$scope.election.children_election_info.natural_order,
function (election_id) {
return $scope.election.childrenElectionNames[election_id];
}
);
} else {
$scope.childrenElections = [];
}
var exhtml = {html: [], scope: {}};
Plugins.hook(
'census-add-csv-modal',
{ exhtml: exhtml }
);
$scope.exhtml = exhtml.html;
$scope = _.extend($scope, exhtml.scope);
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
}
);
| agoravoting/agora-gui-admin | avAdmin/admin-directives/elcensus/add-csv-modal.js | JavaScript | agpl-3.0 | 1,844 |
(function() {
'use strict';
angular
.module('blocks.logger')
.factory('logListeners', logListeners);
/**
* @ngdoc service
* @name spaghetto.logger:logListeners
*
* @description
* Manage different log listeners so that log messages can have various
* destinations.
*
*
* The default behaviour is to send log messages to :
*
* * '$log' : Angular simple logging service, writing into the browser's console
* * 'toaster' : Toaster screen notifications
*
* You can change this behaviour by installing new log listeners and/or removing
* the default ones
* ## Log listener definition
* <pre>
*
// here instead of an exdample, we should definie the required properties (with ngdoc)
of a logListener object
* </pre>
*
*/
/* @ngInject */
function logListeners() {
var listeners = {};
var service = {
addListener: addListener,
getListeners: getListeners,
removeListener: removeListener
};
return service;
///////////////
/**
* @ngdoc method
* @name addListener
* @methodOf spaghetto.logger:logListeners
* @kind function
*
* @description
* Add log listener
*
* ## Add a Log listener
* <pre>
// define my Log Listener
var myLogListener = {
error : errorLog,
info : infoLog,
success : successLog,
warning : warningLog
}
function errorLog(msg, data, title) {
console.log('Error: ' + title + '\n' + data);
}
function infoLog(msg, data, title) {
console.log('Info: ' + title + '\n' + data);
}
function successLog(msg, data, title) {
console.log('Success: ' + title + '\n' + data);
}
function warningLog(msg, data, title) {
console.log('Warning: ' + title + '\n' + data);
}
logListeners.addListener('mylog', myLogListener);
* </pre>
* @param {string} name log listener name
* @param {Object} logListener log listener object
* @param {Function} logListener.error log an error message
* @param {Function} logListener.info log an info message
* @param {Function} logListener.success log a success message
* @param {Function} logListener.warning log a warning message
*/
function addListener(name, logListener) {
listeners[name] = logListener;
}
/**
* @ngdoc method
* @name removeListener
* @methodOf spaghetto.logger:logListeners
* @kind function
*
* @description
* Remove a log listener
*
* ## Remove a log listener
* <pre>
// 'toastr' log listener is installed by default
// if you want to remove it, you can do:
logListeners.removeListener('toastr');
* </pre>
* @param {string} name log listener name
*/
function removeListener(name) {
delete listeners[name];
}
/**
* @ngdoc method
* @name getListeners
* @methodOf spaghetto.logger:logListeners
* @kind function
*
* @description
* returns all installed log listeners
*
* @return {Array} keys is the log listener name
* and value is the log listener object
**/
function getListeners() {
return listeners;
}
}
}());
| aurelien-rainone/spaghetto | src/client/app/blocks/logger/loglisteners.js | JavaScript | agpl-3.0 | 3,869 |
<?php
namespace Chill\PersonBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\ExecutionContextInterface;
use CL\CLHistoryBundle\Entity\IsHistoryContainer;
use CL\CLHistoryBundle\Entity\HasHistory;
use CL\CLHistoryBundle\Entity\HistoryHelper;
/**
* Person
*/
class Person implements IsHistoryContainer, HasHistory {
/**
* @var integer
*/
private $id;
/**
* @var string
*/
private $name;
/**
* @var string
*/
private $surname;
/**
* @var \DateTime
*/
private $dateOfBirth;
/**
* @var string
*/
private $placeOfBirth = '';
/**
* @var string
*/
private $genre;
const GENRE_MAN = 'MAN';
const GENRE_WOMAN = 'WOM';
/**
* @var string
*/
private $civil_union = self::CIVIL_UNKNOW;
/*Célibataire
Marié(e)
Veuf – Veuve
Séparé(e)
Divorcé(e)
Cohabitant légal
Indéterminé
ou une valeur vide lorsque la donnée nest pas connue*/
const CIVIL_SINGLE = 'single';
const CIVIL_WIDOW = 'widow';
const CIVIL_SEPARATED = 'separated';
const CIVIL_DIVORCED = 'divorced';
const CIVIL_COHAB = 'cohab';
const CIVIL_UNKNOW = 'unknow';
/**
* @var integer
*/
private $nbOfChild = 0;
/**
* @var string
*/
private $belgian_national_number;
/**
* @var string
*/
private $memo = '';
/**
* @var string
*/
private $address = '';
/**
* @var string
*/
private $email = '';
/**
* @var \CL\Chill\MainBundle\Entity\Country
*/
private $countryOfBirth;
/**
* @var \CL\Chill\MainBundle\Entity\Country
*/
private $nationality;
/**
*
* @var \Doctrine\Common\Collections\ArrayCollection
*/
private $history;
/**
*
* @var boolean
*/
private $proxyHistoryOpenState = false;
const HISTORY_DOMAIN = 'person';
/**
*
* @var string
*/
private $historyId = null;
const ACTION_UPDATE = 'update';
const ACTION_CREATE = 'create';
public function __construct(\DateTime $opening = null) {
$this->history = new \Doctrine\Common\Collections\ArrayCollection();
if ($opening === null) {
$opening = new \DateTime();
}
$this->open($opening);
//create an helper with key "update", and set "creation" instead
$this->getHistoryHelper(self::ACTION_UPDATE)
->setAction(self::ACTION_CREATE);
}
/**
*
* @param \Chill\PersonBundle\Entity\PersonHistoryFile $history
* @uses PersonHistoryFile::setPerson
*/
public function addHistoryFile(PersonHistoryFile $history) {
$history->setPerson($this);
$this->history->add($history);
}
/**
* set the Person file as open at the given date.
*
* For updating a opening's date, you should update PersonHistoryFile instance
* directly.
*
* For closing a file, @see this::close
*
* To check if the Person and his history is consistent, use validation.
*
* @param \DateTime $date
*/
public function open(\DateTime $date, $memo = '') {
$history = new PersonHistoryFile($date);
$history->setMemo($memo);
$this->proxyHistoryOpenState = true;
$this->addHistoryFile($history);
}
/**
*
* Set the Person file as closed at the given date.
*
* For update a closing date, you should update PersonHistoryFile instance
* directly.
*
* To check if the Person and his history are consistent, use validation.
*
* @param \DateTime $date
* @param string $motive
* @param string $memo
* @throws \Exception if two lines of history are open.
*/
public function close(\DateTime $date, $motive, $memo = '') {
$histories = $this->history;
$found = false;
foreach ($histories as $history) {
if ($history->isOpen()) {
if ($found === true) {
throw new \Exception('two open line in history were found. This should not happen.');
}
$history->setDateClosing($date);
$history->setMotive($motive);
$history->setMemo($memo);
$this->proxyHistoryOpenState = false;
$found = true;
}
}
}
/**
*
* @return null|PersonHistoryFile
*/
public function getCurrentHistory() {
if ($this->proxyHistoryOpenState === false) {
return null;
}
foreach ($this->history as $history) {
if ($history->isOpen()) {
return $history;
}
}
}
/**
*
* @return \Doctrine\Common\Collections\ArrayCollection
*/
public function getHistories() {
return $this->history;
}
/**
*
* @return PersonHistoryFile[]
*/
public function getHistoriesOrdered() {
$histories = $this->getHistories()->toArray();
//order by date :
usort($histories, function($a, $b) {
$dateA = $a->getDateOpening();
$dateB = $b->getDateOpening();
if ($dateA == $dateB) {
$dateEA = $a->getDateClosing();
$dateEB = $b->getDateClosing();
if ($dateEA == $dateEB) {
return 0;
}
if ($dateEA < $dateEB) {
return -1;
} else {
return +1;
}
}
if ($dateA < $dateB) {
return -1 ;
} else {
return 1;
}
});
return $histories;
}
public function isOpen() {
return $this->proxyHistoryOpenState;
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set name
*
* @param string $name
* @return Person
*/
public function setName($name)
{
if ($name !== $this->name) {
$this->getHistoryHelper(self::ACTION_UPDATE)
->registerChange('name', $this->name, $name);
$this->name = $name;
}
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set surname
*
* @param string $surname
* @return Person
*/
public function setSurname($surname)
{
$this->surname = $surname;
return $this;
}
/**
* Get surname
*
* @return string
*/
public function getSurname()
{
return $this->surname;
}
/**
* Set dateOfBirth
*
* @param \DateTime $dateOfBirth
* @return Person
*/
public function setDateOfBirth($dateOfBirth)
{
$this->dateOfBirth = $dateOfBirth;
return $this;
}
/**
* Get dateOfBirth
*
* @return \DateTime
*/
public function getDateOfBirth()
{
return $this->dateOfBirth;
}
/**
* Set placeOfBirth
*
* @param string $placeOfBirth
* @return Person
*/
public function setPlaceOfBirth($placeOfBirth)
{
if ($placeOfBirth === null) {
$placeOfBirth = '';
}
$this->placeOfBirth = $placeOfBirth;
return $this;
}
/**
* Get placeOfBirth
*
* @return string
*/
public function getPlaceOfBirth()
{
return $this->placeOfBirth;
}
/**
* Set genre
*
* @param string $genre
* @return Person
*/
public function setGenre($genre)
{
$this->genre = $genre;
return $this;
}
/**
* Get genre
*
* @return string
*/
public function getGenre()
{
return $this->genre;
}
/**
* return gender as a Numeric form.
* Useful for translation :-)
* @return int
*/
public function getGenreNumeric() {
if ($this->getGenre() == self::GENRE_WOMAN)
return 1;
else
return 0;
}
/**
* Set civil_union
*
* @param string $civilUnion
* @return Person
*/
public function setCivilUnion($civilUnion)
{
if ($this->civil_union !== $civilUnion) {
$this->getHistoryHelper(self::ACTION_UPDATE)
->registerChange('civil_union', $this->civil_union, $civilUnion);
$this->civil_union = $civilUnion;
}
return $this;
}
/**
* Get civil_union
*
* @return string
*/
public function getCivilUnion()
{
return $this->civil_union;
}
/**
* Set nbOfChild
*
* @param integer $nbOfChild
* @return Person
*/
public function setNbOfChild($nbOfChild)
{
$this->nbOfChild = $nbOfChild;
return $this;
}
/**
* Get nbOfChild
*
* @return integer
*/
public function getNbOfChild()
{
return $this->nbOfChild;
}
/**
* Set belgian_national_number
*
* @param string $belgianNationalNumber
* @return Person
*/
public function setBelgianNationalNumber($belgianNationalNumber)
{
if ($belgianNationalNumber === null) {
$belgianNationalNumber = '';
}
$this->belgian_national_number = $belgianNationalNumber;
return $this;
}
/**
* Get belgian_national_number
*
* @return string
*/
public function getBelgianNationalNumber()
{
return $this->belgian_national_number;
}
/**
* Set memo
*
* @param string $memo
* @return Person
*/
public function setMemo($memo)
{
if ($memo === null) {
$memo = '';
}
if ($this->memo !== $memo) {
$this->getHistoryHelper(self::ACTION_UPDATE)
->registerChange('memo', $this->memo, $memo);
$this->memo = $memo;
}
return $this;
}
/**
* Get memo
*
* @return string
*/
public function getMemo()
{
return $this->memo;
}
/**
* Set address
*
* @param string $address
* @return Person
*/
public function setAddress($address)
{
if ($address === null) {
$address = '';
}
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set email
*
* @param string $email
* @return Person
*/
public function setEmail($email)
{
if ($email === null) {
$email = '';
}
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set countryOfBirth
*
* @param \CL\Chill\MainBundle\Entity\Country $countryOfBirth
* @return Person
*/
public function setCountryOfBirth(\CL\Chill\MainBundle\Entity\Country $countryOfBirth = null)
{
if ($this->countryOfBirth->getId() !== $countryOfBirth->getId()) {
$this->getHistoryHelper(self::ACTION_UPDATE)
->registerChange('country_of_birth',
$this->countryOfBirth->getLabel(),
$countryOfBirth->getLabel());
$this->countryOfBirth = $countryOfBirth;
}
return $this;
}
/**
* Get countryOfBirth
*
* @return \CL\Chill\MainBundle\Entity\Country
*/
public function getCountryOfBirth()
{
return $this->countryOfBirth;
}
/**
* Set nationality
*
* @param \CL\Chill\MainBundle\Entity\Country $nationality
* @return Person
*/
public function setNationality(\CL\Chill\MainBundle\Entity\Country $nationality = null)
{
$this->nationality = $nationality;
return $this;
}
/**
* Get nationality
*
* @return \CL\Chill\MainBundle\Entity\Country
*/
public function getNationality()
{
return $this->nationality;
}
public function getLabel() {
return $this->getSurname()." ".$this->getName();
}
public function __toString() {
return $this->getLabel();
}
// VALIDATION
public function isHistoryValid(ExecutionContextInterface $context) {
$r = $this->checkHistoryIsNotCovering();
if ($r !== true) {
if ($r['result'] === self::ERROR_OPENING_NOT_CLOSED_IS_BEFORE_NEW_LINE) {
$context->addViolationAt('history',
'validation.Person.constraint.history.open_history_without_closing',
array() );
return;
}
$context->addViolationAt('history',
'validation.Person.constraint.history.opening_is_before_closing',
array(
'%dateOpening%' => $r['dateOpening']->format('d-m-Y'),
'%dateClosing%' => $r['dateClosing']->format('d-m-Y'),
'%date%' => $r['date']->format('d-m-Y')
)
);
}
}
const ERROR_OPENING_IS_INSIDE_CLOSING = 1;
const ERROR_OPENING_NOT_CLOSED_IS_BEFORE_NEW_LINE = 2;
const ERROR_OPENING_NOT_CLOSE_IS_INSIDE_CLOSED_HISTORY_LINE = 3;
const ERROR_OPENING_IS_BEFORE_OTHER_LINE_AND_CLOSED_IS_AFTER_THIS_LINE = 4;
public function checkHistoryIsNotCovering() {
$histories = $this->getHistoriesOrdered();
//check order :
$oldOpening = array();
$oldClosing = array();
$i = 0;
foreach ($histories as $key => $history) {
//history is open : we must check the arent any history after
if ($history->isOpen()) {
foreach ($histories as $subKey => $against) {
//if we are checking the same, continue
if ($key === $subKey) {
continue;
}
if ($history->getDateOpening() > $against->getDateOpening()
&& $history->getDateOpening() < $against->getDateOpening()) {
// the history date opening is inside another opening line
return array(
'result' => self::ERROR_OPENING_NOT_CLOSE_IS_INSIDE_CLOSED_HISTORY_LINE,
'dateOpening' => $against->getDateOpening(),
'dateClosing' => $against->getDateClosing(),
'date' => $history->getDateOpening()
);
}
if ($history->getDateOpening() < $against->getDateOpening()
&& $history->getDateClosing() > $against->getDateClosing()) {
// the history date opening is inside another opening line
return array(
'result' => self::ERROR_OPENING_IS_BEFORE_OTHER_LINE_AND_CLOSED_IS_AFTER_THIS_LINE,
'dateOpening' => $against->getDateOpening(),
'dateClosing' => $against->getDateClosing(),
'date' => $history->getDateOpening()
);
}
//if we have an aopening later...
if ($history->getDateOpening() < $against->getDateClosing()) {
return array( 'result' => self::ERROR_OPENING_NOT_CLOSED_IS_BEFORE_NEW_LINE,
'dateOpening' => $against->getDateOpening(),
'dateClosing' => $against->getDateClosing(),
'date' => $history->getDateOpening()
);
}
}
} else {
//we must check there is not covering lines
foreach ($histories as $subKey => $against) {
//check if dateOpening is inside an `against` line
if ($history->getDateOpening() > $against->getDateOpening()
&& $history->getDateOpening() < $against->getDateClosing()) {
return array(
'result' => self::ERROR_OPENING_IS_INSIDE_CLOSING,
'dateOpening' => $against->getDateOpening(),
'dateClosing' => $against->getDateClosing(),
'date' => $history->getDateOpening()
);
}
}
}
}
return true;
}
public function getDomain() {
return self::HISTORY_DOMAIN;
}
public function getHistoryId() {
return $this->historyId;
}
public function setHistoryId($id) {
$this->historyId = $id;
}
/**
*
* @var \CL\CLHistoryBundle\Entity\HistoryHelper
*/
private $historyHelper = array();
private function getHistoryHelper($helper) {
if (!isset($this->historyHelper[$helper])) {
$this->historyHelper[$helper] = new HistoryHelper();
$this->historyHelper[$helper]->setAction($helper);
}
return $this->historyHelper[$helper];
}
public function getEntityName() {
return 'person';
}
public function getHistory() {
$histories = array();
foreach ($this->historyHelper as $historyHelper) {
$histories = $histories->toArray();
}
return $histories;
}
public function getParentContainers() {
return array($this);
}
public function getVersion() {
return 0;
}
} | Champs-Libres/ChillPersonBundle | Entity/Person.php | PHP | agpl-3.0 | 19,339 |
<?php
/**
* StatusNet, the distributed open-source microblogging tool
*
* Register a new user account
*
* PHP version 5
*
* LICENCE: This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Login
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @copyright 2008-2009 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
if (!defined('STATUSNET') && !defined('LACONICA')) {
exit(1);
}
/**
* An action for registering a new user account
*
* @category Login
* @package StatusNet
* @author Evan Prodromou <evan@status.net>
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
* @link http://status.net/
*/
class RegisterAction extends Action
{
/**
* Has there been an error?
*/
var $error = null;
/**
* Have we registered?
*/
var $registered = false;
/**
* Are we processing an invite?
*/
var $invite = null;
/**
* Prepare page to run
*
*
* @param $args
* @return string title
*/
function prepare($args)
{
parent::prepare($args);
$this->code = $this->trimmed('code');
if (empty($this->code)) {
common_ensure_session();
if (array_key_exists('invitecode', $_SESSION)) {
$this->code = $_SESSION['invitecode'];
}
}
if (common_config('site', 'inviteonly') && empty($this->code)) {
$this->clientError(_('Sorry, only invited people can register.'));
return false;
}
if (!empty($this->code)) {
$this->invite = Invitation::staticGet('code', $this->code);
if (empty($this->invite)) {
$this->clientError(_('Sorry, invalid invitation code.'));
return false;
}
// Store this in case we need it
common_ensure_session();
$_SESSION['invitecode'] = $this->code;
}
return true;
}
/**
* Title of the page
*
* @return string title
*/
function title()
{
if ($this->registered) {
return _('Registration successful');
} else {
return _('Register');
}
}
/**
* Handle input, produce output
*
* Switches on request method; either shows the form or handles its input.
*
* Checks if registration is closed and shows an error if so.
*
* @param array $args $_REQUEST data
*
* @return void
*/
function handle($args)
{
parent::handle($args);
if (common_config('site', 'closed')) {
$this->clientError(_('Registration not allowed.'));
} else if (common_logged_in()) {
$this->clientError(_('Already logged in.'));
} else if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$this->tryRegister();
} else {
$this->showForm();
}
}
function showScripts()
{
parent::showScripts();
$this->autofocus('nickname');
}
/**
* Try to register a user
*
* Validates the input and tries to save a new user and profile
* record. On success, shows an instructions page.
*
* @return void
*/
function tryRegister()
{
if (Event::handle('StartRegistrationTry', array($this))) {
$token = $this->trimmed('token');
if (!$token || $token != common_session_token()) {
$this->showForm(_('There was a problem with your session token. '.
'Try again, please.'));
return;
}
$nickname = $this->trimmed('nickname');
$email = $this->trimmed('email');
$fullname = $this->trimmed('fullname');
$homepage = $this->trimmed('homepage');
$bio = $this->trimmed('bio');
$location = $this->trimmed('location');
// We don't trim these... whitespace is OK in a password!
$password = $this->arg('password');
$confirm = $this->arg('confirm');
// invitation code, if any
$code = $this->trimmed('code');
if ($code) {
$invite = Invitation::staticGet($code);
}
if (common_config('site', 'inviteonly') && !($code && $invite)) {
$this->clientError(_('Sorry, only invited people can register.'));
return;
}
// Input scrubbing
try {
$nickname = Nickname::normalize($nickname);
} catch (NicknameException $e) {
$this->showForm($e->getMessage());
}
$email = common_canonical_email($email);
if (!$this->boolean('license')) {
$this->showForm(_('You cannot register if you don\'t '.
'agree to the license.'));
} else if ($email && !Validate::email($email, common_config('email', 'check_domain'))) {
$this->showForm(_('Not a valid email address.'));
} else if ($this->nicknameExists($nickname)) {
$this->showForm(_('Nickname already in use. Try another one.'));
} else if (!User::allowed_nickname($nickname)) {
$this->showForm(_('Not a valid nickname.'));
} else if ($this->emailExists($email)) {
$this->showForm(_('Email address already exists.'));
} else if (!is_null($homepage) && (strlen($homepage) > 0) &&
!Validate::uri($homepage,
array('allowed_schemes' =>
array('http', 'https')))) {
$this->showForm(_('Homepage is not a valid URL.'));
return;
} else if (!is_null($fullname) && mb_strlen($fullname) > 255) {
$this->showForm(_('Full name is too long (maximum 255 characters).'));
return;
} else if (Profile::bioTooLong($bio)) {
$this->showForm(sprintf(_m('Bio is too long (maximum %d character).',
'Bio is too long (maximum %d characters).',
Profile::maxBio()),
Profile::maxBio()));
return;
} else if (!is_null($location) && mb_strlen($location) > 255) {
$this->showForm(_('Location is too long (maximum 255 characters).'));
return;
} else if (strlen($password) < 6) {
$this->showForm(_('Password must be 6 or more characters.'));
return;
} else if ($password != $confirm) {
$this->showForm(_('Passwords don\'t match.'));
} else if ($user = User::register(array('nickname' => $nickname,
'password' => $password,
'email' => $email,
'fullname' => $fullname,
'homepage' => $homepage,
'bio' => $bio,
'location' => $location,
'code' => $code))) {
if (!$user) {
$this->showForm(_('Invalid username or password.'));
return;
}
// success!
if (!common_set_user($user)) {
$this->serverError(_('Error setting user.'));
return;
}
// this is a real login
common_real_login(true);
if ($this->boolean('rememberme')) {
common_debug('Adding rememberme cookie for ' . $nickname);
common_rememberme($user);
}
Event::handle('EndRegistrationTry', array($this));
// Re-init language env in case it changed (not yet, but soon)
common_init_language();
$this->showSuccess();
} else {
$this->showForm(_('Invalid username or password.'));
}
}
}
/**
* Does the given nickname already exist?
*
* Checks a canonical nickname against the database.
*
* @param string $nickname nickname to check
*
* @return boolean true if the nickname already exists
*/
function nicknameExists($nickname)
{
$user = User::staticGet('nickname', $nickname);
return is_object($user);
}
/**
* Does the given email address already exist?
*
* Checks a canonical email address against the database.
*
* @param string $email email address to check
*
* @return boolean true if the address already exists
*/
function emailExists($email)
{
$email = common_canonical_email($email);
if (!$email || strlen($email) == 0) {
return false;
}
$user = User::staticGet('email', $email);
return is_object($user);
}
// overrrided to add entry-title class
function showPageTitle() {
if (Event::handle('StartShowPageTitle', array($this))) {
$this->element('h1', array('class' => 'entry-title'), $this->title());
}
}
// overrided to add hentry, and content-inner class
function showContentBlock()
{
$this->elementStart('div', array('id' => 'content', 'class' => 'hentry'));
$this->showPageTitle();
$this->showPageNoticeBlock();
$this->elementStart('div', array('id' => 'content_inner',
'class' => 'entry-content'));
// show the actual content (forms, lists, whatever)
$this->showContent();
$this->elementEnd('div');
$this->elementEnd('div');
}
/**
* Instructions or a notice for the page
*
* Shows the error, if any, or instructions for registration.
*
* @return void
*/
function showPageNotice()
{
if ($this->registered) {
return;
} else if ($this->error) {
$this->element('p', 'error', $this->error);
} else {
$instr =
common_markup_to_html(_('With this form you can create '.
'a new account. ' .
'You can then post notices and '.
'link up to friends and colleagues.'));
$this->elementStart('div', 'instructions');
$this->raw($instr);
$this->elementEnd('div');
}
}
/**
* Wrapper for showing a page
*
* Stores an error and shows the page
*
* @param string $error Error, if any
*
* @return void
*/
function showForm($error=null)
{
$this->error = $error;
$this->showPage();
}
/**
* Show the page content
*
* Either shows the registration form or, if registration was successful,
* instructions for using the site.
*
* @return void
*/
function showContent()
{
if ($this->registered) {
$this->showSuccessContent();
} else {
$this->showFormContent();
}
}
/**
* Show the registration form
*
* @return void
*/
function showFormContent()
{
$code = $this->trimmed('code');
$invite = null;
if ($code) {
$invite = Invitation::staticGet($code);
}
if (common_config('site', 'inviteonly') && !($code && $invite)) {
$this->clientError(_('Sorry, only invited people can register.'));
return;
}
$this->elementStart('form', array('method' => 'post',
'id' => 'form_register',
'class' => 'form_settings',
'action' => common_local_url('register')));
$this->elementStart('fieldset');
$this->element('legend', null, 'Account settings');
$this->hidden('token', common_session_token());
if ($this->code) {
$this->hidden('code', $this->code);
}
$this->elementStart('ul', 'form_data');
if (Event::handle('StartRegistrationFormData', array($this))) {
$this->elementStart('li');
$this->input('nickname', _('Nickname'), $this->trimmed('nickname'),
_('1-64 lowercase letters or numbers, no punctuation or spaces.'));
$this->elementEnd('li');
$this->elementStart('li');
$this->password('password', _('Password'),
_('6 or more characters.'));
$this->elementEnd('li');
$this->elementStart('li');
$this->password('confirm', _('Confirm'),
_('Same as password above.'));
$this->elementEnd('li');
$this->elementStart('li');
if ($this->invite && $this->invite->address_type == 'email') {
$this->input('email', _('Email'), $this->invite->address,
_('Used only for updates, announcements, '.
'and password recovery.'));
} else {
$this->input('email', _('Email'), $this->trimmed('email'),
_('Used only for updates, announcements, '.
'and password recovery.'));
}
$this->elementEnd('li');
$this->elementStart('li');
$this->input('fullname', _('Full name'),
$this->trimmed('fullname'),
_('Longer name, preferably your "real" name.'));
$this->elementEnd('li');
$this->elementStart('li');
$this->input('homepage', _('Homepage'),
$this->trimmed('homepage'),
_('URL of your homepage, blog, '.
'or profile on another site.'));
$this->elementEnd('li');
$this->elementStart('li');
$maxBio = Profile::maxBio();
if ($maxBio > 0) {
// TRANS: Tooltip for field label in form for profile settings. Plural
// TRANS: is decided by the number of characters available for the
// TRANS: biography (%d).
$bioInstr = sprintf(_m('Describe yourself and your interests in %d character',
'Describe yourself and your interests in %d characters',
$maxBio),
$maxBio);
} else {
$bioInstr = _('Describe yourself and your interests');
}
$this->textarea('bio', _('Bio'),
$this->trimmed('bio'),
$bioInstr);
$this->elementEnd('li');
$this->elementStart('li');
$this->input('location', _('Location'),
$this->trimmed('location'),
_('Where you are, like "City, '.
'State (or Region), Country".'));
$this->elementEnd('li');
Event::handle('EndRegistrationFormData', array($this));
$this->elementStart('li', array('id' => 'settings_rememberme'));
$this->checkbox('rememberme', _('Remember me'),
$this->boolean('rememberme'),
_('Automatically login in the future; '.
'not for shared computers!'));
$this->elementEnd('li');
$attrs = array('type' => 'checkbox',
'id' => 'license',
'class' => 'checkbox',
'name' => 'license',
'value' => 'true');
if ($this->boolean('license')) {
$attrs['checked'] = 'checked';
}
$this->elementStart('li');
$this->element('input', $attrs);
$this->elementStart('label', array('class' => 'checkbox', 'for' => 'license'));
$this->raw($this->licenseCheckbox());
$this->elementEnd('label');
$this->elementEnd('li');
}
$this->elementEnd('ul');
$this->submit('submit', _('Register'));
$this->elementEnd('fieldset');
$this->elementEnd('form');
}
function licenseCheckbox()
{
$out = '';
switch (common_config('license', 'type')) {
case 'private':
// TRANS: Copyright checkbox label in registration dialog, for private sites.
// TRANS: %1$s is the StatusNet sitename.
$out .= htmlspecialchars(sprintf(
_('I understand that content and data of %1$s are private and confidential.'),
common_config('site', 'name')));
// fall through
case 'allrightsreserved':
if ($out != '') {
$out .= ' ';
}
if (common_config('license', 'owner')) {
// TRANS: Copyright checkbox label in registration dialog, for all rights reserved with a specified copyright owner.
$out .= htmlspecialchars(sprintf(
_('My text and files are copyright by %1$s.'),
common_config('license', 'owner')));
} else {
// TRANS: Copyright checkbox label in registration dialog, for all rights reserved with ownership left to contributors.
$out .= htmlspecialchars(_('My text and files remain under my own copyright.'));
}
// TRANS: Copyright checkbox label in registration dialog, for all rights reserved.
$out .= ' ' . _('All rights reserved.');
break;
case 'cc': // fall through
default:
// TRANS: Copyright checkbox label in registration dialog, for Creative Commons-style licenses.
$message = _('My text and files are available under %s ' .
'except this private data: password, ' .
'email address, IM address, and phone number.');
$link = '<a href="' .
htmlspecialchars(common_config('license', 'url')) .
'">' .
htmlspecialchars(common_config('license', 'title')) .
'</a>';
$out .= sprintf(htmlspecialchars($message), $link);
}
return $out;
}
/**
* Show some information about registering for the site
*
* Save the registration flag, run showPage
*
* @return void
*/
function showSuccess()
{
$this->registered = true;
$this->showPage();
}
/**
* Show some information about registering for the site
*
* Gives some information and options for new registrees.
*
* @return void
*/
function showSuccessContent()
{
$nickname = $this->arg('nickname');
$profileurl = common_local_url('showstream',
array('nickname' => $nickname));
$this->elementStart('div', 'success');
$instr = sprintf(_('Congratulations, %1$s! And welcome to %%%%site.name%%%%. '.
'From here, you may want to...'. "\n\n" .
'* Go to [your profile](%2$s) '.
'and post your first message.' . "\n" .
'* Add a [Jabber/GTalk address]'.
'(%%%%action.imsettings%%%%) '.
'so you can send notices '.
'through instant messages.' . "\n" .
'* [Search for people](%%%%action.peoplesearch%%%%) '.
'that you may know or '.
'that share your interests. ' . "\n" .
'* Update your [profile settings]'.
'(%%%%action.profilesettings%%%%)'.
' to tell others more about you. ' . "\n" .
'* Read over the [online docs](%%%%doc.help%%%%)'.
' for features you may have missed. ' . "\n\n" .
'Thanks for signing up and we hope '.
'you enjoy using this service.'),
$nickname, $profileurl);
$this->raw(common_markup_to_html($instr));
$have_email = $this->trimmed('email');
if ($have_email) {
$emailinstr = _('(You should receive a message by email '.
'momentarily, with ' .
'instructions on how to confirm '.
'your email address.)');
$this->raw(common_markup_to_html($emailinstr));
}
$this->elementEnd('div');
}
/**
* Show the login group nav menu
*
* @return void
*/
function showLocalNav()
{
$nav = new LoginGroupNav($this);
$nav->show();
}
function showNoticeForm()
{
}
}
| zcopley/zcopleys-statusnet-clone | actions/register.php | PHP | agpl-3.0 | 22,427 |
#include "CLP.h"
#include <sstream>
#include <iostream>
namespace osuCrypto
{
void CLP::parse(int argc, char const*const* argv)
{
if (argc > 0)
{
std::stringstream ss;
auto ptr = argv[0];
while (*ptr != 0)
ss << *ptr++;
mProgramName = ss.str();
}
for (int i = 1; i < argc;)
{
auto ptr = argv[i];
if (*ptr++ != '-')
{
throw CommandLineParserError();
}
std::stringstream ss;
while (*ptr != 0)
ss << *ptr++;
++i;
ptr = argv[i];
std::pair<std::string, std::list<std::string>> keyValues;
keyValues.first = ss.str();;
while (i < argc && (ptr[0] != '-' || (ptr[0] == '-' && ptr[1] >= '0' && ptr[1] <= '9')))
{
ss.str("");
while (*ptr != 0)
ss << *ptr++;
keyValues.second.push_back(ss.str());
++i;
ptr = argv[i];
}
mKeyValues.emplace(keyValues);
}
}
void CLP::setDefault(std::string key, std::string value)
{
if (hasValue(key) == false)
{
if (isSet(key))
{
mKeyValues[key].emplace_back(value);
}
else
{
mKeyValues.emplace(std::make_pair(key, std::list<std::string>{ value }));
}
}
}
void CLP::setDefault(std::vector<std::string> keys, std::string value)
{
if (hasValue(keys) == false)
{
setDefault(keys[0], value);
}
}
bool CLP::isSet(std::string name)
{
return mKeyValues.find(name) != mKeyValues.end();
}
bool CLP::isSet(std::vector<std::string> names)
{
for (auto name : names)
{
if (isSet(name))
{
return true;
}
}
return false;
}
bool CLP::hasValue(std::string name)
{
return mKeyValues.find(name) != mKeyValues.end() && mKeyValues[name].size();
}
bool CLP::hasValue(std::vector<std::string> names)
{
for (auto name : names)
{
if (hasValue(name))
{
return true;
}
}
return false;
}
//
//int CLP::getInt(std::vector<std::string> names, std::string failMessage)
//{
// for (auto name : names)
// {
// if (hasValue(name))
// {
// return getInt(name);
// }
// }
//
// if (failMessage != "")
// std::cout << failMessage << std::endl;
//
// throw CommandLineParserError();
//}
//
//double CLP::getDouble(std::string name)
//{
// std::stringstream ss;
// ss << *mKeyValues[name].begin();
//
// double ret;
// ss >> ret;
//
// return ret;
//}
//
//double CLP::getDouble(std::vector<std::string> names, std::string failMessage)
//{
// for (auto name : names)
// {
// if (hasValue(name))
// {
// return getDouble(name);
// }
// }
//
// if (failMessage != "")
// std::cout << failMessage << std::endl;
//
// throw CommandLineParserError();
//}
//
//std::string CLP::getString(std::string name)
//{
// return *mKeyValues[name].begin();
//}
//
//std::list<std::string> CLP::getStrings(std::string name)
//{
// return mKeyValues[name];
//}
//
//std::list<std::string> CLP::getStrings(std::vector<std::string> names, std::string failMessage)
//{
// for (auto name : names)
// {
// if (hasValue(name))
// {
// return getStrings(name);
// }
// }
//
// if (failMessage != "")
// std::cout << failMessage << std::endl;
//
// throw CommandLineParserError();
//}
//
//
//std::string CLP::getString(std::vector<std::string> names, std::string failMessage)
//{
// for (auto name : names)
// {
// if (hasValue(name))
// {
// return getString(name);
// }
// }
//
// if (failMessage != "")
// std::cout << failMessage << std::endl;
//
// throw CommandLineParserError();
//}
//
}
| cris-iisc/mpc-primitives | crislib/libscapi/lib/libOTe/cryptoTools/cryptoTools/Common/CLP.cpp | C++ | agpl-3.0 | 4,799 |
/*
carsharing-ds: car sharing datasource for the integreen cloud
Copyright (C) 2015 TIS Innovation Park - Bolzano/Bozen - Italy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.bz.tis.integreen.carsharingbzit;
import it.bz.idm.bdp.dto.DataTypeDto;
import it.bz.idm.bdp.dto.SimpleRecordDto;
import it.bz.idm.bdp.dto.TypeMapDto;
import it.bz.idm.bdp.dto.carsharing.CarsharingStationDto;
import it.bz.idm.bdp.dto.carsharing.CarsharingVehicleDto;
import it.bz.tis.integreen.carsharingbzit.api.ApiClient;
import it.bz.tis.integreen.carsharingbzit.api.BoundingBox;
import it.bz.tis.integreen.carsharingbzit.api.GetStationRequest;
import it.bz.tis.integreen.carsharingbzit.api.GetStationResponse;
import it.bz.tis.integreen.carsharingbzit.api.GetVehicleRequest;
import it.bz.tis.integreen.carsharingbzit.api.GetVehicleResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListStationByBoundingBoxRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListStationsByCityRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListStationsByCityResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListVehicleOccupancyByStationRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListVehicleOccupancyByStationResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListVehicleOccupancyByStationResponse.VehicleAndOccupancies;
import it.bz.tis.integreen.carsharingbzit.api.ListVehiclesByStationsRequest;
import it.bz.tis.integreen.carsharingbzit.api.ListVehiclesByStationsResponse;
import it.bz.tis.integreen.carsharingbzit.api.ListVehiclesByStationsResponse.StationAndVehicles;
import it.bz.tis.integreen.carsharingbzit.tis.IXMLRPCPusher;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import it.bz.idm.bdp.util.IntegreenException;
/**
*
* @author Davide Montesin <d@vide.bz>
*/
public class ConnectorLogic
{
final static long INTERVALL = 10L * 60L * 1000L;
public static final String CARSHARINGSTATION_DATASOURCE = "Carsharingstation";
public static final String CARSHARINGCAR_DATASOURCE = "Carsharingcar";
static final SimpleDateFormat SIMPLE_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); // 2014-09-15T12:00:00
static HashMap<String, String[]> process(ApiClient apiClient,
String[] cityUIDs,
IXMLRPCPusher xmlrpcPusher,
HashMap<String, String[]> vehicleIdsByStationIds,
long updateTime,
ActivityLog activityLog,
ArrayList<ActivityLog> lock) throws IOException
{
if (vehicleIdsByStationIds == null) // Do a full sync
{
vehicleIdsByStationIds = processSyncStations(apiClient, cityUIDs, xmlrpcPusher, activityLog, lock);
}
processPusDatas(apiClient, xmlrpcPusher, vehicleIdsByStationIds, updateTime, activityLog, lock);
return vehicleIdsByStationIds;
}
static HashMap<String, String[]> processSyncStations(ApiClient apiClient,
String[] cityUIDs,
IXMLRPCPusher xmlrpcPusher,
ActivityLog activityLog,
ArrayList<ActivityLog> lock) throws IOException
{
///////////////////////////////////////////////////////////////
// Stations by city
///////////////////////////////////////////////////////////////
// ListStationsByCityRequest request = new ListStationsByCityRequest(cityUIDs);
// ListStationsByCityResponse response = apiClient.callWebService(request, ListStationsByCityResponse.class);
// CarsharingStationDto[] stations = response.getCityAndStations()[0].getStation();
///////////////////////////////////////////////////////////////
// Stations by Bounding Box
///////////////////////////////////////////////////////////////
List<BoundingBox> boxes = new ArrayList<BoundingBox>();
boxes.add(new BoundingBox(10.375214,46.459147,11.059799,46.86113));
boxes.add(new BoundingBox(11.015081,46.450277,11.555557,46.765265));
boxes.add(new BoundingBox(11.458354,46.533418,11.99883,46.847924));
boxes.add(new BoundingBox(11.166573,46.218327,11.521568,46.455303));
boxes.add(new BoundingBox(11.092758,46.794448,11.797256,47.018653));
boxes.add(new BoundingBox(11.959305,46.598506,12.423477,47.098175));
Set<String> stationSet = new HashSet<String>();
for (BoundingBox box:boxes){
ListStationByBoundingBoxRequest request = new ListStationByBoundingBoxRequest(box);
ListStationsByBoundingBoxResponse response = apiClient.callWebService(request, ListStationsByBoundingBoxResponse.class);
if (response != null){
CarsharingStationDto[] stations = response.getStation();
for (int i = 0; i < stations.length; i++)
{
stationSet.add(stations[i].getId());
}
}
}
///////////////////////////////////////////////////////////////
// Stations details
///////////////////////////////////////////////////////////////
String[] stationIds = stationSet.toArray(new String[stationSet.size()]);
GetStationRequest requestGetStation = new GetStationRequest(stationIds);
GetStationResponse responseGetStation = apiClient.callWebService(requestGetStation, GetStationResponse.class);
///////////////////////////////////////////////////////////////
// Vehicles by stations
///////////////////////////////////////////////////////////////
ListVehiclesByStationsRequest vehicles = new ListVehiclesByStationsRequest(stationIds);
ListVehiclesByStationsResponse responseVehicles = apiClient.callWebService(vehicles,
ListVehiclesByStationsResponse.class);
///////////////////////////////////////////////////////////////
// Vehicles details
///////////////////////////////////////////////////////////////
HashMap<String, String[]> vehicleIdsByStationIds = new HashMap<>();
ArrayList<String> veichleIds = new ArrayList<String>();
for (StationAndVehicles stationVehicles : responseVehicles.getStationAndVehicles())
{
String[] vehicleIds = new String[stationVehicles.getVehicle().length];
vehicleIdsByStationIds.put(stationVehicles.getStation().getId(), vehicleIds);
for (int i = 0; i < stationVehicles.getVehicle().length; i++)
{
CarsharingVehicleDto carsharingVehicleDto = stationVehicles.getVehicle()[i];
veichleIds.add(carsharingVehicleDto.getId());
vehicleIds[i] = carsharingVehicleDto.getId();
}
}
GetVehicleRequest requestVehicleDetails = new GetVehicleRequest(veichleIds.toArray(new String[0]));
GetVehicleResponse responseVehicleDetails = apiClient.callWebService(requestVehicleDetails,
GetVehicleResponse.class);
///////////////////////////////////////////////////////////////
// Write data to integreen
///////////////////////////////////////////////////////////////
Object result = xmlrpcPusher.syncStations(CARSHARINGSTATION_DATASOURCE, responseGetStation.getStation());
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "syncStations("
+ CARSHARINGSTATION_DATASOURCE
+ "): "
+ responseGetStation.getStation().length
+ "\n";
}
result = xmlrpcPusher.syncStations(CARSHARINGCAR_DATASOURCE, responseVehicleDetails.getVehicle());
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "syncStations("
+ CARSHARINGCAR_DATASOURCE
+ "): "
+ responseVehicleDetails.getVehicle().length
+ "\n";
}
return vehicleIdsByStationIds;
}
static void processPusDatas(ApiClient apiClient,
IXMLRPCPusher xmlrpcPusher,
HashMap<String, String[]> vehicleIdsByStationIds,
long updateTime,
ActivityLog activityLog,
ArrayList<ActivityLog> lock) throws IOException
{
///////////////////////////////////////////////////////////////
// Read vehicles occupancy and calculate summaries
///////////////////////////////////////////////////////////////
String created = String.valueOf(updateTime);
// Current and forecast
for (long forecast : new long[] { 0, 30L * 60L * 1000L })
{
String begin = String.valueOf(updateTime + forecast);
// TODO begin buffer depends on car type
String begin_carsharing = SIMPLE_DATE_FORMAT.format(new Date(updateTime - 30L * 60L * 1000L + forecast));
String end = SIMPLE_DATE_FORMAT.format(new Date(updateTime + INTERVALL + forecast));
String[] stationIds = vehicleIdsByStationIds.keySet().toArray(new String[0]);
Arrays.sort(stationIds);
HashMap<String, TypeMapDto> stationData = new HashMap<String, TypeMapDto>();
HashMap<String, TypeMapDto> vehicleData = new HashMap<String, TypeMapDto>();
for (String stationId : stationIds)
{
String[] vehicleIds = vehicleIdsByStationIds.get(stationId);
ListVehicleOccupancyByStationRequest occupancyByStationRequest = new ListVehicleOccupancyByStationRequest(begin_carsharing,
end,
stationId,
vehicleIds);
ListVehicleOccupancyByStationResponse responseOccupancy = apiClient.callWebService(occupancyByStationRequest,
ListVehicleOccupancyByStationResponse.class);
VehicleAndOccupancies[] occupancies = responseOccupancy.getVehicleAndOccupancies();
if (occupancies== null)
continue;
if (occupancies.length != vehicleIds.length) // Same number of responses as the number to requests
{
throw new IllegalStateException();
}
int free = 0;
for (VehicleAndOccupancies vehicleOccupancy : occupancies)
{
if (vehicleOccupancy.getOccupancy().length > 1)
{
throw new IllegalStateException("Why???");
}
int state = 0; // free
if (vehicleOccupancy.getOccupancy().length == 1)
{
state = 1;
}
else
{
free++;
}
TypeMapDto typeMap = new TypeMapDto();
vehicleData.put(vehicleOccupancy.getVehicle().getId(), typeMap);
String type = "unknown";
if (begin.equals(created))
type = DataTypeDto.AVAILABILITY;
else
type = DataTypeDto.FUTURE_AVAILABILITY;
Set<SimpleRecordDto> dtos = typeMap.getRecordsByType().get(type);
if (dtos == null){
dtos = new HashSet<SimpleRecordDto>();
typeMap.getRecordsByType().put(type, dtos);
}
dtos.add(new SimpleRecordDto(updateTime + forecast,state+0.,600));
}
Set<SimpleRecordDto> dtos = new HashSet<SimpleRecordDto>();
TypeMapDto typeMap = new TypeMapDto();
typeMap.getRecordsByType().put(DataTypeDto.NUMBER_AVAILABE, dtos);
if (begin.equals(created))
dtos.add(new SimpleRecordDto(updateTime + forecast, free+0.,600));
stationData.put(stationId, typeMap );
}
///////////////////////////////////////////////////////////////
// Write data to integreen
///////////////////////////////////////////////////////////////
Object result = xmlrpcPusher.pushData(CARSHARINGSTATION_DATASOURCE, new Object[]{stationData});
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "pushData(" + CARSHARINGSTATION_DATASOURCE + "): " + stationData.size()+ "\n";
}
result = xmlrpcPusher.pushData(CARSHARINGCAR_DATASOURCE, new Object[]{vehicleData});
if (result instanceof IntegreenException)
{
throw new IOException("IntegreenException");
}
synchronized (lock)
{
activityLog.report += "pushData(" + CARSHARINGCAR_DATASOURCE + "): " + vehicleData.size() + "\n";
}
}
}
}
| tis-innovation-park/carsharing-ds | src/main/java/it/bz/tis/integreen/carsharingbzit/ConnectorLogic.java | Java | agpl-3.0 | 14,481 |
/*
Copyright (C) 2014 Härnösands kommun
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Action for print using mapfish.
*/
Ext.define('OpenEMap.action.Print', {
extend : 'OpenEMap.action.Action',
require : 'GeoExt.plugins.PrintExtent',
constructor : function(config) {
var mapPanel = config.mapPanel;
var printExtent = mapPanel.plugins[0];
var printProvider = printExtent.printProvider;
printProvider.customParams = {attribution: config.mapPanel.config.attribution.trim(), mapTitle: ''};
var printDialog = null;
var page = null;
var onTransformComplete = function() {
var scale = printDialog.down('#scale');
scale.select(page.scale);
};
var onBeforedownload = function() {
if (printDialog) printDialog.setLoading(false);
};
var onPrintexception = function(printProvider, response) {
if (printDialog) printDialog.setLoading(false);
Ext.Msg.show({
title:'Felmeddelande',
msg: 'Print failed.\n\n' + response.responseText,
icon: Ext.Msg.ERROR
});
};
var close = function() {
printProvider.un('beforedownload', onBeforedownload);
printProvider.on('printexception', onPrintexception);
printExtent.control.events.unregister('transformcomplete', null, onTransformComplete);
printExtent.removePage(page);
printExtent.hide();
printDialog = null;
};
var onClose = function() {
close();
control.deactivate();
};
config.iconCls = config.iconCls || 'action-print';
config.tooltip = config.tooltip || 'Skriv ut';
config.toggleGroup = 'extraTools';
var Custom = OpenLayers.Class(OpenLayers.Control, {
initialize: function(options) {
OpenLayers.Control.prototype.initialize.apply(
this, arguments
);
},
type: OpenLayers.Control.TYPE_TOGGLE,
activate: function() {
if (printDialog) {
return;
}
// NOTE: doing a hide/show at first display fixes interaction problems with preview extent for unknown reasons
printExtent.hide();
printExtent.show();
page = printExtent.addPage();
printProvider.dpis.data.items.forEach(function(d){
var validDpi = false;
if (d.data.name === '72'){
validDpi = true;
d.data.name = 'Låg (' +d.data.name + ' dpi)';
}
else if (d.data.name === '150'){
validDpi = true;
d.data.name = 'Medel (' +d.data.name + ' dpi)';
}
else if (d.data.name === '300'){
validDpi = true;
d.data.name = 'Hög (' +d.data.name + ' dpi)';
}
});
printProvider.layouts.data.items.forEach(function(p){
if (/landscape$/.test(p.data.name)){
p.data.displayName = p.data.name.replace('landscape', 'liggande');
} else if (/portrait$/.test(p.data.name)){
p.data.displayName = p.data.name.replace('portrait', 'stående');
}
});
printDialog = new Ext.Window({
autoHeight : true,
width : 290,
resizable: false,
layout : 'fit',
bodyPadding : '5 5 0',
title: 'Utskriftsinställningar',
listeners: {
close: onClose
},
items : [ {
xtype : 'form',
layout : 'anchor',
defaults : {
anchor : '100%'
},
fieldDefaults : {
labelWidth : 120
},
items : [ {
xtype : 'textfield',
fieldLabel: 'Rubrik',
valueField: 'mapTitle',
itemId : 'mapTitle',
queryMode: 'local',
value: printProvider.customParams.mapTitle,
listeners: {
change: function(textfield){
printProvider.customParams.mapTitle = textfield.value;
}
}
},{
xtype : 'combo',
fieldLabel: 'Pappersformat',
store : printProvider.layouts,
displayField : 'displayName',
valueField : 'name',
itemId : 'printLayouts',
queryMode: 'local',
value : printProvider.layouts.getAt(0).get("name"),
listeners: {
select: function(combo, records, eOpts) {
var record = records[0];
printProvider.setLayout(record);
}
}
}, {
xtype : 'combo',
fieldLabel: 'Kvalité',
store : printProvider.dpis,
displayField : 'name',
valueField : 'value',
queryMode: 'local',
value: printProvider.dpis.first().get("value"),
listeners: {
select: function(combo, records, eOpts) {
var record = records[0];
printProvider.setDpi(record);
}
}
}, {
xtype : 'combo',
fieldLabel: 'Skala',
store : printProvider.scales,
displayField : 'name',
valueField : 'value',
queryMode: 'local',
itemId: 'scale',
value: printProvider.scales.first().get("value"),
listeners: {
select: function(combo, records, eOpts) {
var record = records[0];
page.setScale(record, "m");
}
}
} ]
} ],
bbar : [ '->', {
text : "Skriv ut",
handler : function() {
printDialog.setLoading(true);
printExtent.print();
}
} ]
});
printDialog.show();
var scale = printDialog.down('#scale');
scale.select(page.scale);
var layoutId = 6;
var printLayouts = printDialog.down('#printLayouts');
printLayouts.select(printLayouts.store.data.get(layoutId));
var currentPrintLayout = printLayouts.store.data.items[layoutId];
printProvider.setLayout(currentPrintLayout);
printExtent.control.events.register('transformcomplete', null, onTransformComplete);
printExtent.control.events.register('transformcomplete', null, onTransformComplete);
printProvider.on('beforedownload', onBeforedownload);
printProvider.on('printexception', onPrintexception);
OpenLayers.Control.prototype.activate.apply(this, arguments);
},
deactivate: function() {
if (printDialog) printDialog.close();
OpenLayers.Control.prototype.deactivate.apply(this, arguments);
}
});
var control = new Custom({
type: OpenLayers.Control.TYPE_TOGGLE
});
config.control = control;
this.callParent(arguments);
}
});
| Sundsvallskommun/OpenEMap-WebUserInterface | src/main/javascript/action/Print.js | JavaScript | agpl-3.0 | 9,608 |
/* @flow */
import oEmbedStorage from './oEmbedStorage';
import getContentType from './getContentType';
import regexes from './regexes';
import providers from './providers';
import type { Embed } from './oEmbedTypes';
function getProperty(prop: string, type: ?string): RegExp {
if (typeof type === 'string') {
return new RegExp("<meta[^>]*property[ ]*=[ ]*['|\"]og:" + type + ':' + prop + "['|\"][^>]*[>]", 'i');
}
return new RegExp("<meta[^>]*property[ ]*=[ ]*['|\"]og:" + prop + "['|\"][^>]*[>]", 'i');
}
function getContent(regex) {
return regex[0].match(regexes.content)[0].match(/['|"].*/)[0].slice(1);
}
function decodeText(text) {
return text
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/ /g, ' ')
.replace(/&#(x?)(\d+);/g, (m, p1, p2) => String.fromCharCode(((p1 === 'x') ? parseInt(p2, 16) : p2)));
}
function parseHTML(body): ?Embed {
const data: Embed = {
type: 'link',
};
const props = [ 'title', 'description' ];
for (let i = 0; i < props.length; i++) {
const match = body.match(getProperty(props[i]));
if (match && match.length) {
data[props[i]] = decodeText(getContent(match));
}
}
const propsWithType = [ 'width', 'height' ];
for (let i = 0; i < propsWithType.length; i++) {
const types = [ 'video', 'image' ];
for (let j = 0; j < types.length; j++) {
const match = body.match(getProperty(propsWithType[i], types[j]));
if (match && match.length) {
data['thumbnail_' + propsWithType[i]] = parseInt(getContent(match), 10);
}
}
}
const imageUrl = body.match(regexes.image);
if (imageUrl) {
data.thumbnail_url = getContent(imageUrl);
}
if (!data.title) {
const matches = body.match(regexes.title);
if (matches && matches.length) {
const title = matches[0].match(/[>][^<]*/);
if (title && title.length) {
data.title = decodeText(title[0].slice(1));
}
}
}
if (!data.description) {
const matches = body.match(regexes.description);
if (matches && matches.length) {
const description = matches[0].match(regexes.content)[0].match(/['|"][^'|^"]*/);
if (description && description.length) {
data.description = decodeText(description[0].slice(1));
}
}
}
if (Object.keys(data).length > 1) {
return data;
}
return null;
}
function extractLink(body) {
const res = body.match(regexes.link);
if (res && res.length) {
return res[0].match(/http[s]?:\/\/[^"']*/i)[0].replace(/&/g, '&');
}
return null;
}
async function fetchData(url: string): Promise<Embed> {
const body = await fetch(url).then(res => res.text()).then(text => text.replace(/(\r\n|\n|\r)/g, ''));
const dataUrl = extractLink(body);
let data;
if (dataUrl) {
data = await (await fetch(dataUrl)).json();
} else {
data = parseHTML(body);
}
if (data) {
oEmbedStorage.set(url, data);
return data;
} else {
throw new Error('Failed to get data from HTML');
}
}
export default async function(url: string): Promise<Embed> {
if (typeof url !== 'string') {
throw new TypeError('URL must be a string');
}
if (!/^https?:\/\//i.test(url)) {
throw new Error("URL must start with 'http://' or 'https://'");
}
const json = await oEmbedStorage.get(url);
if (json) {
return json;
}
let endpoint;
for (let i = 0, l = providers.length; i < l; i++) {
const provider = providers[i];
if (provider[0].test(url)) {
endpoint = provider[1] + '?format=json&maxheight=240&url=' + encodeURIComponent(url);
}
}
if (endpoint) {
const data = await fetch(endpoint).then(res => res.json());
oEmbedStorage.set(url, data);
return data;
}
const contentType = await getContentType(url);
if (contentType) {
if (contentType.indexOf('image') > -1) {
return {
type: 'link',
thumbnail_url: url,
};
} else if (contentType.indexOf('text/html') > -1) {
return fetchData(url);
}
}
throw new Error('No oEmbed data found for ' + url);
}
| Anup-Allamsetty/pure | src/modules/oembed/oEmbed.js | JavaScript | agpl-3.0 | 3,946 |
# This file is part of authapi.
# Copyright (C) 2014-2020 Agora Voting SL <contact@nvotes.com>
# authapi is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License.
# authapi is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
# You should have received a copy of the GNU Affero General Public License
# along with authapi. If not, see <http://www.gnu.org/licenses/>.
from django.conf.urls import url
from .decorators import captcha_required
from captcha import views
urlpatterns = [
url(r'^new/', views.new_captcha, name='new_captcha'),
]
| agoravoting/authapi | authapi/captcha/urls.py | Python | agpl-3.0 | 874 |
/*
* Copyright (C) 2005 Luca Veltri - University of Parma - Italy
*
* This file is part of MjSip (http://www.mjsip.org)
*
* MjSip is free software; you can redistribute it and/or modify
* it under the terms of the Affero GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MjSip 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
* Affero GNU General Public License for more details.
*
* You should have received a copy of the Affero GNU General Public License
* along with MjSip; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author(s):
* Luca Veltri (luca.veltri@unipr.it)
*/
package org.zoolu.sip.provider;
import org.zoolu.sip.message.Message;
/** A SipInterfaceListener listens for SipInterface onReceivedMessage(SipInterfaceListener,Message) events.
*/
public interface SipInterfaceListener
{
/** When a new Message is received by the SipInterface. */
public void onReceivedMessage(SipInterface sip, Message message);
}
| ging/isabel | components/gateway/GWSIP/mjsip_1.6/src/org/zoolu/sip/provider/SipInterfaceListener.java | Java | agpl-3.0 | 1,263 |
package net.wayward_realms.waywardchat.irc;
import net.wayward_realms.waywardchat.WaywardChat;
import org.pircbotx.Channel;
import org.pircbotx.PircBotX;
import org.pircbotx.User;
import org.pircbotx.hooks.ListenerAdapter;
import org.pircbotx.hooks.events.MessageEvent;
public class IrcMessageListener extends ListenerAdapter<PircBotX> {
private WaywardChat plugin;
public IrcMessageListener(WaywardChat plugin) {
this.plugin = plugin;
}
@Override
public void onMessage(MessageEvent<PircBotX> event) {
final User user = event.getUser();
final Channel channel = event.getChannel();
final String message = event.getMessage();
if (user != plugin.getIrcBot().getUserBot()) {
if (!message.startsWith("!")) {
plugin.handleChat(user, channel, message);
}
}
}
}
| WaywardRealms/Wayward | WaywardChat/src/main/java/net/wayward_realms/waywardchat/irc/IrcMessageListener.java | Java | agpl-3.0 | 872 |
# © 2008-2020 Dorin Hongu <dhongu(@)gmail(.)com
# See README.rst file on addons root folder for license details
{
"name": "Romania - Invoice Report ",
"summary": "Localizare Terrabit",
"version": "14.0.3.0.3",
"author": "Dorin Hongu," "Odoo Community Association (OCA)",
"website": "https://github.com/OCA/l10n-romania",
"license": "AGPL-3",
"category": "Generic Modules",
"depends": [
"base",
"account",
"l10n_ro_config",
"purchase",
# "deltatech_watermark"
],
"data": [
"views/invoice_report.xml",
"views/voucher_report.xml",
"views/payment_report.xml",
# 'views/account_invoice_view.xml',
"views/account_voucher_report.xml",
"views/account_bank_statement_view.xml",
"views/statement_report.xml",
# 'views/res_partner_view.xml',
],
}
| dhongu/l10n-romania | l10n_ro_invoice_report/__manifest__.py | Python | agpl-3.0 | 887 |
(function (factory) {
if (typeof define === 'function') {
if(define.amd) {
define(['common/metastore', 'jslet', 'mock/employee-mock'], factory);
} else {
define(function(require, exports, module) {
module.exports = factory();
});
}
} else {
factory();
}
})(function () {
/********************************** 定义数据集 ************************************************/
//datasetMetaStore定义在公共js:common/datasetmetastore.js中
//将数据集定义信息仓库加到datasetFactory中,创建Dataset时会仓库里去定义信息
jslet.data.datasetFactory.addMetaStore(window.datasetMetaStore);
//通过工厂方法,可以自动创建主数据集及相关的数据集
jslet.data.datasetFactory.createDataset('employee').done(function() {
jslet.ui.install(function() {
var dsEmployee = jslet.data.getDataset('employee');
dsEmployee.query();
});
});
//绑定按钮事件
$('#chkShowSeqenceCol').click(function() {
var checked = $('#chkShowSeqenceCol')[0].checked;
//设置表格是否有序号列
jslet('#tblEmployee').hasSeqCol(checked).renderAll();
});
$('#chkShowSelectCol').click(function() {
var checked = $('#chkShowSelectCol')[0].checked;
//设置表格是否有选择列
jslet('#tblEmployee').hasSelectCol(checked).renderAll();
});
$('#btnFixedRows').click(function() {
var count = parseInt($('#txtFixedRows').val());
//设置表格固定行数
jslet('#tblEmployee').fixedRows(count).renderAll();
});
$('#btnFixedCols').click(function() {
var count = parseInt($('#txtFixedCols').val());
//设置表格固定列数
jslet('#tblEmployee').fixedCols(count).renderAll();
});
$('#btnSetRowClick').click(function() {
var dsEmployee = jslet.data.getDataset('employee');
//设置表格单击事件
jslet('#tblEmployee').onRowClick(function() {
jslet.ui.info('你点击了第:' + (dsEmployee.recno() + 1) + ' 行!', null, null, 1000);
});
});
$('#btnClearRowClick').click(function() {
//清除表格单击事件
jslet('#tblEmployee').onRowClick(null);
});
$('#btnSetRowDblClick').click(function() {
var dsEmployee = jslet.data.getDataset('employee');
//设置表格双击事件
jslet('#tblEmployee').onRowClick(null); //先清除单击事件
jslet('#tblEmployee').onRowDblClick(function() {
jslet.ui.info('你双击了第:' + (dsEmployee.recno() + 1) + ' 行!', null, null, 1000);
});
});
$('#btnClearRowDblClick').click(function() {
//清除表格双击事件
jslet('#tblEmployee').onRowDblClick(null);
});
$('#btnSetSelect').click(function() {
var dsEmployee = jslet.data.getDataset('employee');
//设置表格选择事件,
jslet('#tblEmployee').onSelect(function() {
jslet.ui.info('你选择了第:' + (dsEmployee.recno() + 1) + ' 行!', null, null, 1000);
});
});
$('#btnClearSelect').click(function() {
//清除表格选择
jslet('#tblEmployee').onSelect(null);
});
$('#btnSelectBy').click(function() {
var dsEmployee = jslet.data.getDataset('employee');
var selectBy = $('#txtSelectBy').val();
//设置表格分组选择(相同值一起选择)
jslet('#tblEmployee').selectBy(selectBy);
});
});
| jslet/jslet | democn/dbcontrol/table/basic.js | JavaScript | agpl-3.0 | 3,253 |
using System;
using Terraria.Localization;
namespace HamstarHelpers.Services.Network.Scraper {
/// <summary>
/// Represents scraped data for the settings of a sent network packet. The actual payload of the generated
/// packet is internal to `NetMessage.SendData(...)` (for now).
/// </summary>
public class ScrapedSentData {
/// <summary></summary>
public int WhoAmI;
/// <summary></summary>
public int MsgType;
/// <summary></summary>
public int RemoteClient;
/// <summary></summary>
public int IgnoreClient;
/// <summary></summary>
public NetworkText Text;
/// <summary></summary>
public int Number;
/// <summary></summary>
public float Number2;
/// <summary></summary>
public float Number3;
/// <summary></summary>
public float Number4;
/// <summary></summary>
public int Number5;
/// <summary></summary>
public int Number6;
/// <summary></summary>
public int Number7;
////////////////
/// <summary></summary>
/// <param name="whoAmI"></param>
/// <param name="msgType"></param>
/// <param name="remoteClient"></param>
/// <param name="ignoreClient"></param>
/// <param name="text"></param>
/// <param name="number"></param>
/// <param name="number2"></param>
/// <param name="number3"></param>
/// <param name="number4"></param>
/// <param name="number5"></param>
/// <param name="number6"></param>
/// <param name="number7"></param>
internal ScrapedSentData(
int whoAmI,
int msgType,
int remoteClient,
int ignoreClient,
NetworkText text,
int number,
float number2,
float number3,
float number4,
int number5,
int number6,
int number7 ) {
this.WhoAmI = whoAmI;
this.MsgType = msgType;
this.RemoteClient = remoteClient;
this.IgnoreClient = ignoreClient;
this.Text = text;
this.Number = number;
this.Number2 = number2;
this.Number3 = number3;
this.Number4 = number4;
this.Number5 = number5;
this.Number6 = number6;
this.Number7 = number7;
}
}
}
| hamstar0/tml-hamstarhelpers-mod | HamstarHelpers/Services/Network/Scraper/ScrapedSentData.cs | C# | agpl-3.0 | 2,038 |
module GoogleClient
extend ActiveSupport::Concern
def google_refresh_token
if auth = self.authentications.find_by_provider('google_oauth2')
auth.refresh_token
else
nil
end
end
end
| atomicjolt/demo_arigato | app/models/concerns/google_client.rb | Ruby | agpl-3.0 | 212 |
#
# Author:: Johannes Krude
# Copyright:: (c) Johannes Krude 2009
# License:: AGPL3
#
#--
# This file is part of filehosting.
#
# filehosting is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# filehosting is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with filehosting. If not, see <http://www.gnu.org/licenses/>.
#++
#
require "filehosting/datasource"
require "filehosting/samplefileinfo"
module FileHosting
# Sample DataSource generates Sample FileInfo's
class SampleDataSource < DataSource
def search_tags(tags, rule= nil)
(1..rand(6)).collect { |x| SampleFileInfo.new }
end
def fileinfo(uuid)
res= SampleFileInfo.new
res.uuid= uuid
res
end
end
end
| johannesk/filehosting | lib/filehosting/sampledatasource.rb | Ruby | agpl-3.0 | 1,149 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2019 Asqatasun.org
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.rules.rgaa30;
import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation;
/**
* Implementation of the rule 12.4.1 of the referential Rgaa 3.0.
*
* For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.0/12.Navigation/Rule-12-4-1.html">the rule 12.4.1 design page.</a>
* @see <a href="http://references.modernisation.gouv.fr/referentiel-technique-0#test-12-4-1"> 12.4.1 rule specification</a>
*/
public class Rgaa30Rule120401 extends AbstractNotTestedRuleImplementation {
/**
* Default constructor
*/
public Rgaa30Rule120401 () {
super();
}
}
| dzc34/Asqatasun | rules/rules-rgaa3.0/src/main/java/org/asqatasun/rules/rgaa30/Rgaa30Rule120401.java | Java | agpl-3.0 | 1,491 |
<?php
namespace App\Models;
use App\Models\Requestable;
use App\Models\SnipeModel;
use App\Presenters\Presentable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Watson\Validating\ValidatingTrait;
/**
* Model for Asset Models. Asset Models contain higher level
* attributes that are common among the same type of asset.
*
* @version v1.0
*/
class AssetModel extends SnipeModel
{
use SoftDeletes;
protected $presenter = 'App\Presenters\AssetModelPresenter';
use Requestable, Presentable;
protected $dates = ['deleted_at'];
protected $table = 'models';
protected $hidden = ['user_id','deleted_at'];
// Declare the rules for the model validation
protected $rules = array(
'name' => 'required|min:1|max:255',
'model_number' => 'max:255|nullable',
'category_id' => 'required|integer|exists:categories,id',
'manufacturer_id' => 'required|integer|exists:manufacturers,id',
'eol' => 'integer:min:0|max:240|nullable',
);
/**
* Whether the model should inject it's identifier to the unique
* validation rules before attempting validation. If this property
* is not set in the model it will default to true.
*
* @var boolean
*/
protected $injectUniqueIdentifier = true;
use ValidatingTrait;
public function setEolAttribute($value)
{
if ($value == '') {
$value = 0;
}
$this->attributes['eol'] = $value;
}
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'category_id',
'depreciation_id',
'eol',
'fieldset_id',
'image',
'manufacturer_id',
'model_number',
'name',
'notes',
'user_id',
];
public function assets()
{
return $this->hasMany('\App\Models\Asset', 'model_id');
}
public function category()
{
return $this->belongsTo('\App\Models\Category', 'category_id');
}
public function depreciation()
{
return $this->belongsTo('\App\Models\Depreciation', 'depreciation_id');
}
public function adminuser()
{
return $this->belongsTo('\App\Models\User', 'user_id');
}
public function manufacturer()
{
return $this->belongsTo('\App\Models\Manufacturer', 'manufacturer_id');
}
public function fieldset()
{
return $this->belongsTo('\App\Models\CustomFieldset', 'fieldset_id');
}
/**
* -----------------------------------------------
* BEGIN QUERY SCOPES
* -----------------------------------------------
**/
/**
* Query builder scope for Deleted assets
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeDeleted($query)
{
return $query->whereNotNull('deleted_at');
}
/**
* scopeInCategory
* Get all models that are in the array of category ids
*
* @param $query
* @param array $categoryIdListing
*
* @return mixed
* @author Vincent Sposato <vincent.sposato@gmail.com>
* @version v1.0
*/
public function scopeInCategory($query, array $categoryIdListing)
{
return $query->whereIn('category_id', $categoryIdListing);
}
/**
* scopeRequestable
* Get all models that are requestable by a user.
*
* @param $query
*
* @return $query
* @author Daniel Meltzer <parallelgrapefruit@gmail.com
* @version v3.5
*/
public function scopeRequestableModels($query)
{
return $query->where('requestable', '1');
}
/**
* Query builder scope to search on text
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeTextSearch($query, $search)
{
return $query->where('models.name', 'LIKE', "%$search%")
->orWhere('model_number', 'LIKE', "%$search%")
->orWhere(function ($query) use ($search) {
$query->whereHas('depreciation', function ($query) use ($search) {
$query->where('depreciations.name', 'LIKE', '%'.$search.'%');
});
})
->orWhere(function ($query) use ($search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where('categories.name', 'LIKE', '%'.$search.'%');
});
})
->orWhere(function ($query) use ($search) {
$query->whereHas('manufacturer', function ($query) use ($search) {
$query->where('manufacturers.name', 'LIKE', '%'.$search.'%');
});
});
}
/**
* Query builder scope to search on text, including catgeory and manufacturer name
*
* @param Illuminate\Database\Query\Builder $query Query builder instance
* @param text $search Search term
*
* @return Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeSearchByManufacturerOrCat($query, $search)
{
return $query->where('models.name', 'LIKE', "%$search%")
->orWhere('model_number', 'LIKE', "%$search%")
->orWhere(function ($query) use ($search) {
$query->whereHas('category', function ($query) use ($search) {
$query->where('categories.name', 'LIKE', '%'.$search.'%');
});
})
->orWhere(function ($query) use ($search) {
$query->whereHas('manufacturer', function ($query) use ($search) {
$query->where('manufacturers.name', 'LIKE', '%'.$search.'%');
});
});
}
/**
* Query builder scope to order on manufacturer
*
* @param \Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return \Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderManufacturer($query, $order)
{
return $query->leftJoin('manufacturers', 'models.manufacturer_id', '=', 'manufacturers.id')->orderBy('manufacturers.name', $order);
}
/**
* Query builder scope to order on category name
*
* @param \Illuminate\Database\Query\Builder $query Query builder instance
* @param text $order Order
*
* @return \Illuminate\Database\Query\Builder Modified query builder
*/
public function scopeOrderCategory($query, $order)
{
return $query->leftJoin('categories', 'models.category_id', '=', 'categories.id')->orderBy('categories.name', $order);
}
}
| bytepark/snipe-it | app/Models/AssetModel.php | PHP | agpl-3.0 | 7,207 |
##############################################################################
#
# Copyright (C) 2014 Comunitea Servicios Tecnológicos All Rights Reserved
# $Kiko Sánchez <kiko@comunitea.com>$
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from odoo import fields, models, api
from datetime import datetime
class OutletLoss(models.Model):
_name = 'outlet.loss'
@api.multi
@api.depends('qty', 'price_outlet', 'price_unit')
def _get_outlet_loss(self):
for loss in self:
loss.total_lost = loss.qty*(loss.price_outlet-loss.price_unit)
product_id = fields.Many2one('product.product', 'Product')
price_unit = fields.Float('Price')
price_outlet = fields.Float('Outlet Price')
total_lost = fields.Float("Outlet Loss", compute=_get_outlet_loss,
store=True, readonly=True)
date_move = fields.Date('Move to outlet on', default=fields.datetime.now())
outlet_ok = fields.Boolean('Outlet')
order_line_id = fields.Many2one('sale.order.line', 'Order Line')
qty = fields.Float('Quantity')
percent = fields.Float('Outlet Percent')
| Comunitea/CMNT_004_15 | project-addons/product_outlet_loss/models/product.py | Python | agpl-3.0 | 1,853 |
<?php
/**
* @package api
* @subpackage objects
*/
class KalturaReportExportFile extends KalturaObject
{
/**
* @var string
*/
public $fileId;
/**
* @var string
*/
public $fileName;
private static $map_between_objects = array
(
"fileId",
"fileName",
);
public function getMapBetweenObjects()
{
return array_merge(parent::getMapBetweenObjects(), self::$map_between_objects);
}
public function toObject($object_to_fill = null, $props_to_skip = array())
{
if (!$object_to_fill)
{
$object_to_fill = new kReportExportFile();
}
return parent::toObject($object_to_fill, $props_to_skip);
}
}
| kaltura/server | api_v3/lib/types/report/export/KalturaReportExportFile.php | PHP | agpl-3.0 | 628 |
// Copyright (c) 2017 Uber Technologies, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
export const FALLBACK_DAG_MAX_NUM_SERVICES = 100 as 100;
export const FALLBACK_TRACE_NAME = '<trace-without-root-span>' as '<trace-without-root-span>';
export const FETCH_DONE = 'FETCH_DONE' as 'FETCH_DONE';
export const FETCH_ERROR = 'FETCH_ERROR' as 'FETCH_ERROR';
export const FETCH_LOADING = 'FETCH_LOADING' as 'FETCH_LOADING';
export const fetchedState = {
DONE: FETCH_DONE,
ERROR: FETCH_ERROR,
LOADING: FETCH_LOADING,
};
| grafana/grafana | packages/jaeger-ui-components/src/constants/index.tsx | TypeScript | agpl-3.0 | 1,036 |
<?php
/**
*
* Manages the batch mechanism
*
* @package Core
* @subpackage Batch
*/
class kBatchManager
{
/**
* batch createFlavorAsset orgenize a convert job data
*
* @param flavorParamsOutputWrap $flavor
* @param int $partnerId
* @param int $entryId
* @param string $flavorAssetId
* @return flavorAsset
*/
public static function createFlavorAsset(flavorParamsOutputWrap $flavor, $partnerId, $entryId, $flavorAssetId = null)
{
$description = kBusinessConvertDL::parseFlavorDescription($flavor);
$flavorAsset = null;
if($flavorAssetId)
$flavorAsset = flavorAssetPeer::retrieveById($flavorAssetId);
if(!$flavorAsset)
$flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entryId, $flavor->getFlavorParamsId());
if($flavorAsset)
{
$description = $flavorAsset->getDescription() . "\n" . $description;
$flavorAsset->setDescription($description);
$flavorAsset->incrementVersion();
}
else
{
// creates the flavor asset
$flavorAsset = new flavorAsset();
$flavorAsset->setPartnerId($partnerId);
$flavorAsset->setEntryId($entryId);
$flavorAsset->setDescription($description);
}
$flavorAsset->setTags($flavor->getTags());
$flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_QUEUED);
$flavorAsset->setFlavorParamsId($flavor->getFlavorParamsId());
$flavorAsset->setFileExt($flavor->getFileExt());
// decided by the business logic layer
if($flavor->_create_anyway)
{
KalturaLog::log("Flavor [" . $flavor->getFlavorParamsId() . "] selected to be created anyway");
}
else
{
if(!$flavor->IsValid())
{
KalturaLog::log("Flavor [" . $flavor->getFlavorParamsId() . "] is invalid");
$flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
$flavorAsset->save();
return null;
}
if($flavor->_force)
{
KalturaLog::log("Flavor [" . $flavor->getFlavorParamsId() . "] is forced");
}
else
{
if($flavor->_isNonComply)
{
KalturaLog::log("Flavor [" . $flavor->getFlavorParamsId() . "] is none-comply");
$flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_NOT_APPLICABLE);
$flavorAsset->save();
return null;
}
KalturaLog::log("Flavor [" . $flavor->getFlavorParamsId() . "] is valid");
}
}
$flavorAsset->save();
// save flavor params
$flavor->setPartnerId($partnerId);
$flavor->setEntryId($entryId);
$flavor->setFlavorAssetId($flavorAsset->getId());
$flavor->setFlavorAssetVersion($flavorAsset->getVersion());
$flavor->save();
return $flavorAsset;
}
/**
* batch createFlavorAsset orgenize a convert job data
*
* @param flavorParamsOutputWrap $flavor
* @param int $partnerId
* @param int $entryId
* @param string $description
* @return flavorAsset
*/
public static function createErrorFlavorAsset(flavorParamsOutputWrap $flavor, $partnerId, $entryId, $description)
{
$flavorAsset = flavorAssetPeer::retrieveByEntryIdAndFlavorParams($entryId, $flavor->getFlavorParamsId());
if($flavorAsset)
{
$description = $flavorAsset->getDescription() . "\n" . $description;
$flavorAsset->setDescription($description);
$flavorAsset->incrementVersion();
}
else
{
// creates the flavor asset
$flavorAsset = new flavorAsset();
$flavorAsset->setPartnerId($partnerId);
$flavorAsset->setEntryId($entryId);
$flavorAsset->setDescription($description);
}
$flavorAsset->setTags($flavor->getTags());
$flavorAsset->setStatus(flavorAsset::FLAVOR_ASSET_STATUS_ERROR);
$flavorAsset->setFlavorParamsId($flavor->getFlavorParamsId());
$flavorAsset->setFileExt($flavor->getFileExt());
$flavorAsset->save();
// save flavor params
$flavor->setPartnerId($partnerId);
$flavor->setEntryId($entryId);
$flavor->setFlavorAssetId($flavorAsset->getId());
$flavor->setFlavorAssetVersion($flavorAsset->getVersion());
$flavor->save();
return $flavorAsset;
}
/**
* batch addMediaInfo adds a media info and updates the flavor asset
*
* @param mediaInfo $mediaInfoDb
* @return mediaInfo
*/
public static function addMediaInfo(mediaInfo $mediaInfoDb)
{
$mediaInfoDb->save();
KalturaLog::log("Added media info [" . $mediaInfoDb->getId() . "] for flavor asset [" . $mediaInfoDb->getFlavorAssetId() . "]");
if(!$mediaInfoDb->getFlavorAssetId())
return $mediaInfoDb;
$flavorAsset = flavorAssetPeer::retrieveById($mediaInfoDb->getFlavorAssetId());
if(!$flavorAsset)
return $mediaInfoDb;
if($flavorAsset->getIsOriginal())
{
KalturaLog::log("Media info is for the original flavor asset");
$tags = null;
$profile = myPartnerUtils::getConversionProfile2ForEntry($flavorAsset->getEntryId());
if($profile)
$tags = $profile->getInputTagsMap();
KalturaLog::log("Flavor asset tags from profile [$tags]");
if(!is_null($tags))
{
$tagsArray = explode(',', $tags);
// support for old migrated profiles
if($profile->getCreationMode() == conversionProfile2::CONVERSION_PROFILE_2_CREATION_MODE_AUTOMATIC_BYPASS_FLV)
{
if(!KDLWrap::CDLIsFLV($mediaInfoDb))
{
$key = array_search(flavorParams::TAG_MBR, $tagsArray);
unset($tagsArray[$key]);
}
}
$finalTagsArray = KDLWrap::CDLMediaInfo2Tags($mediaInfoDb, $tagsArray);
$finalTags = join(',', $finalTagsArray);
KalturaLog::log("Flavor asset tags from KDL [$finalTags]");
$flavorAsset->setTags($finalTags);
}
}
KalturaLog::log("KDLWrap::ConvertMediainfoCdl2FlavorAsset(" . $mediaInfoDb->getId() . ", " . $flavorAsset->getId() . ");");
KDLWrap::ConvertMediainfoCdl2FlavorAsset($mediaInfoDb, $flavorAsset);
$flavorAsset->save();
// if(!$flavorAsset->hasTag(flavorParams::TAG_MBR))
// return $mediaInfoDb;
$entry = entryPeer::retrieveByPK($flavorAsset->getEntryId());
if(!$entry)
return $mediaInfoDb;
$entry->setDimensions($mediaInfoDb->getVideoWidth(), $mediaInfoDb->getVideoHeight());
$entry->setLengthInMsecs($mediaInfoDb->getContainerDuration());
$entry->save();
return $mediaInfoDb;
}
// common to all the jobs using the BatchJob table
public static function freeExclusiveBatchJob($id, kExclusiveLockKey $lockKey, $resetExecutionAttempts = false)
{
return kBatchExclusiveLock::freeExclusive($id, $lockKey, $resetExecutionAttempts);
}
public static function getQueueSize($schedulerId, $workerId, $jobType, $filter)
{
$priority = self::getNextJobPriority($jobType);
$c = new Criteria();
$filter->attachToCriteria($c);
return kBatchExclusiveLock::getQueueSize($c, $schedulerId, $workerId, $priority, $jobType);
// // gets queues length
// $c = new Criteria();
// $filter->attachToCriteria($c);
//
// $crit = $c->getNewCriterion(BatchJobPeer::CHECK_AGAIN_TIMEOUT, time(), Criteria::LESS_THAN);
// $crit->addOr($c->getNewCriterion(BatchJobPeer::CHECK_AGAIN_TIMEOUT, null, Criteria::ISNULL));
// $c->addAnd($crit);
//
// $queueSize = BatchJobPeer::doCount($c, false, myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2));
//
// // gets queues length
// $c = new Criteria();
// $c->add(BatchJobPeer::SCHEDULER_ID, $schedulerId);
// $c->add(BatchJobPeer::WORKER_ID, $workerId);
// $c->add(BatchJobPeer::PROCESSOR_EXPIRATION, time(), Criteria::LESS_THAN);
// $c->add(BatchJobPeer::EXECUTION_ATTEMPTS, BatchJobPeer::getMaxExecutionAttempts($jobType), Criteria::LESS_THAN);
// $c->add(BatchJobPeer::JOB_TYPE, $jobType);
// $queueSize += BatchJobPeer::doCount($c, false, myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2));
//
// return $queueSize;
}
public static function cleanExclusiveJobs()
{
$jobs = kBatchExclusiveLock::getExpiredJobs();
foreach($jobs as $job)
{
KalturaLog::log("Cleaning job id[" . $job->getId() . "]");
kJobsManager::updateBatchJob($job, BatchJob::BATCHJOB_STATUS_FATAL);
}
$c = new Criteria();
$c->add(BatchJobPeer::STATUS, BatchJobPeer::getClosedStatusList(), Criteria::IN);
$c->add(BatchJobPeer::BATCH_INDEX, null, Criteria::ISNOTNULL);
// MUST be the master DB
$jobs = BatchJobPeer::doSelect($c, myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2));
foreach($jobs as $job)
{
KalturaLog::log("Cleaning job id[" . $job->getId() . "]");
$job->setSchedulerId(null);
$job->setWorkerId(null);
$job->setBatchIndex(null);
$job->setProcessorExpiration(null);
$job->save();
}
return count($jobs);
}
// common to all the jobs using the BatchJob table
public static function updateExclusiveBatchJob($id, kExclusiveLockKey $lockKey, BatchJob $dbBatchJob, $entryStatus = null)
{
$dbBatchJob = kBatchExclusiveLock::updateExclusive($id, $lockKey, $dbBatchJob);
$event = new kBatchJobStatusEvent($dbBatchJob, $entryStatus);
kEventsManager::raiseEvent($event);
return $dbBatchJob;
}
public static function getExclusiveAlmostDoneJobs(kExclusiveLockKey $lockKey, $maxExecutionTime, $numberOfJobs, $jobType, BatchJobFilter $filter)
{
$priority = self::getNextJobPriority($jobType);
$c = new Criteria();
$filter->attachToCriteria($c);
return kBatchExclusiveLock::getExclusiveAlmostDoneJobs($c, $lockKey, $maxExecutionTime, $numberOfJobs, $priority, $jobType);
}
/*
* Find what is the priority that should be used for next task
*/
public static function getNextJobPriority($jobType)
{
//$priorities = array(1 => 33, 2 => 27, 3 => 20, 4 => 13, 5 => 7);
$priorities = kConf::get('priority_percent');
$createdAt = time() - kConf::get('priority_time_range');
// $createdAt = kConf::get('priority_time_range');
$c = new Criteria();
$c->add(BatchJobPeer::CREATED_AT, $createdAt, Criteria::GREATER_THAN);
$c->add(BatchJobPeer::JOB_TYPE, $jobType);
$c->add(BatchJobPeer::STATUS, BatchJob::BATCHJOB_STATUS_PENDING);
$c->clearSelectColumns();
$c->addSelectColumn('MAX(' . BatchJobPeer::PRIORITY . ')');
$stmt = BatchJobPeer::doSelectStmt($c, myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2));
$maxPriority = $stmt->fetchColumn();
// gets the current queues
$c = new Criteria();
$c->add(BatchJobPeer::CREATED_AT, $createdAt, Criteria::GREATER_THAN);
$c->add(BatchJobPeer::JOB_TYPE, $jobType);
$c->add(BatchJobPeer::STATUS, BatchJob::BATCHJOB_STATUS_PENDING, Criteria::GREATER_THAN);
$c->addGroupByColumn(BatchJobPeer::PRIORITY);
// To prevent stress on the master DB - use the slave for checking the queue sizes
$queues = BatchJobPeer::doCountGroupBy($c, myDbHelper::getConnection(myDbHelper::DB_HELPER_CONN_PROPEL2));
// copy the queues and calcs the total
$total = 0;
$queues_size = array();
foreach($queues as $queue)
{
$queues_size[$queue['PRIORITY']] = $queue[BatchJobPeer::COUNT];
$total += $queue[BatchJobPeer::COUNT];
}
// go over the priorities and see if its percent not used
foreach($priorities as $priority => $top_percent)
{
if($priority > $maxPriority)
continue;
if(! isset($queues_size[$priority]))
return $priority;
$percent = $queues_size[$priority] / ($total / 100);
if($percent < $top_percent)
return $priority;
}
return 1;
}
public static function updateEntry(BatchJob $dbBatchJob, $status)
{
$entry = $dbBatchJob->getEntry();
if(!$entry)
return null;
// entry status didn't change - no need to send notification
if($entry->getStatus() == $status)
return $entry;
// backward compatibility
// if entry has kshow, and this is the first entry in the mix,
// the thumbnail of the entry should be copied into the mix entry
if ($status == entry::ENTRY_STATUS_READY)
myEntryUtils::createRoughcutThumbnailFromEntry($entry, false);
// entry status is ready and above, not changing status through batch job
if($entry->getStatus() >= entry::ENTRY_STATUS_READY)
return $entry;
$entry->setStatus($status);
$entry->save();
kFlowHelper::createEntryUpdateNotification($dbBatchJob);
return $entry;
}
} | MimocomMedia/kaltura | package/app/app/alpha/apps/kaltura/lib/batch2/kBatchManager.php | PHP | agpl-3.0 | 12,374 |
/**
* @license Copyright (c) 2003-2020, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'a11yhelp', 'gu', {
title: 'એક્ક્ષેબિલિટી ની વિગતો',
contents: 'હેલ્પ. આ બંધ કરવા ESC દબાવો.',
legend: [
{
name: 'જનરલ',
items: [
{
name: 'એડિટર ટૂલબાર',
legend: 'Press ${toolbarFocus} to navigate to the toolbar. Move to the next and previous toolbar group with TAB and SHIFT+TAB. Move to the next and previous toolbar button with RIGHT ARROW or LEFT ARROW. Press SPACE or ENTER to activate the toolbar button.' // MISSING
},
{
name: 'એડિટર ડાયલોગ',
legend:
'Inside a dialog, press TAB to navigate to the next dialog element, press SHIFT+TAB to move to the previous dialog element, press ENTER to submit the dialog, press ESC to cancel the dialog. When a dialog has multiple tabs, the tab list can be reached either with ALT+F10 or with TAB as part of the dialog tabbing order. With tab list focused, move to the next and previous tab with RIGHT and LEFT ARROW, respectively.' // MISSING
},
{
name: 'Editor Context Menu', // MISSING
legend: 'Press ${contextMenu} or APPLICATION KEY to open context-menu. Then move to next menu option with TAB or DOWN ARROW. Move to previous option with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the menu option. Open sub-menu of current option with SPACE or ENTER or RIGHT ARROW. Go back to parent menu item with ESC or LEFT ARROW. Close context menu with ESC.' // MISSING
},
{
name: 'Editor List Box', // MISSING
legend: 'Inside a list-box, move to next list item with TAB OR DOWN ARROW. Move to previous list item with SHIFT+TAB or UP ARROW. Press SPACE or ENTER to select the list option. Press ESC to close the list-box.' // MISSING
},
{
name: 'Editor Element Path Bar', // MISSING
legend: 'Press ${elementsPathFocus} to navigate to the elements path bar. Move to next element button with TAB or RIGHT ARROW. Move to previous button with SHIFT+TAB or LEFT ARROW. Press SPACE or ENTER to select the element in editor.' // MISSING
}
]
},
{
name: 'કમાંડસ',
items: [
{
name: 'અન્ડું કમાંડ',
legend: '$ દબાવો {undo}'
},
{
name: 'ફરી કરો કમાંડ',
legend: '$ દબાવો {redo}'
},
{
name: 'બોલ્દનો કમાંડ',
legend: '$ દબાવો {bold}'
},
{
name: ' Italic command', // MISSING
legend: 'Press ${italic}' // MISSING
},
{
name: ' Underline command', // MISSING
legend: 'Press ${underline}' // MISSING
},
{
name: ' Link command', // MISSING
legend: 'Press ${link}' // MISSING
},
{
name: ' Toolbar Collapse command', // MISSING
legend: 'Press ${toolbarCollapse}' // MISSING
},
{
name: ' Access previous focus space command', // MISSING
legend: 'Press ${accessPreviousSpace} to access the closest unreachable focus space before the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING
},
{
name: ' Access next focus space command', // MISSING
legend: 'Press ${accessNextSpace} to access the closest unreachable focus space after the caret, for example: two adjacent HR elements. Repeat the key combination to reach distant focus spaces.' // MISSING
},
{
name: ' Accessibility Help', // MISSING
legend: 'Press ${a11yHelp}' // MISSING
},
{
name: ' Paste as plain text', // MISSING
legend: 'Press ${pastetext}', // MISSING
legendEdge: 'Press ${pastetext}, followed by ${paste}' // MISSING
}
]
}
],
tab: 'Tab', // MISSING
pause: 'Pause', // MISSING
capslock: 'Caps Lock', // MISSING
escape: 'Escape', // MISSING
pageUp: 'Page Up', // MISSING
pageDown: 'Page Down', // MISSING
leftArrow: 'Left Arrow', // MISSING
upArrow: 'Up Arrow', // MISSING
rightArrow: 'Right Arrow', // MISSING
downArrow: 'Down Arrow', // MISSING
insert: 'Insert', // MISSING
leftWindowKey: 'Left Windows key', // MISSING
rightWindowKey: 'Right Windows key', // MISSING
selectKey: 'Select key', // MISSING
numpad0: 'Numpad 0', // MISSING
numpad1: 'Numpad 1', // MISSING
numpad2: 'Numpad 2', // MISSING
numpad3: 'Numpad 3', // MISSING
numpad4: 'Numpad 4', // MISSING
numpad5: 'Numpad 5', // MISSING
numpad6: 'Numpad 6', // MISSING
numpad7: 'Numpad 7', // MISSING
numpad8: 'Numpad 8', // MISSING
numpad9: 'Numpad 9', // MISSING
multiply: 'Multiply', // MISSING
add: 'Add', // MISSING
subtract: 'Subtract', // MISSING
decimalPoint: 'Decimal Point', // MISSING
divide: 'Divide', // MISSING
f1: 'F1', // MISSING
f2: 'F2', // MISSING
f3: 'F3', // MISSING
f4: 'F4', // MISSING
f5: 'F5', // MISSING
f6: 'F6', // MISSING
f7: 'F7', // MISSING
f8: 'F8', // MISSING
f9: 'F9', // MISSING
f10: 'F10', // MISSING
f11: 'F11', // MISSING
f12: 'F12', // MISSING
numLock: 'Num Lock', // MISSING
scrollLock: 'Scroll Lock', // MISSING
semiColon: 'Semicolon', // MISSING
equalSign: 'Equal Sign', // MISSING
comma: 'Comma', // MISSING
dash: 'Dash', // MISSING
period: 'Period', // MISSING
forwardSlash: 'Forward Slash', // MISSING
graveAccent: 'Grave Accent', // MISSING
openBracket: 'Open Bracket', // MISSING
backSlash: 'Backslash', // MISSING
closeBracket: 'Close Bracket', // MISSING
singleQuote: 'Single Quote' // MISSING
} );
| astrobin/astrobin | astrobin/static/astrobin/ckeditor/plugins/a11yhelp/dialogs/lang/gu.js | JavaScript | agpl-3.0 | 5,574 |
<?php
require_once "connect.php";
$userId = 3;
$record_serial = 2;
$suspensoQuery = "SELECT 1 FROM reservation WHERE userid = '$userId' AND record_serial = '$record_serial' LIMIT 1";
$result = pg_query($connection,$suspensoQuery);
echo $result;
$number = pg_num_rows($result);
if($number != 1){
echo "pode inserir esta bagaça";
}else{
echo "esse viadao ja reservou sá poha essa semana";
}
//Close connection
pg_close($connection);
?>
| weldermarcosxd/Ionic-Sliding-Test | platforms/android/assets/www/model/teste.php | PHP | agpl-3.0 | 467 |
//////////////////////////////////////////////////////////////////
//
// FreeLing - Open Source Language Analyzers
//
// Copyright (C) 2014 TALP Research Center
// Universitat Politecnica de Catalunya
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Affero General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// 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
// Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero 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
//
// contact: Lluis Padro (padro@lsi.upc.es)
// TALP Research Center
// despatx C6.212 - Campus Nord UPC
// 08034 Barcelona. SPAIN
//
////////////////////////////////////////////////////////////////
#include <sstream>
#include <fstream>
#include "freeling/morfo/traces.h"
#include "freeling/morfo/util.h"
#include "freeling/morfo/configfile.h"
#include "freeling/morfo/semdb.h"
using namespace std;
namespace freeling {
#define MOD_TRACENAME L"SEMDB"
#define MOD_TRACECODE SENSES_TRACE
///////////////////////////////////////////////////////////////
/// Constructor of the auxiliary class "sense_info"
///////////////////////////////////////////////////////////////
sense_info::sense_info(const wstring &syn, const wstring &data) {
// store sense identifier
sense=syn;
if (not data.empty()) {
// split data string into fields
list<wstring> fields=util::wstring2list(data,L" ");
// iterate over field list and store each appropriately
list<wstring>::iterator f=fields.begin();
//first field: list of hypernyms
if ((*f)!=L"-") parents=util::wstring2list(*f,L":");
// second field: WN semantic file
f++; semfile=(*f);
// third filed: List of EWN top-ontology labels
f++; if ((*f)!=L"-") tonto=util::wstring2list(*f,L":");
// fourth field: SUMO concept
f++; if ((*f)!=L"-") sumo=*f;
// fifth field: OpenCYC concept
f++; if ((*f)!=L"-") cyc=*f;
}
}
///////////////////////////////////////////////////////////////
/// Obtain parent list as string (useful for Java API
///////////////////////////////////////////////////////////////
wstring sense_info::get_parents_string() const {
return util::list2wstring(parents,L":");
}
///////////////////////////////////////////////////////////////
/// Create the sense annotator
///////////////////////////////////////////////////////////////
semanticDB::semanticDB(const std::wstring &wsdFile) {
wstring formFile,dictFile,wnFile;
wstring path=wsdFile.substr(0,wsdFile.find_last_of(L"/\\")+1);
// store PoS appearing in mapping to select relevant dictionary entries later.
set<wstring> posset;
enum sections {WN_POS_MAP, DATA_FILES};
config_file cfg(true);
cfg.add_section(L"WNposMap",WN_POS_MAP);
cfg.add_section(L"DataFiles",DATA_FILES);
if (not cfg.open(wsdFile))
ERROR_CRASH(L"Error opening configuration file "+wsdFile);
// read disambiguator configuration file
wstring line;
while (cfg.get_content_line(line)) {
switch (cfg.get_section()) {
case WN_POS_MAP: { // reading map freeling PoS -> WNPoS lemma
wistringstream sin;
sin.str(line);
posmaprule r; // read and store a posmap rule, eg: "VMP v (VMP00SM)" or "N n L"
sin>>r.pos>>r.wnpos>>r.lemma;
posmap.push_back(r);
if (r.lemma!=L"L" and r.lemma!=L"F")
posset.insert(r.lemma);
break;
}
case DATA_FILES: { // reading names for data files
wistringstream sin;
sin.str(line);
wstring key; wstring fname;
sin>>key>>fname;
if (key==L"formDictFile") formFile=util::absolute(fname,path);
else if (key==L"senseDictFile") dictFile=util::absolute(fname,path);
else if (key==L"wnFile") wnFile=util::absolute(fname,path);
break;
}
default: break;
}
}
cfg.close();
// load the necessary entries from the form dictionary,
// store them reversed for access (lema,PoS)->form
if (formFile.empty() or posset.size()==0)
form_dict=NULL;
else {
wifstream fform;
util::open_utf8_file(fform, formFile);
if (fform.fail()) ERROR_CRASH(L"Error opening formDict file "+formFile);
form_dict = new database(DB_MAP);
while (getline(fform,line)) {
wistringstream sin; sin.str(line);
// get form, 1st field
wstring form;
sin>>form;
// get pairs lemma-pos and select those relevant
wstring lema,tag;
while (sin>>lema>>tag) {
if (posset.find(tag)!=posset.end())
form_dict->add_database(lema+L" "+tag,form);
}
}
fform.close();
}
// load semanticDB if needed.
if (dictFile.empty())
sensesdb=NULL;
else {
wifstream fsens;
util::open_utf8_file(fsens, dictFile);
if (fsens.fail()) ERROR_CRASH(L"Error opening senseDict file "+dictFile);
sensesdb = new database(DB_MAP);
while (getline(fsens,line)) {
wistringstream sin; sin.str(line);
// get sense, 1st field
wstring sens;
sin>>sens;
wstring tag= sens.substr(sens.find(L"-")+1);
// get words for current sense. Store both sense->words and word->sense records
wstring wd;
while (sin>>wd) {
sensesdb->add_database(L"S:"+sens,wd);
sensesdb->add_database(L"W:"+wd+L":"+tag, sens);
}
}
fsens.close();
}
// load WN structure if needed
if (wnFile.empty())
wndb=NULL;
else
wndb = new database(wnFile) ;
}
////////////////////////////////////////////////
/// Destroy sense annotator module, close database.
////////////////////////////////////////////////
semanticDB::~semanticDB() {
delete sensesdb;
delete wndb;
delete form_dict;
}
///////////////////////////////////////////////////////////////
/// Get senses for a lemma+pos
///////////////////////////////////////////////////////////////
list<wstring> semanticDB::get_word_senses(const wstring &form, const wstring &lemma, const wstring &pos) const {
// get pairs (lemma,pos) to search in WN for this analysis
list<pair<wstring,wstring> > searchlist;
get_WN_keys(form, lemma, pos, searchlist);
// search senses for each lemma/tag in the list
list<wstring> lsen;
list<pair<wstring,wstring> >::iterator p;
for (p=searchlist.begin(); p!=searchlist.end(); p++) {
TRACE(4,L" .. searching "+p->first+L" "+p->second);
list<wstring> s = util::wstring2list(sensesdb->access_database(L"W:"+p->first+L":"+p->second), L" ");
lsen.insert(lsen.end(),s.begin(),s.end());
}
if (not lsen.empty()) {
TRACE(4,L" .. senses found: "+util::list2wstring(lsen,L"/"));
}
return lsen;
}
///////////////////////////////////////////////////////////////
/// Get synonyms for a sense+pos
///////////////////////////////////////////////////////////////
list<wstring> semanticDB::get_sense_words(const wstring &sens) const{
return util::wstring2list(sensesdb->access_database(L"S:"+sens), L" ");
}
///////////////////////////////////////////////////////////////
/// Get info for a sense+pos
///////////////////////////////////////////////////////////////
sense_info semanticDB::get_sense_info(const wstring &syn) const{
/// access DB and split obtained data_string into fields
/// and store appropriately in a sense_info object
sense_info sinf(syn,wndb->access_database(syn));
/// add also list of synset words
sinf.words=get_sense_words(syn);
return sinf;
}
//////////////////////////////////////////////
/// Compute list of lemma-pos to search in WN for given
/// word and analysis, according to mapping rules.
//////////////////////////////////////////////
void semanticDB::get_WN_keys(const wstring &form, const wstring &lemma, const wstring &tag, list<pair<wstring,wstring> > &searchlist) const {
searchlist.clear();
// check all possible mappings to WN-PoS
list<posmaprule>::const_iterator p;
for (p=posmap.begin(); p!=posmap.end(); p++) {
TRACE(4,L"Check tag "+tag+L" with posmap: "+p->pos+L" "+p->wnpos+L" "+p->lemma);
if (tag.find(p->pos)==0) {
TRACE(4,L" matched");
// rule matches word PoS. Add pair lemma/pos to the list
wstring lm;
if (p->lemma==L"L") lm=lemma;
else if (p->lemma==L"F") lm=form;
else { // interpret it as a PoS tag
TRACE(3,L"Found word matching special map: "+lemma+L" "+p->lemma);
lm = form_dict->access_database(lemma+L" "+p->lemma);
}
// split list in case there are more than one form
list<wstring> fms=util::wstring2list(lm,L" ");
for (list<wstring>::iterator ifm=fms.begin(); ifm!=fms.end(); ifm++) {
TRACE(3,L"Adding word '"+form+L"' to be searched with pos="+p->wnpos+L" and lemma="+(*ifm));
searchlist.push_back(make_pair(*ifm,p->wnpos));
}
}
}
}
} // namespace
| TALP-UPC/freeling | src/libfreeling/semdb.cc | C++ | agpl-3.0 | 9,732 |
export default {
standard: {
credits: { enabled: false },
chart: {
spacingBottom: 20,
style: {
fontFamily: "'proxima', 'Helvetica', sans-serif' ",
paddingTop: '20px' // Make room for buttons
}
},
exporting: {
buttons: {
contextButton: {
onclick: function () {
this.exportChart({type: 'jpeg'})
},
symbol: null,
text: 'Export',
x: -20,
y: -30,
theme: {
style: {
color: '#039',
textDecoration: 'underline'
}
}
}
}
},
title: ''
}
}
| unicef/rhizome | webapp/src/components/highchart/themes.js | JavaScript | agpl-3.0 | 663 |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-isegory',
version='0.1',
packages=['isegory'],
include_package_data=True,
license='AGPL',
description='A simple Django app to declare the provenance of a dataset.',
long_description=README,
url='http://github.com/jdelacueva/django-isegory/',
author='Javier de la Cueva',
author_email='jdelacueva@derecho-internet.org',
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: AGPL',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| jdelacueva/django-isegory | setup.py | Python | agpl-3.0 | 1,049 |
# Recall is a program for storing bookmarks of different things
# Copyright (C) 2012 Cal Paterson
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import uuid
from bottle import Bottle, request, response, abort
import bcrypt
from recall.data import whitelist, blacklist
from recall import convenience as c
from recall import plugins, jobs, messages
app = Bottle()
app.install(plugins.exceptions)
app.install(plugins.ppjson)
app.install(plugins.auth)
app.install(plugins.cors)
app.error_handler = plugins.handler_dict
logger = c.logger("people")
@app.get("/")
def users():
abort(503, "Not yet implemented")
@app.get("/<who>/")
def user_(who):
try:
return whitelist(c.db().users.find_one({"email": who}), [
"email",
"firstName",
"pseudonym"
])
except TypeError:
logger.warn("Asked about {email}, but that is not a user".format(
email=who))
abort(404, "User not found")
@app.get("/<who>/self")
def _self(who, user):
if who != user["email"]:
response.status = 400
else:
return whitelist(user, ["pseudonym",
"firstName",
"surname",
"email",
"private_email"])
@app.post("/<who>/")
def request_invite(who):
# FIXME: Don't allow the pseudonym "public"
user = whitelist(request.json, [
"pseudonym",
"firstName",
"surname",
"private_email",
"token",
])
if "private_email" not in user:
abort(400, "You must provide a private_email field")
user["email_key"] = str(uuid.uuid4())
user["registered"] = c.unixtime()
user["email"] = who
c.db().users.ensure_index("email", unique=True)
c.db().users.insert(user, safe=True)
response.status = 202
logger.info("{email} subscribed".format(email=who))
jobs.enqueue(messages.SendInvite(user))
@app.post("/<who>/<email_key>")
def verify_email(who, email_key):
if "RECALL_TEST_MODE" in c.settings or "RECALL_DEBUG_MODE" in c.settings:
salt = bcrypt.gensalt(1)
else:
salt = bcrypt.gensalt()
password_hash = bcrypt.hashpw(request.json["password"], salt)
spec = {"email_key": email_key, "verified": {"$exists": False}}
update = {"$set": {"password_hash": password_hash,
"verified": c.unixtime()}}
success = c.db().users.update(spec, update, safe=True)["updatedExisting"]
if not success:
if c.db().users.find_one({"email_key": email_key}):
logger.warn("{email} tried to verify a second time".format(email=who))
abort(403, "Already verified")
else:
logger.warn("Someone tried to verify with a key, but it doesn't exist")
abort(404, "Don't know that key")
user = c.db().users.find_one({"email_key": email_key})
response.status = 201
return blacklist(user, ["_id", "email_key", "password_hash"])
| calpaterson/recall | src/recall/people.py | Python | agpl-3.0 | 3,665 |
# -*- coding: utf-8 -*-
require 'rails_helper'
RSpec.describe MessagesController, type: :controller do
let(:admin) { create(:user_admin) }
let(:message) { create(:message) }
let(:tag) { create(:tag, forum: message.forum) }
before(:each) do
# ensure that message and tag exist
message
tag
s = Setting.new
s.options['min_tags_per_message'] = 1
s.options['max_tags_per_message'] = 3
s.save!
end
describe 'GET #show' do
render_views
it 'shows a message' do
get :show, params: message_params_from_slug(message)
end
it 'shows no versions link if there are no versions but an edit_author is set' do
message.edit_author = admin.username
message.save!
get :show, params: message_params_from_slug(message)
expect(response.body).not_to have_css('.versions')
end
it 'shows versions link if there are versions' do
message.edit_author = admin.username
message.versions.create!(subject: message.subject, content: message.content, author: message.author)
message.save!
get :show, params: message_params_from_slug(message)
expect(response.body).to have_css('.versions')
end
it 'redirects to correct form when accessing via wrong forum' do
forum1 = create(:write_forum)
message.forum = forum1
get :show, params: message_params_from_slug(message).merge(curr_forum: forum1.slug)
expect(response).to redirect_to message_url(message.thread, message)
end
it 'sets readmode cookie when overwriting via query string' do
get :show, params: message_params_from_slug(message).merge(rm: 'thread-view')
expect(response.cookies['cf_readmode']).to eq 'thread-view'
end
it "doesn't set readmode cookie when overwriting via query string and signed in" do
sign_in admin
get :show, params: message_params_from_slug(message).merge(rm: 'thread-view')
expect(response.cookies['cf_readmode']).to be_nil
end
end
describe 'GET #new' do
it 'shows a new message form' do
get :new, params: message_params_from_slug(message)
expect(assigns(:message)).to be_a_new(Message)
end
end
describe 'POST #create' do
it 'creates a new message' do
expect do
post :create, params: message_params_from_slug(message).merge(tags: [tag.tag_name],
message: attributes_for(:message,
forum: message.thread.forum))
end.to change(Message, :count).by(1)
expect(response).to redirect_to message_url(message.thread, assigns(:message))
end
it 'fails to create a new message because of 0 tags' do
post :create, params: message_params_from_slug(message).merge(message: attributes_for(:message, forum: message.thread.forum))
expect(response).to render_template 'new'
end
it 'fails to create a new message because of too many tags' do
post :create,
params: message_params_from_slug(message)
.merge(message: attributes_for(:message, forum: message.thread.forum),
tags: ['old republic', 'rebellion', 'aldebaran', 'luke'])
expect(response).to render_template 'new'
end
it 'fails to create a new message because of missing attributes' do
attrs = attributes_for(:message, forum: message.thread.forum)
attrs.delete(:author)
post :create, params: message_params_from_slug(message).merge(tags: [tag.tag_name], message: attrs)
expect(response).to render_template 'new'
end
it 'fails to create a post with a spammy subject' do
s = Setting.first!
s.options['subject_black_list'] = 'some spammy text'
s.save!
attrs = attributes_for(:message, forum: message.thread.forum)
attrs[:subject] = 'some spammy text'
post :create, params: message_params_from_slug(message).merge(tags: [tag.tag_name], message: attrs)
expect(response).to render_template 'new'
end
it 'fails to create a post with spammy content' do
s = Setting.first!
s.options['content_black_list'] = 'some spammy text'
s.save!
attrs = attributes_for(:message, forum: message.thread.forum)
attrs[:content] = 'some spammy text'
post :create, params: message_params_from_slug(message).merge(tags: [tag.tag_name], message: attrs)
expect(response).to render_template 'new'
end
end
describe 'POST #retag' do
it 'changes tags' do
sign_in admin
expect do
post :retag, params: message_params_from_slug(message).merge(tags: [tag.tag_name])
end.to change(message.tags, :count).by(1)
end
it 'creates new tag' do
sign_in admin
expect do
post :retag, params: message_params_from_slug(message).merge(tags: ['old republic'])
end.to change(message.tags, :count).by(1)
end
it 'only allows max_tags tags' do
sign_in admin
post :retag, params: message_params_from_slug(message).merge(tags: ['old republic', 'rebellion',
'aldebaran', 'luke'])
message.tags.reload
expect(message.tags.length).to be 0
expect(response).to be_success
end
it "doesn't allow 0 tags" do
sign_in admin
post :retag, params: message_params_from_slug(message).merge(tags: [])
message.tags.reload
expect(message.tags.length).to be 0
expect(response).to be_success
end
end
describe 'GET #edit' do
it 'shows the edit form as admin' do
sign_in admin
get :edit, params: message_params_from_slug(message)
expect(response).to render_template 'edit'
end
it 'shows the edit form as owner' do
sign_in message.owner
get :edit, params: message_params_from_slug(message)
expect(response).to render_template 'edit'
end
it 'redirects when trying to edit as anonymous' do
get :edit, params: message_params_from_slug(message)
expect(response).to redirect_to message_url(message.thread, message)
end
it 'redirects when trying to edit as wrong user' do
user1 = create(:user)
sign_in user1
get :edit, params: message_params_from_slug(message)
expect(response).to redirect_to message_url(message.thread, message)
end
end
describe 'POST #update' do
it 'updates a message to markdown' do
message.format = 'cforum'
message.save
sign_in admin
post :update, params: message_params_from_slug(message).merge(message: message.attributes,
tags: ['rebellion'])
expect(response).to redirect_to message_url(message.thread, assigns(:message))
message.reload
expect(message.format).to eq 'markdown'
end
it "doesn't create a version when format is not markdown" do
message.format = 'cforum'
message.save
sign_in admin
expect do
post :update, params: message_params_from_slug(message).merge(message: message.attributes,
tags: ['rebellion'])
end.to change(message.versions, :count).by(0)
end
it 'renders new when anon' do
post :update, params: message_params_from_slug(message).merge(message: message.attributes,
tags: ['rebellion'])
expect(response).to render_template 'new'
end
it 'renders new when wrong user' do
user1 = create(:user)
sign_in user1
post :update, params: message_params_from_slug(message).merge(message: message.attributes,
tags: ['rebellion'])
expect(response).to render_template 'new'
end
it 'updates search index when content changed' do
sign_in admin
message.author = 'Jar Jar Binks'
expect do
post :update, params: message_params_from_slug(message).merge(message: message.attributes,
tags: ['rebellion'])
end.to change(SearchDocument, :count).by(1)
end
end
end
# eof
| CountOrlok/cforum | spec/controllers/messages_controller_spec.rb | Ruby | agpl-3.0 | 8,350 |
/*
* jPOS Project [http://jpos.org]
* Copyright (C) 2000-2010 Alejandro P. Revilla
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jpos.ee.pm.struts.actions;
import java.util.ArrayList;
import java.util.List;
import org.jpos.ee.pm.converter.Converter;
import org.jpos.ee.pm.converter.ConverterException;
import org.jpos.ee.pm.converter.IgnoreConvertionException;
import org.jpos.ee.pm.core.EntityInstanceWrapper;
import org.jpos.ee.pm.core.Field;
import org.jpos.ee.pm.core.PMException;
import org.jpos.ee.pm.struts.PMStrutsContext;
import org.jpos.ee.pm.validator.ValidationResult;
import org.jpos.ee.pm.validator.Validator;
import org.jpos.util.LogEvent;
import org.jpos.util.Logger;
public abstract class FieldProcessingActionSupport extends EntityActionSupport {
protected void proccessField(PMStrutsContext ctx, Field field, EntityInstanceWrapper wrapper) throws PMException {
LogEvent evt = ctx.getPresentationManager().getLog().createDebug();
evt.addMessage("Field [" + field.getId() + "] ");
final List<String> parameterValues = getParameterValues(ctx,field);
int i = 0;
for (String value : parameterValues) {
evt.addMessage(" Object to convert: " + value);
try {
final Converter converter = field.getConverters().getConverterForOperation(ctx.getOperation().getId());
Object converted = getConvertedValue(ctx, field, value, wrapper, converter);
evt.addMessage(" Object converted: " + converted);
doProcessField(wrapper, i, converter, ctx, field, converted);
} catch (IgnoreConvertionException e) {
//Do nothing, just ignore conversion.
}
i++;
}
Logger.log(evt);
}
protected void doProcessField(EntityInstanceWrapper wrapper, int i, final Converter converter, PMStrutsContext ctx, Field field, Object converted) throws PMException {
final Object o = wrapper.getInstance(i);
if (converter.getValidate()) {
if (validateField(ctx, field, wrapper, converted)) {
ctx.getPresentationManager().set(o, field.getProperty(), converted);
}
} else {
ctx.getPresentationManager().set(o, field.getProperty(), converted);
}
}
protected Object getConvertedValue(PMStrutsContext ctx, Field field, String values, EntityInstanceWrapper wrapper, final Converter converter) throws ConverterException {
ctx.put(PM_FIELD, field);
ctx.put(PM_FIELD_VALUE, values);
ctx.put(PM_ENTITY_INSTANCE_WRAPPER, wrapper);
final Object converted = converter.build(ctx);
return converted;
}
private boolean validateField(PMStrutsContext ctx, Field field, EntityInstanceWrapper wrapper, Object o) throws PMException {
boolean ok = true;
if (field.getValidators() != null) {
for (Validator fv : field.getValidators()) {
ctx.put(PM_ENTITY_INSTANCE, wrapper.getInstance());
ctx.put(PM_FIELD, field);
ctx.put(PM_FIELD_VALUE, o);
ValidationResult vr = fv.validate(ctx);
ctx.getErrors().addAll(vr.getMessages());
ok = ok && vr.isSuccessful();
}
}
return ok;
}
private String getParamValues(PMStrutsContext ctx, String name, String separator) {
String[] ss = ctx.getRequest().getParameterValues(name);
if (ss != null) {
StringBuilder s = new StringBuilder();
if (ss != null && ss.length > 0) {
s.append(ss[0]);
}
//In this case we have a multivalue input
for (int i = 1; i < ss.length; i++) {
s.append(separator);
s.append(ss[i]);
}
return s.toString();
} else {
return null;
}
}
protected List<String> getParameterValues(PMStrutsContext ctx, Field field) {
List<String> result = new ArrayList<String>();
String eid = "f_" + field.getId();
String s = getParamValues(ctx, eid, ";");
int i = 0;
if (s == null) {
s = "";
}
while(s != null){
result.add(s);
i++;
s = getParamValues(ctx, eid + "_" + i, ";");
}
return result;
}
}
| jpaoletti/jPOS-Presentation-Manager | modules/pm_struts/src/org/jpos/ee/pm/struts/actions/FieldProcessingActionSupport.java | Java | agpl-3.0 | 5,057 |
include SessionHelper
describe API::AssignmentsController do
let(:course) { create :course, status: true }
let(:student) { create(:course_membership, :student, course: course).user }
let(:professor) { create(:course_membership, :professor, course: course).user }
let!(:assignment) { create(:assignment, course: course) }
let!(:predicted_earned_grade) { create :predicted_earned_grade, student: student, assignment: assignment }
let!(:grade) { create :grade, student: student, assignment: assignment }
context "as professor" do
before do
login_user(professor)
allow(controller).to receive(:current_course).and_return(course)
allow(controller).to receive(:current_user).and_return(professor)
end
describe "GET index" do
it "assigns assignments, no grade or student" do
get :index, format: :json
expect(assigns(:assignments).first.id).to eq(assignment.id)
expect(assigns :student).to be_nil
expect(assigns :predicted_earned_grades).to be_nil
expect(assigns :grades).to be_nil
expect(response).to render_template(:index)
end
describe "ordered by position" do
it "orders primarily by postions and secondarily by assignment type position" do
assignment.assignment_type.update(position: 2)
at2 = create :assignment_type, position: 1, course: course
a2 = create :assignment, position: 1, assignment_type: at2, course: course
a3 = create :assignment, position: 1, assignment_type: assignment.assignment_type, course: course
a4 = create :assignment, position: 2, assignment_type: at2, course: course
assignment.update(position: 5)
get :index, format: :json
expect(assigns(:assignments).pluck(:position)).to eq([1,1,2,5])
expect(assigns(:assignments).pluck(:id)).to eq([a2.id, a3.id, a4.id, assignment.id])
end
end
end
describe "GET show" do
it "assigns the assignment" do
get :show, params: { id: assignment.id }, format: :json
expect(assigns(:assignment).id).to eq(assignment.id)
expect(response).to render_template(:show)
end
end
describe "PUT update" do
let(:objective) { create :learning_objective }
it "updates boolean attributes from params" do
expect(assignment.visible).to be_truthy
post :update, params: {
id: assignment.id, assignment: { visible: false}}, format: :json
assignment.reload
expect(assignment.visible).to be_falsey
end
it "creates learning objective links" do
assignment_params = attributes_for(:assignment).merge linked_objective_ids: [objective.id]
expect{ post :update, params: { assignment: assignment_params, id: assignment.id }, format: :json }.to \
change(LearningObjectiveLink, :count).by 1
expect(LearningObjectiveLink.last.course_id).to eq assignment.course_id
end
end
describe "POST sort" do
it "sorts the assignments by params" do
second_assignment = create(:assignment, assignment_type: assignment.assignment_type)
course.assignments << second_assignment
post :sort, params: { assignment: [second_assignment.id, assignment.id] }
expect(assignment.reload.position).to eq(2)
expect(second_assignment.reload.position).to eq(1)
end
end
end
context "as student" do
before do
login_user(student)
allow(controller).to receive(:current_course).and_return(course)
allow(controller).to receive(:current_user).and_return(student)
end
describe "GET index" do
context "when the course is active" do
it "assigns the assignments with predictions and grades and a call to update" do
get :index, format: :json
expect(assigns(:assignments).first.id).to eq(assignment.id)
expect(assigns :student).to eq(student)
expect(assigns :predicted_earned_grades).to eq([predicted_earned_grade])
expect(assigns :grades).to eq([grade])
expect(assigns(:allow_updates)).to be_truthy
expect(response).to render_template(:index)
end
end
context "when the course is not active" do
it "assigns the assignments with predictions and grades and a call to update" do
course.status = false
get :index, format: :json
expect(assigns :student).to eq(student)
expect(assigns :predicted_earned_grades).to eq([predicted_earned_grade])
expect(assigns :grades).to eq([grade])
expect(assigns(:allow_updates)).to be_falsey
expect(response).to render_template(:index)
end
end
end
end
context "as faculty previewing as student" do
before do
login_as_impersonating_agent(professor, student)
allow(controller).to receive(:current_course).and_return(course)
allow(controller).to receive(:current_user).and_return(student)
end
describe "GET index" do
it "assigns the assignments with grades, no predictions and no call to update" do
get :index, format: :json
expect(assigns(:assignments).first.id).to eq(assignment.id)
expect(assigns :student).to eq(student)
expect(assigns :predicted_earned_grades).to be_nil
expect(assigns :grades).to eq([grade])
expect(assigns(:allow_updates)).to be_falsey
expect(response).to render_template(:index)
end
end
end
end
| UM-USElab/gradecraft-development | spec/controllers/api/assignments_controller_spec.rb | Ruby | agpl-3.0 | 5,527 |
<p>Sorry no content could be found.</p> | proudcity/wp-proud-core | modules/proud-teasers/templates/teasers-empty.php | PHP | agpl-3.0 | 39 |
<?php
/**
* @author Morris Jobke <hey@morrisjobke.de>
* @author Robin Appelman <icewind@owncloud.com>
*
* @copyright Copyright (c) 2015, ownCloud, Inc.
* @license AGPL-3.0
*
* This code is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License, version 3,
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
namespace OC\Hooks;
abstract class LegacyEmitter extends BasicEmitter {
protected function emit($scope, $method, array $arguments = array()) {
\OC_Hook::emit($scope, $method, $arguments);
parent::emit($scope, $method, $arguments);
}
}
| lrytz/core | lib/private/hooks/legacyemitter.php | PHP | agpl-3.0 | 1,041 |
from collections import defaultdict
from fs.errors import ResourceNotFoundError
import logging
import inspect
import re
from path import path
from django.http import Http404
from django.conf import settings
from .module_render import get_module
from xmodule.course_module import CourseDescriptor
from xmodule.modulestore import Location, XML_MODULESTORE_TYPE
from xmodule.modulestore.django import modulestore
from xmodule.contentstore.content import StaticContent
from xmodule.modulestore.exceptions import ItemNotFoundError, InvalidLocationError
from courseware.model_data import FieldDataCache
from static_replace import replace_static_urls
from courseware.access import has_access
import branding
log = logging.getLogger(__name__)
def get_request_for_thread():
"""Walk up the stack, return the nearest first argument named "request"."""
frame = None
try:
for f in inspect.stack()[1:]:
frame = f[0]
code = frame.f_code
if code.co_varnames[:1] == ("request",):
return frame.f_locals["request"]
elif code.co_varnames[:2] == ("self", "request",):
return frame.f_locals["request"]
finally:
del frame
def get_course(course_id, depth=0):
"""
Given a course id, return the corresponding course descriptor.
If course_id is not valid, raises a ValueError. This is appropriate
for internal use.
depth: The number of levels of children for the modulestore to cache.
None means infinite depth. Default is to fetch no children.
"""
try:
course_loc = CourseDescriptor.id_to_location(course_id)
return modulestore().get_instance(course_id, course_loc, depth=depth)
except (KeyError, ItemNotFoundError):
raise ValueError("Course not found: {}".format(course_id))
except InvalidLocationError:
raise ValueError("Invalid location: {}".format(course_id))
def get_course_by_id(course_id, depth=0):
"""
Given a course id, return the corresponding course descriptor.
If course_id is not valid, raises a 404.
depth: The number of levels of children for the modulestore to cache. None means infinite depth
"""
try:
course_loc = CourseDescriptor.id_to_location(course_id)
return modulestore().get_instance(course_id, course_loc, depth=depth)
except (KeyError, ItemNotFoundError):
raise Http404("Course not found.")
except InvalidLocationError:
raise Http404("Invalid location")
def get_course_with_access(user, course_id, action, depth=0):
"""
Given a course_id, look up the corresponding course descriptor,
check that the user has the access to perform the specified action
on the course, and return the descriptor.
Raises a 404 if the course_id is invalid, or the user doesn't have access.
depth: The number of levels of children for the modulestore to cache. None means infinite depth
"""
course = get_course_by_id(course_id, depth=depth)
if not has_access(user, course, action):
# Deliberately return a non-specific error message to avoid
# leaking info about access control settings
raise Http404("Course not found.")
return course
def get_opt_course_with_access(user, course_id, action):
"""
Same as get_course_with_access, except that if course_id is None,
return None without performing any access checks.
"""
if course_id is None:
return None
return get_course_with_access(user, course_id, action)
def course_image_url(course):
"""Try to look up the image url for the course. If it's not found,
log an error and return the dead link"""
if course.static_asset_path or modulestore().get_modulestore_type(course.location.course_id) == XML_MODULESTORE_TYPE:
return '/static/' + (course.static_asset_path or getattr(course, 'data_dir', '')) + "/images/course_image.jpg"
else:
loc = course.location.replace(tag='c4x', category='asset', name=course.course_image)
_path = StaticContent.get_url_path_from_location(loc)
return _path
def find_file(filesystem, dirs, filename):
"""
Looks for a filename in a list of dirs on a filesystem, in the specified order.
filesystem: an OSFS filesystem
dirs: a list of path objects
filename: a string
Returns d / filename if found in dir d, else raises ResourceNotFoundError.
"""
for directory in dirs:
filepath = path(directory) / filename
if filesystem.exists(filepath):
return filepath
raise ResourceNotFoundError("Could not find {0}".format(filename))
def get_course_about_section(course, section_key):
"""
This returns the snippet of html to be rendered on the course about page,
given the key for the section.
Valid keys:
- overview
- title
- university
- number
- short_description
- description
- key_dates (includes start, end, exams, etc)
- video
- course_staff_short
- course_staff_extended
- requirements
- syllabus
- textbook
- faq
- more_info
- ocw_links
"""
# Many of these are stored as html files instead of some semantic
# markup. This can change without effecting this interface when we find a
# good format for defining so many snippets of text/html.
# TODO: Remove number, instructors from this list
if section_key in ['short_description', 'description', 'key_dates', 'video',
'course_staff_short', 'course_staff_extended',
'requirements', 'syllabus', 'textbook', 'faq', 'more_info',
'number', 'instructors', 'overview',
'effort', 'end_date', 'prerequisites', 'ocw_links']:
try:
request = get_request_for_thread()
loc = course.location.replace(category='about', name=section_key)
# Use an empty cache
field_data_cache = FieldDataCache([], course.id, request.user)
about_module = get_module(
request.user,
request,
loc,
field_data_cache,
course.id,
not_found_ok=True,
wrap_xmodule_display=False,
static_asset_path=course.static_asset_path
)
html = ''
if about_module is not None:
html = about_module.render('student_view').content
return html
except ItemNotFoundError:
log.warning("Missing about section {key} in course {url}".format(
key=section_key, url=course.location.url()))
return None
elif section_key == "title":
return course.display_name_with_default
elif section_key == "university":
return course.display_org_with_default
elif section_key == "number":
return course.display_number_with_default
raise KeyError("Invalid about key " + str(section_key))
def get_course_info_section(request, course, section_key):
"""
This returns the snippet of html to be rendered on the course info page,
given the key for the section.
Valid keys:
- handouts
- guest_handouts
- updates
- guest_updates
"""
loc = Location(course.location.tag, course.location.org, course.location.course, 'course_info', section_key)
# Use an empty cache
field_data_cache = FieldDataCache([], course.id, request.user)
info_module = get_module(
request.user,
request,
loc,
field_data_cache,
course.id,
wrap_xmodule_display=False,
static_asset_path=course.static_asset_path
)
html = ''
if info_module is not None:
html = info_module.render('student_view').content
return html
# TODO: Fix this such that these are pulled in as extra course-specific tabs.
# arjun will address this by the end of October if no one does so prior to
# then.
def get_course_syllabus_section(course, section_key):
"""
This returns the snippet of html to be rendered on the syllabus page,
given the key for the section.
Valid keys:
- syllabus
- guest_syllabus
"""
# Many of these are stored as html files instead of some semantic
# markup. This can change without effecting this interface when we find a
# good format for defining so many snippets of text/html.
if section_key in ['syllabus', 'guest_syllabus']:
try:
filesys = course.system.resources_fs
# first look for a run-specific version
dirs = [path("syllabus") / course.url_name, path("syllabus")]
filepath = find_file(filesys, dirs, section_key + ".html")
with filesys.open(filepath) as html_file:
return replace_static_urls(
html_file.read().decode('utf-8'),
getattr(course, 'data_dir', None),
course_id=course.location.course_id,
static_asset_path=course.static_asset_path,
)
except ResourceNotFoundError:
log.exception("Missing syllabus section {key} in course {url}".format(
key=section_key, url=course.location.url()))
return "! Syllabus missing !"
raise KeyError("Invalid about key " + str(section_key))
def get_courses_by_university(user, domain=None):
'''
Returns dict of lists of courses available, keyed by course.org (ie university).
Courses are sorted by course.number.
'''
# TODO: Clean up how 'error' is done.
# filter out any courses that errored.
visible_courses = get_courses(user, domain)
universities = defaultdict(list)
for course in visible_courses:
universities[course.org].append(course)
return universities
def get_courses(user, domain=None):
'''
Returns a list of courses available, sorted by course.number
'''
courses = branding.get_visible_courses(domain)
courses = [c for c in courses if has_access(user, c, 'see_exists')]
courses = sorted(courses, key=lambda course: course.number)
return courses
def sort_by_announcement(courses):
"""
Sorts a list of courses by their announcement date. If the date is
not available, sort them by their start date.
"""
# Sort courses by how far are they from they start day
key = lambda course: course.sorting_score
courses = sorted(courses, key=key)
return courses
def get_cms_course_link_by_id(course_id):
"""
Returns a proto-relative link to course_index for editing the course in cms, assuming that the course is actually
cms-backed. If course_id is improperly formatted, just return the root of the cms
"""
format_str = r'^(?P<org>[^/]+)/(?P<course>[^/]+)/(?P<name>[^/]+)$'
host = "//{}/".format(settings.CMS_BASE) # protocol-relative
m_obj = re.match(format_str, course_id)
if m_obj:
return "{host}{org}/{course}/course/{name}".format(host=host,
org=m_obj.group('org'),
course=m_obj.group('course'),
name=m_obj.group('name'))
return host
| abo-abo/edx-platform | lms/djangoapps/courseware/courses.py | Python | agpl-3.0 | 11,362 |
/*
* Copyright (c) 2014
*
* This file is licensed under the Affero General Public License version 3
* or later.
*
* See the COPYING-README file.
*
*/
(function() {
OC.Update = {
_started : false,
/**
* Start the upgrade process.
*
* @param $el progress list element
*/
start: function($el, options) {
if (this._started) {
return;
}
var hasWarnings = false;
this.$el = $el;
this._started = true;
this.addMessage(t(
'core',
'Updating {productName} to version {version}, this may take a while.', {
productName: options.productName || 'ownCloud',
version: options.version
}),
'bold'
).append('<br />'); // FIXME: these should be ul/li with CSS paddings!
var updateEventSource = new OC.EventSource(OC.webroot+'/core/ajax/update.php');
updateEventSource.listen('success', function(message) {
$('<span>').append(message).append('<br />').appendTo($el);
});
updateEventSource.listen('notice', function(message) {
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
hasWarnings = true;
});
updateEventSource.listen('error', function(message) {
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
message = t('core', 'Please reload the page.');
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
updateEventSource.close();
});
updateEventSource.listen('failure', function(message) {
$('<span>').addClass('error').append(message).append('<br />').appendTo($el);
$('<span>')
.addClass('bold')
.append(t('core', 'The update was unsuccessful. ' +
'Please report this issue to the ' +
'<a href="https://github.com/owncloud/core/issues" target="_blank">ownCloud community</a>.'))
.appendTo($el);
});
updateEventSource.listen('done', function() {
if (hasWarnings) {
$('<span>').addClass('bold')
.append('<br />')
.append(t('core', 'The update was successful. There were warnings.'))
.appendTo($el);
var message = t('core', 'Please reload the page.');
$('<span>').append('<br />').append(message).append('<br />').appendTo($el);
} else {
// FIXME: use product name
$('<span>').addClass('bold')
.append('<br />')
.append(t('core', 'The update was successful. Redirecting you to ownCloud now.'))
.appendTo($el);
setTimeout(function () {
OC.redirect(OC.webroot);
}, 3000);
}
});
},
addMessage: function(message, className) {
var $span = $('<span>');
$span.addClass(className).append(message).append('<br />').appendTo(this.$el);
return $span;
}
};
})();
$(document).ready(function() {
$('.updateButton').on('click', function() {
var $updateEl = $('.update');
var $progressEl = $('.updateProgress');
$progressEl.removeClass('hidden');
$('.updateOverview').addClass('hidden');
OC.Update.start($progressEl, {
productName: $updateEl.attr('data-productname'),
version: $updateEl.attr('data-version'),
});
return false;
});
});
| lrytz/core | core/js/update.js | JavaScript | agpl-3.0 | 3,085 |
<?php
include_once '../../../lib/defaults.php';
include_once '../fns/require_note.php';
include_once '../../lib/mysqli.php';
list($note, $id, $user) = require_note($mysqli);
unset($_SESSION['notes/view/messages']);
$base = '../../';
$fnsDir = '../../fns';
include_once "$fnsDir/NoteRevisions/indexOnNote.php";
include_once '../../lib/mysqli.php';
$revisions = NoteRevisions\indexOnNote($mysqli, $id);
if ($revisions) {
$items = [];
include_once "$fnsDir/export_date_ago.php";
include_once "$fnsDir/Page/imageArrowLinkWithDescription.php";
foreach ($revisions as $revision) {
$item_id = $revision->id;
$items[] = Page\imageArrowLinkWithDescription(
export_date_ago($revision->insert_time, true),
'R'.($revision->revision + 1), "view/?id=$item_id",
'restore-defaults', ['id' => $item_id]);
}
$content = join('<div class="hr"></div>', $items);
} else {
include_once "$fnsDir/Page/info.php";
$content = Page\info('History is empty');
}
include_once "$fnsDir/Page/create.php";
$content = \Page\create(
[
'title' => "Note #$id",
'href' => "../view/?id=$id#history",
],
'History',
$content
);
include_once "$fnsDir/compressed_js_script.php";
include_once "$fnsDir/echo_user_page.php";
echo_user_page($user, "Note #$id History", $content, $base, [
'scripts' => compressed_js_script('dateAgo', $base),
]);
| zvini/website | www/notes/history/index.php | PHP | agpl-3.0 | 1,425 |
//-----------------------------------------------------------------------
// <copyright file="ListaChiamateInCorsoMarkerResult.cs" company="CNVVF">
// Copyright (C) 2017 - CNVVF
//
// This file is part of SOVVF.
// SOVVF is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// SOVVF is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
// </copyright>
//-----------------------------------------------------------------------
using SO115App.Models.Classi.Marker;
using System.Collections.Generic;
namespace SO115App.API.Models.Servizi.CQRS.Queries.Marker.ListaChiamateInCorsoMarker
{
/// <summary>
/// DTO di output
/// </summary>
public class ListaChiamateInCorsoMarkerResult
{
/// <summary>
/// La sintesi delle richieste di assistenza
/// </summary>
public IEnumerable<ChiamateInCorso> ListaChiamateInCorsoMarker
{ get; set; }
}
}
| vvfosprojects/sovvf | src/backend/SO115App.Models/Servizi/CQRS/Queries/GestioneSoccorso/Marker/ListaChiamateInCorso/ListaChiamateInCorsoMarkerResult.cs | C# | agpl-3.0 | 1,432 |
<?php
namespace Spec\Minds\Core\Pro;
use Minds\Common\Repository\Response;
use Minds\Core\Config;
use Minds\Core\Pro\Domain;
use Minds\Core\Pro\Repository;
use Minds\Core\Pro\Settings;
use Minds\Core\Pro\Manager as ProManager;
use Minds\Core\EntitiesBuilder;
use Minds\Entities\User;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class DomainSpec extends ObjectBehavior
{
/** @var Config */
protected $config;
/** @var Repository */
protected $repository;
/** @var EntitiesBuilder */
protected $entitiesBuilder;
/** @var ProManager */
protected $proManager;
public function let(
Config $config,
Repository $repository,
EntitiesBuilder $entitiesBuilder,
ProManager $proManager
) {
$this->config = $config;
$this->repository = $repository;
$this->entitiesBuilder = $entitiesBuilder;
$this->proManager = $proManager;
$this->beConstructedWith($config, $repository, $entitiesBuilder, $proManager);
$entitiesBuilder->single(Argument::any())
->willReturn(new User);
}
public function it_is_initializable()
{
$this->shouldHaveType(Domain::class);
}
public function it_should_lookup(
Response $getListResponse,
Settings $settings
) {
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this->repository->getList([
'domain' => 'phpspec-test.com'
])
->shouldBeCalled()
->willReturn($getListResponse);
$getListResponse->first()
->shouldBeCalled()
->willReturn($settings);
$this->proManager->setUser(Argument::any())
->willReturn($this->proManager);
$this->proManager->hydrate($settings)
->willReturn($settings);
$this
->lookup('phpspec-test.com')
->shouldReturn($settings);
}
public function it_should_not_lookup_if_root_domain()
{
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this->repository->getList(Argument::cetera())
->shouldNotBeCalled();
$this
->lookup('phpspec.test')
->shouldReturn(null);
}
public function it_should_check_if_domain_is_unavailable(
Response $getListResponse,
Settings $settings
) {
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this->repository->getList([
'domain' => 'phpspec-test.com'
])
->shouldBeCalled()
->willReturn($getListResponse);
$getListResponse->first()
->shouldBeCalled()
->willReturn($settings);
$settings->getUserGuid()
->shouldBeCalled()
->willReturn(1001);
$this->proManager->setUser(Argument::any())
->willReturn($this->proManager);
$this->proManager->hydrate($settings)
->willReturn($settings);
$this
->isAvailable('phpspec-test.com', 1000)
->shouldReturn(false);
}
public function it_should_check_if_domain_is_available_if_same_owner(
Response $getListResponse,
Settings $settings
) {
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this->repository->getList([
'domain' => 'phpspec-test.com'
])
->shouldBeCalled()
->willReturn($getListResponse);
$getListResponse->first()
->shouldBeCalled()
->willReturn($settings);
$settings->getUserGuid()
->shouldBeCalled()
->willReturn(1000);
$this->proManager->setUser(Argument::any())
->willReturn($this->proManager);
$this->proManager->hydrate($settings)
->willReturn($settings);
$this
->isAvailable('phpspec-test.com', 1000)
->shouldReturn(true);
}
public function it_should_check_if_domain_is_available(
Response $getListResponse
) {
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this->repository->getList([
'domain' => 'phpspec-test.com'
])
->shouldBeCalled()
->willReturn($getListResponse);
$getListResponse->first()
->shouldBeCalled()
->willReturn(null);
$this
->isAvailable('phpspec-test.com', 1000)
->shouldReturn(true);
}
public function it_should_return_as_unavailable_if_root_domain()
{
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this->repository->getList(Argument::cetera())
->shouldNotBeCalled();
$this
->isAvailable('phpspec.test', 1000)
->shouldReturn(false);
}
public function it_should_check_if_root_domain()
{
$this->config->get('pro')
->shouldBeCalled()
->willReturn([
'root_domains' => ['phpspec.test']
]);
$this
->isRoot('phpspec.test')
->shouldReturn(true);
$this
->isRoot('not-a-root-phpspec.test')
->shouldReturn(false);
}
public function it_should_get_icon(
Settings $settings,
User $owner
) {
$owner->getIconURL(Argument::type('string'))
->shouldBeCalled()
->willReturn('http://phpspec/icon');
$this
->getIcon($settings, $owner)
->shouldReturn('http://phpspec/icon');
}
}
| Minds/engine | Spec/Core/Pro/DomainSpec.php | PHP | agpl-3.0 | 6,166 |
/*
* Copyright 2012 McEvoy Software Ltd.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* 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 io.milton.http.json;
import io.milton.http.Auth;
import io.milton.http.FileItem;
import io.milton.http.Range;
import io.milton.http.Request;
import io.milton.http.Request.Method;
import io.milton.http.Response.Status;
import io.milton.http.exceptions.BadRequestException;
import io.milton.http.exceptions.ConflictException;
import io.milton.http.exceptions.NotAuthorizedException;
import io.milton.http.webdav.PropFindResponse;
import io.milton.http.webdav.PropFindResponse.NameAndError;
import io.milton.resource.PostableResource;
import io.milton.resource.Resource;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import net.sf.json.JsonConfig;
import net.sf.json.util.CycleDetectionStrategy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropPatchJsonResource extends JsonResource implements PostableResource {
private static final Logger log = LoggerFactory.getLogger(PropPatchJsonResource.class);
private final Resource wrappedResource;
private final JsonPropPatchHandler patchHandler;
private final String encodedUrl;
private PropFindResponse resp;
public PropPatchJsonResource( Resource wrappedResource, JsonPropPatchHandler patchHandler, String encodedUrl ) {
super( wrappedResource, Request.Method.PROPPATCH.code, null );
this.wrappedResource = wrappedResource;
this.encodedUrl = encodedUrl;
this.patchHandler = patchHandler;
}
public void sendContent( OutputStream out, Range range, Map<String, String> params, String contentType ) throws IOException, NotAuthorizedException {
log.debug( "sendContent");
JsonConfig cfg = new JsonConfig();
cfg.setIgnoreTransientFields( true );
cfg.setCycleDetectionStrategy( CycleDetectionStrategy.LENIENT );
List<FieldError> errors = new ArrayList<FieldError>();
if( resp != null && resp.getErrorProperties() != null ) {
log.debug( "error props: " + resp.getErrorProperties().size());
for( Status stat : resp.getErrorProperties().keySet() ) {
List<NameAndError> props = resp.getErrorProperties().get( stat );
for( NameAndError ne : props ) {
errors.add( new FieldError( ne.getName().getLocalPart(), ne.getError(), stat.code ) );
}
}
}
log.debug( "errors size: " + errors.size());
FieldError[] arr = new FieldError[errors.size()];
arr = errors.toArray( arr );
Writer writer = new PrintWriter( out );
JSON json = JSONSerializer.toJSON( arr, cfg );
json.write( writer );
writer.flush();
}
@Override
public boolean authorise( Request request, Method method, Auth auth ) {
// leave authorisation to the proppatch processing
return true;
}
public String processForm( Map<String, String> parameters, Map<String, FileItem> files ) throws BadRequestException, NotAuthorizedException, ConflictException {
resp = patchHandler.process( wrappedResource, encodedUrl, parameters );
return null;
}
@Override
public Method applicableMethod() {
return Method.PROPPATCH;
}
public class FieldError {
private String name;
private String description;
private int code;
public FieldError( String name, String description, int code ) {
this.name = name;
this.description = description;
this.code = code;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription( String description ) {
this.description = description;
}
public int getCode() {
return code;
}
public void setCode( int code ) {
this.code = code;
}
}
}
| FullMetal210/milton2 | milton-server/src/main/java/io/milton/http/json/PropPatchJsonResource.java | Java | agpl-3.0 | 5,053 |
import io
import pytest
import databot
import pandas as pd
from databot.db.utils import Row
from databot.exporters.utils import flatten_nested_lists, flatten_nested_dicts, get_level_keys, flatten, sort_fields
from databot.exporters import jsonl
from databot.exporters import pandas
@pytest.fixture
def data():
return {
'a': 1,
'b': 2,
'c': {
'x': 1,
'y': 2,
'z': ['foo', 'bar', 'baz'],
}
}
def test_flatten_rows_update(data):
rows = [
Row(key=1, value={'text': 'abc'}),
Row(key=1, value={'text': 'abcde'}),
]
update = {'size': databot.this.value.text.apply(len)}
assert list(flatten(rows, include=['key', 'size'], update=update)) == [
('key', 'size'),
(1, 3),
(1, 5),
]
def test_flattenjson():
rows = [
{'key': 1, 'value': {'foo': 'bar', 'events': [
{'name': 'Event 1', 'date': '2017-01-01', 'people': ['a', 'b']},
{'name': 'Event 2', 'date': '2017-01-02', 'people': ['a']},
]}},
{'key': 2, 'value': {'foo': 'baz', 'events': [
{'name': 'Event 3', 'date': '2017-01-03', 'people': ['x', 'y']},
{'name': 'Event 4', 'date': '2017-01-04', 'people': ['z']},
]}},
]
assert list(map(dict, flatten_nested_lists(rows, include={('key',), ('value', 'events', 'date')}))) == [
{('key',): 1, ('value', 'events', 'date'): '2017-01-01'},
{('key',): 1, ('value', 'events', 'date'): '2017-01-02'},
{('key',): 2, ('value', 'events', 'date'): '2017-01-03'},
{('key',): 2, ('value', 'events', 'date'): '2017-01-04'},
]
assert list(map(dict, flatten_nested_lists(rows, include={('key',), ('value', 'events', 'people')}))) == [
{('key',): 1, ('value', 'events', 'people'): 'a'},
{('key',): 1, ('value', 'events', 'people'): 'b'},
{('key',): 1, ('value', 'events', 'people'): 'a'},
{('key',): 2, ('value', 'events', 'people'): 'x'},
{('key',): 2, ('value', 'events', 'people'): 'y'},
{('key',): 2, ('value', 'events', 'people'): 'z'},
]
assert [{v for k, v in x} for x in flatten_nested_lists(rows, include=[('key',), ('value',)])] == [
{1, 'bar', '2017-01-01', 'Event 1', 'a'},
{1, 'bar', '2017-01-01', 'Event 1', 'b'},
{1, 'bar', '2017-01-02', 'Event 2', 'a'},
{2, 'baz', '2017-01-03', 'Event 3', 'x'},
{2, 'baz', '2017-01-03', 'Event 3', 'y'},
{2, 'baz', '2017-01-04', 'Event 4', 'z'},
]
assert [{v for k, v in x} for x in flatten_nested_lists(rows)] == [
{1, 'bar', '2017-01-01', 'Event 1', 'a'},
{1, 'bar', '2017-01-01', 'Event 1', 'b'},
{1, 'bar', '2017-01-02', 'Event 2', 'a'},
{2, 'baz', '2017-01-03', 'Event 3', 'x'},
{2, 'baz', '2017-01-03', 'Event 3', 'y'},
{2, 'baz', '2017-01-04', 'Event 4', 'z'},
]
def test_flatten_nested_dicts():
assert set(flatten_nested_dicts({'a': 1, 'b': 2, 'c': 3})) == {
(('a',), 1),
(('b',), 2),
(('c',), 3),
}
def test_flatten_nested_dicts_include():
assert set(flatten_nested_dicts({'a': 1, 'b': 2, 'c': 3}, include=[('b',), ('a',), ('c',)])) == {
(('b',), 2),
(('a',), 1),
(('c',), 3),
}
def test_get_level_keys():
assert list(get_level_keys(keys=['c', 'b', 'a'], field=(), include=())) == ['a', 'b', 'c']
assert list(get_level_keys(keys=['c', 'b', 'a'], field=(), include=[('b',), ('a',), ('c',)])) == ['b', 'a', 'c']
assert list(get_level_keys(keys=['c', 'b', 'a'], field=('x',), include=())) == ['a', 'b', 'c']
assert list(get_level_keys(keys=['c', 'b', 'a'], field=('x',), include=[('x', 'b',), ('x', 'c',)])) == ['b', 'c']
assert list(get_level_keys(keys=['c', 'b', 'a'], field=(), include=[('b',), ('x',)])) == ['b']
assert list(get_level_keys(keys=['c', 'b', 'a'], field=('x', 'y'), include=[('x',)])) == ['a', 'b', 'c']
def test_flatten():
rows = [
Row(key=1, value={'foo': 'bar', 'events': [
{'name': 'Event 1', 'date': '2017-01-01', 'people': ['a', 'b']},
{'name': 'Event 2', 'date': '2017-01-02', 'people': ['a']},
]}),
Row(key=2, value={'foo': 'baz', 'events': [
{'name': 'Event 3', 'date': '2017-01-03', 'people': ['x', 'y']},
{'name': 'Event 4', 'date': '2017-01-04', 'people': ['z']},
]}),
]
assert list(flatten(rows)) == [
('events.date', 'events.name', 'events.people', 'foo', 'key'),
('2017-01-01', 'Event 1', 'a', 'bar', 1),
('2017-01-01', 'Event 1', 'b', 'bar', 1),
('2017-01-02', 'Event 2', 'a', 'bar', 1),
('2017-01-03', 'Event 3', 'x', 'baz', 2),
('2017-01-03', 'Event 3', 'y', 'baz', 2),
('2017-01-04', 'Event 4', 'z', 'baz', 2),
]
assert list(flatten(rows, include=('key', 'foo', 'events.people'))) == [
('key', 'foo', 'events.people'),
(1, 'bar', 'a'),
(1, 'bar', 'b'),
(1, 'bar', 'a'),
(2, 'baz', 'x'),
(2, 'baz', 'y'),
(2, 'baz', 'z'),
]
assert list(flatten(rows, include=('key', 'foo'))) == [
('key', 'foo'),
(1, 'bar'),
(2, 'baz'),
]
def test_sort_fields():
def _(fields, include):
fields = [tuple(x.split('.')) for x in fields]
include = [tuple(x.split('.')) for x in include]
return ['.'.join(x) for x in sort_fields(fields, include)]
assert _(['c', 'b', 'a'], []) == ['a', 'b', 'c']
assert _(['c', 'b', 'a'], ['a', 'c']) == ['a', 'c']
assert _(['x.c', 'x.b', 'x.a'], ['x']) == ['x.a', 'x.b', 'x.c']
assert _(['z', 'x.b', 'x.a'], ['x', 'z']) == ['x.a', 'x.b', 'z']
def test_flatten_rows_update_without_include(data):
rows = [
Row(key=1, value={'text': 'abc'}),
Row(key=1, value={'text': 'abcde'}),
]
update = {'size': databot.this.value.text.apply(len)}
assert list(flatten(rows, update=update)) == [
('key', 'size', 'text'),
(1, 3, 'abc'),
(1, 5, 'abcde'),
]
def test_flatten_rows_callable_update(data):
rows = [
Row(key=1, value={'text': 'abc'}),
Row(key=1, value={'text': 'abcde'}),
]
def update(row):
return {'size': len(row.value['text'])}
assert list(flatten(rows, update=update)) == [
('size',),
(3,),
(5,),
]
def test_flatten_rows_include(data):
rows = [
Row(key=1, value={'a': 1}),
Row(key=2, value={'b': 2}),
]
assert list(flatten(rows, include=['a', 'b'])) == [
('a', 'b'),
(1, None),
(None, 2),
]
def test_flatten_rows_include_value(data):
rows = [
Row(key=1, value='a'),
Row(key=2, value='b'),
]
assert list(flatten(rows, include=['key', 'value'])) == [
('key', 'value'),
(1, 'a'),
(2, 'b'),
]
def test_flatten_rows_value(data):
rows = [
Row(key=1, value='a'),
Row(key=2, value='b'),
]
assert list(flatten(rows)) == [
('key', 'value'),
(1, 'a'),
(2, 'b'),
]
def test_flatten_int_key(data):
rows = [
Row(key=1, value={'year': {2000: 1, 2001: 2}}),
Row(key=2, value={'year': {2000: 3, 2001: 4}}),
]
assert list(flatten(rows)) == [
('key', 'year.2000', 'year.2001'),
(1, 1, 2),
(2, 3, 4),
]
def test_flatten_list(data):
rows = [
Row(key=1, value={'events': [
{'name': 'Event 1', 'date': '2017-01-01'},
{'name': 'Event 2', 'date': '2017-02-01'},
]}),
Row(key=2, value={'events': [
{'name': 'Event 3', 'date': '2017-03-01'},
{'name': 'Event 4', 'date': '2017-04-01'},
]}),
]
assert list(flatten(rows)) == [
('events.date', 'events.name', 'key'),
('2017-01-01', 'Event 1', 1),
('2017-02-01', 'Event 2', 1),
('2017-03-01', 'Event 3', 2),
('2017-04-01', 'Event 4', 2),
]
def test_jsonl(bot):
pipe = bot.define('p1').append([('1', 'a'), ('2', 'b')])
stream = io.StringIO()
jsonl.export(stream, pipe.rows())
assert stream.getvalue().splitlines() == [
'{"key": "1", "value": "a"}',
'{"key": "2", "value": "b"}',
]
def test_jsonl_dict(bot):
pipe = bot.define('p1').append([('1', {'a': 2}), ('2', {'b': 3})])
stream = io.StringIO()
jsonl.export(stream, pipe.rows())
assert stream.getvalue().splitlines() == [
'{"key": "1", "a": 2}',
'{"key": "2", "b": 3}',
]
def test_pandas_rows_to_dataframe_items():
rows = [
[1, 'a', 'x'],
[2, 'b', 'y'],
]
assert list(pandas.rows_to_dataframe_items(rows, 0)) == [
(1, ['a', 'x']),
(2, ['b', 'y'])
]
assert list(pandas.rows_to_dataframe_items(rows, 2)) == [
('x', [1, 'a']),
('y', [2, 'b'])
]
def test_pandas(bot):
pipe = bot.define('p1').append([
(1, {'a': 10}),
(2, {'a': 20}),
])
assert [dict(x._asdict()) for x in pipe.export(pd).itertuples()] == [
{'Index': 1, 'a': 10.0},
{'Index': 2, 'a': 20.0},
]
| sirex/databot | tests/test_export.py | Python | agpl-3.0 | 9,232 |
<?php
/**
* Ask the server to silently close the connection.
*
* @author Ivan Shumkov
* @package Rediska
* @subpackage Commands
* @version 0.5.10
* @link http://rediska.geometria-lab.net
* @license http://www.opensource.org/licenses/bsd-license.php
*/
class Rediska_Command_Quit extends Rediska_Command_Abstract
{
protected $_affectedConnections = array();
/**
* Create command
*
* @return Rediska_Connection_Exec
*/
public function create()
{
$command = array('QUIT');
$this->_affectedConnections = $this->_rediska->getConnections();
$commands = array();
foreach($this->_affectedConnections as $connection) {
$commands[] = new Rediska_Connection_Exec($connection, $command);
}
return $commands;
}
public function write()
{
parent::write();
foreach($this->_affectedConnections as $connection) {
$connection->disconnect();
}
return true;
}
public function read()
{
return true;
}
} | laclasse-com/php-cas-server | lib/Rediska/Command/Quit.php | PHP | agpl-3.0 | 1,076 |
/*
* Asqatasun - Automated webpage assessment
* Copyright (C) 2008-2020 Asqatasun.org
*
* This file is part of Asqatasun.
*
* Asqatasun is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact us by mail: asqatasun AT asqatasun DOT org
*/
package org.asqatasun.entity.audit;
import java.util.Date;
import org.asqatasun.entity.Entity;
/**
*
* @author jkowalczyk
*/
public interface Content extends Entity {
/**
*
* @return the audit
*/
Audit getAudit();
/**
*
* @return the date of loading
*/
Date getDateOfLoading();
/**
*
* @return the URI
*/
String getURI();
/**
*
* @return the http Status Code
*/
int getHttpStatusCode();
/**
*
* @param audit
* the audit to set
*/
void setAudit(Audit audit);
/**
*
* @param dateOfLoading
* the date of loading to set
*/
void setDateOfLoading(Date dateOfLoading);
/**
*
* @param uri
* the URI to set
*/
void setURI(String uri);
/**
*
* @param httpStatusCode
* the Http Status Code when fetched the content
*/
void setHttpStatusCode(int httpStatusCode);
}
| Asqatasun/Asqatasun | engine/asqatasun-api/src/main/java/org/asqatasun/entity/audit/Content.java | Java | agpl-3.0 | 1,871 |
import request from './request'
export type UUID = string
export type DateTime = string
// for options see class names here: https://github.com/GothenburgBitFactory/taskwarrior/blob/01696a307b6785be973e3e6428e6ade2a3872c1e/src/columns/ColUDA.h#L36
export type TaskwarriorDataType = 'string' | 'numeric' | 'date' | 'duration'
export interface Task {
id: UUID
uuid: UUID // Same as 'id'
short_id: number
// status: for options see https://github.com/GothenburgBitFactory/taskwarrior/blob/6727d08da05b1090e0eda2270bc35d09a4528e87/src/Task.h#L71
status: 'pending' | 'completed' | 'deleted' | 'recurring' | 'waiting'
urgency: number
description: string
project?: string
due?: DateTime
entry: DateTime
modified: DateTime
start?: DateTime
end?: DateTime
wait?: DateTime
until?: DateTime
scheduled?: DateTime
depends?: UUID[]
blocks?: UUID[]
annotations?: string[]
tags?: string[]
imask?: string
udas: {
[key: string]: any | undefined
}
}
export const TaskFieldTypes: {[key: string]: TaskwarriorDataType} = {
id: 'string',
uuid: 'string',
short_id: 'string',
status: 'string',
urgency: 'numeric',
description: 'string',
project: 'string',
due: 'date',
entry: 'date',
modified: 'date',
start: 'date',
end: 'date',
wait: 'date',
until: 'date',
scheduled: 'date',
}
export const TaskArrayFieldTypes: {[key: string]: TaskwarriorDataType} = {
depends: 'string',
blocks: 'string',
annotations: 'string',
tags: 'string',
imask: 'string',
}
export interface TaskUpdate extends Partial<Task> {}
export async function getTasks(): Promise<Task[]> {
return request<Task[]>('GET', 'tasks', {})
}
export async function getTask(uuid: UUID): Promise<Task> {
return request<Task>('GET', `tasks/${uuid}`, {})
}
export async function createTask(task: TaskUpdate): Promise<Task> {
return request<Task>('POST', `tasks`, {
data: task,
})
}
export async function updateTask(task: Task): Promise<void> {
return request<void>('PUT', `tasks/${task.uuid}`, {
data: task,
})
}
export async function completeTask(uuid: UUID): Promise<void> {
return request<void>('DELETE', `tasks/${uuid}`, {})
}
export async function deleteTask(uuid: UUID): Promise<void> {
return request<void>('POST', `tasks/${uuid}/delete`, {})
}
export async function startTask(uuid: UUID): Promise<void> {
return request<void>('POST', `tasks/${uuid}/start`, {})
}
export async function stopTask(uuid: UUID): Promise<void> {
return request<void>('POST', `tasks/${uuid}/stop`, {})
}
| coddingtonbear/inthe.am | ui/src/clients/tasks.ts | TypeScript | agpl-3.0 | 2,548 |
############################################################################
#
# OSIS stands for Open Student Information System. It's an application
# designed to manage the core business of higher education institutions,
# such as universities, faculties, institutes and professional schools.
# The core business involves the administration of students, teachers,
# courses, programs and so on.
#
# Copyright (C) 2015-2018 Université catholique de Louvain (http://www.uclouvain.be)
#
# 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.
#
# A copy of this license - GNU General Public License - is available
# at the root of the source code of this program. If not,
# see http://www.gnu.org/licenses/.
#
############################################################################
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, render
from base.models.person import Person
from base.views.learning_units.common import get_learning_unit_identification_context
@login_required
def learning_unit_identification(request, learning_unit_year_id):
person = get_object_or_404(Person, user=request.user)
context = get_learning_unit_identification_context(learning_unit_year_id, person)
learning_unit_year = context['learning_unit_year']
if learning_unit_year.is_external():
template = "learning_unit/external/read.html"
permission = 'base.can_access_externallearningunityear'
else:
template = "learning_unit/identification.html"
permission = 'base.can_access_learningunit'
if not person.user.has_perm(permission):
raise PermissionDenied
return render(request, template, context)
| uclouvain/osis_louvain | base/views/learning_units/detail.py | Python | agpl-3.0 | 2,249 |