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 |
|---|---|---|---|---|---|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace ptConfigurator
{
public partial class frmConnect : Form
{
int iProgressCounter = 0;
public frmConnect()
{
InitializeComponent();
}
private void frmConnect_Load(object sender, EventArgs e)
{
label2.Text = "Entering Configuration";
label1.Text = "Connect the tracker to the selected serial port and power it on. Pressing the reset button may be necessary if it is not already in configuration mode.";
}
private void timer1_Tick(object sender, EventArgs e)
{
if (iProgressCounter < 100) iProgressCounter++;
progressBar1.Value = iProgressCounter;
}
private void label1_Click(object sender, EventArgs e)
{
}
}
} | custom-ds/arduinotrack-configurator | ptConfigurator/frmConnect.cs | C# | gpl-3.0 | 964 |
package Aula_4.Carro;
import java.awt.Graphics2D;
public class RodaAros extends Roda {
int n;
public RodaAros(int n, int raio, int xi, int yi) {
super(raio, xi, yi, 0);
this.n = n;
}
/*public RodaAros(int xi, int yi) {
super(17, xi, yi, 0);
n = 8;
raio = 17;
}*/
public void draw(Graphics2D g2d) {
double ang_inc = 2 * Math.PI / n;
for (int i = 0; i < n; i++) {
g2d.drawLine(xi, yi, (int) (Math.cos(ang_inicial) * raio + xi), (int) (Math.sin(ang_inicial) * raio + yi));
ang_inicial += ang_inc;
}
g2d.drawOval(xi - raio, yi - raio, raio * 2, raio * 2);
}
public void avanca(int npixel) {
xi -= npixel;
ang_inicial -= Math.toRadians(10);
}
public void recua(int npixel) {
xi += npixel;
ang_inicial += Math.toRadians(10);
}
} | mini890/2D-Computer-Graphics | src/Aula_4/Carro/RodaAros.java | Java | gpl-3.0 | 818 |
import { PushRequest } from './../protocol/push/PushRequest';
import { PushRequestNewObject } from './../protocol/push/PushRequestNewObject';
import { PushRequestObject } from './../protocol/push/PushRequestObject';
import { PushResponse } from './../protocol/push/PushResponse';
import { PushResponseNewObject } from './../protocol/push/PushResponseNewObject';
import { ResponseType } from './../protocol/ResponseType';
import { SyncResponse } from './../protocol/sync/SyncResponse';
import { INewSessionObject, ISessionObject, SessionObject } from './SessionObject';
import { IWorkspace } from './Workspace';
import { WorkspaceObject } from './WorkspaceObject';
export interface ISession {
hasChanges: boolean;
get(id: string): ISessionObject;
create(objectTypeName: string): ISessionObject;
delete(object: ISessionObject): void;
pushRequest(): PushRequest;
pushResponse(saveResponse: PushResponse): void;
reset(): void;
}
export class Session implements ISession {
private static idCounter = 0;
public hasChanges: boolean;
private sessionObjectById: { [id: string]: ISessionObject } = {};
private newSessionObjectById: { [id: string]: INewSessionObject } = {};
constructor(private workspace: IWorkspace) {
this.hasChanges = false;
}
public get(id: string): ISessionObject {
if (!id) {
return undefined;
}
let sessionObject: ISessionObject = this.sessionObjectById[id];
if (sessionObject === undefined) {
sessionObject = this.newSessionObjectById[id];
if (sessionObject === undefined) {
const workspaceObject: WorkspaceObject = this.workspace.get(id);
const constructor: any = this.workspace.constructorByName[
workspaceObject.objectType.name
];
sessionObject = new constructor();
sessionObject.session = this;
sessionObject.workspaceObject = workspaceObject;
sessionObject.objectType = workspaceObject.objectType;
this.sessionObjectById[sessionObject.id] = sessionObject;
}
}
return sessionObject;
}
public create(objectTypeName: string): ISessionObject {
const constructor: any = this.workspace.constructorByName[objectTypeName];
const newSessionObject: INewSessionObject = new constructor();
newSessionObject.session = this;
newSessionObject.objectType = this.workspace.metaPopulation.objectTypeByName[
objectTypeName
];
newSessionObject.newId = (--Session.idCounter).toString();
this.newSessionObjectById[newSessionObject.newId] = newSessionObject;
this.hasChanges = true;
return newSessionObject;
}
public delete(object: ISessionObject): void {
if (!object.isNew) {
throw new Error('Existing objects can not be deleted');
}
const newSessionObject = object as SessionObject;
const newId = newSessionObject.newId;
if (this.newSessionObjectById && this.newSessionObjectById.hasOwnProperty(newId)) {
Object.keys(this.newSessionObjectById).forEach((key: string) =>
(this.newSessionObjectById[key] as SessionObject).onDelete(newSessionObject),
);
if (this.sessionObjectById) {
Object.keys(this.sessionObjectById).forEach((key: string) =>
(this.sessionObjectById[key] as SessionObject).onDelete(newSessionObject),
);
}
newSessionObject.reset();
delete this.newSessionObjectById[newId];
}
}
public reset(): void {
if (this.newSessionObjectById) {
Object.keys(this.newSessionObjectById).forEach((key: string) =>
this.newSessionObjectById[key].reset(),
);
}
if (this.sessionObjectById) {
Object.keys(this.sessionObjectById).forEach((key: string) =>
this.sessionObjectById[key].reset(),
);
}
this.hasChanges = false;
}
public pushRequest(): PushRequest {
const data: PushRequest = new PushRequest();
data.newObjects = [];
data.objects = [];
if (this.newSessionObjectById) {
Object.keys(this.newSessionObjectById).forEach((key: string) => {
const newSessionObject: INewSessionObject = this.newSessionObjectById[
key
];
const objectData: PushRequestNewObject = newSessionObject.saveNew();
if (objectData !== undefined) {
data.newObjects.push(objectData);
}
});
}
if (this.sessionObjectById) {
Object.keys(this.sessionObjectById).forEach((key: string) => {
const sessionObject: ISessionObject = this.sessionObjectById[key];
const objectData: PushRequestObject = sessionObject.save();
if (objectData !== undefined) {
data.objects.push(objectData);
}
});
}
return data;
}
public pushResponse(pushResponse: PushResponse): void {
if (pushResponse.newObjects) {
Object.keys(pushResponse.newObjects).forEach((key: string) => {
const pushResponseNewObject: PushResponseNewObject =
pushResponse.newObjects[key];
const newId: string = pushResponseNewObject.ni;
const id: string = pushResponseNewObject.i;
const newSessionObject: INewSessionObject = this.newSessionObjectById[
newId
];
const syncResponse: SyncResponse = {
hasErrors: false,
objects: [
{
i: id,
methods: [],
roles: [],
t: newSessionObject.objectType.name,
v: '',
},
],
responseType: ResponseType.Sync,
userSecurityHash: '#', // This should trigger a load on next check
};
delete this.newSessionObjectById[newId];
delete newSessionObject.newId;
this.workspace.sync(syncResponse);
const workspaceObject: WorkspaceObject = this.workspace.get(id);
newSessionObject.workspaceObject = workspaceObject;
this.sessionObjectById[id] = newSessionObject;
});
}
if (Object.getOwnPropertyNames(this.newSessionObjectById).length !== 0) {
throw new Error('Not all new objects received ids');
}
}
}
| Allors/allors | Platform/Workspace/Typescript/src/allors/framework/workspace/Session.ts | TypeScript | gpl-3.0 | 6,112 |
/*
Nodics - Enterprice Micro-Services Management Framework
Copyright (c) 2017 Nodics All rights reserved.
This software is the confidential and proprietary information of Nodics ("Confidential Information").
You shall not disclose such Confidential Information and shall use it only in accordance with the
terms of the license agreement you entered into with Nodics.
*/
const _ = require('lodash');
const RequireFromString = require('require-from-string');
module.exports = {
/**
* This function is used to initiate entity loader process. If there is any functionalities, required to be executed on entity loading.
* defined it that with Promise way
* @param {*} options
*/
init: function (options) {
return new Promise((resolve, reject) => {
resolve(true);
});
},
/**
* This function is used to finalize entity loader process. If there is any functionalities, required to be executed after entity loading.
* defined it that with Promise way
* @param {*} options
*/
postInit: function (options) {
return new Promise((resolve, reject) => {
resolve(true);
});
},
getClass: function (request) {
return new Promise((resolve, reject) => {
let className = request.className;
SERVICE.DefaultClassConfigurationService.get({
tenant: 'default',
query: {
code: className
}
}).then(success => {
let classDefinition = 'No data found for class: ' + className;
if (success.result && success.result.length > 0 && success.result[0].body) {
classDefinition = success.result[0].body.toString('utf8');
classDefinition = classDefinition.replaceAll('\n', '').replaceAll("\"", "");
}
resolve(classDefinition);
}).catch(error => {
reject(error);
});
});
},
getSnapshot: function (request) {
return new Promise((resolve, reject) => {
let className = request.className;
let type = request.type;
if (!type || !global[type]) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invlid type: ' + type));
} else if (!className || !global[type][className.toUpperCaseFirstChar()]) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invlid className: ' + className));
} else {
var cache = [];
let finalClassData = JSON.stringify(global[type][className.toUpperCaseFirstChar()], function (key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
if (typeof value === 'function') {
return value.toString();
} else if (typeof value === 'string') {
return '\'' + value + '\'';
} else {
return value;
}
}, 4);
resolve('module.exports = ' + finalClassData.replace(/\\n/gm, '\n').replace(/\\t/gm, '').replaceAll("\"", "") + ';');
}
});
},
updateClass: function (request) {
return new Promise((resolve, reject) => {
let className = request.className;
let type = request.type;
this.finalizeClass(className, request.body).then(success => {
this.save({
tenant: 'default',
model: {
code: className,
type: type,
active: true,
body: success
}
}).then(success => {
resolve(success);
}).catch(error => {
reject(error);
});
}).catch(error => {
reject(error);
});
});
},
finalizeClass: function (className, body) {
let byteBody = null;
return new Promise((resolve, reject) => {
SERVICE.DefaultClassConfigurationService.get({
tenant: 'default',
query: {
code: className
}
}).then(success => {
if (success.result && success.result.length > 0 && success.result[0].body) {
let currentClassBody = RequireFromString('module.exports = ' +
body.replace(/\\n/gm, '\n').replaceAll("\"", "") + ';');
let mergedClass = _.merge(RequireFromString(success.result[0].body.toString('utf8')), currentClassBody);
let finalClassData = JSON.stringify(mergedClass, function (key, value) {
if (typeof value === 'function') {
return value.toString();
} else if (typeof value === 'string') {
return '\'' + value + '\'';
} else {
return value;
}
}, 4);
finalClassData = 'module.exports = ' + finalClassData.replace(/\\n/gm, '\n').replace(/\\t/gm, '').replaceAll("\"", "") + ';';
byteBody = Buffer.from(finalClassData, 'utf8');
} else {
byteBody = Buffer.from('module.exports = ' + body + ';', 'utf8');
}
resolve(byteBody);
}).catch(error => {
reject(error);
});
});
},
classUpdateEventHandler: function (request) {
return new Promise((resolve, reject) => {
if (!request.event.data.models || request.event.data.models.length <= 0) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'ClassName can not be null or empty'));
}
this.get({
tenant: 'default',
query: {
code: {
$in: request.event.data.models
}
}
}).then(success => {
if (success.result && success.result.length > 0) {
success.result.forEach(classData => {
let classObject = RequireFromString(classData.body.toString('utf8'));
if (global[classData.type]) {
if (global[classData.type][classData.code.toUpperCaseFirstChar()]) {
global[classData.type][classData.code.toUpperCaseFirstChar()] = _.merge(
GLOBAL[classData.type][classData.code.toUpperCaseFirstChar()],
classObject);
} else {
global[classData.type][classData.code.toUpperCaseFirstChar()] = classObject;
}
this.LOG.debug('Successfully updated class: ' + classData.code);
resolve('Successfully updated class: ' + classData.code);
} else {
this.LOG.error('Invalid type: ' + classData.code);
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invalid type: ' + classData.type));
}
});
} else {
this.LOG.error('Could not found any data for class name ' + request.event.data.models);
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Could not found any data for class name ' + request.event.data.models));
}
}).catch(error => {
reject(error);
});
});
},
loadPersistedClasses: function () {
return new Promise((resolve, reject) => {
this.get({
tenant: 'default'
}).then(success => {
try {
if (success.result && success.result.length > 0) {
success.result.forEach(classModel => {
let classBody = RequireFromString(classModel.body.toString('utf8'));
if (global[classModel.type][classModel.code.toUpperCaseFirstChar()]) {
global[classModel.type][classModel.code.toUpperCaseFirstChar()] = _.merge(
global[classModel.type][classModel.code.toUpperCaseFirstChar()], classBody
);
} else {
global[classModel.type][classModel.code.toUpperCaseFirstChar()] = classBody;
}
});
}
resolve(true);
} catch (error) {
reject(error);
}
}).catch(error => {
reject(error);
});
});
},
executeClass: function (request) {
return new Promise((resolve, reject) => {
if (!request.body.className) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'ClassName can not be null or empty'));
} else if (!request.body.type || !GLOBAL[request.body.type]) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Invalid type: ' + request.body.type + ' it should not be null, empty or wrong value'));
} else if (!GLOBAL[request.body.type][request.body.className.toUpperCaseFirstChar()]) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Class: ' + request.body.className + ' not exist, please validate your request'));
} else if (!request.body.operationName || !GLOBAL[request.body.type][request.body.className.toUpperCaseFirstChar()][request.body.operationName]) {
reject(new CLASSES.NodicsError('ERR_SYS_00001', 'Operation name: ' + request.body.operationName + ' can not be null or empty'));
} else {
let entityString = request.body.type + '.' + request.body.className.toUpperCaseFirstChar() + '.' + request.body.operationName;
entityString = entityString + '(';
if (request.body.params && request.body.params.length > 0) {
for (let counter = 0; counter < request.body.params.length; counter++) {
entityString = entityString + 'request.body.params[' + counter + ']';
if (counter <= request.body.params.length - 1) {
entityString = entityString + ',';
}
}
}
entityString = entityString + ')';
if (request.body.isReturnPromise) {
eval(entityString).then(success => {
resolve(success);
}).catch(error => {
reject(error);
});
} else {
try {
let response = eval(entityString);
if (!response) response = 'void';
resolve({
message: 'Successfully executed operation: ' + request.body.operationName + ' from class: ' + request.body.className,
response: response
});
} catch (error) {
reject(new CLASSES.NodicsError(error, null, 'ERR_SYS_00000'));
}
}
}
});
}
}; | Nodics/nodics | gFramework/nDynamo/src/service/class/defaultClassConfigurationService.js | JavaScript | gpl-3.0 | 11,955 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.camera.stress;
import com.android.camera.CameraActivity;
import android.app.Instrumentation;
import android.content.Intent;
import android.os.Environment;
import android.provider.MediaStore;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
import android.view.KeyEvent;
import java.io.BufferedWriter;
import java.io.FileWriter;
/**
* Junit / Instrumentation test case for camera test
*
*/
public class CameraLatency extends ActivityInstrumentationTestCase2 <CameraActivity> {
private String TAG = "CameraLatency";
private static final int TOTAL_NUMBER_OF_IMAGECAPTURE = 20;
private static final long WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN = 4000;
private static final String CAMERA_TEST_OUTPUT_FILE =
Environment.getExternalStorageDirectory().toString() + "/mediaStressOut.txt";
private long mTotalAutoFocusTime;
private long mTotalShutterLag;
private long mTotalShutterToPictureDisplayedTime;
private long mTotalPictureDisplayedToJpegCallbackTime;
private long mTotalJpegCallbackFinishTime;
private long mTotalFirstPreviewTime;
private long mAvgAutoFocusTime;
private long mAvgShutterLag = mTotalShutterLag;
private long mAvgShutterToPictureDisplayedTime;
private long mAvgPictureDisplayedToJpegCallbackTime;
private long mAvgJpegCallbackFinishTime;
private long mAvgFirstPreviewTime;
public CameraLatency() {
super(CameraActivity.class);
}
@Override
protected void setUp() throws Exception {
// Make sure camera starts with still picture capturing mode
Intent intent = new Intent(MediaStore.INTENT_ACTION_STILL_IMAGE_CAMERA);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(getInstrumentation().getTargetContext(),
CameraActivity.class);
setActivityIntent(intent);
getActivity();
super.setUp();
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
public void testImageCapture() {
Log.v(TAG, "start testImageCapture test");
Instrumentation inst = getInstrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_DOWN);
try {
for (int i = 0; i < TOTAL_NUMBER_OF_IMAGECAPTURE; i++) {
Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_DPAD_CENTER);
Thread.sleep(WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
//skip the first measurement
if (i != 0) {
CameraActivity c = getActivity();
// if any of the latency var accessor methods return -1 then the
// camera is set to a different module other than PhotoModule so
// skip the shot and try again
if (c.getAutoFocusTime() != -1) {
mTotalAutoFocusTime += c.getAutoFocusTime();
mTotalShutterLag += c.getShutterLag();
mTotalShutterToPictureDisplayedTime +=
c.getShutterToPictureDisplayedTime();
mTotalPictureDisplayedToJpegCallbackTime +=
c.getPictureDisplayedToJpegCallbackTime();
mTotalJpegCallbackFinishTime += c.getJpegCallbackFinishTime();
mTotalFirstPreviewTime += c.getFirstPreviewTime();
}
else {
i--;
continue;
}
}
}
} catch (Exception e) {
Log.v(TAG, "Got exception", e);
}
//ToDO: yslau
//1) Need to get the baseline from the cupcake so that we can add the
//failure condition of the camera latency.
//2) Only count those number with succesful capture. Set the timer to invalid
//before capture and ignore them if the value is invalid
int numberofRun = TOTAL_NUMBER_OF_IMAGECAPTURE - 1;
mAvgAutoFocusTime = mTotalAutoFocusTime / numberofRun;
mAvgShutterLag = mTotalShutterLag / numberofRun;
mAvgShutterToPictureDisplayedTime =
mTotalShutterToPictureDisplayedTime / numberofRun;
mAvgPictureDisplayedToJpegCallbackTime =
mTotalPictureDisplayedToJpegCallbackTime / numberofRun;
mAvgJpegCallbackFinishTime =
mTotalJpegCallbackFinishTime / numberofRun;
mAvgFirstPreviewTime =
mTotalFirstPreviewTime / numberofRun;
try {
FileWriter fstream = null;
fstream = new FileWriter(CAMERA_TEST_OUTPUT_FILE, true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Camera Latency : \n");
out.write("Number of loop: " + TOTAL_NUMBER_OF_IMAGECAPTURE + "\n");
out.write("Avg AutoFocus = " + mAvgAutoFocusTime + "\n");
out.write("Avg mShutterLag = " + mAvgShutterLag + "\n");
out.write("Avg mShutterToPictureDisplayedTime = "
+ mAvgShutterToPictureDisplayedTime + "\n");
out.write("Avg mPictureDisplayedToJpegCallbackTime = "
+ mAvgPictureDisplayedToJpegCallbackTime + "\n");
out.write("Avg mJpegCallbackFinishTime = " +
mAvgJpegCallbackFinishTime + "\n");
out.write("Avg FirstPreviewTime = " +
mAvgFirstPreviewTime + "\n");
out.close();
fstream.close();
} catch (Exception e) {
fail("Camera Latency write output to file");
}
Log.v(TAG, "The Image capture wait time = " +
WAIT_FOR_IMAGE_CAPTURE_TO_BE_TAKEN);
Log.v(TAG, "Avg AutoFocus = " + mAvgAutoFocusTime);
Log.v(TAG, "Avg mShutterLag = " + mAvgShutterLag);
Log.v(TAG, "Avg mShutterToPictureDisplayedTime = "
+ mAvgShutterToPictureDisplayedTime);
Log.v(TAG, "Avg mPictureDisplayedToJpegCallbackTime = "
+ mAvgPictureDisplayedToJpegCallbackTime);
Log.v(TAG, "Avg mJpegCallbackFinishTime = " + mAvgJpegCallbackFinishTime);
Log.v(TAG, "Avg FirstPreviewTime = " + mAvgFirstPreviewTime);
}
}
| s20121035/rk3288_android5.1_repo | packages/apps/Camera2/tests/src/com/android/camera/stress/CameraLatency.java | Java | gpl-3.0 | 7,032 |
#! /usr/bin/python
import sys
sys.path.append('../')
from toolbox.hreaders import token_readers as reader
from toolbox.hreducers import list_reducer as reducer
SOLO_FACTURA = False
def reduction(x,y):
v1 = x.split(',')
v2 = y.split(',')
r = x if int(v1[1])>=int(v2[1]) else y
return r
_reader = reader.Token_reader("\t",1)
_reducer = reducer.List_reducer(reduction) #x: previous reduction result, y: next element
if SOLO_FACTURA:
for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(V.split(',')[0],V.split(',')[1])
V = _reducer.out.split(',')
print '{}\t{}'.format(V[0],V[1])
else:
for line in sys.stdin:
key, value = _reader.read_all(line)
K,V = _reducer.reduce(key,value)
if K:
print '{}\t{}'.format(K,V)
print '{}\t{}'.format(key,V) | xavi783/u-tad | Modulo4/ejercicio3/reducer.py | Python | gpl-3.0 | 915 |
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011-2014 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM is free software: you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
OpenFOAM is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
\*---------------------------------------------------------------------------*/
#include "radialActuationDiskSource.H"
#include "geometricOneField.H"
#include "addToRunTimeSelectionTable.H"
// * * * * * * * * * * * * * * Static Data Members * * * * * * * * * * * * * //
namespace Foam
{
namespace fv
{
defineTypeNameAndDebug(radialActuationDiskSource, 0);
addToRunTimeSelectionTable
(
option,
radialActuationDiskSource,
dictionary
);
}
}
// * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * //
Foam::fv::radialActuationDiskSource::radialActuationDiskSource
(
const word& name,
const word& modelType,
const dictionary& dict,
const fvMesh& mesh
)
:
actuationDiskSource(name, modelType, dict, mesh),
radialCoeffs_(coeffs_.lookup("coeffs"))
{
Info<< " - creating radial actuation disk zone: " << name_ << endl;
}
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
void Foam::fv::radialActuationDiskSource::addSup
(
fvMatrix<vector>& eqn,
const label fieldI
)
{
const scalargpuField& cellsV = mesh_.V().getField();
vectorgpuField& Usource = eqn.source();
const vectorgpuField& U = eqn.psi();
if (V_ > VSMALL)
{
addRadialActuationDiskAxialInertialResistance
(
Usource,
cells_,
cellsV,
geometricOneField(),
U
);
}
}
void Foam::fv::radialActuationDiskSource::addSup
(
const volScalarField& rho,
fvMatrix<vector>& eqn,
const label fieldI
)
{
const scalargpuField& cellsV = mesh_.V();
vectorgpuField& Usource = eqn.source();
const vectorgpuField& U = eqn.psi();
if (V_ > VSMALL)
{
addRadialActuationDiskAxialInertialResistance
(
Usource,
cells_,
cellsV,
rho,
U
);
}
}
void Foam::fv::radialActuationDiskSource::writeData(Ostream& os) const
{
actuationDiskSource::writeData(os);
}
bool Foam::fv::radialActuationDiskSource::read(const dictionary& dict)
{
if (option::read(dict))
{
coeffs_.readIfPresent("diskDir", diskDir_);
coeffs_.readIfPresent("Cp", Cp_);
coeffs_.readIfPresent("Ct", Ct_);
coeffs_.readIfPresent("diskArea", diskArea_);
coeffs_.lookup("coeffs") >> radialCoeffs_;
return true;
}
else
{
return false;
}
}
// ************************************************************************* //
| Atizar/RapidCFD-dev | src/fvOptions/sources/derived/radialActuationDiskSource/radialActuationDiskSource.C | C++ | gpl-3.0 | 3,628 |
/*
* Kerbal Space App
*
* Copyright (C) 2014 Jim Pekarek (Amagi82)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amagi82.kerbalspaceapp;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OptionalDataException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Parcelable;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MissionPlanner extends Activity {
StableArrayAdapter mAdapter;
ListView mListView;
BackgroundContainer mBackgroundContainer;
ArrayList<MissionData> missionData = new ArrayList<MissionData>();
HashMap<Long, Integer> mItemIdTopMap = new HashMap<Long, Integer>();
boolean mSwiping = false, mItemPressed = false;
int totalDeltaV;
TextView tvTotalDeltaV;
private static final int SWIPE_DURATION = 250;
private static final int MOVE_DURATION = 150;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mission_planner);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowTitleEnabled(true);
getActionBar().setTitle(R.string.title_activity_mission_planner);
if (savedInstanceState == null) {
// Load saved missionData if available.
try {
FileInputStream inStream = new FileInputStream(Environment.getExternalStorageDirectory() + File.separator + "MissionData");
ObjectInputStream objectInStream = new ObjectInputStream(inStream);
int count = objectInStream.readInt();
for (int i = 0; i < count; i++)
missionData.add((MissionData) objectInStream.readObject());
objectInStream.close();
} catch (OptionalDataException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// if the list is empty, add the default planet
if (missionData.size() == 0) {
missionData = setFirstMissionData();
}
} else {
missionData = savedInstanceState.getParcelableArrayList("key");
}
mBackgroundContainer = (BackgroundContainer) findViewById(R.id.listViewBackground);
mListView = (ListView) findViewById(R.id.list);
tvTotalDeltaV = (TextView) findViewById(R.id.tvTotalDeltaV);
mAdapter = new StableArrayAdapter(this, missionData, mTouchListener);
// add the newDestination button as a footer below the listview
ImageView newDestination = new ImageView(this);
newDestination.setImageResource(R.drawable.ic_plus);
mListView.addFooterView(newDestination);
newDestination.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int possibleIconState = 0; // Lets MissionDestination know which icons it's allowed to use
if (missionData.size() < 1) {
possibleIconState = 1;
}
Intent intent = new Intent(MissionPlanner.this, MissionDestination.class);
intent.putExtra("possibleIconState", possibleIconState);
intent.putExtra("isNewItem", true); // Places the result as a new item in the listview
startActivityForResult(intent, 0);
}
});
mListView.setAdapter(mAdapter);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putParcelableArrayList("key", missionData);
super.onSaveInstanceState(outState);
}
@Override
public void onResume() {
super.onResume();
// This is in onResume so it refreshes deltaV when the user returns from adjusting settings
SharedPreferences prefs = getSharedPreferences("settings", MODE_PRIVATE);
int mClearanceValue = prefs.getInt("mClearanceValue", 1000);
int mMarginsValues = prefs.getInt("mMarginsValue", 10);
int mInclinationValues = prefs.getInt("mInclinationValue", 30);
float mMarginsValue = (float) mMarginsValues / 100 + 1;
float mInclinationValue = (float) mInclinationValues / 100;
// Update OrbitalMechanics with the new values
OrbitalMechanics.mClearanceValue = mClearanceValue;
OrbitalMechanics.mMarginsValue = mMarginsValue;
OrbitalMechanics.mInclinationValue = mInclinationValue;
refreshDeltaV();
}
// This method calculates the total delta V and displays it at the bottom
private void refreshDeltaV() {
totalDeltaV = 0;
for (int i = 0; i < missionData.size(); i++) {
int takeoffDeltaV = 0, transferDeltaV = 0, landingDeltaV = 0;
if (missionData.get(i).getIconStatus() == 3) {
takeoffDeltaV = OrbitalMechanics.getToOrbit(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(),
missionData.get(i).getOrbitAltitude());
}
if (missionData.get(i).getLanding()) {
landingDeltaV = OrbitalMechanics.getLandingDeltaV(missionData.get(i).getPlanetId(),
missionData.get(i).getTakeoffAltitude(), missionData.get(i).getOrbitAltitude());
}
if (missionData.get(i).getToOrbit() && missionData.get(i).getLanding()) {
takeoffDeltaV = OrbitalMechanics.getToOrbit(missionData.get(i).getPlanetId(), missionData.get(i).getTakeoffAltitude(),
missionData.get(i).getOrbitAltitude());
}
if (i != 0) {
transferDeltaV = OrbitalMechanics.getTransferDeltaV(missionData.get(i - 1).getPlanetId(), missionData.get(i).getPlanetId(),
missionData.get(i - 1).getOrbitAltitude(), missionData.get(i).getOrbitAltitude());
}
totalDeltaV = totalDeltaV + takeoffDeltaV + transferDeltaV + landingDeltaV;
}
String value = NumberFormat.getNumberInstance(Locale.getDefault()).format(totalDeltaV);
tvTotalDeltaV.setText(value + " m/s");
}
// Save missionData on pause
@Override
public void onPause() {
super.onPause();
try {
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "MissionData");
file.createNewFile();
FileOutputStream outStream = new FileOutputStream(file);
ObjectOutputStream objectOutStream = new ObjectOutputStream(outStream);
objectOutStream.writeInt(missionData.size());
for (MissionData r : missionData)
objectOutStream.writeObject(r);
objectOutStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// Handles touch events to fade/move dragged items as they are swiped out
private final View.OnTouchListener mTouchListener = new View.OnTouchListener() {
float mDownX;
private int mSwipeSlop = -1;
@Override
public boolean onTouch(final View v, MotionEvent event) {
if (mSwipeSlop < 0) {
mSwipeSlop = ViewConfiguration.get(MissionPlanner.this).getScaledTouchSlop();
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mItemPressed) {
// Multi-item swipes not handled
return false;
}
mItemPressed = true;
mDownX = event.getX();
break;
case MotionEvent.ACTION_CANCEL:
v.setAlpha(1);
v.setTranslationX(0);
mItemPressed = false;
break;
case MotionEvent.ACTION_MOVE: {
float x = event.getX() + v.getTranslationX();
float deltaX = x - mDownX;
float deltaXAbs = Math.abs(deltaX);
if (!mSwiping) {
if (deltaXAbs > mSwipeSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
mBackgroundContainer.showBackground(v.getTop(), v.getHeight());
}
}
if (mSwiping) {
v.setTranslationX((x - mDownX));
v.setAlpha(1 - deltaXAbs / v.getWidth());
}
}
break;
case MotionEvent.ACTION_UP: {
// User let go - figure out whether to animate the view out, or back into place
if (mSwiping) {
float x = event.getX() + v.getTranslationX();
float deltaX = x - mDownX;
float deltaXAbs = Math.abs(deltaX);
float fractionCovered = 0;
float endX;
float endAlpha;
final boolean remove;
if (deltaXAbs > v.getWidth() / 4) {
// Greater than a quarter of the width - animate it out
fractionCovered = deltaXAbs / v.getWidth();
endX = deltaX < 0 ? -v.getWidth() : v.getWidth();
endAlpha = 0;
remove = true;
} else {
// Not far enough - animate it back
fractionCovered = 1 - (deltaXAbs / v.getWidth());
endX = 0;
endAlpha = 1;
remove = false;
}
// Animate position and alpha of swiped item
long duration = (int) ((1 - fractionCovered) * SWIPE_DURATION);
mListView.setEnabled(false);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
v.animate().setDuration(duration).alpha(endAlpha).translationX(endX).setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
// Restore animated values
v.setAlpha(1);
v.setTranslationX(0);
if (remove) {
animateRemoval(mListView, v);
} else {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
}
});
} else {
v.animate().setDuration(duration).alpha(endAlpha).translationX(endX).withEndAction(new Runnable() {
@Override
public void run() {
// Restore animated values
v.setAlpha(1);
v.setTranslationX(0);
if (remove) {
animateRemoval(mListView, v);
} else {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
}
});
}
mItemPressed = false;
break;
}
}
// Item was clicked - allow user to edit list item
mItemPressed = false;
int position = mListView.getPositionForView(v);
int possibleIconState = 0;
if (position == 0) {
possibleIconState = 1;
}
Intent intent = new Intent(MissionPlanner.this, MissionDestination.class);
intent.putExtra("listItem", (Parcelable) missionData.get(position));
intent.putExtra("possibleIconState", possibleIconState);
intent.putExtra("isNewItem", false);
startActivityForResult(intent, position);
break;
default:
return false;
}
return true;
}
};
/**
* This method animates all other views in the ListView container (not including ignoreView) into their final positions. It is called
* after ignoreView has been removed from the adapter, but before layout has been run. The approach here is to figure out where
* everything is now, then allow layout to run, then figure out where everything is after layout, and then to run animations between all
* of those start/end positions.
*/
private void animateRemoval(final ListView listview, View viewToRemove) {
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
View child = listview.getChildAt(i);
if (child != viewToRemove) {
int position = firstVisiblePosition + i;
long itemId = mAdapter.getItemId(position);
mItemIdTopMap.put(itemId, child.getTop());
}
}
// Delete the item from the adapter
int position = mListView.getPositionForView(viewToRemove);
mAdapter.remove(mAdapter.getItem(position));
mAdapter.notifyDataSetChanged();
refreshDeltaV();
final ViewTreeObserver observer = listview.getViewTreeObserver();
observer.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
@Override
public boolean onPreDraw() {
observer.removeOnPreDrawListener(this);
boolean firstAnimation = true;
int firstVisiblePosition = listview.getFirstVisiblePosition();
for (int i = 0; i < listview.getChildCount(); ++i) {
final View child = listview.getChildAt(i);
int position = firstVisiblePosition + i;
long itemId = mAdapter.getItemId(position);
Integer startTop = mItemIdTopMap.get(itemId);
int top = child.getTop();
if (startTop != null) {
if (startTop != top) {
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
child.animate().setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
} else {
child.animate().withEndAction(new Runnable() {
@Override
public void run() {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
firstAnimation = false;
}
}
}
} else {
// Animate new views along with the others. The catch is that they did not
// exist in the start state, so we must calculate their starting position
// based on neighboring views.
int childHeight = child.getHeight() + listview.getDividerHeight();
startTop = top + (i > 0 ? childHeight : -childHeight);
int delta = startTop - top;
child.setTranslationY(delta);
child.animate().setDuration(MOVE_DURATION).translationY(0);
if (firstAnimation) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
child.animate().setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
} else {
child.animate().withEndAction(new Runnable() {
@Override
public void run() {
mBackgroundContainer.hideBackground();
mSwiping = false;
mListView.setEnabled(true);
}
});
firstAnimation = false;
}
}
}
}
mItemIdTopMap.clear();
return true;
}
});
}
// Inflate the menu; this adds items to the action bar if it is present.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mission_planner, menu);
return true;
}
// Action bar functionality
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
break;
case R.id.action_settings:
startActivity(new Intent(this, Settings.class));
break;
case R.id.action_delete:
missionData.clear();
setFirstMissionData();
mAdapter.notifyDataSetChanged();
refreshDeltaV();
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration config) {
super.onConfigurationChanged(config);
if (Settings.language == null) {
Settings.language = Locale.getDefault();
} else if (!config.locale.equals(Settings.language) && !Locale.getDefault().equals(Settings.language)) {
config.locale = Settings.language;
Locale.setDefault(config.locale);
getBaseContext().getResources().updateConfiguration(config, getResources().getDisplayMetrics());
recreate();
}
}
// Grab the parcel from MissionDestination, and either add a new listview item or update an existing one
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
MissionData result = data.getParcelableExtra("returnItem");
if (data.getBooleanExtra("isNewItem", true)) {
missionData.add(result);
} else {
missionData.set(requestCode, result);
}
mAdapter.notifyDataSetChanged();
refreshDeltaV();
}
if (resultCode == RESULT_CANCELED) {
}
}
// Adds Kerbin as the default departure planet
private ArrayList<MissionData> setFirstMissionData() {
MissionData a = new MissionData(4, false, 0, true, 100000, 3);
missionData.add(a);
return missionData;
}
} | Amagi82/KerbalSpaceApp | src/com/amagi82/kerbalspaceapp/MissionPlanner.java | Java | gpl-3.0 | 17,210 |
package alexiil.mods.load.json.subtypes;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import net.minecraft.util.ResourceLocation;
import alexiil.mods.load.baked.func.BakedFunction;
import alexiil.mods.load.baked.func.FunctionBaker;
import alexiil.mods.load.baked.insn.BakedInstruction;
import alexiil.mods.load.baked.render.BakedPanoramaRender;
import alexiil.mods.load.json.JsonImage;
public class JsonImagePanorama extends JsonImage {
public JsonImagePanorama(ResourceLocation resourceLocation, String image) {
super("", image, null, null, null, null, null, null, null);
this.resourceLocation = resourceLocation;
}
@Override
protected JsonImagePanorama actuallyConsolidate() {
return this;
}
@Override
protected BakedPanoramaRender actuallyBake(Map<String, BakedFunction<?>> functions) {
BakedFunction<Double> angle = FunctionBaker.bakeFunctionDouble("seconds * 40", functions);
return new BakedPanoramaRender(angle, image);
}
@Override
public List<BakedInstruction> bakeInstructions(Map<String, BakedFunction<?>> functions) {
return Collections.emptyList();
}
}
| Adaptivity/BetterLoadingScreen | src/main/java/alexiil/mods/load/json/subtypes/JsonImagePanorama.java | Java | gpl-3.0 | 1,195 |
#include "privatestorage.h"
#include <definitions/namespaces.h>
#include <definitions/stanzahandlerorders.h>
#include <utils/options.h>
#include <utils/stanza.h>
#include <utils/logger.h>
#define PRIVATE_STORAGE_TIMEOUT 30000
#define SHC_NOTIFYDATACHANGED "/message/x[@xmlns='" NS_VACUUM_PRIVATESTORAGE_UPDATE "']"
PrivateStorage::PrivateStorage()
{
FXmppStreamManager = NULL;
FPresenceManager = NULL;
FStanzaProcessor = NULL;
FSHINotifyDataChanged = -1;
}
PrivateStorage::~PrivateStorage()
{
}
//IPlugin
void PrivateStorage::pluginInfo(IPluginInfo *APluginInfo)
{
APluginInfo->name = tr("Private Storage");
APluginInfo->description = tr("Allows other modules to store arbitrary data on a server");
APluginInfo->version = "1.0";
APluginInfo->author = "Potapov S.A. aka Lion";
APluginInfo->homePage = "http://www.vacuum-im.org";
APluginInfo->dependences.append(STANZAPROCESSOR_UUID);
}
bool PrivateStorage::initConnections(IPluginManager *APluginManager, int &AInitOrder)
{
Q_UNUSED(AInitOrder);
IPlugin *plugin = APluginManager->pluginInterface("IXmppStreamManager").value(0,NULL);
if (plugin)
{
FXmppStreamManager = qobject_cast<IXmppStreamManager *>(plugin->instance());
if (FXmppStreamManager)
{
connect(FXmppStreamManager->instance(), SIGNAL(streamOpened(IXmppStream *)), SLOT(onXmppStreamOpened(IXmppStream *)));
connect(FXmppStreamManager->instance(), SIGNAL(streamAboutToClose(IXmppStream *)), SLOT(onXmppStreamAboutToClose(IXmppStream *)));
connect(FXmppStreamManager->instance(), SIGNAL(streamClosed(IXmppStream *)), SLOT(onXmppStreamClosed(IXmppStream *)));
}
}
plugin = APluginManager->pluginInterface("IStanzaProcessor").value(0,NULL);
if (plugin)
{
FStanzaProcessor = qobject_cast<IStanzaProcessor *>(plugin->instance());
}
plugin = APluginManager->pluginInterface("IPresenceManager").value(0,NULL);
if (plugin)
{
FPresenceManager = qobject_cast<IPresenceManager *>(plugin->instance());
if (FPresenceManager)
{
connect(FPresenceManager->instance(),SIGNAL(presenceAboutToClose(IPresence *, int, const QString &)),
SLOT(onPresenceAboutToClose(IPresence *, int, const QString &)));
}
}
return FStanzaProcessor!=NULL;
}
bool PrivateStorage::initObjects()
{
if (FStanzaProcessor)
{
IStanzaHandle handle;
handle.handler = this;
handle.order = SHO_MI_PRIVATESTORAGE;
handle.conditions.append(SHC_NOTIFYDATACHANGED);
handle.direction = IStanzaHandle::DirectionIn;
FSHINotifyDataChanged = FStanzaProcessor->insertStanzaHandle(handle);
}
return true;
}
bool PrivateStorage::stanzaReadWrite(int AHandleId, const Jid &AStreamJid, Stanza &AStanza, bool &AAccept)
{
if (AHandleId == FSHINotifyDataChanged)
{
AAccept = true;
QDomElement dataElem = AStanza.firstElement("x",NS_VACUUM_PRIVATESTORAGE_UPDATE).firstChildElement();
while (!dataElem.isNull())
{
LOG_STRM_INFO(AStreamJid,QString("Private data update notify received, ns=%1").arg(dataElem.namespaceURI()));
emit dataChanged(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
dataElem = dataElem.nextSiblingElement();
}
return true;
}
return false;
}
void PrivateStorage::stanzaRequestResult(const Jid &AStreamJid, const Stanza &AStanza)
{
if (FSaveRequests.contains(AStanza.id()))
{
QDomElement dataElem = FSaveRequests.take(AStanza.id());
if (AStanza.type() == "result")
{
LOG_STRM_INFO(AStreamJid,QString("Private data saved on server, ns=%1, id=%2").arg(dataElem.namespaceURI(),AStanza.id()));
notifyDataChanged(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
}
else
{
LOG_STRM_WARNING(AStreamJid,QString("Private data saved in local storage, ns=%1, id=%2: %3").arg(dataElem.namespaceURI(),AStanza.id(),XmppStanzaError(AStanza).condition()));
}
saveOptionsElement(AStreamJid,dataElem);
emit dataSaved(AStanza.id(),AStreamJid,dataElem);
}
else if (FLoadRequests.contains(AStanza.id()))
{
QDomElement dataElem;
QDomElement loadElem = FLoadRequests.take(AStanza.id());
if (AStanza.type() == "result")
{
dataElem = AStanza.firstElement("query",NS_JABBER_PRIVATE).firstChildElement(loadElem.tagName());
LOG_STRM_INFO(AStreamJid,QString("Private data loaded from server, ns=%1, id=%2").arg(loadElem.namespaceURI(),AStanza.id()));
}
else
{
LOG_STRM_WARNING(AStreamJid,QString("Private data loaded from local storage, ns=%1, id=%2: %3").arg(loadElem.namespaceURI(),AStanza.id(),XmppStanzaError(AStanza).condition()));
}
if (dataElem.isNull())
dataElem = loadOptionsElement(AStreamJid,loadElem.tagName(),loadElem.namespaceURI());
emit dataLoaded(AStanza.id(),AStreamJid,insertElement(AStreamJid,dataElem));
}
else if (FRemoveRequests.contains(AStanza.id()))
{
QDomElement dataElem = FRemoveRequests.take(AStanza.id());
if (AStanza.type() == "result")
{
LOG_STRM_INFO(AStreamJid,QString("Private data removed from server, ns=%1, id=%2").arg(dataElem.namespaceURI(),AStanza.id()));
notifyDataChanged(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
}
else
{
LOG_STRM_WARNING(AStreamJid,QString("Private data removed from local storage, ns=%1, id=%2: %3").arg(dataElem.namespaceURI(),AStanza.id(),XmppStanzaError(AStanza).condition()));
}
removeElement(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
removeOptionsElement(AStreamJid,dataElem.tagName(),dataElem.namespaceURI());
emit dataRemoved(AStanza.id(),AStreamJid,dataElem);
}
}
bool PrivateStorage::isOpen(const Jid &AStreamJid) const
{
return FStreamElements.contains(AStreamJid);
}
bool PrivateStorage::isLoaded(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace) const
{
return !getData(AStreamJid,ATagName,ANamespace).isNull();
}
QDomElement PrivateStorage::getData(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace) const
{
QDomElement elem = FStreamElements.value(AStreamJid).firstChildElement(ATagName);
while (!elem.isNull() && elem.namespaceURI()!=ANamespace)
elem= elem.nextSiblingElement(ATagName);
return elem;
}
QString PrivateStorage::saveData(const Jid &AStreamJid, const QDomElement &AElement)
{
if (FStanzaProcessor && isOpen(AStreamJid) && !AElement.tagName().isEmpty() && !AElement.namespaceURI().isEmpty())
{
Stanza request("iq");
request.setType("set").setId(FStanzaProcessor->newId());
QDomElement elem = request.addElement("query",NS_JABBER_PRIVATE);
elem.appendChild(AElement.cloneNode(true));
if (FStanzaProcessor->sendStanzaRequest(this,AStreamJid,request,PRIVATE_STORAGE_TIMEOUT))
{
LOG_STRM_INFO(AStreamJid,QString("Private data save request sent, ns=%1, id=%2").arg(AElement.namespaceURI(),request.id()));
if (FPreClosedStreams.contains(AStreamJid))
notifyDataChanged(AStreamJid,AElement.tagName(),AElement.namespaceURI());
FSaveRequests.insert(request.id(),insertElement(AStreamJid,AElement));
return request.id();
}
else
{
LOG_STRM_WARNING(AStreamJid,QString("Failed to send private data save request, ns=%1").arg(AElement.namespaceURI()));
}
}
else if (!isOpen(AStreamJid))
{
REPORT_ERROR("Failed to save private data: Storage is not opened");
}
else if (AElement.tagName().isEmpty() || AElement.namespaceURI().isEmpty())
{
REPORT_ERROR("Failed to save private data: Invalid data");
}
return QString::null;
}
QString PrivateStorage::loadData(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace)
{
if (FStanzaProcessor && isOpen(AStreamJid) && !ATagName.isEmpty() && !ANamespace.isEmpty())
{
Stanza request("iq");
request.setType("get").setId(FStanzaProcessor->newId());
QDomElement elem = request.addElement("query",NS_JABBER_PRIVATE);
QDomElement dataElem = elem.appendChild(request.createElement(ATagName,ANamespace)).toElement();
if (FStanzaProcessor->sendStanzaRequest(this,AStreamJid,request,PRIVATE_STORAGE_TIMEOUT))
{
LOG_STRM_INFO(AStreamJid,QString("Private data load request sent, ns=%1, id=%2").arg(ANamespace,request.id()));
FLoadRequests.insert(request.id(),dataElem);
return request.id();
}
else
{
LOG_STRM_WARNING(AStreamJid,QString("Failed to send private data load request, ns=%1").arg(ANamespace));
}
}
else if (!isOpen(AStreamJid))
{
REPORT_ERROR("Failed to load private data: Storage is not opened");
}
else if (ATagName.isEmpty() || ANamespace.isEmpty())
{
REPORT_ERROR("Failed to load private data: Invalid params");
}
return QString::null;
}
QString PrivateStorage::removeData(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace)
{
if (FStanzaProcessor && isOpen(AStreamJid) && !ATagName.isEmpty() && !ANamespace.isEmpty())
{
Stanza request("iq");
request.setType("set").setId(FStanzaProcessor->newId());
QDomElement elem = request.addElement("query",NS_JABBER_PRIVATE);
elem = elem.appendChild(request.createElement(ATagName,ANamespace)).toElement();
if (FStanzaProcessor->sendStanzaRequest(this,AStreamJid,request,PRIVATE_STORAGE_TIMEOUT))
{
LOG_STRM_INFO(AStreamJid,QString("Private data remove request sent, ns=%1, id=%2").arg(ANamespace,request.id()));
QDomElement dataElem = getData(AStreamJid,ATagName,ANamespace);
if (dataElem.isNull())
dataElem = insertElement(AStreamJid,elem);
if (FPreClosedStreams.contains(AStreamJid))
notifyDataChanged(AStreamJid,ATagName,ANamespace);
FRemoveRequests.insert(request.id(),dataElem);
return request.id();
}
else
{
LOG_STRM_WARNING(AStreamJid,QString("Failed to send private data remove request, ns=%1").arg(ANamespace));
}
}
else if (!isOpen(AStreamJid))
{
REPORT_ERROR("Failed to remove private data: Storage is not opened");
}
else if (ATagName.isEmpty() || ANamespace.isEmpty())
{
REPORT_ERROR("Failed to remove private data: Invalid params");
}
return QString::null;
}
void PrivateStorage::notifyDataChanged(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace)
{
IPresence *presence = FPresenceManager!=NULL ? FPresenceManager->findPresence(AStreamJid) : NULL;
if (FStanzaProcessor && presence && presence->isOpen())
{
foreach(const IPresenceItem &item, presence->findItems(AStreamJid))
{
if (item.itemJid != AStreamJid)
{
Stanza notify("message");
notify.setTo(item.itemJid.full());
QDomElement xElem = notify.addElement("x",NS_VACUUM_PRIVATESTORAGE_UPDATE);
xElem.appendChild(notify.createElement(ATagName,ANamespace));
if (FStanzaProcessor->sendStanzaOut(AStreamJid,notify))
LOG_STRM_DEBUG(AStreamJid,QString("Private data updated notify sent, to=%1, ns=%2").arg(item.itemJid.full(),ANamespace));
else
LOG_STRM_WARNING(AStreamJid,QString("Failed to send private data updated notify, to=%1, ns=%2").arg(item.itemJid.full(),ANamespace));
}
}
}
}
QDomElement PrivateStorage::insertElement(const Jid &AStreamJid, const QDomElement &AElement)
{
removeElement(AStreamJid,AElement.tagName(),AElement.namespaceURI());
QDomElement streamElem = FStreamElements.value(AStreamJid);
return streamElem.appendChild(AElement.cloneNode(true)).toElement();
}
void PrivateStorage::removeElement(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace)
{
if (FStreamElements.contains(AStreamJid))
FStreamElements[AStreamJid].removeChild(getData(AStreamJid,ATagName,ANamespace));
}
void PrivateStorage::saveOptionsElement(const Jid &AStreamJid, const QDomElement &AElement) const
{
if (AStreamJid.isValid() && !AElement.tagName().isEmpty() && !AElement.namespaceURI().isEmpty())
{
QDomDocument doc;
doc.appendChild(doc.createElement("storage")).appendChild(AElement.cloneNode(true));
QString nodePath = QString("private-storage[%1].%2[%3]").arg(AStreamJid.pBare()).arg(AElement.tagName()).arg(AElement.namespaceURI());
Options::setFileValue(Options::encrypt(doc.toByteArray(0)),nodePath);
}
}
QDomElement PrivateStorage::loadOptionsElement(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace) const
{
QDomDocument doc;
if (AStreamJid.isValid() && !ATagName.isEmpty() && !ANamespace.isEmpty())
{
QString nodePath = QString("private-storage[%1].%2[%3]").arg(AStreamJid.pBare()).arg(ATagName).arg(ANamespace);
doc.setContent(Options::decrypt(Options::fileValue(nodePath).toByteArray()).toByteArray(),true);
QDomElement dataElem = doc.documentElement().firstChildElement();
if (dataElem.tagName()!=ATagName || dataElem.namespaceURI()!=ANamespace)
{
doc.clear();
doc.appendChild(doc.createElement("storage")).appendChild(doc.createElementNS(ANamespace,ATagName));
}
}
return doc.documentElement().firstChildElement();
}
void PrivateStorage::removeOptionsElement(const Jid &AStreamJid, const QString &ATagName, const QString &ANamespace) const
{
if (AStreamJid.isValid() && !ATagName.isEmpty() && !ANamespace.isEmpty())
{
QString nodePath = QString("private-storage[%1].%2[%3]").arg(AStreamJid.pBare()).arg(ATagName).arg(ANamespace);
Options::setFileValue(QVariant(),nodePath);
}
}
void PrivateStorage::onXmppStreamOpened(IXmppStream *AXmppStream)
{
LOG_STRM_INFO(AXmppStream->streamJid(),"Private storage opened");
FStreamElements.insert(AXmppStream->streamJid(),FStorage.appendChild(FStorage.createElement("stream")).toElement());
emit storageOpened(AXmppStream->streamJid());
}
void PrivateStorage::onXmppStreamAboutToClose(IXmppStream *AXmppStream)
{
LOG_STRM_INFO(AXmppStream->streamJid(),"Private storage about to close");
emit storageAboutToClose(AXmppStream->streamJid());
}
void PrivateStorage::onXmppStreamClosed(IXmppStream *AXmppStream)
{
LOG_STRM_INFO(AXmppStream->streamJid(),"Private storage closed");
FPreClosedStreams -= AXmppStream->streamJid();
emit storageClosed(AXmppStream->streamJid());
FStorage.removeChild(FStreamElements.take(AXmppStream->streamJid()));
}
void PrivateStorage::onPresenceAboutToClose(IPresence *APresence, int AShow, const QString &AStatus)
{
Q_UNUSED(AShow); Q_UNUSED(AStatus);
FPreClosedStreams += APresence->streamJid();
emit storageNotifyAboutToClose(APresence->streamJid());
}
Q_EXPORT_PLUGIN2(plg_privatestorage, PrivateStorage)
| Nikoli/vacuum-im | src/plugins/privatestorage/privatestorage.cpp | C++ | gpl-3.0 | 14,432 |
<?php
/**
* Mobile class
*
* @author Arnia (dev@karybu.org)
*/
class MobileInstance
{
/**
* Whether mobile or not mobile mode
* @var bool
*/
var $ismobile = null;
/**
* Get current mobile mode
*
* @return bool If mobile mode returns true or false
*/
function isFromMobilePhone()
{
if ($this->ismobile !== null) {
return $this->ismobile;
}
$db_info = Context::getDBInfo();
if (isset($db_info->use_mobile_view)) {
if ($db_info->use_mobile_view != "Y" || Context::get('full_browse') || $_COOKIE["FullBrowse"]) {
return ($this->ismobile = false);
}
}
$xe_web_path = Context::pathToUrl(_KARYBU_PATH_);
// default setting. if there is cookie for a device, Karybu do not have to check if it is mobile or not and it will enhance performace of the server.
$this->ismobile = false;
$m = Context::get('m');
if (strlen($m) == 1) {
if ($m == "1") {
$this->ismobile = true;
} elseif ($m == "0") {
$this->ismobile = false;
}
} elseif (isset($_COOKIE['mobile'])) {
if ($_COOKIE['user-agent'] == md5($_SERVER['HTTP_USER_AGENT'])) {
if ($_COOKIE['mobile'] == 'true') {
$this->ismobile = true;
} else {
$this->ismobile = false;
}
} else {
$this->ismobile = false;
setcookie("mobile", false, 0, $xe_web_path);
setcookie("user-agent", false, 0, $xe_web_path);
if (!$this->isMobilePadCheckByAgent() && $this->isMobileCheckByAgent()) {
$this->ismobile = true;
}
}
} else {
if ($this->isMobilePadCheckByAgent()) {
$this->ismobile = false;
} else {
if ($this->isMobileCheckByAgent()) {
$this->ismobile = true;
}
}
}
if ($this->ismobile !== null) {
if ($this->ismobile == true) {
if ($_COOKIE['mobile'] != 'true') {
$_COOKIE['mobile'] = 'true';
setcookie("mobile", 'true', 0, $xe_web_path);
}
} elseif (!isset($_COOKIE['mobile']) || $_COOKIE['mobile'] != 'false') {
$_COOKIE['mobile'] = 'false';
setcookie("mobile", 'false', 0, $xe_web_path);
}
if (!isset($_COOKIE['user-agent']) || $_COOKIE['user-agent'] != md5($_SERVER['HTTP_USER_AGENT'])) {
setcookie("user-agent", md5($_SERVER['HTTP_USER_AGENT']), 0, $xe_web_path);
}
}
return $this->ismobile;
}
/**
* Detect mobile device by user agent
*
* @return bool Returns true on mobile device or false.
*/
function isMobileCheckByAgent()
{
static $UACheck;
if (isset($UACheck)) {
return $UACheck;
}
// stripos is only for PHP5.
$mobileAgent = unserialize(
strtolower(
serialize(
array(
'iPod',
'iPhone',
'Android',
'BlackBerry',
'SymbianOS',
'Bada',
'Kindle',
'Wii',
'SCH-',
'SPH-',
'CANU-',
'Windows Phone',
'Windows CE',
'POLARIS',
'Palm',
'Dorothy Browser',
'Mobile',
'Opera Mobi',
'Opera Mini',
'Minimo',
'AvantGo',
'NetFront',
'Nokia',
'LGPlayer',
'SonyEricsson',
'HTC'
)
)
)
);
if ($this->isMobilePadCheckByAgent()) {
$UACheck = true;
return true;
}
foreach ($mobileAgent as $agent) {
// stripos is only for PHP5..
$httpUA = strtolower($_SERVER['HTTP_USER_AGENT']);
if (strpos($httpUA, $agent) !== false) {
$UACheck = true;
return true;
}
}
$UACheck = false;
return false;
}
/**
* Check if user-agent is a tablet PC as iPad or Andoid tablet.
*
* @return bool TRUE for tablet, and FALSE for else.
*/
function isMobilePadCheckByAgent()
{
static $UACheck;
if (isset($UACheck)) {
return $UACheck;
}
$padAgent = array('iPad', 'Android', 'webOS', 'hp-tablet', 'PlayBook');
// Android with 'Mobile' string is not a tablet-like device, and 'Andoroid' without 'Mobile' string is a tablet-like device.
// $exceptionAgent[0] contains exception agents for all exceptions.
$exceptionAgent = array(0 => array('Opera Mini', 'Opera Mobi'), 'Android' => 'Mobile');
foreach ($padAgent as $agent) {
if (strpos($_SERVER['HTTP_USER_AGENT'], $agent) !== false) {
if (!isset($exceptionAgent[$agent])) {
$UACheck = true;
return true;
} elseif (strpos($_SERVER['HTTP_USER_AGENT'], $exceptionAgent[$agent]) === false) {
// If the agent is the Android, that can be either tablet and mobile phone.
foreach ($exceptionAgent[0] as $val) {
if (strpos($_SERVER['HTTP_USER_AGENT'], $val) !== false) {
$UACheck = false;
return false;
}
}
$UACheck = true;
return true;
}
}
}
$UACheck = false;
return false;
}
/**
* Set mobile mode
*
* @param bool $ismobile
* @return void
*/
function setMobile($ismobile)
{
$this->ismobile = $ismobile;
}
}
/**
* Will be replaced with MobileInstance
*
* @deprecated
*/
class Mobile
{
/** @var MobileInstance */
private static $mobile;
public static function setRequestMobileInfo(MobileInstance $mobile)
{
self::$mobile = $mobile;
}
public static function &getInstance()
{
return self::$mobile;
}
public static function isFromMobilePhone()
{
return self::$mobile->isFromMobilePhone();
}
public static function isMobileCheckByAgent()
{
return self::$mobile->isMobileCheckByAgent();
}
public static function isMobilePadCheckByAgent()
{
return self::$mobile->isMobilePadCheckByAgent();
}
public static function setMobile($mobile)
{
self::$mobile->setMobile($mobile);
}
} | arnia/Karybu | classes/mobile/Mobile.class.php | PHP | gpl-3.0 | 7,236 |
import React from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Typography } from 'antd';
const { Paragraph } = Typography;
export default (props: any): React.ReactNode => {
return (
<PageHeaderWrapper {...props} title="欢迎使用!">
<Card>
<Typography>
<Paragraph>
欢迎使用!
</Paragraph>
</Typography>
</Card>
</PageHeaderWrapper>
);
};
| KevinWG/OSS.Core | FrontEnds/Admin/ClientApp/src/pages/home/Welcome.tsx | TypeScript | gpl-3.0 | 467 |
<?php
return array (
'Show Exact Online invoice' => 'Afficher la facture Exact Online',
'Ordered by' => 'Commander par',
'Invoiced to' => 'Facturé à',
'Order date' => 'Date de commande',
'Payment condition' => 'Condition de paiement',
'Your reference' => 'Vos références',
'Status' => 'Statut',
'Remarks' => 'Remarques',
'Amount' => 'Montant',
'Net price' => 'Prix net',
'VAT code' => 'TVA',
'VAT percentage' => 'Pourcentage TVA',
'Price' => 'Prix',
'VAT price' => 'Prix TVA',
'Open fee' => 'Sans frais',
'Could not find invoice.' => 'Impossible de retrouver la facture.',
'Exact Online division number' => 'Numéro de division Exact Online',
'description' => 'Ajoute une fonction d\'export au module "Facturation" pour Exact Online. Ajoute également une fonction dans le module "Projets" pour afficher les factures provenant d\'Exact Online',
'Type' => 'Type',
'Article' => 'Article',
'Start' => 'Début',
'Add Exact Online invoice' => 'Ajouter une facture Exact Online',
'Exact Online' => 'Exact Online',
'Fill out the form and click \'Connect\'.' => 'Remplissez le formulaire et cliquez sur \'Connecter\'.',
'Client id' => 'ID du client',
'Client secret' => 'Secret du client',
'Username / E-mail' => 'Nom d\'utilisateur / Email',
'Products id' => 'ID du produit',
'Journal' => 'Journal',
'Expiration token' => 'Jeton d\'expiration',
'Connect' => 'Connecter',
);
| deependhulla/powermail-debian9 | files/rootdir/usr/local/src/groupoffice-6.3/modules/exactonline/language/fr.php | PHP | gpl-3.0 | 1,433 |
const
{series} = require("gulp"),
bump = require("./gulp_modules/task-bump"),
bump_minor = require("./gulp_modules/task-bump-minor"),
bump_major = require("./gulp_modules/task-bump-major"),
readme = require("./gulp_modules/task-readme"),
replace_version = require("./gulp_modules/task-replace-version"),
make_pot = series(replace_version, require("./gulp_modules/task-pot")),
// pot = series(make_pot, require("./gulp_modules/task-clean-pot")),
pot = make_pot,
pomo = series(pot, require("./gulp_modules/task-tivwp_pomo")),
sass = require("./gulp_modules/task-sass"),
uglify = require("./gulp_modules/task-uglify"),
product_info = require("./gulp_modules/task-product-info"),
dist = series(readme, sass, uglify, product_info, pomo)
;
exports.bump = bump;
exports.bump_minor = bump_minor;
exports.bump_major = bump_major;
exports.readme = readme;
exports.replace_version = replace_version;
exports.pot = pot;
exports.pomo = pomo;
exports.sass = sass;
exports.uglify = uglify;
exports.dist = dist;
exports.default = exports.dist;
| WPGlobus/WPGlobus | Gulpfile.js | JavaScript | gpl-3.0 | 1,044 |
/*
* MidiEditor
* Copyright (C) 2010 Markus Schwenk
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "KeySignatureEvent.h"
KeySignatureEvent::KeySignatureEvent(int channel, int tonality, bool minor, MidiTrack *track) : MidiEvent(channel, track){
_tonality = tonality;
_minor = minor;
}
KeySignatureEvent::KeySignatureEvent(const KeySignatureEvent &other) : MidiEvent(other){
_tonality = other._tonality;
_minor = other._minor;
}
int KeySignatureEvent::type() const {
return KeySignatureEventType;
}
int KeySignatureEvent::line(){
return KEY_SIGNATURE_EVENT_LINE;
}
QString KeySignatureEvent::toMessage(){
return "";
}
QByteArray KeySignatureEvent::save(){
QByteArray array = QByteArray();
array.append(byte(0xFF));
array.append(byte(0x59 | channel()));
array.append(byte(0x02));
array.append(byte(tonality()));
if(_minor){
array.append(byte(0x01));
} else {
array.append(byte(0x00));
}
return array;
}
ProtocolEntry *KeySignatureEvent::copy(){
return new KeySignatureEvent(*this);
}
void KeySignatureEvent::reloadState(ProtocolEntry *entry){
KeySignatureEvent *other = qobject_cast<KeySignatureEvent*>(entry);
if(!other){
return;
}
MidiEvent::reloadState(entry);
_tonality = other->_tonality;
_minor = other->_minor;
}
QString KeySignatureEvent::typeString(){
return "Key Signature Event";
}
int KeySignatureEvent::tonality(){
return _tonality;
}
bool KeySignatureEvent::minor(){
return _minor;
}
void KeySignatureEvent::setTonality(int t){
ProtocolEntry *toCopy = copy();
_tonality = t;
addProtocolEntry(toCopy, this);
}
void KeySignatureEvent::setMinor(bool minor){
ProtocolEntry *toCopy = copy();
_minor = minor;
addProtocolEntry(toCopy, this);
}
QString KeySignatureEvent::toString(int tonality, bool minor){
QString text = "";
if(!minor){
switch(tonality){
case 0: {
text = "C";
break;
}
case 1: {
text = "G";
break;
}
case 2: {
text = "D";
break;
}
case 3: {
text = "A";
break;
}
case 4: {
text = "E";
break;
}
case 5: {
text = "B";
break;
}
case 6: {
text = "F sharp";
break;
}
case -1: {
text = "F";
break;
}
case -2: {
text = "B flat";
break;
}
case -3: {
text = "E flat";
break;
}
case -4: {
text = "A flat";
break;
}
case -5: {
text = "D flat";
break;
}
case -6: {
text = "G flat";
break;
}
}
text += " major";
} else {
switch(tonality){
case 0: {
text = "a";
break;
}
case 1: {
text = "e";
break;
}
case 2: {
text = "b";
break;
}
case 3: {
text = "f sharp";
break;
}
case 4: {
text = "c sharp";
break;
}
case 5: {
text = "g sharp";
break;
}
case 6: {
text = "d sharp";
break;
}
case -1: {
text = "d";
break;
}
case -2: {
text = "g";
break;
}
case -3: {
text = "c";
break;
}
case -4: {
text = "f";
break;
}
case -5: {
text = "b flat";
break;
}
case -6: {
text = "e flat";
break;
}
}
text += " minor";
}
return text;
}
| easyaspi314/MidiEditor | src/MidiEvent/KeySignatureEvent.cpp | C++ | gpl-3.0 | 3,781 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* MOODLE VERSION INFORMATION
*
* This file defines the current version of the core Moodle code being used.
* This is compared against the values stored in the database to determine
* whether upgrades should be performed (see lib/db/*.php)
*
* @package core
* @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$version = 2015102800.00; // YYYYMMDD = weekly release date of this DEV branch.
// RR = release increments - 00 in DEV branches.
// .XX = incremental changes.
$release = '3.0beta+ (Build: 20151028)'; // Human-friendly version name
$branch = '30'; // This version's branch.
$maturity = MATURITY_BETA; // This version's maturity level.
| edurenye/moodle | version.php | PHP | gpl-3.0 | 1,638 |
<?php
/**
* xmlseclibs.php
*
* Copyright (c) 2007-2010, Robert Richards <rrichards@cdatazone.org>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* * Neither the name of Robert Richards nor the names of his
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @author Robert Richards <rrichards@cdatazone.org>
* @copyright 2007-2010 Robert Richards <rrichards@cdatazone.org>
* @license http://www.opensource.org/licenses/bsd-license.php BSD License
* @version 1.3.0-dev
*/
/*
Functions to generate simple cases of Exclusive Canonical XML - Callable function is C14NGeneral()
i.e.: $canonical = C14NGeneral($domelement, TRUE);
*/
/* helper function */
function sortAndAddAttrs($element, $arAtts) {
$newAtts = array();
foreach ($arAtts AS $attnode) {
$newAtts[$attnode->nodeName] = $attnode;
}
ksort($newAtts);
foreach ($newAtts as $attnode) {
$element->setAttribute($attnode->nodeName, $attnode->nodeValue);
}
}
/* helper function */
function canonical($tree, $element, $withcomments) {
if ($tree->nodeType != XML_DOCUMENT_NODE) {
$dom = $tree->ownerDocument;
} else {
$dom = $tree;
}
if ($element->nodeType != XML_ELEMENT_NODE) {
if ($element->nodeType == XML_DOCUMENT_NODE) {
foreach ($element->childNodes AS $node) {
canonical($dom, $node, $withcomments);
}
return;
}
if ($element->nodeType == XML_COMMENT_NODE && !$withcomments) {
return;
}
$tree->appendChild($dom->importNode($element, TRUE));
return;
}
$arNS = array();
if ($element->namespaceURI != "") {
if ($element->prefix == "") {
$elCopy = $dom->createElementNS($element->namespaceURI, $element->nodeName);
} else {
$prefix = $tree->lookupPrefix($element->namespaceURI);
if ($prefix == $element->prefix) {
$elCopy = $dom->createElementNS($element->namespaceURI, $element->nodeName);
} else {
$elCopy = $dom->createElement($element->nodeName);
$arNS[$element->namespaceURI] = $element->prefix;
}
}
} else {
$elCopy = $dom->createElement($element->nodeName);
}
$tree->appendChild($elCopy);
/* Create DOMXPath based on original document */
$xPath = new DOMXPath($element->ownerDocument);
/* Get namespaced attributes */
$arAtts = $xPath->query('attribute::*[namespace-uri(.) != ""]', $element);
/* Create an array with namespace URIs as keys, and sort them */
foreach ($arAtts AS $attnode) {
if (array_key_exists($attnode->namespaceURI, $arNS) &&
($arNS[$attnode->namespaceURI] == $attnode->prefix)) {
continue;
}
$prefix = $tree->lookupPrefix($attnode->namespaceURI);
if ($prefix != $attnode->prefix) {
$arNS[$attnode->namespaceURI] = $attnode->prefix;
} else {
$arNS[$attnode->namespaceURI] = NULL;
}
}
if (count($arNS) > 0) {
asort($arNS);
}
/* Add namespace nodes */
foreach ($arNS AS $namespaceURI => $prefix) {
if ($prefix != NULL) {
$elCopy->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:" . $prefix, $namespaceURI);
}
}
if (count($arNS) > 0) {
ksort($arNS);
}
/* Get attributes not in a namespace, and then sort and add them */
$arAtts = $xPath->query('attribute::*[namespace-uri(.) = ""]', $element);
sortAndAddAttrs($elCopy, $arAtts);
/* Loop through the URIs, and then sort and add attributes within that namespace */
foreach ($arNS as $nsURI => $prefix) {
$arAtts = $xPath->query('attribute::*[namespace-uri(.) = "' . $nsURI . '"]', $element);
sortAndAddAttrs($elCopy, $arAtts);
}
foreach ($element->childNodes AS $node) {
canonical($elCopy, $node, $withcomments);
}
}
/*
* @author OrangePeople Software Ltda <soporte@orangepeople.cl>
* helper function
* Modification by Hermann Alexander Arriagada Méndez
* for IssuerSerial
*/
function getIssuerName($X509Cert) {
/*$handler = fopen($X509Cert, "r");
$cert = fread($handler, 8192);
fclose($handler);*/
$cert = $X509Cert;
$cert_as_array = openssl_x509_parse($cert);
$name = $cert_as_array['name'];
$name = str_replace("/", ",", $name);
$name = substr($name, 1, strlen($name));
return $name;
}
/*
* @author OrangePeople Software Ltda <soporte@orangepeople.cl>
* helper function
* Modification by Hermann Alexander Arriagada Méndez
* for IssuerSerial
*/
function getSerialNumber($X509Cert) {
/*$handler = fopen($X509Cert, "r");
$cert = fread($handler, 8192);
fclose($handler);*/
$cert = $X509Cert;
$cert_as_array = openssl_x509_parse($cert);
$serialNumber = $cert_as_array['serialNumber'];
return $serialNumber;
}
/*
$element - DOMElement for which to produce the canonical version of
$exclusive - boolean to indicate exclusive canonicalization (must pass TRUE)
$withcomments - boolean indicating wether or not to include comments in canonicalized form
*/
function C14NGeneral($element, $exclusive = FALSE, $withcomments = FALSE) {
/* IF PHP 5.2+ then use built in canonical functionality */
$php_version = explode('.', PHP_VERSION);
if (($php_version[0] > 5) || ($php_version[0] == 5 && $php_version[1] >= 2)) {
return $element->C14N($exclusive, $withcomments);
}
/* Must be element or document */
if (!$element instanceof DOMElement && !$element instanceof DOMDocument) {
return NULL;
}
/* Currently only exclusive XML is supported */
if ($exclusive == FALSE) {
throw new Exception("Only exclusive canonicalization is supported in this version of PHP");
}
$copyDoc = new DOMDocument();
canonical($copyDoc, $element, $withcomments);
return $copyDoc->saveXML($copyDoc->documentElement, LIBXML_NOEMPTYTAG);
}
class XMLSecurityKey {
const TRIPLEDES_CBC = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc';
const AES128_CBC = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc';
const AES192_CBC = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc';
const AES256_CBC = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
const RSA_1_5 = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5';
const RSA_OAEP_MGF1P = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p';
const DSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#dsa-sha1';
const RSA_SHA1 = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
const RSA_SHA256 = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
private $cryptParams = array();
public $type = 0;
public $key = NULL;
public $passphrase = "";
public $iv = NULL;
public $name = NULL;
public $keyChain = NULL;
public $isEncrypted = FALSE;
public $encryptedCtx = NULL;
public $guid = NULL;
/**
* This variable contains the certificate as a string if this key represents an X509-certificate.
* If this key doesn't represent a certificate, this will be NULL.
*/
private $x509Certificate = NULL;
/* This variable contains the certificate thunbprint if we have loaded an X509-certificate. */
private $X509Thumbprint = NULL;
public function __construct($type, $params = NULL) {
srand();
switch ($type) {
case (XMLSecurityKey::TRIPLEDES_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_TRIPLEDES;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#tripledes-cbc';
break;
case (XMLSecurityKey::AES128_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes128-cbc';
break;
case (XMLSecurityKey::AES192_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes192-cbc';
break;
case (XMLSecurityKey::AES256_CBC):
$this->cryptParams['library'] = 'mcrypt';
$this->cryptParams['cipher'] = MCRYPT_RIJNDAEL_128;
$this->cryptParams['mode'] = MCRYPT_MODE_CBC;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#aes256-cbc';
break;
case (XMLSecurityKey::RSA_1_5):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#rsa-1_5';
if (is_array($params) && !empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
return;
case (XMLSecurityKey::RSA_OAEP_MGF1P):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['padding'] = OPENSSL_PKCS1_OAEP_PADDING;
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p';
$this->cryptParams['hash'] = NULL;
if (is_array($params) && !empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
return;
case (XMLSecurityKey::RSA_SHA1):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2000/09/xmldsig#rsa-sha1';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
if (is_array($params) && !empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
case (XMLSecurityKey::RSA_SHA256):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
$this->cryptParams['digest'] = 'SHA256';
if (is_array($params) && !empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
case (XMLSecurityKey::DSA_SHA1):
$this->cryptParams['library'] = 'openssl';
$this->cryptParams['method'] = 'http://www.w3.org/2000/09/xmldsig#dsa-sha1';
$this->cryptParams['padding'] = OPENSSL_PKCS1_PADDING;
if (is_array($params) && !empty($params['type'])) {
if ($params['type'] == 'public' || $params['type'] == 'private') {
$this->cryptParams['type'] = $params['type'];
break;
}
}
throw new Exception('Certificate "type" (private/public) must be passed via parameters');
break;
default:
throw new Exception('Invalid Key Type');
return;
}
$this->type = $type;
}
public function generateSessionKey() {
$key = '';
if (!empty($this->cryptParams['cipher']) && !empty($this->cryptParams['mode'])) {
$keysize = mcrypt_module_get_algo_key_size($this->cryptParams['cipher']);
/* Generating random key using iv generation routines */
if (($keysize > 0) && ($td = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', $this->cryptParams['mode'], ''))) {
if ($this->cryptParams['cipher'] == MCRYPT_RIJNDAEL_128) {
$keysize = 16;
if ($this->type == XMLSecurityKey::AES256_CBC) {
$keysize = 32;
} elseif ($this->type == XMLSecurityKey::AES192_CBC) {
$keysize = 24;
}
}
while (strlen($key) < $keysize) {
$key .= mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
}
mcrypt_module_close($td);
$key = substr($key, 0, $keysize);
$this->key = $key;
}
}
return $key;
}
public static function getRawThumbprint($cert) {
$arCert = explode("\n", $cert);
$data = '';
$inData = FALSE;
foreach ($arCert AS $curData) {
if (!$inData) {
if (strncmp($curData, '-----BEGIN CERTIFICATE', 22) == 0) {
$inData = TRUE;
}
} else {
if (strncmp($curData, '-----END CERTIFICATE', 20) == 0) {
$inData = FALSE;
break;
}
$data .= trim($curData);
}
}
if (!empty($data)) {
return strtolower(sha1(base64_decode($data)));
}
return NULL;
}
public function loadKey($key, $isFile = FALSE, $isCert = FALSE) {
if ($isFile) {
$this->key = file_get_contents($key);
} else {
$this->key = $key;
}
if ($isCert) {
$this->key = openssl_x509_read($this->key);
openssl_x509_export($this->key, $str_cert);
$this->x509Certificate = $str_cert;
$this->key = $str_cert;
} else {
$this->x509Certificate = NULL;
}
if ($this->cryptParams['library'] == 'openssl') {
if ($this->cryptParams['type'] == 'public') {
if ($isCert) {
/* Load the thumbprint if this is an X509 certificate. */
$this->X509Thumbprint = self::getRawThumbprint($this->key);
}
$this->key = openssl_get_publickey($this->key);
} else {
$this->key = openssl_get_privatekey($this->key, $this->passphrase);
}
} else if ($this->cryptParams['cipher'] == MCRYPT_RIJNDAEL_128) {
/* Check key length */
switch ($this->type) {
case (XMLSecurityKey::AES256_CBC):
if (strlen($this->key) < 25) {
throw new Exception('Key must contain at least 25 characters for this cipher');
}
break;
case (XMLSecurityKey::AES192_CBC):
if (strlen($this->key) < 17) {
throw new Exception('Key must contain at least 17 characters for this cipher');
}
break;
}
}
}
private function encryptMcrypt($data) {
$td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
$this->iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
mcrypt_generic_init($td, $this->key, $this->iv);
if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
$bs = mcrypt_enc_get_block_size($td);
for ($datalen0 = $datalen = strlen($data); (($datalen % $bs) != ($bs - 1)); $datalen++)
$data.=chr(rand(1, 127));
$data.=chr($datalen - $datalen0 + 1);
}
$encrypted_data = $this->iv . mcrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
return $encrypted_data;
}
private function decryptMcrypt($data) {
$td = mcrypt_module_open($this->cryptParams['cipher'], '', $this->cryptParams['mode'], '');
$iv_length = mcrypt_enc_get_iv_size($td);
$this->iv = substr($data, 0, $iv_length);
$data = substr($data, $iv_length);
mcrypt_generic_init($td, $this->key, $this->iv);
$decrypted_data = mdecrypt_generic($td, $data);
mcrypt_generic_deinit($td);
mcrypt_module_close($td);
if ($this->cryptParams['mode'] == MCRYPT_MODE_CBC) {
$dataLen = strlen($decrypted_data);
$paddingLength = substr($decrypted_data, $dataLen - 1, 1);
$decrypted_data = substr($decrypted_data, 0, $dataLen - ord($paddingLength));
}
return $decrypted_data;
}
private function encryptOpenSSL($data) {
if ($this->cryptParams['type'] == 'public') {
if (!openssl_public_encrypt($data, $encrypted_data, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure encrypting Data');
return;
}
} else {
if (!openssl_private_encrypt($data, $encrypted_data, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure encrypting Data');
return;
}
}
return $encrypted_data;
}
private function decryptOpenSSL($data) {
if ($this->cryptParams['type'] == 'public') {
if (!openssl_public_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure decrypting Data');
return;
}
} else {
if (!openssl_private_decrypt($data, $decrypted, $this->key, $this->cryptParams['padding'])) {
throw new Exception('Failure decrypting Data');
return;
}
}
return $decrypted;
}
private function signOpenSSL($data) {
$algo = OPENSSL_ALGO_SHA1;
if (!empty($this->cryptParams['digest'])) {
$algo = $this->cryptParams['digest'];
}
if (!openssl_sign($data, $signature, $this->key, $algo)) {
throw new Exception('Failure Signing Data: ' . openssl_error_string() . ' - ' . $algo);
return;
}
return $signature;
}
private function verifyOpenSSL($data, $signature) {
$algo = OPENSSL_ALGO_SHA1;
$return_value = false;
if (!empty($this->cryptParams['digest'])) {
$algo = $this->cryptParams['digest'];
}
$verify_value = openssl_verify($data, $signature, $this->key, $algo);
if ($verify_value == 1) {
$return_value = true;
}
return $return_value;
}
public function encryptData($data) {
switch ($this->cryptParams['library']) {
case 'mcrypt':
return $this->encryptMcrypt($data);
break;
case 'openssl':
return $this->encryptOpenSSL($data);
break;
}
}
public function decryptData($data) {
switch ($this->cryptParams['library']) {
case 'mcrypt':
return $this->decryptMcrypt($data);
break;
case 'openssl':
return $this->decryptOpenSSL($data);
break;
}
}
public function signData($data) {
switch ($this->cryptParams['library']) {
case 'openssl':
return $this->signOpenSSL($data);
break;
}
}
public function verifySignature($data, $signature) {
switch ($this->cryptParams['library']) {
case 'openssl':
return $this->verifyOpenSSL($data, $signature);
break;
}
}
public function getAlgorith() {
return $this->cryptParams['method'];
}
static function makeAsnSegment($type, $string) {
switch ($type) {
case 0x02:
if (ord($string) > 0x7f)
$string = chr(0) . $string;
break;
case 0x03:
$string = chr(0) . $string;
break;
}
$length = strlen($string);
if ($length < 128) {
$output = sprintf("%c%c%s", $type, $length, $string);
} else if ($length < 0x0100) {
$output = sprintf("%c%c%c%s", $type, 0x81, $length, $string);
} else if ($length < 0x010000) {
$output = sprintf("%c%c%c%c%s", $type, 0x82, $length / 0x0100, $length % 0x0100, $string);
} else {
$output = NULL;
}
return($output);
}
/* Modulus and Exponent must already be base64 decoded */
static function convertRSA($modulus, $exponent) {
/* make an ASN publicKeyInfo */
$exponentEncoding = XMLSecurityKey::makeAsnSegment(0x02, $exponent);
$modulusEncoding = XMLSecurityKey::makeAsnSegment(0x02, $modulus);
$sequenceEncoding = XMLSecurityKey:: makeAsnSegment(0x30, $modulusEncoding . $exponentEncoding);
$bitstringEncoding = XMLSecurityKey::makeAsnSegment(0x03, $sequenceEncoding);
$rsaAlgorithmIdentifier = pack("H*", "300D06092A864886F70D0101010500");
$publicKeyInfo = XMLSecurityKey::makeAsnSegment(0x30, $rsaAlgorithmIdentifier . $bitstringEncoding);
/* encode the publicKeyInfo in base64 and add PEM brackets */
$publicKeyInfoBase64 = base64_encode($publicKeyInfo);
$encoding = "-----BEGIN PUBLIC KEY-----\n";
$offset = 0;
while ($segment = substr($publicKeyInfoBase64, $offset, 64)) {
$encoding = $encoding . $segment . "\n";
$offset += 64;
}
return $encoding . "-----END PUBLIC KEY-----\n";
}
public function serializeKey($parent) {
}
/**
* Retrieve the X509 certificate this key represents.
*
* Will return the X509 certificate in PEM-format if this key represents
* an X509 certificate.
*
* @return The X509 certificate or NULL if this key doesn't represent an X509-certificate.
*/
public function getX509Certificate() {
return $this->x509Certificate;
}
/* Get the thumbprint of this X509 certificate.
*
* Returns:
* The thumbprint as a lowercase 40-character hexadecimal number, or NULL
* if this isn't a X509 certificate.
*/
public function getX509Thumbprint() {
return $this->X509Thumbprint;
}
}
class XMLSecurityDSig {
const XMLDSIGNS = 'http://www.w3.org/2000/09/xmldsig#';
const SHA1 = 'http://www.w3.org/2000/09/xmldsig#sha1';
const SHA256 = 'http://www.w3.org/2001/04/xmlenc#sha256';
const SHA512 = 'http://www.w3.org/2001/04/xmlenc#sha512';
const RIPEMD160 = 'http://www.w3.org/2001/04/xmlenc#ripemd160';
const C14N = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
const C14N_COMMENTS = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments';
const EXC_C14N = 'http://www.w3.org/2001/10/xml-exc-c14n#';
const EXC_C14N_COMMENTS = 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments';
const NS_ENVELOPE = 'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"';
const NS_XMLDSIG = 'xmlns:ds="http://www.w3.org/2000/09/xmldsig#"';
const template = '<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:SignedInfo>
<ds:SignatureMethod />
</ds:SignedInfo>
</ds:Signature>';
public $sigNode = NULL;
public $idKeys = array();
public $idNS = array();
private $signedInfo = NULL;
private $body = NULL;
private $xPathCtx = NULL;
private $canonicalMethod = NULL;
private $prefix = 'ds';
private $searchpfx = 'secdsig';
/* This variable contains an associative array of validated nodes. */
private $validatedNodes = NULL;
public function __construct() {
$sigdoc = new DOMDocument();
$sigdoc->loadXML(XMLSecurityDSig::template);
$this->sigNode = $sigdoc->documentElement;
}
private function resetXPathObj() {
$this->xPathCtx = NULL;
}
private function getXPathObj() {
if (empty($this->xPathCtx) && !empty($this->sigNode)) {
$xpath = new DOMXPath($this->sigNode->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$this->xPathCtx = $xpath;
}
return $this->xPathCtx;
}
static function generate_GUID($prefix = 'pfx') {
$uuid = md5(uniqid(rand(), true));
$guid = $prefix . substr($uuid, 0, 8) . "-" .
substr($uuid, 8, 4) . "-" .
substr($uuid, 12, 4) . "-" .
substr($uuid, 16, 4) . "-" .
substr($uuid, 20, 12);
return $guid;
}
public function locateSignature($objDoc) {
if ($objDoc instanceof DOMDocument) {
$doc = $objDoc;
} else {
$doc = $objDoc->ownerDocument;
}
if ($doc) {
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = ".//secdsig:Signature";
$nodeset = $xpath->query($query, $objDoc);
$this->sigNode = $nodeset->item(0);
return $this->sigNode;
}
return NULL;
}
public function createNewSignNode($name, $value = NULL) {
$doc = $this->sigNode->ownerDocument;
if (!is_null($value)) {
$node = $doc->createElementNS(XMLSecurityDSig::XMLDSIGNS, $this->prefix . ':' . $name, $value);
} else {
$node = $doc->createElementNS(XMLSecurityDSig::XMLDSIGNS, $this->prefix . ':' . $name);
}
return $node;
}
public function setCanonicalMethod($method) {
switch ($method) {
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$this->canonicalMethod = $method;
break;
default:
throw new Exception('Invalid Canonical Method');
}
if ($xpath = $this->getXPathObj()) {
$query = './' . $this->searchpfx . ':SignedInfo';
$nodeset = $xpath->query($query, $this->sigNode);
if ($sinfo = $nodeset->item(0)) {
$query = './' . $this->searchpfx . 'CanonicalizationMethod';
$nodeset = $xpath->query($query, $sinfo);
if (!($canonNode = $nodeset->item(0))) {
$canonNode = $this->createNewSignNode('CanonicalizationMethod');
$sinfo->insertBefore($canonNode, $sinfo->firstChild);
}
$canonNode->setAttribute('Algorithm', $this->canonicalMethod);
}
}
}
private function canonicalizeData($node, $canonicalmethod, $arXPath = NULL, $prefixList = NULL) {
$exclusive = FALSE;
$withComments = FALSE;
switch ($canonicalmethod) {
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
$exclusive = FALSE;
$withComments = FALSE;
break;
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
$withComments = TRUE;
break;
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
$exclusive = TRUE;
break;
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$exclusive = TRUE;
$withComments = TRUE;
break;
}
/* Support PHP versions < 5.2 not containing C14N methods in DOM extension */
$php_version = explode('.', PHP_VERSION);
if (($php_version[0] < 5) || ($php_version[0] == 5 && $php_version[1] < 2)) {
if (!is_null($arXPath)) {
throw new Exception("PHP 5.2.0 or higher is required to perform XPath Transformations");
}
return C14NGeneral($node, $exclusive, $withComments);
}
return $node->C14N($exclusive, $withComments, $arXPath, $prefixList);
}
public function canonicalizeSignedInfo() {
$doc = $this->sigNode->ownerDocument;
$canonicalmethod = NULL;
if ($doc) {
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($signInfoNode = $nodeset->item(0)) {
$query = "./secdsig:CanonicalizationMethod";
$nodeset = $xpath->query($query, $signInfoNode);
if ($canonNode = $nodeset->item(0)) {
$canonicalmethod = $canonNode->getAttribute('Algorithm');
}
$this->signedInfo = $this->canonicalizeData($signInfoNode, $canonicalmethod);
$this->addEnvelopeNamespace();
return $this->signedInfo;
}
}
return NULL;
}
public function addEnvelopeNamespace() {
$this->signedInfo = str_replace(self::NS_XMLDSIG, self::NS_XMLDSIG . " " . self::NS_ENVELOPE, $this->signedInfo);
}
public function canonicalizeBody() {
$doc = $this->sigNode->ownerDocument;
$canonicalmethod = NULL;
if ($doc) {
$xpath = $this->getXPathObj();
$query = '//*[local-name()="Body"]';
$nodeset = $xpath->query($query);
$bodyNode = $nodeset->item(0);
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($signInfoNode = $nodeset->item(0)) {
$query = "./secdsig:CanonicalizationMethod";
$nodeset = $xpath->query($query, $signInfoNode);
if ($canonNode = $nodeset->item(0)) {
$canonicalmethod = $canonNode->getAttribute('Algorithm');
}
$this->body = $this->canonicalizeData($bodyNode, $canonicalmethod);
return $this->body;
}
}
return NULL;
}
public function calculateDigest($digestAlgorithm, $data) {
switch ($digestAlgorithm) {
case XMLSecurityDSig::SHA1:
$alg = 'sha1';
break;
case XMLSecurityDSig::SHA256:
$alg = 'sha256';
break;
case XMLSecurityDSig::SHA512:
$alg = 'sha512';
break;
case XMLSecurityDSig::RIPEMD160:
$alg = 'ripemd160';
break;
default:
throw new Exception("Cannot validate digest: Unsupported Algorith <$digestAlgorithm>");
}
if (function_exists('hash')) {
return base64_encode(hash($alg, $data, TRUE));
} elseif (function_exists('mhash')) {
$alg = "MHASH_" . strtoupper($alg);
return base64_encode(mhash(constant($alg), $data));
} elseif ($alg === 'sha1') {
return base64_encode(sha1($data, TRUE));
} else {
throw new Exception('xmlseclibs is unable to calculate a digest. Maybe you need the mhash library?');
}
}
public function validateDigest($refNode, $data) {
$xpath = new DOMXPath($refNode->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = 'string(./secdsig:DigestMethod/@Algorithm)';
$digestAlgorithm = $xpath->evaluate($query, $refNode);
$digValue = $this->calculateDigest($digestAlgorithm, $data);
$query = 'string(./secdsig:DigestValue)';
$digestValue = $xpath->evaluate($query, $refNode);
return ($digValue == $digestValue);
}
public function processTransforms($refNode, $objData) {
$data = $objData;
$xpath = new DOMXPath($refNode->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = './secdsig:Transforms/secdsig:Transform';
$nodelist = $xpath->query($query, $refNode);
$canonicalMethod = 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315';
$arXPath = NULL;
$prefixList = NULL;
foreach ($nodelist AS $transform) {
$algorithm = $transform->getAttribute("Algorithm");
switch ($algorithm) {
case 'http://www.w3.org/2001/10/xml-exc-c14n#':
case 'http://www.w3.org/2001/10/xml-exc-c14n#WithComments':
$node = $transform->firstChild;
while ($node) {
if ($node->localName == 'InclusiveNamespaces') {
if ($pfx = $node->getAttribute('PrefixList')) {
$arpfx = array();
$pfxlist = explode(" ", $pfx);
foreach ($pfxlist AS $pfx) {
$val = trim($pfx);
if (!empty($val)) {
$arpfx[] = $val;
}
}
if (count($arpfx) > 0) {
$prefixList = $arpfx;
}
}
break;
}
$node = $node->nextSibling;
}
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315':
case 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments':
$canonicalMethod = $algorithm;
break;
case 'http://www.w3.org/TR/1999/REC-xpath-19991116':
$node = $transform->firstChild;
while ($node) {
if ($node->localName == 'XPath') {
$arXPath = array();
$arXPath['query'] = '(.//. | .//@* | .//namespace::*)[' . $node->nodeValue . ']';
$arXpath['namespaces'] = array();
$nslist = $xpath->query('./namespace::*', $node);
foreach ($nslist AS $nsnode) {
if ($nsnode->localName != "xml") {
$arXPath['namespaces'][$nsnode->localName] = $nsnode->nodeValue;
}
}
break;
}
$node = $node->nextSibling;
}
break;
}
}
if ($data instanceof DOMNode) {
$data = $this->canonicalizeData($objData, $canonicalMethod, $arXPath, $prefixList);
}
return $data;
}
public function processRefNode($refNode) {
$dataObject = NULL;
if ($uri = $refNode->getAttribute("URI")) {
$arUrl = parse_url($uri);
if (empty($arUrl['path'])) {
if ($identifier = $arUrl['fragment']) {
$xPath = new DOMXPath($refNode->ownerDocument);
if ($this->idNS && is_array($this->idNS)) {
foreach ($this->idNS AS $nspf => $ns) {
$xPath->registerNamespace($nspf, $ns);
}
}
$iDlist = '@Id="' . $identifier . '"';
if (is_array($this->idKeys)) {
foreach ($this->idKeys AS $idKey) {
$iDlist .= " or @$idKey='$identifier'";
}
}
$query = '//*[' . $iDlist . ']';
$dataObject = $xPath->query($query)->item(0);
} else {
$dataObject = $refNode->ownerDocument;
}
} else {
$dataObject = file_get_contents($arUrl);
}
} else {
$dataObject = $refNode->ownerDocument;
}
$data = $this->processTransforms($refNode, $dataObject);
if (!$this->validateDigest($refNode, $data)) {
return FALSE;
}
if ($dataObject instanceof DOMNode) {
/* Add this node to the list of validated nodes. */
if (!empty($identifier)) {
$this->validatedNodes[$identifier] = $dataObject;
} else {
$this->validatedNodes[] = $dataObject;
}
}
return TRUE;
}
public function getRefNodeID($refNode) {
if ($uri = $refNode->getAttribute("URI")) {
$arUrl = parse_url($uri);
if (empty($arUrl['path'])) {
if ($identifier = $arUrl['fragment']) {
return $identifier;
}
}
}
return null;
}
public function getRefIDs() {
$refids = array();
$doc = $this->sigNode->ownerDocument;
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo/secdsig:Reference";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length == 0) {
throw new Exception("Reference nodes not found");
}
foreach ($nodeset AS $refNode) {
$refids[] = $this->getRefNodeID($refNode);
}
return $refids;
}
public function validateReference() {
$doc = $this->sigNode->ownerDocument;
if (!$doc->isSameNode($this->sigNode)) {
$this->sigNode->parentNode->removeChild($this->sigNode);
}
$xpath = $this->getXPathObj();
$query = "./secdsig:SignedInfo/secdsig:Reference";
$nodeset = $xpath->query($query, $this->sigNode);
if ($nodeset->length == 0) {
throw new Exception("Reference nodes not found");
}
/* Initialize/reset the list of validated nodes. */
$this->validatedNodes = array();
foreach ($nodeset AS $refNode) {
if (!$this->processRefNode($refNode)) {
/* Clear the list of validated nodes. */
$this->validatedNodes = NULL;
throw new Exception("Reference validation failed");
}
}
return TRUE;
}
private function addRefInternal($sinfoNode, $node, $algorithm, $arTransforms = NULL, $options = NULL) {
$prefix = NULL;
$prefix_ns = NULL;
$id_name = 'Id';
$overwrite_id = TRUE;
$force_uri = FALSE;
if (is_array($options)) {
$prefix = empty($options['prefix']) ? NULL : $options['prefix'];
$prefix_ns = empty($options['prefix_ns']) ? NULL : $options['prefix_ns'];
$id_name = empty($options['id_name']) ? 'Id' : $options['id_name'];
$overwrite_id = !isset($options['overwrite']) ? TRUE : (bool) $options['overwrite'];
$force_uri = !isset($options['force_uri']) ? FALSE : (bool) $options['force_uri'];
}
$attname = $id_name;
if (!empty($prefix)) {
$attname = $prefix . ':' . $attname;
}
$refNode = $this->createNewSignNode('Reference');
$sinfoNode->appendChild($refNode);
if (!$node instanceof DOMDocument) {
$uri = NULL;
if (!$overwrite_id) {
$uri = $node->getAttributeNS($prefix_ns, $attname);
}
if (empty($uri)) {
$uri = XMLSecurityDSig::generate_GUID();
$node->setAttributeNS($prefix_ns, $attname, $uri);
}
$refNode->setAttribute("URI", '#' . $uri);
} elseif ($force_uri) {
$refNode->setAttribute("URI", '');
}
$transNodes = $this->createNewSignNode('Transforms');
$refNode->appendChild($transNodes);
if (is_array($arTransforms)) {
foreach ($arTransforms AS $transform) {
$transNode = $this->createNewSignNode('Transform');
$transNodes->appendChild($transNode);
if (is_array($transform) &&
(!empty($transform['http://www.w3.org/TR/1999/REC-xpath-19991116'])) &&
(!empty($transform['http://www.w3.org/TR/1999/REC-xpath-19991116']['query']))) {
$transNode->setAttribute('Algorithm', 'http://www.w3.org/TR/1999/REC-xpath-19991116');
$XPathNode = $this->createNewSignNode('XPath', $transform['http://www.w3.org/TR/1999/REC-xpath-19991116']['query']);
$transNode->appendChild($XPathNode);
if (!empty($transform['http://www.w3.org/TR/1999/REC-xpath-19991116']['namespaces'])) {
foreach ($transform['http://www.w3.org/TR/1999/REC-xpath-19991116']['namespaces'] AS $prefix => $namespace) {
$XPathNode->setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:$prefix", $namespace);
}
}
} else {
$transNode->setAttribute('Algorithm', $transform);
}
}
} elseif (!empty($this->canonicalMethod)) {
$transNode = $this->createNewSignNode('Transform');
$transNodes->appendChild($transNode);
$transNode->setAttribute('Algorithm', $this->canonicalMethod);
}
$canonicalData = $this->processTransforms($refNode, $node);
$digValue = $this->calculateDigest($algorithm, $canonicalData);
$digestMethod = $this->createNewSignNode('DigestMethod');
$refNode->appendChild($digestMethod);
$digestMethod->setAttribute('Algorithm', $algorithm);
$digestValue = $this->createNewSignNode('DigestValue', $digValue);
$refNode->appendChild($digestValue);
}
public function addReference($node, $algorithm, $arTransforms = NULL, $options = NULL) {
if ($xpath = $this->getXPathObj()) {
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($sInfo = $nodeset->item(0)) {
$this->addRefInternal($sInfo, $node, $algorithm, $arTransforms, $options);
}
}
}
public function addReferenceList($arNodes, $algorithm, $arTransforms = NULL, $options = NULL) {
if ($xpath = $this->getXPathObj()) {
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($sInfo = $nodeset->item(0)) {
foreach ($arNodes AS $node) {
$this->addRefInternal($sInfo, $node, $algorithm, $arTransforms, $options);
}
}
}
}
public function addObject($data, $mimetype = NULL, $encoding = NULL) {
$objNode = $this->createNewSignNode('Object');
$this->sigNode->appendChild($objNode);
if (!empty($mimetype)) {
$objNode->setAtribute('MimeType', $mimetype);
}
if (!empty($encoding)) {
$objNode->setAttribute('Encoding', $encoding);
}
if ($data instanceof DOMElement) {
$newData = $this->sigNode->ownerDocument->importNode($data, TRUE);
} else {
$newData = $this->sigNode->ownerDocument->createTextNode($data);
}
$objNode->appendChild($newData);
return $objNode;
}
public function locateKey($node = NULL) {
if (empty($node)) {
$node = $this->sigNode;
}
if (!$node instanceof DOMNode) {
return NULL;
}
if ($doc = $node->ownerDocument) {
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = "string(./secdsig:SignedInfo/secdsig:SignatureMethod/@Algorithm)";
$algorithm = $xpath->evaluate($query, $node);
if ($algorithm) {
try {
$objKey = new XMLSecurityKey($algorithm, array('type' => 'public'));
} catch (Exception $e) {
return NULL;
}
return $objKey;
}
}
return NULL;
}
public function verify($objKey) {
$doc = $this->sigNode->ownerDocument;
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = "string(./secdsig:SignatureValue)";
$sigValue = $xpath->evaluate($query, $this->sigNode);
if (empty($sigValue)) {
throw new Exception("Unable to locate SignatureValue");
}
return $objKey->verifySignature($this->signedInfo, base64_decode($sigValue));
}
public function getSigValue() {
$doc = $this->sigNode->ownerDocument;
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
$query = "string(./secdsig:SignatureValue)";
$sigValue = $xpath->evaluate($query, $this->sigNode);
if (empty($sigValue)) {
throw new Exception("Unable to locate SignatureValue");
}
return $sigValue;
}
/* Compare with SHA1 algorithm */
public function compareDigest($data) {
$digestValue = $this->sigNode->firstChild->nodeValue;
$digestValueBody = $this->calculateDigest(self::SHA1, $data);
return ($digestValue == $digestValueBody);
}
public function signData($objKey, $data) {
return $objKey->signData($data);
}
public function sign($objKey, $appendToNode = NULL) {
// If we have a parent node append it now so C14N properly works
if ($appendToNode != NULL) {
$this->resetXPathObj();
$this->appendSignature($appendToNode);
$this->sigNode = $appendToNode->lastChild;
}
if ($xpath = $this->getXPathObj()) {
$query = "./secdsig:SignedInfo";
$nodeset = $xpath->query($query, $this->sigNode);
if ($sInfo = $nodeset->item(0)) {
$query = "./secdsig:SignatureMethod";
$nodeset = $xpath->query($query, $sInfo);
$sMethod = $nodeset->item(0);
$sMethod->setAttribute('Algorithm', $objKey->type);
$data = $this->canonicalizeData($sInfo, $this->canonicalMethod);
$sigValue = base64_encode($this->signData($objKey, $data));
$sigValueNode = $this->createNewSignNode('SignatureValue', $sigValue);
if ($infoSibling = $sInfo->nextSibling) {
$infoSibling->parentNode->insertBefore($sigValueNode, $infoSibling);
} else {
$this->sigNode->appendChild($sigValueNode);
}
}
}
}
public function appendCert() {
}
public function appendKey($objKey, $parent = NULL) {
$objKey->serializeKey($parent);
}
/**
* This function inserts the signature element.
*
* The signature element will be appended to the element, unless $beforeNode is specified. If $beforeNode
* is specified, the signature element will be inserted as the last element before $beforeNode.
*
* @param $node The node the signature element should be inserted into.
* @param $beforeNode The node the signature element should be located before.
*/
public function insertSignature($node, $beforeNode = NULL) {
$document = $node->ownerDocument;
$signatureElement = $document->importNode($this->sigNode, TRUE);
if ($beforeNode == NULL) {
$node->insertBefore($signatureElement);
} else {
$node->insertBefore($signatureElement, $beforeNode);
}
}
public function appendSignature($parentNode, $insertBefore = FALSE) {
$beforeNode = $insertBefore ? $parentNode->firstChild : NULL;
$this->insertSignature($parentNode, $beforeNode);
}
static function get509XCert($cert, $isPEMFormat = TRUE) {
$certs = XMLSecurityDSig::staticGet509XCerts($cert, $isPEMFormat);
if (!empty($certs)) {
return $certs[0];
}
return '';
}
static function staticGet509XCerts($certs, $isPEMFormat = TRUE) {
if ($isPEMFormat) {
$data = '';
$certlist = array();
$arCert = explode("\n", $certs);
$inData = FALSE;
foreach ($arCert AS $curData) {
if (!$inData) {
if (strncmp($curData, '-----BEGIN CERTIFICATE', 22) == 0) {
$inData = TRUE;
}
} else {
if (strncmp($curData, '-----END CERTIFICATE', 20) == 0) {
$inData = FALSE;
$certlist[] = $data;
$data = '';
continue;
}
$data .= trim($curData);
}
}
return $certlist;
} else {
return array($certs);
}
}
static function staticAdd509Cert($parentRef, $cert, $isPEMFormat = TRUE, $isURL = False, $xpath = NULL) {
if ($isURL) {
$cert = file_get_contents($cert);
}
if (!$parentRef instanceof DOMElement) {
throw new Exception('Invalid parent Node parameter');
}
$baseDoc = $parentRef->ownerDocument;
if (empty($xpath)) {
$xpath = new DOMXPath($parentRef->ownerDocument);
$xpath->registerNamespace('secdsig', XMLSecurityDSig::XMLDSIGNS);
}
$query = "./secdsig:KeyInfo";
$nodeset = $xpath->query($query, $parentRef);
$keyInfo = $nodeset->item(0);
if (!$keyInfo) {
$inserted = FALSE;
$keyInfo = $baseDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:KeyInfo');
$query = "./secdsig:Object";
$nodeset = $xpath->query($query, $parentRef);
if ($sObject = $nodeset->item(0)) {
$sObject->parentNode->insertBefore($keyInfo, $sObject);
$inserted = TRUE;
}
if (!$inserted) {
$parentRef->appendChild($keyInfo);
}
}
// Add all certs if there are more than one
$certs = XMLSecurityDSig::staticGet509XCerts($cert, $isPEMFormat);
// Atach X509 data node
$x509DataNode = $baseDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:X509Data');
$keyInfo->appendChild($x509DataNode);
// Atach all certificate nodes
foreach ($certs as $X509Cert) {
$x509CertNode = $baseDoc->createElementNS(XMLSecurityDSig::XMLDSIGNS, 'ds:X509Certificate', $X509Cert);
$x509DataNode->appendChild($x509CertNode);
}
}
public function add509Cert($cert, $isPEMFormat = TRUE, $isURL = False) {
if ($xpath = $this->getXPathObj()) {
self::staticAdd509Cert($this->sigNode, $cert, $isPEMFormat, $isURL, $xpath);
}
}
/* This function retrieves an associative array of the validated nodes.
*
* The array will contain the id of the referenced node as the key and the node itself
* as the value.
*
* Returns:
* An associative array of validated nodes or NULL if no nodes have been validated.
*/
public function getValidatedNodes() {
return $this->validatedNodes;
}
}
class XMLSecEnc {
const template = "<xenc:EncryptedData xmlns:xenc='http://www.w3.org/2001/04/xmlenc#'>
<xenc:CipherData>
<xenc:CipherValue></xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>";
const Element = 'http://www.w3.org/2001/04/xmlenc#Element';
const Content = 'http://www.w3.org/2001/04/xmlenc#Content';
const URI = 3;
const XMLENCNS = 'http://www.w3.org/2001/04/xmlenc#';
private $encdoc = NULL;
private $rawNode = NULL;
public $type = NULL;
public $encKey = NULL;
private $references = array();
public function __construct() {
$this->_resetTemplate();
}
private function _resetTemplate() {
$this->encdoc = new DOMDocument();
$this->encdoc->loadXML(XMLSecEnc::template);
}
public function addReference($name, $node, $type) {
if (!$node instanceOf DOMNode) {
throw new Exception('$node is not of type DOMNode');
}
$curencdoc = $this->encdoc;
$this->_resetTemplate();
$encdoc = $this->encdoc;
$this->encdoc = $curencdoc;
$refuri = XMLSecurityDSig::generate_GUID();
$element = $encdoc->documentElement;
$element->setAttribute("Id", $refuri);
$this->references[$name] = array("node" => $node, "type" => $type, "encnode" => $encdoc, "refuri" => $refuri);
}
public function setNode($node) {
$this->rawNode = $node;
}
public function encryptNode($objKey, $replace = TRUE) {
$data = '';
if (empty($this->rawNode)) {
throw new Exception('Node to encrypt has not been set');
}
if (!$objKey instanceof XMLSecurityKey) {
throw new Exception('Invalid Key');
}
$doc = $this->rawNode->ownerDocument;
$xPath = new DOMXPath($this->encdoc);
$objList = $xPath->query('/xenc:EncryptedData/xenc:CipherData/xenc:CipherValue');
$cipherValue = $objList->item(0);
if ($cipherValue == NULL) {
throw new Exception('Error locating CipherValue element within template');
}
switch ($this->type) {
case (XMLSecEnc::Element):
$data = $doc->saveXML($this->rawNode);
$this->encdoc->documentElement->setAttribute('Type', XMLSecEnc::Element);
break;
case (XMLSecEnc::Content):
$children = $this->rawNode->childNodes;
foreach ($children AS $child) {
$data .= $doc->saveXML($child);
}
$this->encdoc->documentElement->setAttribute('Type', XMLSecEnc::Content);
break;
default:
throw new Exception('Type is currently not supported');
return;
}
$encMethod = $this->encdoc->documentElement->appendChild($this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:EncryptionMethod'));
$encMethod->setAttribute('Algorithm', $objKey->getAlgorith());
$cipherValue->parentNode->parentNode->insertBefore($encMethod, $cipherValue->parentNode);
$strEncrypt = base64_encode($objKey->encryptData($data));
$value = $this->encdoc->createTextNode($strEncrypt);
$cipherValue->appendChild($value);
if ($replace) {
switch ($this->type) {
case (XMLSecEnc::Element):
if ($this->rawNode->nodeType == XML_DOCUMENT_NODE) {
return $this->encdoc;
}
$importEnc = $this->rawNode->ownerDocument->importNode($this->encdoc->documentElement, TRUE);
$this->rawNode->parentNode->replaceChild($importEnc, $this->rawNode);
return $importEnc;
break;
case (XMLSecEnc::Content):
$importEnc = $this->rawNode->ownerDocument->importNode($this->encdoc->documentElement, TRUE);
while ($this->rawNode->firstChild) {
$this->rawNode->removeChild($this->rawNode->firstChild);
}
$this->rawNode->appendChild($importEnc);
return $importEnc;
break;
}
}
}
public function encryptReferences($objKey) {
$curRawNode = $this->rawNode;
$curType = $this->type;
foreach ($this->references AS $name => $reference) {
$this->encdoc = $reference["encnode"];
$this->rawNode = $reference["node"];
$this->type = $reference["type"];
try {
$encNode = $this->encryptNode($objKey);
$this->references[$name]["encnode"] = $encNode;
} catch (Exception $e) {
$this->rawNode = $curRawNode;
$this->type = $curType;
throw $e;
}
}
$this->rawNode = $curRawNode;
$this->type = $curType;
}
public function decryptNode($objKey, $replace = TRUE) {
$data = '';
if (empty($this->rawNode)) {
throw new Exception('Node to decrypt has not been set');
}
if (!$objKey instanceof XMLSecurityKey) {
throw new Exception('Invalid Key');
}
$doc = $this->rawNode->ownerDocument;
$xPath = new DOMXPath($doc);
$xPath->registerNamespace('xmlencr', XMLSecEnc::XMLENCNS);
/* Only handles embedded content right now and not a reference */
$query = "./xmlencr:CipherData/xmlencr:CipherValue";
$nodeset = $xPath->query($query, $this->rawNode);
if ($node = $nodeset->item(0)) {
$encryptedData = base64_decode($node->nodeValue);
$decrypted = $objKey->decryptData($encryptedData);
if ($replace) {
switch ($this->type) {
case (XMLSecEnc::Element):
$newdoc = new DOMDocument();
$newdoc->loadXML($decrypted);
if ($this->rawNode->nodeType == XML_DOCUMENT_NODE) {
return $newdoc;
}
$importEnc = $this->rawNode->ownerDocument->importNode($newdoc->documentElement, TRUE);
$this->rawNode->parentNode->replaceChild($importEnc, $this->rawNode);
return $importEnc;
break;
case (XMLSecEnc::Content):
if ($this->rawNode->nodeType == XML_DOCUMENT_NODE) {
$doc = $this->rawNode;
} else {
$doc = $this->rawNode->ownerDocument;
}
$newFrag = $doc->createDocumentFragment();
$newFrag->appendXML($decrypted);
$parent = $this->rawNode->parentNode;
$parent->replaceChild($newFrag, $this->rawNode);
return $parent;
break;
default:
return $decrypted;
}
} else {
return $decrypted;
}
} else {
throw new Exception("Cannot locate encrypted data");
}
}
public function encryptKey($srcKey, $rawKey, $append = TRUE) {
if ((!$srcKey instanceof XMLSecurityKey) || (!$rawKey instanceof XMLSecurityKey)) {
throw new Exception('Invalid Key');
}
$strEncKey = base64_encode($srcKey->encryptData($rawKey->key));
$root = $this->encdoc->documentElement;
$encKey = $this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:EncryptedKey');
if ($append) {
$keyInfo = $root->appendChild($this->encdoc->createElementNS('http://www.w3.org/2000/09/xmldsig#', 'dsig:KeyInfo'));
$keyInfo->appendChild($encKey);
} else {
$this->encKey = $encKey;
}
$encMethod = $encKey->appendChild($this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:EncryptionMethod'));
$encMethod->setAttribute('Algorithm', $srcKey->getAlgorith());
if (!empty($srcKey->name)) {
$keyInfo = $encKey->appendChild($this->encdoc->createElementNS('http://www.w3.org/2000/09/xmldsig#', 'dsig:KeyInfo'));
$keyInfo->appendChild($this->encdoc->createElementNS('http://www.w3.org/2000/09/xmldsig#', 'dsig:KeyName', $srcKey->name));
}
$cipherData = $encKey->appendChild($this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:CipherData'));
$cipherData->appendChild($this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:CipherValue', $strEncKey));
if (is_array($this->references) && count($this->references) > 0) {
$refList = $encKey->appendChild($this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:ReferenceList'));
foreach ($this->references AS $name => $reference) {
$refuri = $reference["refuri"];
$dataRef = $refList->appendChild($this->encdoc->createElementNS(XMLSecEnc::XMLENCNS, 'xenc:DataReference'));
$dataRef->setAttribute("URI", '#' . $refuri);
}
}
return;
}
public function decryptKey($encKey) {
if (!$encKey->isEncrypted) {
throw new Exception("Key is not Encrypted");
}
if (empty($encKey->key)) {
throw new Exception("Key is missing data to perform the decryption");
}
return $this->decryptNode($encKey, FALSE);
}
public function locateEncryptedData($element) {
if ($element instanceof DOMDocument) {
$doc = $element;
} else {
$doc = $element->ownerDocument;
}
if ($doc) {
$xpath = new DOMXPath($doc);
$query = "//*[local-name()='EncryptedData' and namespace-uri()='" . XMLSecEnc::XMLENCNS . "']";
$nodeset = $xpath->query($query);
return $nodeset->item(0);
}
return NULL;
}
public function locateKey($node = NULL) {
if (empty($node)) {
$node = $this->rawNode;
}
if (!$node instanceof DOMNode) {
return NULL;
}
if ($doc = $node->ownerDocument) {
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('xmlsecenc', XMLSecEnc::XMLENCNS);
$query = ".//xmlsecenc:EncryptionMethod";
$nodeset = $xpath->query($query, $node);
if ($encmeth = $nodeset->item(0)) {
$attrAlgorithm = $encmeth->getAttribute("Algorithm");
try {
$objKey = new XMLSecurityKey($attrAlgorithm, array('type' => 'private'));
} catch (Exception $e) {
return NULL;
}
return $objKey;
}
}
return NULL;
}
static function staticLocateKeyInfo($objBaseKey = NULL, $node = NULL) {
if (empty($node) || (!$node instanceof DOMNode)) {
return NULL;
}
if ($doc = $node->ownerDocument) {
$xpath = new DOMXPath($doc);
$xpath->registerNamespace('xmlsecenc', XMLSecEnc::XMLENCNS);
$xpath->registerNamespace('xmlsecdsig', XMLSecurityDSig::XMLDSIGNS);
$query = "./xmlsecdsig:KeyInfo";
$nodeset = $xpath->query($query, $node);
if ($encmeth = $nodeset->item(0)) {
foreach ($encmeth->childNodes AS $child) {
switch ($child->localName) {
case 'KeyName':
if (!empty($objBaseKey)) {
$objBaseKey->name = $child->nodeValue;
}
break;
case 'KeyValue':
foreach ($child->childNodes AS $keyval) {
switch ($keyval->localName) {
case 'DSAKeyValue':
throw new Exception("DSAKeyValue currently not supported");
break;
case 'RSAKeyValue':
$modulus = NULL;
$exponent = NULL;
if ($modulusNode = $keyval->getElementsByTagName('Modulus')->item(0)) {
$modulus = base64_decode($modulusNode->nodeValue);
}
if ($exponentNode = $keyval->getElementsByTagName('Exponent')->item(0)) {
$exponent = base64_decode($exponentNode->nodeValue);
}
if (empty($modulus) || empty($exponent)) {
throw new Exception("Missing Modulus or Exponent");
}
$publicKey = XMLSecurityKey::convertRSA($modulus, $exponent);
$objBaseKey->loadKey($publicKey);
break;
}
}
break;
case 'RetrievalMethod':
/* Not currently supported */
break;
case 'EncryptedKey':
$objenc = new XMLSecEnc();
$objenc->setNode($child);
if (!$objKey = $objenc->locateKey()) {
throw new Exception("Unable to locate algorithm for this Encrypted Key");
}
$objKey->isEncrypted = TRUE;
$objKey->encryptedCtx = $objenc;
XMLSecEnc::staticLocateKeyInfo($objKey, $child);
return $objKey;
break;
case 'X509Data':
if ($x509certNodes = $child->getElementsByTagName('X509Certificate')) {
if ($x509certNodes->length > 0) {
$x509cert = $x509certNodes->item(0)->textContent;
$x509cert = str_replace(array("\r", "\n"), "", $x509cert);
$x509cert = "-----BEGIN CERTIFICATE-----\n" . chunk_split($x509cert, 64, "\n") . "-----END CERTIFICATE-----\n";
$objBaseKey->loadKey($x509cert, FALSE, TRUE);
}
}
break;
}
}
}
return $objBaseKey;
}
return NULL;
}
public function locateKeyInfo($objBaseKey = NULL, $node = NULL) {
if (empty($node)) {
$node = $this->rawNode;
}
return XMLSecEnc::staticLocateKeyInfo($objBaseKey, $node);
}
}
| sGarciaCL/Transbank | libwebpay/soap/xmlseclibs.php | PHP | gpl-3.0 | 69,538 |
<?php
/* Copyright (C) 2006 Technikum-Wien
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*
* Authors: Christian Paminger < christian.paminger@technikum-wien.at >
* Andreas Oesterreicher < andreas.oesterreicher@technikum-wien.at >
* Rudolf Hangl < rudolf.hangl@technikum-wien.at >
* Gerald Simane-Sequens < gerald.simane-sequens@technikum-wien.at >
*/
/**
* Changes: 23.10.2004: Anpassung an neues DB-Schema (WM)
*/
require_once('../../config/vilesci.config.inc.php');
require_once('../../include/basis_db.class.php');
if (!$db = new basis_db())
die('Es konnte keine Verbindung zum Server aufgebaut werden.');
require_once('../../include/functions.inc.php');
?>
<html>
<head>
<title>Kontakte - eMail-Verteiler</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="../../skin/vilesci.css" type="text/css">
</head>
<body class="background_main">
<h4>Kontakte - eMail-Verteiler</h4>
<br>
<h3>Module</h3>
<table class="liste">
<tr class="liste" >
<?php
if(!($erg=$db->db_query("SELECT studiengang_kz, bezeichnung, UPPER(typ::varchar(1) || kurzbz) as kurzbz FROM public.tbl_studiengang ORDER BY kurzbz ASC")))
die($db->db_last_error());
$num_rows=$db->db_num_rows($erg);
for ($i=0;$i<$num_rows;$i++)
{
$row=$db->db_fetch_object($erg, $i);
echo "<th>$row->kurzbz<BR><SMALL>$row->bezeichnung</SMALL></th>";
}
?>
</tr>
<tr bgcolor="#DDDDDD" valign="top">
<?php
for ($i=0; $i<$num_rows; $i++)
{
echo "<td nowrap>";
$row=$db->db_fetch_object($erg, $i);
$stg_id=$row->studiengang_kz;
$stg_kzbz=$row->kurzbz;
$sql_query="SELECT * FROM public.tbl_gruppe WHERE studiengang_kz=$stg_id ORDER BY gruppe_kurzbz";
//echo $sql_query;
if(!($result=$db->db_query($sql_query)))
die($db->db_last_error());
$nr_sem=$db->db_num_rows($result);
for ($j=0; $j<$nr_sem; $j++)
{
$row_sem=$db->db_fetch_object($result, $j);
if($row_sem->mailgrp=='t')
echo "<a class=\"h1\" href=\"mailto:$row_sem->gruppe_kurzbz@technikum-wien.at\">$row_sem->gruppe_kurzbz</a><br>";
else
echo "$row_sem->gruppe_kurzbz<br>";
echo "<a target=\"_blank\" class=\"linkgreen\" href=\"studenten_liste_export.php?einheitid=$row_sem->gruppe_kurzbz\"> (Liste)</a><br>";
}
echo"</td>";
}
?>
</tr>
</table>
<h3>Studenten</h3>
<table class="liste">
<tr class="liste">
<?php
if(!($erg=$db->db_query("SELECT studiengang_kz, bezeichnung, UPPER(typ::varchar(1) || kurzbz) as kurzbz FROM public.tbl_studiengang ORDER BY kurzbz ASC")))
die($db->db_last_error());
$num_rows=$db->db_num_rows($erg);
for ($i=0;$i<$num_rows;$i++)
{
$row=$db->db_fetch_object($erg, $i);
echo "<th>$row->kurzbz<BR><SMALL>$row->bezeichnung</SMALL></th>";
}
?>
</tr>
<tr bgcolor="#DDDDDD">
<?php
for ($i=0; $i<$num_rows; $i++)
{
echo "<td nowrap valign= \"top\">";
$row=$db->db_fetch_object($erg, $i);
$stg_id=$row->studiengang_kz;
$stg_kzbz=$row->kurzbz;
$sql_query="SELECT DISTINCT semester FROM public.tbl_student WHERE studiengang_kz=$stg_id ORDER BY semester";
//echo $sql_query;
if(!($result_sem=$db->db_query($sql_query)))
die($db->db_last_error());
$nr_sem=$db->db_num_rows($result_sem);
for ($j=0; $j<$nr_sem; $j++)
{
$row_sem=$db->db_fetch_object($result_sem, $j);
$stg_kzbz_lo=strtolower($stg_kzbz);
echo "<a class=\"h1\" href=\"mailto:$stg_kzbz_lo$row_sem->semester@technikum-wien.at\">$stg_kzbz-$row_sem->semester</a><br>";
$sql_query="SELECT DISTINCT verband FROM public.tbl_student WHERE studiengang_kz=$stg_id AND semester=$row_sem->semester ORDER BY verband";
//echo $sql_query;
if(!($result_ver=$db->db_query($sql_query)))
die($db->db_last_error());
$nr_ver=$db->db_num_rows($result_ver);
for ($k=0; $k<$nr_ver; $k++)
{
$row_ver=$db->db_fetch_object($result_ver, $k);
$ver_lo=strtolower($row_ver->verband);
echo " - <a class=\"linkblue\" href=\"mailto:$stg_kzbz_lo$row_sem->semester$ver_lo@technikum-wien.at\">$stg_kzbz-$row_sem->semester$row_ver->verband</a><br>";
$sql_query="SELECT DISTINCT gruppe FROM public.tbl_student WHERE studiengang_kz=$stg_id AND semester=$row_sem->semester AND verband='$row_ver->verband' ORDER BY gruppe";
//echo $sql_query;
if(!($result_grp=$db->db_query($sql_query)))
die($db->db_last_error());
$nr_grp=$db->db_num_rows($result_grp);
for ($l=0; $l<$nr_grp; $l++)
{
$row_grp=$db->db_fetch_object($result_grp, $l);
echo " - <a class=\"linkgreen\" href=\"mailto:$stg_kzbz_lo$row_sem->semester$ver_lo$row_grp->gruppe@technikum-wien.at\">$stg_kzbz-$row_sem->semester$row_ver->verband$row_grp->gruppe</a><br>";
echo "<a target=\"_blank\" class=\"linkgreen\" href=\"studenten_liste_export.php?stgid=$stg_id&stg_kzbz=$stg_kzbz_lo&sem=$row_sem->semester&ver=$ver_lo&grp=$row_grp->gruppe\"> (Liste)</a><br>";
}
}
}
echo"</td>";
}
?>
</tr>
</table>
</body>
</html>
| zsh2938/FHC-Core | vilesci/kommunikation/kontakt.php | PHP | gpl-3.0 | 5,668 |
package unagoclient.partner;
import unagoclient.Global;
import unagoclient.gui.*;
import javax.swing.*;
/**
* Displays a send dialog, when the partner presses "Send" in the GoFrame. The
* message is appended to the PartnerFrame.
*/
public class PartnerSendQuestion extends CloseDialog {
/**
*
*/
private static final long serialVersionUID = 1L;
PartnerGoFrame F;
JTextField T;
PartnerFrame PF;
public PartnerSendQuestion(PartnerGoFrame f, PartnerFrame pf) {
super(f, Global.resourceString("Send"), false);
this.F = f;
this.PF = pf;
this.add("North", new MyLabel(Global.resourceString("Message_")));
this.add("Center", this.T = new GrayTextField(25));
final JPanel p = new MyPanel();
p.add(new ButtonAction(this, Global.resourceString("Say")));
p.add(new ButtonAction(this, Global.resourceString("Cancel")));
this.add("South", new Panel3D(p));
Global.setpacked(this, "partnersend", 200, 150);
this.validate();
this.setVisible(true);
}
@Override
public void doAction(String o) {
Global.notewindow(this, "partnersend");
if (Global.resourceString("Say").equals(o)) {
if (!this.T.getText().equals("")) {
this.PF.out(this.T.getText());
this.F.addComment(Global.resourceString("Said__")
+ this.T.getText());
}
this.setVisible(false);
this.dispose();
} else if (Global.resourceString(Global.resourceString("Cancel"))
.equals(o)) {
this.setVisible(false);
this.dispose();
} else {
super.doAction(o);
}
}
}
| rdnz/UnaGo | unagoclient/partner/PartnerSendQuestion.java | Java | gpl-3.0 | 1,804 |
package com.baeldung.reflect;
public class Person {
private String fullName;
public Person(String fullName) {
this.fullName = fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getFullName() {
return fullName;
}
}
| Niky4000/UsefulUtils | projects/tutorials-master/tutorials-master/core-java-modules/core-java-8/src/main/java/com/baeldung/reflect/Person.java | Java | gpl-3.0 | 278 |
# coding=utf8
r"""
csection.py -- Create a tree of contents, organized by sections and inside
sections the exercises unique_name.
AUTHOR:
- Pedro Cruz (2012-01): initial version
- Pedro Cruz (2016-03): improvment for smc
An exercise could contain um its %summary tag line a description of section
in form::
%sumary section descriptive text; subsection descriptive text; etc
The class transform contents of some MegUA database into a tree of sections specifying exercises as leaves.
Then, this tree can be flushed out to some file or output system.
STRUTURE SAMPLE::
contents -> { 'Section1': Section('Section1',0), 'Section2': Section('Section2',0) }
For each Section object see below in this file.
A brief description is:
* a SectionClassifier is the "book" made with keys (chapter names) that are keys of a dictionary.
* SectionClassifier is a dictionary: keys are the chapter names and the values are Section objects.
* a Section object is defined by
* a name (the key of the SectionClassifiers appears again in sec_name)
* level (0 if it is top level sections: chapters, and so on)
* a list of exercises beloging to the section and
* a dictionary of subsections (again Section objects)
* Section = (sec_name, level, [list of exercises names], dict( subsections ) )
EXAMPLES:
Test with:
::
sage -t csection.py
Create or edit a database:
::
sage: from megua.megbook import MegBook
sage: meg = MegBook(r'_input/csection.sqlite')
Save a new or changed exercise
::
sage: txt=r'''
....: %Summary Primitives; Imediate primitives; Trigonometric
....:
....: Here, is a summary.
....:
....: %Problem Some Name
....: What is the primitive of $a x + b@()$ ?
....:
....: %Answer
....: The answer is $prim+C$, for $C in \mathbb{R}$.
....:
....: class E28E28_pimtrig_001(ExerciseBase):
....: pass
....: '''
sage: meg.save(txt)
-------------------------------
Instance of: E28E28_pimtrig_001
-------------------------------
==> Summary:
Here, is a summary.
==> Problem instance
What is the primitive of $a x + b$ ?
==> Answer instance
The answer is $prim+C$, for $C in \mathbb{R}$.
sage: txt=r'''
....: %Summary Primitives; Imediate primitives; Trigonometric
....:
....: Here, is a summary.
....:
....: %Problem Some Name2
....: What is the primitive of $a x + b@()$ ?
....:
....: %Answer
....: The answer is $prim+C$, for $C in \mathbb{R}$.
....:
....: class E28E28_pimtrig_002(ExerciseBase):
....: pass
....: '''
sage: meg.save(txt)
-------------------------------
Instance of: E28E28_pimtrig_002
-------------------------------
==> Summary:
Here, is a summary.
==> Problem instance
What is the primitive of $a x + b$ ?
==> Answer instance
The answer is $prim+C$, for $C in \mathbb{R}$.
sage: txt=r'''
....: %Summary Primitives; Imediate primitives; Polynomial
....:
....: Here, is a summary.
....:
....: %Problem Some Problem 1
....: What is the primitive of $a x + b@()$ ?
....:
....: %Answer
....: The answer is $prim+C$, for $C in \mathbb{R}$.
....:
....: class E28E28_pdirect_001(ExerciseBase):
....: pass
....: '''
sage: meg.save(txt)
-------------------------------
Instance of: E28E28_pdirect_001
-------------------------------
==> Summary:
Here, is a summary.
==> Problem instance
What is the primitive of $a x + b$ ?
==> Answer instance
The answer is $prim+C$, for $C in \mathbb{R}$.
sage: txt=r'''
....: %Summary
....:
....: Here, is a summary.
....:
....: %Problem
....: What is the primitive of $a x + b@()$ ?
....:
....: %Answer
....: The answer is $prim+C$, for $C in \mathbb{R}$.
....:
....: class E28E28_pdirect_003(ExerciseBase):
....: pass
....: '''
sage: meg.save(txt)
Each exercise can belong to a section/subsection/subsubsection.
Write sections using ';' in the '%summary' line. For ex., '%summary Section; Subsection; Subsubsection'.
<BLANKLINE>
Each problem can have a suggestive name.
Write in the '%problem' line a name, for ex., '%problem The Fish Problem'.
<BLANKLINE>
Check exercise E28E28_pdirect_003 for the above warnings.
-------------------------------
Instance of: E28E28_pdirect_003
-------------------------------
==> Summary:
Here, is a summary.
==> Problem instance
What is the primitive of $a x + b$ ?
==> Answer instance
The answer is $prim+C$, for $C in \mathbb{R}$.
Travel down the tree sections:
::
sage: s = SectionClassifier(meg.megbook_store)
sage: s.textprint()
Primitives
Imediate primitives
Polynomial
> E28E28_pdirect_001
Trigonometric
> E28E28_pimtrig_001
> E28E28_pimtrig_002
E28E28_pdirect
> E28E28_pdirect_003
Testing a recursive iterator:
::
sage: meg = MegBook("_input/paula.sqlite")
sage: s = SectionClassifier(meg.megbook_store)
sage: for section in s.section_iterator():
....: print section
"""
#*****************************************************************************
# Copyright (C) 2011,2016 Pedro Cruz <PedroCruz@ua.pt>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************************************************************
#PYHTON modules
import collections
#MEGUA modules
from megua.localstore import ExIter
class SectionClassifier:
"""
"""
def __init__(self,megbook_store,max_level=4,debug=False,exerset=None):
#save megstore reference
self.megbook_store = megbook_store
self.max_level = max_level
#Exercise set or none for all
self.exercise_set = exerset
#dictionary of sections
self.contents = dict()
self.classify()
def classify(self):
"""
Classify by sections.
"""
for row in ExIter(self.megbook_store):
if self.exercise_set and not row['unique_name'] in self.exercise_set:
continue
#get a list in form ["section", "subsection", "subsubsection", ...]
sec_list = str_to_list(row['sections_text'])
if sec_list == [] or sec_list == [u'']:
sec_list = [ first_part(row['unique_name']) ]
#sec_list contain at least one element.
if not sec_list[0] in self.contents:
self.contents[sec_list[0]] = Section(sec_list[0])
#sec_list contains less than `max_level` levels
subsec_list = sec_list[1:self.max_level]
self.contents[sec_list[0]].add(row['unique_name'],subsec_list)
def textprint(self):
"""
Textual print of all the contents.
"""
for c in self.contents:
self.contents[c].textprint()
def section_iterator(self):
r"""
OUTPUT:
- an iterator yielding (secname, sorted exercises)
"""
# A stack-based alternative to the traverse_tree method above.
od_top = collections.OrderedDict(sorted(self.contents.items()))
stack = []
for secname,section in od_top.iteritems():
stack.append(section)
while stack:
section_top = stack.pop(0) #remove left element
yield section_top
od_sub = collections.OrderedDict(sorted(section_top.subsections.items()))
desc = []
for secname,section in od_sub.iteritems():
desc.append(section)
stack[:0] = desc #add elemnts from desc list at left (":0")
class Section:
r"""
Section = (sec_name, level, [list of exercises names], dict( subsections ) )
"""
def __init__(self,sec_name,level=0):
self.sec_name = sec_name
self.level = level
#Exercises of this section (self).
self.exercises = []
#This section (self) can have subsections.
self.subsections = dict()
def __str__(self):
return self.level*" " + self.sec_name.encode("utf8") + " has " + str(len(self.exercises))
def __repr__(self):
return self.level*" " + self.sec_name.encode("utf8") + " has " + str(len(self.exercises))
def add(self,exname,sections):
r"""
Recursive function to add an exercise to """
if sections == []:
self.exercises.append(exname)
self.exercises.sort()
return
if not sections[0] in self.subsections:
self.subsections[sections[0]] = Section(sections[0],self.level+1)
self.subsections[sections[0]].add(exname,sections[1:])
def textprint(self):
"""
Textual print of the contents of this section and, recursivly, of the subsections.
"""
sp = " "*self.level
print sp + self.sec_name
for e in self.exercises:
print sp+r"> "+e
for sub in self.subsections:
self.subsections[sub].textprint()
def str_to_list(s):
"""
Convert::
'section description; subsection description; subsubsection description'
into::
[ 'section description', 'subsection description', 'subsubsection description']
"""
sl = s.split(';')
for i in range(len(sl)):
sl[i] = sl[i].strip()
return sl
def first_part(s):
"""
Usually exercise are named like `E12X34_name_001` and this routine extracts `E12X34` or `top` if no underscore is present.
"""
p = s.find("_")
p = s.find("_",p+1)
if p!=-1:
s = s[:p]
if s=='':
s = 'top'
return s
| jpedroan/megua | megua/csection.py | Python | gpl-3.0 | 10,442 |
# Copyright 2008 Dan Smith <dsmith@danplanet.com>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import struct
import re
import time
import logging
from chirp import chirp_common, errors, util, memmap
from chirp.settings import RadioSetting, RadioSettingGroup, \
RadioSettingValueBoolean, RadioSettings
LOG = logging.getLogger(__name__)
CMD_CLONE_OUT = 0xE2
CMD_CLONE_IN = 0xE3
CMD_CLONE_DAT = 0xE4
CMD_CLONE_END = 0xE5
SAVE_PIPE = None
class IcfFrame:
"""A single ICF communication frame"""
src = 0
dst = 0
cmd = 0
payload = ""
def __str__(self):
addrs = {0xEE: "PC",
0xEF: "Radio"}
cmds = {0xE0: "ID",
0xE1: "Model",
0xE2: "Clone out",
0xE3: "Clone in",
0xE4: "Clone data",
0xE5: "Clone end",
0xE6: "Clone result"}
return "%s -> %s [%s]:\n%s" % (addrs[self.src], addrs[self.dst],
cmds[self.cmd],
util.hexprint(self.payload))
def __init__(self):
pass
def parse_frame_generic(data):
"""Parse an ICF frame of unknown type from the beginning of @data"""
frame = IcfFrame()
frame.src = ord(data[2])
frame.dst = ord(data[3])
frame.cmd = ord(data[4])
try:
end = data.index("\xFD")
except ValueError:
return None, data
frame.payload = data[5:end]
return frame, data[end+1:]
class RadioStream:
"""A class to make reading a stream of IcfFrames easier"""
def __init__(self, pipe):
self.pipe = pipe
self.data = ""
def _process_frames(self):
if not self.data.startswith("\xFE\xFE"):
LOG.error("Out of sync with radio:\n%s" % util.hexprint(self.data))
raise errors.InvalidDataError("Out of sync with radio")
elif len(self.data) < 5:
return [] # Not enough data for a full frame
frames = []
while self.data:
try:
cmd = ord(self.data[4])
except IndexError:
break # Out of data
try:
frame, rest = parse_frame_generic(self.data)
if not frame:
break
elif frame.src == 0xEE and frame.dst == 0xEF:
# PC echo, ignore
pass
else:
frames.append(frame)
self.data = rest
except errors.InvalidDataError, e:
LOG.error("Failed to parse frame (cmd=%i): %s" % (cmd, e))
return []
return frames
def get_frames(self, nolimit=False):
"""Read any pending frames from the stream"""
while True:
_data = self.pipe.read(64)
if not _data:
break
else:
self.data += _data
if not nolimit and len(self.data) > 128 and "\xFD" in self.data:
break # Give us a chance to do some status
if len(self.data) > 1024:
break # Avoid an endless loop of chewing garbage
if not self.data:
return []
return self._process_frames()
def get_model_data(radio, mdata="\x00\x00\x00\x00"):
"""Query the @radio for its model data"""
send_clone_frame(radio, 0xe0, mdata, raw=True)
stream = RadioStream(radio.pipe)
frames = stream.get_frames()
if len(frames) != 1:
raise errors.RadioError("Unexpected response from radio")
return frames[0].payload
def get_clone_resp(pipe, length=None, max_count=None):
"""Read the response to a clone frame"""
def exit_criteria(buf, length, cnt, max_count):
"""Stop reading a clone response if we have enough data or encounter
the end of a frame"""
if max_count is not None:
if cnt >= max_count:
return True
if length is None:
return buf.endswith("\xfd")
else:
return len(buf) == length
resp = ""
cnt = 0
while not exit_criteria(resp, length, cnt, max_count):
resp += pipe.read(1)
cnt += 1
return resp
def send_clone_frame(radio, cmd, data, raw=False, checksum=False):
"""Send a clone frame with @cmd and @data to the @radio"""
payload = radio.get_payload(data, raw, checksum)
frame = "\xfe\xfe\xee\xef%s%s\xfd" % (chr(cmd), payload)
if SAVE_PIPE:
LOG.debug("Saving data...")
SAVE_PIPE.write(frame)
# LOG.debug("Sending:\n%s" % util.hexprint(frame))
# LOG.debug("Sending:\n%s" % util.hexprint(hed[6:]))
if cmd == 0xe4:
# Uncomment to avoid cloning to the radio
# return frame
pass
radio.pipe.write(frame)
if radio.MUNCH_CLONE_RESP:
# Do max 2*len(frame) read(1) calls
get_clone_resp(radio.pipe, max_count=2*len(frame))
return frame
def process_data_frame(radio, frame, _mmap):
"""Process a data frame, adding the payload to @_mmap"""
_data = radio.process_frame_payload(frame.payload)
# Checksum logic added by Rick DeWitt, 9/2019, issue # 7075
if len(_mmap) >= 0x10000: # This map size not tested for checksum
saddr, = struct.unpack(">I", _data[0:4])
length, = struct.unpack("B", _data[4])
data = _data[5:5+length]
sumc, = struct.unpack("B", _data[5+length])
addr1, = struct.unpack("B", _data[0])
addr2, = struct.unpack("B", _data[1])
addr3, = struct.unpack("B", _data[2])
addr4, = struct.unpack("B", _data[3])
else: # But this one has been tested for raw mode radio (IC-2730)
saddr, = struct.unpack(">H", _data[0:2])
length, = struct.unpack("B", _data[2])
data = _data[3:3+length]
sumc, = struct.unpack("B", _data[3+length])
addr1, = struct.unpack("B", _data[0])
addr2, = struct.unpack("B", _data[1])
addr3 = 0
addr4 = 0
cs = addr1 + addr2 + addr3 + addr4 + length
for byte in data:
cs += ord(byte)
vx = ((cs ^ 0xFFFF) + 1) & 0xFF
if sumc != vx:
LOG.error("Bad checksum in address %04X frame: %02x "
"calculated, %02x sent!" % (saddr, vx, sumc))
raise errors.InvalidDataError(
"Checksum error in download! "
"Try disabling High Speed Clone option in Settings.")
try:
_mmap[saddr] = data
except IndexError:
LOG.error("Error trying to set %i bytes at %05x (max %05x)" %
(bytes, saddr, len(_mmap)))
return saddr, saddr + length
def start_hispeed_clone(radio, cmd):
"""Send the magic incantation to the radio to go fast"""
buf = ("\xFE" * 20) + \
"\xEE\xEF\xE8" + \
radio.get_model() + \
"\x00\x00\x02\x01\xFD"
LOG.debug("Starting HiSpeed:\n%s" % util.hexprint(buf))
radio.pipe.write(buf)
radio.pipe.flush()
resp = radio.pipe.read(128)
LOG.debug("Response:\n%s" % util.hexprint(resp))
LOG.info("Switching to 38400 baud")
radio.pipe.baudrate = 38400
buf = ("\xFE" * 14) + \
"\xEE\xEF" + \
chr(cmd) + \
radio.get_model()[:3] + \
"\x00\xFD"
LOG.debug("Starting HiSpeed Clone:\n%s" % util.hexprint(buf))
radio.pipe.write(buf)
radio.pipe.flush()
def _clone_from_radio(radio):
md = get_model_data(radio)
if md[0:4] != radio.get_model():
LOG.info("This model: %s" % util.hexprint(md[0:4]))
LOG.info("Supp model: %s" % util.hexprint(radio.get_model()))
raise errors.RadioError("I can't talk to this model")
if radio.is_hispeed():
start_hispeed_clone(radio, CMD_CLONE_OUT)
else:
send_clone_frame(radio, CMD_CLONE_OUT, radio.get_model(), raw=True)
LOG.debug("Sent clone frame")
stream = RadioStream(radio.pipe)
addr = 0
_mmap = memmap.MemoryMap(chr(0x00) * radio.get_memsize())
last_size = 0
while True:
frames = stream.get_frames()
if not frames:
break
for frame in frames:
if frame.cmd == CMD_CLONE_DAT:
src, dst = process_data_frame(radio, frame, _mmap)
if last_size != (dst - src):
LOG.debug("ICF Size change from %i to %i at %04x" %
(last_size, dst - src, src))
last_size = dst - src
if addr != src:
LOG.debug("ICF GAP %04x - %04x" % (addr, src))
addr = dst
elif frame.cmd == CMD_CLONE_END:
LOG.debug("End frame (%i):\n%s" %
(len(frame.payload), util.hexprint(frame.payload)))
LOG.debug("Last addr: %04x" % addr)
if radio.status_fn:
status = chirp_common.Status()
status.msg = "Cloning from radio"
status.max = radio.get_memsize()
status.cur = addr
radio.status_fn(status)
return _mmap
def clone_from_radio(radio):
"""Do a full clone out of the radio's memory"""
try:
return _clone_from_radio(radio)
except Exception, e:
raise errors.RadioError("Failed to communicate with the radio: %s" % e)
def send_mem_chunk(radio, start, stop, bs=32):
"""Send a single chunk of the radio's memory from @start-@stop"""
_mmap = radio.get_mmap()
status = chirp_common.Status()
status.msg = "Cloning to radio"
status.max = radio.get_memsize()
for i in range(start, stop, bs):
if i + bs < stop:
size = bs
else:
size = stop - i
if radio.get_memsize() >= 0x10000:
chunk = struct.pack(">IB", i, size)
else:
chunk = struct.pack(">HB", i, size)
chunk += _mmap[i:i+size]
send_clone_frame(radio,
CMD_CLONE_DAT,
chunk,
raw=False,
checksum=True)
if radio.status_fn:
status.cur = i+bs
radio.status_fn(status)
return True
def _clone_to_radio(radio):
global SAVE_PIPE
# Uncomment to save out a capture of what we actually write to the radio
# SAVE_PIPE = file("pipe_capture.log", "w", 0)
md = get_model_data(radio)
if md[0:4] != radio.get_model():
raise errors.RadioError("I can't talk to this model")
# This mimics what the Icom software does, but isn't required and just
# takes longer
# md = get_model_data(radio, mdata=md[0:2]+"\x00\x00")
# md = get_model_data(radio, mdata=md[0:2]+"\x00\x00")
stream = RadioStream(radio.pipe)
if radio.is_hispeed():
start_hispeed_clone(radio, CMD_CLONE_IN)
else:
send_clone_frame(radio, CMD_CLONE_IN, radio.get_model(), raw=True)
frames = []
for start, stop, bs in radio.get_ranges():
if not send_mem_chunk(radio, start, stop, bs):
break
frames += stream.get_frames()
send_clone_frame(radio, CMD_CLONE_END, radio.get_endframe(), raw=True)
if SAVE_PIPE:
SAVE_PIPE.close()
SAVE_PIPE = None
for i in range(0, 10):
try:
frames += stream.get_frames(True)
result = frames[-1]
except IndexError:
LOG.debug("Waiting for clone result...")
time.sleep(0.5)
if len(frames) == 0:
raise errors.RadioError("Did not get clone result from radio")
return result.payload[0] == '\x00'
def clone_to_radio(radio):
"""Initiate a full memory clone out to @radio"""
try:
return _clone_to_radio(radio)
except Exception, e:
logging.exception("Failed to communicate with the radio")
raise errors.RadioError("Failed to communicate with the radio: %s" % e)
def convert_model(mod_str):
"""Convert an ICF-style model string into what we get from the radio"""
data = ""
for i in range(0, len(mod_str), 2):
hexval = mod_str[i:i+2]
intval = int(hexval, 16)
data += chr(intval)
return data
def convert_data_line(line):
"""Convert an ICF data line to raw memory format"""
if line.startswith("#"):
return ""
line = line.strip()
if len(line) == 38:
# Small memory (< 0x10000)
size = int(line[4:6], 16)
data = line[6:]
else:
# Large memory (>= 0x10000)
size = int(line[8:10], 16)
data = line[10:]
_mmap = ""
i = 0
while i < (size * 2):
try:
val = int("%s%s" % (data[i], data[i+1]), 16)
i += 2
_mmap += struct.pack("B", val)
except ValueError, e:
LOG.debug("Failed to parse byte: %s" % e)
break
return _mmap
def read_file(filename):
"""Read an ICF file and return the model string and memory data"""
f = file(filename)
mod_str = f.readline()
dat = f.readlines()
model = convert_model(mod_str.strip())
_mmap = ""
for line in dat:
if not line.startswith("#"):
_mmap += convert_data_line(line)
return model, memmap.MemoryMap(_mmap)
def is_9x_icf(filename):
"""Returns True if @filename is an IC9x ICF file"""
f = file(filename)
mdata = f.read(8)
f.close()
return mdata in ["30660000", "28880000"]
def is_icf_file(filename):
"""Returns True if @filename is an ICF file"""
f = file(filename)
data = f.readline()
data += f.readline()
f.close()
data = data.replace("\n", "").replace("\r", "")
return bool(re.match("^[0-9]{8}#", data))
class IcomBank(chirp_common.Bank):
"""A bank that works for all Icom radios"""
# Integral index of the bank (not to be confused with per-memory
# bank indexes
index = 0
class IcomNamedBank(IcomBank):
"""A bank with an adjustable name"""
def set_name(self, name):
"""Set the name of the bank"""
pass
class IcomBankModel(chirp_common.BankModel):
"""Icom radios all have pretty much the same simple bank model. This
central implementation can, with a few icom-specific radio interfaces
serve most/all of them"""
def get_num_mappings(self):
return self._radio._num_banks
def get_mappings(self):
banks = []
for i in range(0, self._radio._num_banks):
index = chr(ord("A") + i)
bank = self._radio._bank_class(self, index, "BANK-%s" % index)
bank.index = i
banks.append(bank)
return banks
def add_memory_to_mapping(self, memory, bank):
self._radio._set_bank(memory.number, bank.index)
def remove_memory_from_mapping(self, memory, bank):
if self._radio._get_bank(memory.number) != bank.index:
raise Exception("Memory %i not in bank %s. Cannot remove." %
(memory.number, bank))
self._radio._set_bank(memory.number, None)
def get_mapping_memories(self, bank):
memories = []
for i in range(*self._radio.get_features().memory_bounds):
if self._radio._get_bank(i) == bank.index:
memories.append(self._radio.get_memory(i))
return memories
def get_memory_mappings(self, memory):
index = self._radio._get_bank(memory.number)
if index is None:
return []
else:
return [self.get_mappings()[index]]
class IcomIndexedBankModel(IcomBankModel,
chirp_common.MappingModelIndexInterface):
"""Generic bank model for Icom radios with indexed banks"""
def get_index_bounds(self):
return self._radio._bank_index_bounds
def get_memory_index(self, memory, bank):
return self._radio._get_bank_index(memory.number)
def set_memory_index(self, memory, bank, index):
if bank not in self.get_memory_mappings(memory):
raise Exception("Memory %i is not in bank %s" % (memory.number,
bank))
if index not in range(*self._radio._bank_index_bounds):
raise Exception("Invalid index")
self._radio._set_bank_index(memory.number, index)
def get_next_mapping_index(self, bank):
indexes = []
for i in range(*self._radio.get_features().memory_bounds):
if self._radio._get_bank(i) == bank.index:
indexes.append(self._radio._get_bank_index(i))
for i in range(0, 256):
if i not in indexes:
return i
raise errors.RadioError("Out of slots in this bank")
def compute_checksum(data):
cs = 0
for byte in data:
cs += ord(byte)
return ((cs ^ 0xFFFF) + 1) & 0xFF
class IcomCloneModeRadio(chirp_common.CloneModeRadio):
"""Base class for Icom clone-mode radios"""
VENDOR = "Icom"
BAUDRATE = 9600
# Ideally, the driver should read clone response after each clone frame
# is sent, but for some reason it hasn't behaved this way for years.
# So not to break the existing tested drivers the MUNCH_CLONE_RESP flag
# was added. It's False by default which brings the old behavior,
# i.e. clone response is not read. The expectation is that new Icom
# drivers will use MUNCH_CLONE_RESP = True and old drivers will be
# gradually migrated to this. Once all Icom drivers will use
# MUNCH_CLONE_RESP = True, this flag will be removed.
MUNCH_CLONE_RESP = False
_model = "\x00\x00\x00\x00" # 4-byte model string
_endframe = "" # Model-unique ending frame
_ranges = [] # Ranges of the mmap to send to the radio
_num_banks = 10 # Most simple Icoms have 10 banks, A-J
_bank_index_bounds = (0, 99)
_bank_class = IcomBank
_can_hispeed = False
@classmethod
def is_hispeed(cls):
"""Returns True if the radio supports hispeed cloning"""
return cls._can_hispeed
@classmethod
def get_model(cls):
"""Returns the Icom model data for this radio"""
return cls._model
@classmethod
def get_endframe(cls):
"""Returns the magic clone end frame for this radio"""
return cls._endframe
@classmethod
def get_ranges(cls):
"""Returns the ranges this radio likes to have in a clone"""
return cls._ranges
def process_frame_payload(self, payload):
"""Convert BCD-encoded data to raw"""
bcddata = payload
data = ""
i = 0
while i+1 < len(bcddata):
try:
val = int("%s%s" % (bcddata[i], bcddata[i+1]), 16)
i += 2
data += struct.pack("B", val)
except ValueError, e:
LOG.error("Failed to parse byte: %s" % e)
break
return data
def get_payload(self, data, raw, checksum):
"""Returns the data with optional checksum BCD-encoded for the radio"""
if raw:
return data
payload = ""
for byte in data:
payload += "%02X" % ord(byte)
if checksum:
payload += "%02X" % compute_checksum(data)
return payload
def sync_in(self):
self._mmap = clone_from_radio(self)
self.process_mmap()
def sync_out(self):
clone_to_radio(self)
def get_bank_model(self):
rf = self.get_features()
if rf.has_bank:
if rf.has_bank_index:
return IcomIndexedBankModel(self)
else:
return IcomBankModel(self)
else:
return None
# Icom-specific bank routines
def _get_bank(self, loc):
"""Get the integral bank index of memory @loc, or None"""
raise Exception("Not implemented")
def _set_bank(self, loc, index):
"""Set the integral bank index of memory @loc to @index, or
no bank if None"""
raise Exception("Not implemented")
def get_settings(self):
return make_speed_switch_setting(self)
def set_settings(self, settings):
return honor_speed_switch_setting(self, settings)
def flip_high_order_bit(data):
return [chr(ord(d) ^ 0x80) for d in list(data)]
def escape_raw_byte(byte):
"""Escapes a raw byte for sending to the radio"""
# Certain bytes are used as control characters to the radio, so if one of
# these bytes is present in the stream to the radio, it gets escaped as
# 0xff followed by (byte & 0x0f)
if ord(byte) > 0xf9:
return "\xff%s" % (chr(ord(byte) & 0xf))
return byte
def unescape_raw_bytes(escaped_data):
"""Unescapes raw bytes from the radio."""
data = ""
i = 0
while i < len(escaped_data):
byte = escaped_data[i]
if byte == '\xff':
if i + 1 >= len(escaped_data):
raise errors.InvalidDataError(
"Unexpected escape character at end of data")
i += 1
byte = chr(0xf0 | ord(escaped_data[i]))
data += byte
i += 1
return data
class IcomRawCloneModeRadio(IcomCloneModeRadio):
"""Subclass for Icom clone-mode radios using the raw data protocol."""
def process_frame_payload(self, payload):
"""Payloads from a raw-clone-mode radio are already in raw format."""
return unescape_raw_bytes(payload)
def get_payload(self, data, raw, checksum):
"""Returns the data with optional checksum in raw format."""
if checksum:
cs = chr(compute_checksum(data))
else:
cs = ""
payload = "%s%s" % (data, cs)
# Escape control characters.
escaped_payload = [escape_raw_byte(b) for b in payload]
return "".join(escaped_payload)
def sync_in(self):
# The radio returns all the bytes with the high-order bit flipped.
_mmap = clone_from_radio(self)
_mmap = flip_high_order_bit(_mmap.get_packed())
self._mmap = memmap.MemoryMap(_mmap)
self.process_mmap()
def get_mmap(self):
_data = flip_high_order_bit(self._mmap.get_packed())
return memmap.MemoryMap(_data)
class IcomLiveRadio(chirp_common.LiveRadio):
"""Base class for an Icom Live-mode radio"""
VENDOR = "Icom"
BAUD_RATE = 38400
_num_banks = 26 # Most live Icoms have 26 banks, A-Z
_bank_index_bounds = (0, 99)
_bank_class = IcomBank
def get_bank_model(self):
rf = self.get_features()
if rf.has_bank:
if rf.has_bank_index:
return IcomIndexedBankModel(self)
else:
return IcomBankModel(self)
else:
return None
def make_speed_switch_setting(radio):
if not radio.__class__._can_hispeed:
return {}
drvopts = RadioSettingGroup("drvopts", "Driver Options")
top = RadioSettings(drvopts)
rs = RadioSetting("drv_clone_speed", "Use Hi-Speed Clone",
RadioSettingValueBoolean(radio._can_hispeed))
drvopts.append(rs)
return top
def honor_speed_switch_setting(radio, settings):
for element in settings:
if element.get_name() == "drvopts":
return honor_speed_switch_setting(radio, element)
if element.get_name() == "drv_clone_speed":
radio.__class__._can_hispeed = element.value.get_value()
return
| tylert/chirp.hg | chirp/drivers/icf.py | Python | gpl-3.0 | 23,992 |
puts "Bem-vindo ao Jogo da Advinhação"
puts "Qual o seu nome?"
nome = gets
puts ("\n\n\n")
#\n para cada linha em branco - refatoração
puts "Neste jogo você tem de advinhar qual o número escolhido entre 0 e 100.
A cada número escolhido vou lhe dar dicas para que você saiba se está perto de acertar."
puts ("\n\n\n")
puts "Vamos começar, " + nome
puts "Escolhendo um número..."
num_secreto = 34
puts "Pronto. Número escolhido, " + nome
puts ("\n\n")
puts "Você tem 3 tentativas. Vamos a primeira?"
#em breve, inserir a limitação de tentativas
puts "Chute um número, " + nome
chute = gets
puts "Será que você acertou? Você chutou " + chute
puts 34 == chute.to_i
# método to_i converte uma string para um inteiro
| geisasantos/estudos-dev-jogos | Ruby/jogo_advinhacao.rb | Ruby | gpl-3.0 | 759 |
var createFakeModel = function () { return sinon.createStubInstance(Backbone.Model); };
var createFakeCollection = function () { return sinon.createStubInstance(Backbone.Collection); };
requireMock.requireWithStubs(
{
'models/SearchParamsModel': sinon.stub().returns(createFakeModel()),
'collections/SearchResultsCollection': sinon.stub().returns(createFakeCollection())
},
[
'views/right_column/results_footer/PaginationControlsView',
'collections/SearchResultsCollection',
'models/SearchParamsModel',
'lib/Mediator'
],
function (
PaginationControlsView,
SearchResultsCollection,
SearchParamsModel,
Mediator
) {
describe('Pagination Controls View', function () {
var mediator,
resultsCollection,
searchParamsModel,
view;
beforeEach(function () {
mediator = sinon.stub(new Mediator());
resultsCollection = new SearchResultsCollection();
resultsCollection.getLastPageNumber = sinon.stub().returns(7);
resultsCollection.getPageNumber = sinon.stub().returns(4);
resultsCollection.getTotalResultsCount = sinon.stub().returns(10);
searchParamsModel = new SearchParamsModel();
searchParamsModel.setPageNumber = sinon.spy();
searchParamsModel.get = sinon.stub();
view = new PaginationControlsView({
collection: resultsCollection,
model: searchParamsModel
});
view.setMediator(mediator);
view.render();
});
describe('Basic rendering and appearance', function () {
it('creates a container element with class .pagination', function () {
expect(view.$el).toHaveClass('pagination');
});
it('has a first page button', function () {
expect(view.$('a[title="Go to page 1"]').length).toEqual(1);
});
it('has a last page button', function () {
expect(view.$('a[title="Go to page 7"]').length).toEqual(1);
});
it('has a previous page button', function () {
expect(view.$('a.prev').length).toEqual(1);
});
it('has a next page button', function () {
expect(view.$('a.next').length).toEqual(1);
});
});
describe('the visible page numbers with 7 pages of results', function () {
var range,
options;
// key: current page
// value: the page numbers that should be visible and clickable
options = {
1: [1, 2, 7],
2: [1, 2, 3, 7],
3: [1, 2, 3, 4, 7],
4: [1, 2, 3, 4, 5, 6, 7],
5: [1, 4, 5, 6, 7],
6: [1, 5, 6, 7],
7: [1, 6, 7]
};
range = [1, 2, 3, 4, 5, 6, 7];
_.each(options, function (visiblePages, currentPage) {
it('gives links for pages ' + visiblePages + ' and only those pages when on page ' + currentPage, function () {
var hiddenPages = _.difference(range, visiblePages);
resultsCollection.getPageNumber = sinon.stub().returns(currentPage);
view.render();
_.each(visiblePages, function (visiblePage) {
expect(view.$el.html()).toContain('title="Go to page ' + visiblePage + '"');
});
_.each(hiddenPages, function (hiddenPage) {
expect(view.$el.html()).not.toContain('title="Go to page ' + hiddenPage + '"');
});
});
});
});
describe('a single page of results', function () {
beforeEach(function () {
resultsCollection.getLastPageNumber = sinon.stub().returns(1);
resultsCollection.getPageNumber = sinon.stub().returns(1);
});
it('is hidden', function () {
view.onSearchComplete();
expect(view.$el).toHaveClass('hidden');
});
});
describe('no results', function () {
beforeEach(function () {
resultsCollection.getTotalResultsCount = sinon.stub().returns(0);
});
it('is hidden', function () {
view.showControls();
view.onSearchComplete();
expect(view.$el).toHaveClass('hidden');
});
});
describe('updating the search params model', function () {
it('decrements the searchParamsModel pageNumber value when the prev page button is clicked', function () {
view.onClickPrevPageButton();
expect(searchParamsModel.setPageNumber).toHaveBeenCalledWith(3);
});
it('sets the searchParamsModel pageNumber value to 1 when the first page button is clicked', function () {
view.onClickPageSelector({
target: view.$('a[title="Go to page 1"]')[0]
});
expect(searchParamsModel.setPageNumber).toHaveBeenCalledWith(1);
});
it('increments the searchParamsModel pageNumber value when the next page button is clicked', function () {
view.onClickNextPageButton();
expect(searchParamsModel.setPageNumber).toHaveBeenCalledWith(5);
});
});
describe('triggering the "search:refinedSearch" event', function () {
it('triggers when a page number is clicked', function () {
view.onClickPageSelector({
target: {
text: '1'
}
});
expect(mediator.trigger).toHaveBeenCalledWith('search:refinedSearch');
});
it('triggers when the previous page button is clicked', function () {
view.onClickPrevPageButton();
expect(mediator.trigger).toHaveBeenCalledWith('search:refinedSearch');
});
it('triggers when the next page button is clicked', function () {
view.onClickNextPageButton();
expect(mediator.trigger).toHaveBeenCalledWith('search:refinedSearch');
});
});
describe('mediated event handling', function () {
beforeEach(function () {
mediator = new Mediator();
view.setMediator(mediator);
});
it('hides itself when the app goes home', function () {
// guard assertion
expect(view.$el).not.toHaveClass('hidden');
mediator.trigger('app:home');
expect(view.$el).toHaveClass('hidden');
});
it('hides itself when a new search is intiated', function () {
// guard assertion
expect(view.$el).not.toHaveClass('hidden');
mediator.trigger('search:initiated');
expect(view.$el).toHaveClass('hidden');
});
it('shows itself when a new set of search results is ready', function () {
view.hideControls();
mediator.trigger('search:complete');
expect(view.$el).not.toHaveClass('hidden');
});
it('shows itself when an in-progress search is canceled if there are previous results', function () {
view.hideControls();
mediator.trigger('search:displayPreviousResults');
expect(view.$el).not.toHaveClass('hidden');
});
});
});
});
| hwilcox/bcube-interface | spec/views/right_column/PaginationControlsView_spec.js | JavaScript | gpl-3.0 | 7,093 |
<?php
/**
* Entrada [ http://www.entrada-project.org ]
*
* This file gives Entrada users the ability to update their user profile.
*
* @author Organisation: Queen's University
* @author Unit: School of Medicine
* @author Developer: Jonathan Fingland <jonathan.fingland@queensu.ca>
* @copyright Copyright 2010 Queen's University. All Rights Reserved.
*
*/
if (!defined("IN_MANAGE_USER_STUDENTS")) {
exit;
} elseif ((!isset($_SESSION["isAuthorized"])) || (!$_SESSION["isAuthorized"])) {
header("Location: ".ENTRADA_URL);
exit;
} elseif(!$ENTRADA_ACL->isLoggedInAllowed("mspr", "create", true) || $user_record["group"] != "student") {
$ONLOAD[] = "setTimeout('window.location=\\'".ENTRADA_URL."/".$MODULE."\\'', 15000)";
add_error("Your account does not have the permissions required to use this module.<br /><br />If you believe you are receiving this message in error please contact <a href=\"mailto:".html_encode($AGENT_CONTACTS["administrator"]["email"])."\">".html_encode($AGENT_CONTACTS["administrator"]["name"])."</a> for assistance.");
echo display_error();
application_log("error", "Group [".$_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["group"]."] and role [".$_SESSION["permissions"][$ENTRADA_USER->getAccessId()]["role"]."] do not have access to this module [".$MODULE."]");
} else {
require_once(dirname(__FILE__)."/includes/functions.inc.php");
$PROXY_ID = $user_record["id"];
$user = User::get($user_record["id"]);
$PAGE_META["title"] = "MSPR";
$PAGE_META["description"] = "";
$PAGE_META["keywords"] = "";
$BREADCRUMB[] = array("url" => ENTRADA_URL."/admin/users/manage/students?section=mspr&id=".$PROXY_ID, "title" => "MSPR");
$PROCESSED = array();
$HEAD[] = "<script language='javascript' src='".ENTRADA_URL."/javascript/ActiveDataEntryProcessor.js'></script>";
$HEAD[] = "<script language='javascript' src='".ENTRADA_URL."/javascript/ActiveEditor.js'></script>";
$HEAD[] = "<script language='javascript' src='".ENTRADA_URL."/javascript/ActiveApprovalProcessor.js'></script>";
$HEAD[] = "<script language='javascript' src='".ENTRADA_URL."/javascript/PriorityList.js'></script>";
if ((is_array($_SESSION["permissions"])) && ($total_permissions = count($_SESSION["permissions"]) > 1)) {
$sidebar_html = "The following individual".((($total_permissions - 1) != 1) ? "s have" : " has")." given you access to their ".APPLICATION_NAME." permission levels:";
$sidebar_html .= "<ul class=\"menu\">\n";
foreach ($_SESSION["permissions"] as $access_id => $result) {
if ($access_id != $ENTRADA_USER->getDefaultAccessId()) {
$sidebar_html .= "<li class=\"checkmark\"><strong>".html_encode($result["fullname"])."</strong><br /><span class=\"content-small\">Exp: ".(($result["expires"]) ? date("D M d/y", $result["expires"]) : "Unknown")."</span></li>\n";
}
}
$sidebar_html .= "</ul>\n";
new_sidebar_item("Delegated Permissions", $sidebar_html, "delegated-permissions", "open");
}
$mspr = MSPR::get($user);
if (!$mspr) { //no mspr yet. create one
MSPR::create($user);
$mspr = MSPR::get($user);
}
if (!$mspr) {
add_notice("MSPR not yet available. Please try again later.");
application_log("error", "Error creating MSPR for user " .$PROXY_ID. ": " . $name . "(".$number.")");
display_status_messages();
} else {
$is_closed = $mspr->isClosed();
$generated = $mspr->isGenerated();
$revision = $mspr->getGeneratedTimestamp();
$number = $user->getNumber();
$name = $user->getFirstname() . " " . $user->getLastname();
if (isset($_GET['get']) && ($type = $_GET['get'])) {
$name = $user->getFirstname() . " " . $user->getLastname();
switch($type) {
case 'html':
header('Content-type: text/html');
header('Content-Disposition: filename="MSPR - '.$name.'('.$number.').html"');
break;
case 'pdf':
header('Content-type: application/pdf');
header('Content-Disposition: attachment; filename="MSPR - '.$name.'('.$number.').pdf"');
break;
default:
add_error("Unknown file type: " . $type);
}
if (!has_error()) {
ob_clear_open_buffers();
flush();
echo $mspr->getMSPRFile($type);
exit();
}
}
$clerkship_core_completed = $mspr["Clerkship Core Completed"];
$clerkship_core_pending = $mspr["Clerkship Core Pending"];
$clerkship_elective_completed = $mspr["Clerkship Electives Completed"];
$clinical_evaluation_comments = $mspr["Clinical Performance Evaluation Comments"];
$critical_enquiry = $mspr["Critical Enquiry"];
$student_run_electives = $mspr["Student-Run Electives"];
$observerships = $mspr["Observerships"];
$international_activities = $mspr["International Activities"];
$internal_awards = $mspr["Internal Awards"];
$external_awards = $mspr["External Awards"];
$studentships = $mspr["Studentships"];
$contributions = $mspr["Contributions to Medical School"];
$leaves_of_absence = $mspr["Leaves of Absence"];
$formal_remediations = $mspr["Formal Remediation Received"];
$disciplinary_actions = $mspr["Disciplinary Actions"];
$community_based_project = $mspr["Community Based Project"];
$research_citations = $mspr["Research"];
$year = $user->getGradYear();
$class_data = MSPRClassData::get($year);
$mspr_close = $mspr->getClosedTimestamp();
if (!$mspr_close && $class_data) { //no custom time.. use the class default
$mspr_close = $class_data->getClosedTimestamp();
}
$faculty = ClinicalFacultyMembers::get();
display_status_messages();
add_mspr_management_sidebar();
?>
<h1>Medical School Performance Report<?php echo ($mspr->isAttentionRequired()) ? ": Attention Required" : ""; ?></h1>
<?php
if ($is_closed) {
?>
<div class="display-notice"><p><strong>Note: </strong>This MSPR is now <strong>closed</strong> to student submissions. (Deadline was <?php echo date("F j, Y \a\\t g:i a",$mspr_close); ?>.) You may continue to approve, unapprove, or reject submissions, however students are unable to submit new data.</p>
<?php if ($generated) { ?>
<p>The latest revision of this MSPR is available in HTML and PDF below: </p>
<span class="file-block"><a href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>&get=html"><img src="<?php echo ENTRADA_URL; ?>/serve-icon.php?ext=html" /> HTML</a>
<a href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>&get=pdf"><img src="<?php echo ENTRADA_URL; ?>/serve-icon.php?ext=pdf" /> PDF</a>
</span>
<span class="edit-block"><a href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr-edit&id=<?php echo $PROXY_ID; ?>&from=user"><img src="<?php echo ENTRADA_URL; ?>/images/btn-edit.gif" /> Edit</a></span>
<div class="clearfix"> </div>
<span class="last-update">Last Updated: <?php echo date("F j, Y \a\\t g:i a",$revision); ?></span>
<?php }?>
<hr />
<a href="<?php echo ENTRADA_URL; ?>/admin/mspr?section=generate&id=<?php echo $PROXY_ID; ?>">Generate Report</a>
</div>
<?php
} elseif ($mspr_close) {
?>
<div class="display-notice"><strong>Note: </strong>The student submission deadline is <?php echo date("F j, Y \a\\t g:i a",$mspr_close); ?>. You may continue to approve, unapprove, or reject submissions after this date, however students will be unable to submit new data.</div>
<?php
}
?>
<div class="mspr-tree">
<a href="#" onclick='document.fire("CollapseHeadings:expand-all");'>Expand All</a> / <a href="#" onclick='document.fire("CollapseHeadings:collapse-all");'>Collapse All</a>
<h2 title="Information Requiring Approval">Information Requiring Approval</h2>
<div id="information-requiring-approval">
<div class="instructions" style="margin-left:2em;margin-top:2ex;">
<strong>Instructions</strong>
<p>The sections below consist of student-submitted information. The submissions require approval or rejection.</p>
<ul>
<li>
If an entry is verifiably accurate and meets criteria, it should be approved.
</li>
<li>
If an entry is verifiably innacurate or contains errors in spelling or formatting, it should be rejected.
</li>
<li>
If previously approved information comes into question, it's status can be reverted to unapproved, and rejected if deemed appropriate.
</li>
<li>
All entries have a background color corresponding to their status:
<ul>
<li>Gray - Approved</li>
<li>Yellow - Pending Approval</li>
<li>Red - Rejected</li>
</ul>
</li>
</ul>
</div>
<div class="section">
<h3 title="Contributions to Medical School" class="collapsable<?php echo ($contributions->isAttentionRequired()) ? "" : " collapsed"; ?>">Contributions to Medical School/Student Life</h3>
<div id="contributions-to-medical-school">
<div id="add_contribution_link" style="float: right;">
<a id="add_contribution" href="<?php echo ENTRADA_URL; ?>/profile?section=mspr&show=contributions_form&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Contribution</a>
</div>
<div class="instructions">
<ul>
<li>Examples of contributions to medical school/student life include:
<ul>
<li>Participation in School of Medicine student government</li>
<li>Committees (such as admissions)</li>
<li>Organizing extra-curricular learning activities and seminars</li>
</ul>
</li>
<li>Examples of submissions that do <em>not</em> qualify:
<ul>
<li>Captain of intramural soccer team.</li>
<li>Member of Oprah's book of the month club.</li>
</ul>
</li>
</ul>
</div>
<div id="update-contribution-box" class="modal-confirmation">
<h1>Edit Contribution to Medical School/Student Life</h1>
<form method="post">
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="role">Role:</label></td>
<td><input name="role" type="text" style="width:40%;"></input> <span class="content-small"><strong>Example</strong>: Interviewer</span></td>
</tr>
<tr>
<td><label class="form-required" for="org_event">Organization/Event:</label></td>
<td><input name="org_event" type="text" style="width:40%;"></input> <span class="content-small"><strong>Example</strong>: Medical School Interview Weekend</span></td>
</tr>
<tr>
<td><label class="form-required" for="start">Start:</label></td>
<td>
<select name="start_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="start_year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select>
</td>
</tr>
<tr>
<td><label class="form-required" for="end">End:</label></td>
<td>
<select tabindex="1" name="end_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="end_year">
<?php
echo build_option("","Year",true);
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, false);
}
?>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<div id="add-contribution-box" class="modal-confirmation">
<h1>Add Contribution to Medical School/Student Life</h1>
<form method="post">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="role">Role:</label></td>
<td><input name="role" type="text" style="width:40%;"></input> <span class="content-small"><strong>Example</strong>: Interviewer</span></td>
</tr>
<tr>
<td><label class="form-required" for="org_event">Organization/Event:</label></td>
<td><input name="org_event" type="text" style="width:40%;"></input> <span class="content-small"><strong>Example</strong>: Medical School Interview Weekend</span></td>
</tr>
<tr>
<td><label class="form-required" for="start">Start:</label></td>
<td>
<select name="start_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="start_year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select>
</td>
</tr>
<tr>
<td><label class="form-required" for="end">End:</label></td>
<td>
<select tabindex="1" name="end_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="end_year">
<?php
echo build_option("","Year",true);
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, false);
}
?>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div class="clear"> </div>
<div id="contributions">
<?php echo display_contributions($contributions,"admin"); ?>
</div>
</div>
</div>
<div class="section">
<h3 title="Critical Enquiry" class="collapsable<?php echo ($critical_enquiry && $critical_enquiry->isAttentionRequired()) ? "" : " collapsed"; ?>">Critical Enquiry</h3>
<div id="critical-enquiry">
<div id="add_critical_enquiry_link" style="float: right;">
<a id="add_critical_enquiry" href="<?php echo ENTRADA_URL; ?>/profile?section=mspr&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Critical Enquiry</a>
</div>
<div class="clear"> </div>
<div id="add-critical-enquiry-box" class="modal-confirmation">
<h1>Add Critical Enquiry</h1>
<form method="post"">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="3%"></col>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tbody>
<tr>
<td> </td>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title" type="text" style="width:40%;" value=""></input></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="organization">Organization:</label></td>
<td><input name="organization" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Queen's University</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Kingston, Ontario</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="supervisor">Supervisor:</label></td>
<td><input name="supervisor" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Dr. Nick Riviera</span></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="update-critical-enquiry-box" class="modal-confirmation">
<h1>Edit Critical Enquiry</h1>
<form method="post">
<table class="mspr_form">
<colgroup>
<col width="3%"></col>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tbody>
<tr>
<td> </td>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title" type="text" style="width:40%;" value=""></input></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="organization">Organization:</label></td>
<td><input name="organization" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Queen's University</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Kingston, Ontario</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="supervisor">Supervisor:</label></td>
<td><input name="supervisor" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Dr. Nick Riviera</span></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<div id="critical_enquiry"><?php echo display_supervised_project($critical_enquiry,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="Community-Based Project" class="collapsable<?php echo ($community_based_project && $community_based_project->isAttentionRequired()) ? "" : " collapsed"; ?>">Community-Based Project</h3>
<div id="community-based-project">
<div id="add_community_based_project_link" style="float: right;">
<a id="add_community_based_project" href="<?php echo ENTRADA_URL; ?>/profile?section=mspr&show=community_based_project_form&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Community-Based Project</a>
</div>
<div class="clear"> </div>
<div id="add-community-based-project-box" class="modal-confirmation">
<h1>Add Community-Based Project</h1>
<form method="post">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="3%"></col>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tbody>
<tr>
<td> </td>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title" type="text" style="width:40%;" value=""></input></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="organization">Organization:</label></td>
<td><input name="organization" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Queen's University</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Kingston, Ontario</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="supervisor">Supervisor:</label></td>
<td><input name="supervisor" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Dr. Nick Riviera</span></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="update-community-based-project-box" class="modal-confirmation">
<h1>Edit Community-Based Project</h1>
<form method="post">
<table class="mspr_form">
<colgroup>
<col width="3%"></col>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tbody>
<tr>
<td> </td>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title" type="text" style="width:40%;" value=""></input></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="organization">Organization:</label></td>
<td><input name="organization" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Queen's University</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Kingston, Ontario</span></td>
</tr>
<tr>
<td> </td>
<td><label class="form-required" for="supervisor">Supervisor:</label></td>
<td><input name="supervisor" type="text" style="width:40%;" value=""></input> <span class="content-small"><strong>Example</strong>: Dr. Nick Riviera</span></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<div id="community_based_project"><?php echo display_supervised_project($community_based_project,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="Research" class="collapsable<?php echo ($research_citations->isAttentionRequired()) ? "" : " collapsed"; ?>">Research</h3>
<div id="research">
<div id="add_research_citation_link" style="float: right;">
<a id="add_research_citation" href="<?php echo ENTRADA_URL; ?>/profile?section=mspr&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Research Citation</a>
</div>
<div class="instructions">
<ul>
<li>Only approve citations of published research in which <?php echo $name; ?> was a named author</li>
<li>Approve a maximum of <em>six</em> research citations</li>
<li>Approved research citations should be in a format following <a href="http://owl.english.purdue.edu/owl/resource/747/01/">MLA guidelines</a></li>
</ul>
</div>
<div class="clear"> </div>
<div id="update-research-box" class="modal-confirmation">
<h1>Edit Research Citation</h1>
<form method="post">
<table class="mspr_form">
<tbody>
<tr>
<td><label class="form-required" for="details">Citation:</label></td>
</tr>
<tr>
<td><textarea name="details" style="width:96%;height:25ex;"></textarea><br /></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<div id="add-research-box" class="modal-confirmation">
<h1>Add Research Citation</h1>
<form method="post">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<tbody>
<tr>
<td><label class="form-required" for="details">Citation:</label></td>
</tr>
<tr>
<td><textarea name="details" style="width:96%;height:25ex;"></textarea><br /></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="research_citations">
<?php echo display_research_citations($research_citations,"admin"); ?>
</div>
</div>
</div>
<div class="section">
<h3 title="External Awards" class="collapsable<?php echo ($external_awards->isAttentionRequired()) ? "" : " collapsed"; ?>">External Awards</h3>
<div id="external-awards">
<div id="add_external_award_link" style="float: right;">
<a id="add_external_award" href="#external-awards-section" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add External Award</a>
</div>
<div class="instructions">
<ul>
<li>Only awards of academic significance should be considered.</li>
<li>Award terms must be provided to be approved. Awards not accompanied by terms should be rejected.</li>
</ul>
</div>
<div id="update-external-award-box" class="modal-confirmation">
<h1>Edit External Award</h1>
<form method="post">
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title" type="text" style="width:60%;"></input></td>
</tr>
<tr>
<td><label class="form-required" for="body">Awarding Body:</label></td>
<td><input name="body" type="text" style="width:60%;"></input></td>
</tr>
<tr>
<td valign="top"><label class="form-required" for="terms">Award Terms:</label></td>
<td><textarea name="terms" style="width: 80%; height: 12ex;" cols="65" rows="20"></textarea></td>
</tr>
<tr>
<td><label class="form-required" for="year">Year Awarded:</label></td>
<td><select name="year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 10;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<div id="add-external-award-box" class="modal-confirmation">
<h1>Add External Award</h1>
<form method="post">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title" type="text" style="width:60%;"></input></td>
</tr>
<tr>
<td><label class="form-required" for="body">Awarding Body:</label></td>
<td><input name="body" type="text" style="width:60%;"></input></td>
</tr>
<tr>
<td valign="top"><label class="form-required" for="terms">Award Terms:</label></td>
<td><textarea name="terms" style="width: 80%; height: 12ex;" cols="65" rows="20"></textarea></td>
</tr>
<tr>
<td><label class="form-required" for="year">Year Awarded:</label></td>
<td><select name="year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 10;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="external_awards"><?php echo display_external_awards($external_awards,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="Observerships Section" class="collapsable collapsed">Observerships</h3>
<div id="observerships-section">
<div id="observerships"><?php echo display_observerships($observerships,"admin", true); ?></div>
</div>
</div>
</div>
<h2 title="Required Information Section">Information Requiring Entry</h2>
<div id="required-information-section">
<div class="section">
<h3 title="Clinical Performance Evaluation Comments Section" class="collapsable collapsed">Clinical Performance Evaluation Comments</h3>
<div id="clinical-performance-evaluation-comments-section">
<div id="add_clineval_link" style="float: right;">
<a id="add_clineval" href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Clinical Performance Evaluation Comment</a>
</div>
<div class="instructions">
<p>Comments should be copied in whole or in part from Clinical Performance Evaluations from the student's clerkship rotations and electives.</p>
<p>There should be one comment for each core rotation and one per received elective.</p>
</div>
<div id="update-clineval-box" class="modal-confirmation">
<h1>Edit Clinical Performance Evaluation Comment</h1>
<form method="post" name="edit_clineval_form">
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="source">Source:</label></td>
<td><input type="text" name="source"></input><span class="content-small"> <strong>Example</strong>: Pediatrics Rotation</span></td>
</tr>
<tr>
<td colspan="2"><label class="form-required" for="text">Comment:</label></td>
</tr>
<tr>
<td colspan="2"><textarea name="text" style="width:96%;height:30ex;"></textarea><br /></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm" id="edit-submission-confirm">Update</button>
</div>
</div>
<div id="add-clineval-box" class="modal-confirmation">
<h1>Add Clinical Performance Evaluation Comment</h1>
<form method="post" name="add_int_act_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="source">Source:</label></td>
<td><input type="text" name="source"></input><span class="content-small"> <strong>Example</strong>: Pediatrics Rotation</span></td>
</tr>
<tr>
<td colspan="2"><label class="form-required" for="text">Comment:</label></td>
</tr>
<tr>
<td colspan="2"><textarea name="text" style="width:96%;height:30ex;"></textarea><br /></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div class="clear"> </div>
<form id="add_clineval_form" name="add_clineval_form" action="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>" method="post" style="display:none;" >
<input type="hidden" name="user_id" value="<?php echo $PROXY_ID; ?>"></input>
<table class="mspr_form">
<colgroup>
<col width="3%"></col>
<col width="25%"></col>
<col width="72%"></col>
</colgroup>
<tfoot>
<tr>
<td colspan="3"> </td>
</tr>
<tr>
<td colspan="3" style="border-top: 2px #CCCCCC solid; padding-top: 5px; text-align: right">
<input type="submit" class="btn btn-primary" name="action" value="Add" />
<div id="hide_clineval_link" style="display:inline-block;">
<a id="hide_clineval" href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Cancel Adding Comment</a>
</div>
</td>
</tr>
</tfoot>
<tbody>
<tr>
<td> </td>
<td><label class="form-required" for="source">Source:</label></td>
<td><input type="text" name="source"></input><span class="content-small"> <strong>Example</strong>: Pediatrics Rotation</span></td>
</tr>
<tr>
<td> </td>
<td valign="top"><label class="form-required" for="text">Comment:</label></td>
<td><textarea name="text" style="width:80%;height:12ex;"></textarea><br /></td>
</tr>
</tbody>
</table>
<div class="clear"> </div>
</form>
<div id="clinical_performance_eval_comments"><?php echo display_clineval($clinical_evaluation_comments,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="Summer Studentships" class="collapsable collapsed">Summer Studentships</h3>
<div id="summer-studentships">
<div id="add_studentship_link" style="float: right;">
<a id="add_studentship" href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&show=studentship_form&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Studentship</a>
</div>
<div class="clear"> </div>
<div id="update-studentship-box" class="modal-confirmation">
<h1>Edit Studentship</h1>
<form method="post" name="edit_studentship_form">
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><input type="text" name="title"></input> <span class="content-small"><strong>Example</strong>: The Canadian Institute of Health Studentship</span></td>
</tr>
<tr>
<td><label class="form-required" for="year">Year Awarded:</label></td>
<td><select name="year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 4;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm" id="edit-submission-confirm">Update</button>
</div>
</div>
<div id="add-studentship-box" class="modal-confirmation">
<h1>Add Studentship</h1>
<form method="post" name="add_studentship_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><input type="text" name="title"></input> <span class="content-small"><strong>Example</strong>: The Canadian Institute of Health Studentship</span></td>
</tr>
<tr>
<td><label class="form-required" for="year">Year Awarded:</label></td>
<td><select name="year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 4;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="studentships"><?php echo display_studentships($studentships,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="International Activities" class="collapsable collapsed">International Activities</h3>
<div id="international-activities">
<div id="add_int_act_link" style="float: right;">
<a id="add_int_act" href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&show=int_act_form&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Activity</a>
</div>
<div class="clear"> </div>
<div id="update-int-act-box" class="modal-confirmation">
<h1>Edit International Activity</h1>
<form method="post" name="edit_int_act_form">
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="25%"></col>
<col width="50%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title"></input></td><td><span class="content-small"><strong>Example:</strong> Geriatrics Observership</span></td>
</tr>
<tr>
<td><label class="form-required" for="site">Site:</label></td>
<td><input name="site"></input></td><td><span class="content-small"><strong>Example:</strong> Tokyo Metropolitan Hospital</span></td>
</tr>
<tr>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location"></input></td><td><span class="content-small"><strong>Example:</strong> Tokyo, Japan</span></td>
</tr>
<tr>
<td><label class="form-required" for="start">Start Date:</label></td>
<td>
<input type="text" name="start" id="int_act_start_edit"></input></td><td><span class="content-small"><strong>Format:</strong> yyyy-mm-dd</span>
</td>
</tr>
<tr>
<td><label class="form-required" for="end">End Date:</label></td>
<td>
<input type="text" name="end" id="int_act_end_edit"></input></td><td>
</td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm" id="edit-submission-confirm">Update</button>
</div>
</div>
<div id="add-int-act-box" class="modal-confirmation">
<h1>Add International Activity</h1>
<form method="post" name="add_int_act_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="25%"></col>
<col width="50%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><input name="title"></input></td><td><span class="content-small"><strong>Example:</strong> Geriatrics Observership</span></td>
</tr>
<tr>
<td><label class="form-required" for="site">Site:</label></td>
<td><input name="site"></input></td><td><span class="content-small"><strong>Example:</strong> Tokyo Metropolitan Hospital</span></td>
</tr>
<tr>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location"></input></td><td><span class="content-small"><strong>Example:</strong> Tokyo, Japan</span></td>
</tr>
<tr>
<td><label class="form-required" for="start">Start Date:</label></td>
<td>
<input type="text" name="start" id="int_act_start"></input></td><td><span class="content-small"><strong>Format:</strong> yyyy-mm-dd</span>
</td>
</tr>
<tr>
<td><label class="form-required" for="end">End Date:</label></td>
<td>
<input type="text" name="end" id="int_act_end"></input></td><td>
</td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="int_acts"><?php echo display_international_activities($international_activities,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="Student-Run Electives" class="collapsable collapsed">Student-Run Electives</h3>
<div id="student-run-electives">
<div id="add_student_run_elective_link" style="float: right;">
<a id="add_student_run_elective" href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Student Run Elective</a>
</div>
<div class="clear"> </div>
<div id="add-sre-box" class="modal-confirmation">
<h1>Add Student-Run Elective/Interest Group</h1>
<form method="post" name="add_sre_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="group_name">Group Name:</label></td>
<td><input name="group_name"></input> <span class="content-small"><strong>Example</strong>: Emergency Medicine Elective</span></td>
</tr>
<tr>
<td><label class="form-required" for="university">University:</label></td>
<td><input name="university" value="Queen's University"></input> <span class="content-small"><strong>Example</strong>: Queen's University</span></td>
</tr>
<tr>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location" value="Kingston, ON"></input> <span class="content-small"><strong>Example</strong>: Kingston, Ontario</span></td>
</tr>
<tr>
<td><label class="form-required" for="start">Start:</label></td>
<td>
<select name="start_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="start_year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select>
</td>
</tr>
<tr>
<td><label class="form-required" for="end">End:</label></td>
<td>
<select name="end_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="end_year">
<?php
echo build_option("","Year",true);
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, false);
}
?>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="update-sre-box" class="modal-confirmation">
<h1>Edit Student-Run Elective/Interest Group</h1>
<form method="post" name="edit_sre_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Edit"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="group_name">Group Name:</label></td>
<td><input name="group_name"></input> <span class="content-small"><strong>Example</strong>: Emergency Medicine Elective</span></td>
</tr>
<tr>
<td><label class="form-required" for="university">University:</label></td>
<td><input name="university" value="Queen's University"></input> <span class="content-small"><strong>Example</strong>: Queen's University</span></td>
</tr>
<tr>
<td><label class="form-required" for="location">Location:</label></td>
<td><input name="location" value="Kingston, ON"></input> <span class="content-small"><strong>Example</strong>: Kingston, Ontario</span></td>
</tr>
<tr>
<td><label class="form-required" for="start">Start:</label></td>
<td>
<select name="start_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="start_year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select>
</td>
</tr>
<tr>
<td><label class="form-required" for="end">End:</label></td>
<td>
<select name="end_month">
<?php
echo build_option("","Month",true);
for($month_num = 1; $month_num <= 12; $month_num++) {
echo build_option($month_num, getMonthName($month_num));
}
?>
</select>
<select name="end_year">
<?php
echo build_option("","Year",true);
$cur_year = (int) date("Y");
$start_year = $cur_year - 6;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, false);
}
?>
</select>
</td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<div class="clear"> </div>
<div id="student_run_electives"><?php echo display_student_run_electives($student_run_electives,"admin"); ?></div>
</div>
</div>
<div class="section">
<h3 title="Internal Awards" class="collapsable collapsed">Internal Awards</h3>
<div id="internal-awards">
<div id="add_internal_award_link" style="float: right;">
<a id="add_internal_award" href="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>" class="btn btn-small btn-success"><i class="icon-plus-sign icon-white"></i> Add Internal Award</a>
</div>
<div class="clear"> </div>
<div id="add-internal-award-box" class="modal-confirmation">
<h1>Add Internal Award</h1>
<form method="post" name="add_internal_award_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Add"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><select name="award_id">
<?php
$query = "SELECT * FROM `student_awards_internal_types` where `disabled` = 0 order by `title` asc";
$results = $db->GetAll($query);
if ($results) {
foreach ($results as $result) {
echo build_option($result['id'], clean_input($result["title"], array("notags", "specialchars")));
}
}
?>
</select></td>
</tr>
<tr>
<td><label class="form-required" for="year">Year Awarded:</label></td>
<td><select name="year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 4;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Submit</button>
</div>
</div>
<div id="update-internal-award-box" class="modal-confirmation">
<h1>Edit Internal Award</h1>
<form method="post" name="edit_internal_award_form">
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<input type="hidden" name="action" value="Edit"></input>
<table class="mspr_form">
<colgroup>
<col width="25%"></col>
<col width="75%"></col>
</colgroup>
<tbody>
<tr>
<td><label class="form-required" for="title">Title:</label></td>
<td><select name="award_id">
<?php
$query = "SELECT * FROM `student_awards_internal_types` where `disabled` = 0 order by `title` asc";
$results = $db->GetAll($query);
if ($results) {
foreach ($results as $result) {
echo build_option($result['id'], clean_input($result["title"], array("notags", "specialchars")));
}
}
?>
</select></td>
</tr>
<tr>
<td><label class="form-required" for="year">Year Awarded:</label></td>
<td><select name="year">
<?php
$cur_year = (int) date("Y");
$start_year = $cur_year - 4;
$end_year = $cur_year + 4;
for ($opt_year = $start_year; $opt_year <= $end_year; ++$opt_year) {
echo build_option($opt_year, $opt_year, $opt_year == $cur_year);
}
?>
</select></td>
</tr>
</tbody>
</table>
</form>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm">Update</button>
</div>
</div>
<form id="add_internal_award_form" name="add_internal_award_form" action="<?php echo ENTRADA_URL; ?>/admin/users/manage/students?section=mspr&id=<?php echo $PROXY_ID; ?>" method="post" style="display:none;" >
<input type="hidden" name="user_id" value="<?php echo $user->getID(); ?>"></input>
<div class="clear"> </div>
</form>
<div id="internal_awards"><?php echo display_internal_awards($internal_awards,"admin"); ?></div>
</div>
</div>
</div>
<h2 title="Extracted Information Section" class="collapsed">Information Extracted from Other Sources</h2>
<div id="extracted-information-section">
<div class="section">
<h3 title="Clerkship Core Rotations Completed Satisfactorily to Date Section" class="collapsable collapsed">Clerkship Core Rotations Completed Satisfactorily to Date</h3>
<div id="clerkship-core-rotations-completed-satisfactorily-to-date-section"><?php echo display_clerkship_core_completed($clerkship_core_completed); ?></div>
</div>
<div class="section">
<h3 title="Clerkship Core Rotations Pending Section" class="collapsable collapsed">Clerkship Core Rotations Pending</h3>
<div id="clerkship-core-rotations-pending-section"><?php echo display_clerkship_core_pending($clerkship_core_pending); ?></div>
</div>
<div class="section">
<h3 title="Clerkship Electives Completed Satisfactorily to Date Section" class="collapsable collapsed">Clerkship Electives Completed Satisfactorily to Date</h3>
<div id="clerkship-electives-completed-satisfactorily-to-date-section"><?php echo display_clerkship_elective_completed($clerkship_elective_completed); ?></div>
</div>
<div class="section">
<h3 title="Leaves of Absence" class="collapsable collapsed">Leaves of Absence</h3>
<div id="leaves-of-absence">
<?php
echo display_mspr_details($leaves_of_absence);
?>
</div>
</div>
<div class="section">
<h3 title="Formal Remediation Received" class="collapsable collapsed">Formal Remediation Received</h3>
<div id="formal-remediation-received">
<?php
echo display_mspr_details($formal_remediations);
?>
</div>
</div>
<div class="section">
<h3 title="Disciplinary Actions" class="collapsable collapsed">Disciplinary Actions</h3>
<div id="disciplinary-actions">
<?php
echo display_mspr_details($disciplinary_actions);
?>
</div>
</div>
</div>
</div>
<div id="reject-submission-box" class="modal-confirmation" style="height: 300px">
<h1>Reject Submission</h1>
<div class="display-notice">
Please confirm that you wish to <strong>reject</strong> this submission.
</div>
<p>
<label for="reject-submission-details" class="form-required">Please provide an explanation for this decision:</label><br />
<textarea id="reject-submission-details" name="reject_verify_details" style="width: 99%; height: 75px" cols="45" rows="5"></textarea>
</p>
<div class="footer">
<button class="btn modal-close">Close</button>
<button class="btn btn-primary pull-right modal-confirm" id="reject-submission-confirm">Reject</button>
</div>
</div>
<script type="text/javascript">
document.observe('dom:loaded', function() {
try {
function get_modal_options() {
return {
overlayOpacity: 0.75,
closeOnClick: 'overlay',
className: 'modal-confirmation',
fade: true,
fadeDuration: 0.30
};
}
var api_url = '<?php echo webservice_url("mspr-admin"); ?>&id=<?php echo $PROXY_ID; ?>&mspr-section=';
var reject_modal = new Control.Modal('reject-submission-box', get_modal_options());
var add_clineval_modal = new Control.Modal('add-clineval-box', get_modal_options());
var edit_clineval_modal = new Control.Modal('update-clineval-box', get_modal_options());
var edit_studentship_modal = new Control.Modal('update-studentship-box', get_modal_options());
var add_studentship_modal = new Control.Modal('add-studentship-box', get_modal_options());
var edit_int_act_modal = new Control.Modal('update-int-act-box', get_modal_options());
var add_int_act_modal = new Control.Modal('add-int-act-box', get_modal_options());
var edit_sre_modal = new Control.Modal('update-sre-box', get_modal_options());
var add_sre_modal = new Control.Modal('add-sre-box', get_modal_options());
var edit_internal_award_modal = new Control.Modal('update-internal-award-box', get_modal_options());
var add_internal_award_modal = new Control.Modal('add-internal-award-box', get_modal_options());
var add_critical_enquiry_modal = new Control.Modal('add-critical-enquiry-box', get_modal_options());
var edit_critical_enquiry_modal = new Control.Modal('update-critical-enquiry-box', get_modal_options());
var add_community_based_project_modal = new Control.Modal('add-community-based-project-box', get_modal_options());
var edit_community_based_project_modal = new Control.Modal('update-community-based-project-box', get_modal_options());
var add_research_modal = new Control.Modal('add-research-box', get_modal_options());
var edit_research_modal = new Control.Modal('update-research-box',get_modal_options());
var add_contribution_modal = new Control.Modal('add-contribution-box', get_modal_options());
var edit_contribution_modal = new Control.Modal('update-contribution-box', get_modal_options());
var add_external_award_modal = new Control.Modal('add-external-award-box', get_modal_options());
var edit_external_award_modal = new Control.Modal('update-external-award-box', get_modal_options());
var research_citations = new ActiveDataEntryProcessor({
url : api_url + 'research_citations',
data_destination: $('research_citations'),
remove_forms_selector: '#research .entry form.remove_form',
new_button: $('add_research_citation_link'),
section:'research_citations',
new_modal: add_research_modal
});
var research_citation_priority_list = new PriorityList({
url : api_url + 'research_citations',
data_destination: $('research_citations'),
format: /research_citation_([0-9]*)$/,
tag: "li",
handle:'.handle',
section:'research_citations',
element: 'citations_list',
params : { user_id: <?php echo $user->getID(); ?> }
});
var research_edit = new ActiveEditor({
url : api_url + 'research_citations',
data_destination: $('research_citations'),
edit_forms_selector: '#research_citations .entry form.edit_form',
edit_modal: edit_research_modal,
section: 'research_citations'
});
var research_citations_approval = new ActiveApprovalProcessor({
url : api_url + 'research_citations',
data_destination: $('research_citations'),
action_form_selector: '#research_citations .entry form.reject_form, #research_citations .entry form.approve_form, #research_citations .entry form.unapprove_form',
section: "research_citations",
reject_modal: reject_modal
});
var critical_enquiry = new ActiveDataEntryProcessor({
url : api_url + 'critical_enquiry',
data_destination: $('critical_enquiry'),
remove_forms_selector: '#critical_enquiry .entry form.remove_form',
new_button: $('add_critical_enquiry_link'),
section:'critical_enquiry',
new_modal: add_critical_enquiry_modal
});
var critical_enquiry_edit = new ActiveEditor({
url : api_url + 'critical_enquiry',
data_destination: $('critical_enquiry'),
edit_forms_selector: '#critical_enquiry .entry form.edit_form',
edit_modal: edit_critical_enquiry_modal,
section: 'critical_enquiry'
});
var critical_enquiry_approval = new ActiveApprovalProcessor({
url : api_url + 'critical_enquiry',
data_destination: $('critical_enquiry'),
action_form_selector: '#critical_enquiry .entry form.reject_form, #critical_enquiry .entry form.approve_form, #critical_enquiry .entry form.unapprove_form',
section: "critical_enquiry",
reject_modal: reject_modal
});
var community_based_project = new ActiveDataEntryProcessor({
url : api_url + 'community_based_project',
data_destination: $('community_based_project'),
remove_forms_selector: '#community_based_project .entry form.remove_form',
new_button: $('add_community_based_project_link'),
section:'community_based_project',
new_modal: add_community_based_project_modal
});
var community_based_project_edit = new ActiveEditor({
url : api_url + 'community_based_project',
data_destination: $('community_based_project'),
edit_forms_selector: '#community_based_project .entry form.edit_form',
edit_modal: edit_community_based_project_modal,
section: 'community_based_project'
});
var community_based_project_approval = new ActiveApprovalProcessor({
url : api_url + 'community_based_project',
data_destination: $('community_based_project'),
action_form_selector: '#community_based_project .entry form.reject_form, #community_based_project .entry form.approve_form, #community_based_project .entry form.unapprove_form',
section: "community_based_project",
reject_modal: reject_modal
});
var external_awards = new ActiveDataEntryProcessor({
url : api_url + 'external_awards',
data_destination: $('external_awards'),
remove_forms_selector: '#external_awards .entry form.remove_form',
new_button: $('add_external_award_link'),
section:'external_awards',
new_modal: add_external_award_modal
});
var external_awards_edit = new ActiveEditor({
url : api_url + 'external_awards',
data_destination: $('external_awards'),
edit_forms_selector: '#external_awards .entry form.edit_form',
edit_modal: edit_external_award_modal,
section: 'external_awards'
});
var external_awards_approval = new ActiveApprovalProcessor({
url : api_url + 'external_awards',
data_destination: $('external_awards'),
action_form_selector: '#external_awards .entry form.reject_form, #external_awards .entry form.approve_form, #external_awards .entry form.unapprove_form',
section: "external_awards",
reject_modal: reject_modal
});
var contributions = new ActiveDataEntryProcessor({
url : api_url + 'contributions',
data_destination: $('contributions'),
remove_forms_selector: '#contributions .entry form.remove_form',
new_button: $('add_contribution_link'),
section:'contributions',
new_modal: add_contribution_modal
});
var contributions_edit = new ActiveEditor({
url : api_url + 'contributions',
data_destination: $('contributions'),
edit_forms_selector: '#contributions .entry form.edit_form',
edit_modal: edit_contribution_modal,
section: 'contributions'
});
var contributions_approval = new ActiveApprovalProcessor({
url : api_url + 'contributions',
data_destination: $('contributions'),
action_form_selector: '#contributions .entry form.reject_form, #contributions .entry form.approve_form, #contributions .entry form.unapprove_form',
section: "contributions",
reject_modal: reject_modal
});
var clineval_comments = new ActiveDataEntryProcessor({
url : api_url + 'clineval',
data_destination: $('clinical_performance_eval_comments'),
remove_forms_selector: '#clinical_performance_eval_comments .entry form.remove_form',
new_button: $('add_clineval_link'),
section: 'clineval',
new_modal: add_clineval_modal
});
var clineval_edit = new ActiveEditor({
url : api_url + 'clineval',
data_destination: $('clinical_performance_eval_comments'),
edit_forms_selector: '#clinical_performance_eval_comments .entry form.edit_form',
edit_modal: edit_clineval_modal,
section: 'clineval'
});
var studentships = new ActiveDataEntryProcessor({
url : api_url + 'studentships',
data_destination: $('studentships'),
remove_forms_selector: '#studentships .entry form.remove_form',
new_button: $('add_studentship_link'),
section: 'studentships',
new_modal: add_studentship_modal
});
var studentships_edit = new ActiveEditor({
url : api_url + 'studentships',
data_destination: $('studentships'),
edit_forms_selector: '#studentships .entry form.edit_form',
edit_modal: edit_studentship_modal,
section: 'studentships'
});
$('int_act_start').observe('focus',function(e) {
showCalendar('',this,this,null,null,0,30,1);
}.bind($('int_act_start')));
$('int_act_end').observe('focus',function(e) {
showCalendar('',this,this,null,null,0,30,1);
}.bind($('int_act_end')));
var int_acts = new ActiveDataEntryProcessor({
url : api_url + 'int_acts',
data_destination: $('int_acts'),
remove_forms_selector: '#int_acts .entry form.remove_form',
new_button: $('add_int_act_link'),
section: 'int_acts',
new_modal: add_int_act_modal
});
$('int_act_start_edit').observe('focus',function(e) {
showCalendar('',this,this,null,null,0,30,1);
}.bind($('int_act_start_edit')));
$('int_act_end_edit').observe('focus',function(e) {
showCalendar('',this,this,null,null,0,30,1);
}.bind($('int_act_end_edit')));
var int_acts_edit = new ActiveEditor({
url : api_url + 'int_acts',
data_destination: $('int_acts'),
edit_forms_selector: '#int_acts .entry form.edit_form',
edit_modal: edit_int_act_modal,
section: 'int_acts'
});
var student_run_electives = new ActiveDataEntryProcessor({
url : api_url + 'student_run_electives',
data_destination: $('student_run_electives'),
remove_forms_selector: '#student_run_electives .entry form.remove_form',
new_button: $('add_student_run_elective_link'),
section: 'student_run_electives',
new_modal: add_sre_modal
});
var student_run_electives_edit = new ActiveEditor({
url : api_url + 'student_run_electives',
data_destination: $('student_run_electives'),
edit_forms_selector: '#student_run_electives .entry form.edit_form',
edit_modal: edit_sre_modal,
section: 'student_run_electives'
});
var internal_awards = new ActiveDataEntryProcessor({
url : api_url + 'internal_awards',
data_destination: $('internal_awards'),
remove_forms_selector: '#internal_awards .entry form.remove_form',
new_button: $('add_internal_award_link'),
section: 'internal_awards',
new_modal: add_internal_award_modal
});
var internal_awards_edit = new ActiveEditor({
url : api_url + 'internal_awards',
data_destination: $('internal_awards'),
edit_forms_selector: '#internal_awards .entry form.edit_form',
edit_modal: edit_internal_award_modal,
section: 'internal_awards'
});
}catch(e) {alert(e);
clog(e);
}
});
</script>
<?php
}
} | mattsimpson/entrada-1x | www-root/core/modules/admin/users/manage/students/mspr.inc.php | PHP | gpl-3.0 | 68,918 |
using System.IO;
using System.Runtime.Serialization;
using WolvenKit.CR2W.Reflection;
using FastMember;
using static WolvenKit.CR2W.Types.Enums;
namespace WolvenKit.CR2W.Types
{
[DataContract(Namespace = "")]
[REDMeta]
public class CBehaviorGraphEngineVectorValueNode : CBehaviorGraphVectorVariableNode
{
[Ordinal(1)] [RED("engineValueType")] public CEnum<EBehaviorEngineVectorValueType> EngineValueType { get; set;}
[Ordinal(2)] [RED("manualControl")] public CBool ManualControl { get; set;}
[Ordinal(3)] [RED("cachedVectorVariable")] public CPtr<CBehaviorVectorVariable> CachedVectorVariable { get; set;}
public CBehaviorGraphEngineVectorValueNode(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ }
public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBehaviorGraphEngineVectorValueNode(cr2w, parent, name);
public override void Read(BinaryReader file, uint size) => base.Read(file, size);
public override void Write(BinaryWriter file) => base.Write(file);
}
} | Traderain/Wolven-kit | WolvenKit.CR2W/Types/W3/RTTIConvert/CBehaviorGraphEngineVectorValueNode.cs | C# | gpl-3.0 | 1,057 |
/**
* Copyright (C) 2011 Matthias Jordan <matthias.jordan@googlemail.com>
*
* This file is part of piRSS.
*
* piRSS 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.
*
* piRSS 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 piRSS. If not, see <http://www.gnu.org/licenses/>.
*/
package de.codefu.android.rss.updateservice;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import de.codefu.android.rss.CursorChangedReceiver;
import de.codefu.android.rss.db.ItemProvider;
/**
* Helper that defines the communication between the Activities and Services.
* <p>
* One important thing covered here are insert intents. An insert intent is an
* intent whose receiver is the {@link InsertService} and that communicates that
* some RSS feed data should be inserted into the database. This intent has two
* different forms:
* <ul>
* <li>One uses the {@link #CONTENT}</li> extra whose value is the data that was
* downloaded from the RSS feed. </li>
* <li>The other form uses the {@link #CONTENT_REF} extra whose value is the ID
* of a row in an auxiliary database table that has the data that was downloaded
* from the RSS feed.</li>
* </ul>
* The reason for this intent having two different kinds of behavior is that
* normally passing the RSS feed data directly is better in terms of CPU cycles.
* But an intent is passed using RPC and for RPC data there is a maximum size.
* So whenever feed data is larger than that maximum size {@link ServiceComm}
* stores it in the database and passes the ID of that database entry using the
* {@link #CONTENT_REF} extra.
*
* @author mj
*/
public class ServiceComm {
/**
* The key for the extra hat has the ID of the feed whose data is attached
* or referenced.
*/
public static final String FEED_ID = "feedid";
/**
* The key for the extra that has the RSS feed data.
*/
private static final String CONTENT = "content";
/**
* The key for the extra that has the ID of the row in the auxiliary table
* where the RSS feed data is stored.
*/
private static final String CONTENT_REF = "contentid";
/**
* Wrapper for the information extracted from the insert intent.
*/
public static class IntentContent {
/**
* The data to insert.
*/
public String content;
/**
* The ID of the feed for which to insert the data.
*/
public long feedId;
}
/**
* The maximum size of data that can be stored in an intent.
*/
// TODO: Get correct max size
private static final int MAX_RPC_SIZE = 50 * 1024;
/**
* Name of a broadcast that is sent when polling starts.
*/
public static final String POLLING_STARTED = "pollingstarted";
/**
* Name of a broadcast that is sent when there are problems during polling.
*/
public static final String POLLING_PROBLEM = "pollingproblem";
/**
* Creates an insert intent.
* <p>
* If the data given is too large for the RPC system (larger than
* {@link #MAX_RPC_SIZE}) the data is stored in a database and the ID of
* that data in the database is stored in the intent. Otherwise the data
* itself is stored in the intent.
*
* @param c
* the context to create the intent for
* @param feedId
* the ID of the feed whose data is in body
* @param body
* the data of the RSS feed
* @return an intent object ready for sending
*/
public static Intent createInsertIntent(Context c, long feedId, String body) {
final Intent i = new Intent(c, InsertService.class);
if (body.length() > MAX_RPC_SIZE) {
final Uri uri = ItemProvider.CONTENT_URI_AUX;
final ContentValues cv = new ContentValues();
cv.put("content", body);
final Uri id = c.getContentResolver().insert(uri, cv);
i.putExtra(CONTENT_REF, id);
}
else {
i.putExtra(CONTENT, body);
}
i.putExtra(FEED_ID, feedId);
Log.d("ServComm", "Created " + i);
return i;
}
/**
* Takes an insert intent created with
* {@link #createInsertIntent(Context, long, String)} and retrieves the data
* in it.
* <p>
* The handling of the data in the intent (reference or directly attached
* data) is totally transparent. The caller also does not have to care about
* the maintenance of the auxiliary table.
*
* @param c
* the content to use for a possible database access
* @param intent
* the intent to read from
* @return the object with the data and feed ID read from the intent.
*/
public static IntentContent getInsertContent(Context c, Intent intent) {
final IntentContent ic = new IntentContent();
final Bundle extras = intent.getExtras();
final Object contentRefO = extras.get(CONTENT_REF);
ic.feedId = extras.getLong(FEED_ID);
if (contentRefO != null) {
if (contentRefO instanceof Uri) {
final Uri contentRef = (Uri) contentRefO;
final Cursor cursor = c.getContentResolver().query(contentRef, null, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
ic.content = cursor.getString(cursor.getColumnIndex(ItemProvider.AUX_COL_CONTENT));
}
cursor.close();
}
c.getContentResolver().delete(contentRef, null, null);
}
Log.i("ServComm", "Read intent for feed " + ic.feedId + " from aux table");
}
else {
ic.content = extras.getString(CONTENT);
Log.i("ServComm", "Read intent for feed " + ic.feedId);
}
return ic;
}
private static void sendBroadcast(Context context, String action) {
final Intent intent = new Intent(action);
intent.setPackage(CursorChangedReceiver.PACKAGE_NAME);
context.sendBroadcast(intent);
}
/**
* Sends a broadcast to announce that the data in the DB has changed.
*
* @param context
* the content to use for sending the intent
*/
public static void sendDataChangedBroadcast(Context context) {
sendBroadcast(context, CursorChangedReceiver.DATA_CHANGED);
}
/**
* Sends a broadcast to announce that polling has stated.
*
* @param context
* the content to use for sending the intent
*/
public static void sendPollingStartedBroadcast(Context context) {
sendBroadcast(context, POLLING_STARTED);
}
/**
* Sends a broadcast to announce that there was a problem during the
* download for a given feed.
*
* @param context
* the content to use for sending the intent
* @param feedId
* the ID of the feed that was attempted to poll
*/
public static void sendPollingProblemBroadcast(Context context, long feedId) {
final Intent intent = new Intent(POLLING_PROBLEM);
intent.setPackage(CursorChangedReceiver.PACKAGE_NAME);
intent.putExtra(FEED_ID, feedId);
context.sendBroadcast(intent);
}
public static void sendPollIntent(Context context, long feedId) {
final Intent i = new Intent(context, UpdateService.class);
i.putExtra(ServiceComm.FEED_ID, feedId);
context.startService(i);
}
/**
* Sends an intent to the {@link AutoPollService} to trigger polling the
* feeds for which automatic polling is configured.
*
* @param context
* the context to use for sending the intent
*/
public static void sendAutoPollIntent(Context context) {
final Intent i = new Intent(context, AutoPollService.class);
context.startService(i);
}
}
| matthiasjordan/piRSS | src/de/codefu/android/rss/updateservice/ServiceComm.java | Java | gpl-3.0 | 8,607 |
#! /usr/bin/env python
# I found this file inside Super Mario Bros python
# written by HJ https://sourceforge.net/projects/supermariobrosp/
# the complete work is licensed under GPL3 although I can not determine# license of this file
# maybe this is the original author, we can contact him/her http://www.pygame.org/project-EzMeNu-855-.html
import pygame
class EzMenu:
def __init__(self, *options):
self.options = options
self.x = 0
self.y = 0
self.font = pygame.font.Font(None, 32)
self.option = 0
self.width = 1
self.color = [0, 0, 0]
self.hcolor = [255, 0, 0]
self.height = len(self.options)*self.font.get_height()
for o in self.options:
text = o[0]
ren = self.font.render(text, 2, (0, 0, 0))
if ren.get_width() > self.width:
self.width = ren.get_width()
def draw(self, surface):
i=0
for o in self.options:
if i==self.option:
clr = self.hcolor
else:
clr = self.color
text = o[0]
ren = self.font.render(text, 2, clr)
if ren.get_width() > self.width:
self.width = ren.get_width()
surface.blit(ren, ((self.x+self.width/2) - ren.get_width()/2, self.y + i*(self.font.get_height()+4)))
i+=1
def update(self, events):
for e in events:
if e.type == pygame.KEYDOWN:
if e.key == pygame.K_DOWN:
self.option += 1
if e.key == pygame.K_UP:
self.option -= 1
if e.key == pygame.K_RETURN:
self.options[self.option][1]()
if self.option > len(self.options)-1:
self.option = 0
if self.option < 0:
self.option = len(self.options)-1
def set_pos(self, x, y):
self.x = x
self.y = y
def set_font(self, font):
self.font = font
def set_highlight_color(self, color):
self.hcolor = color
def set_normal_color(self, color):
self.color = color
def center_at(self, x, y):
self.x = x-(self.width/2)
self.y = y-(self.height/2)
| juanjosegzl/learningpygame | ezmenu.py | Python | gpl-3.0 | 2,298 |
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.IO;
using System.Text;
using System.Xml;
namespace ICSharpCode.ILSpy {
/// <summary>
/// Static methods for determining the type of a file.
/// </summary>
static class GuessFileType {
public static FileType DetectFileType(Stream stream) {
StreamReader reader;
if (stream.Length >= 2) {
int firstByte = stream.ReadByte();
int secondByte = stream.ReadByte();
switch ((firstByte << 8) | secondByte) {
case 0xfffe: // UTF-16 LE BOM / UTF-32 LE BOM
case 0xfeff: // UTF-16 BE BOM
stream.Position -= 2;
reader = new StreamReader(stream, detectEncodingFromByteOrderMarks: true);
break;
case 0xefbb: // start of UTF-8 BOM
if (stream.ReadByte() == 0xbf) {
reader = new StreamReader(stream, Encoding.UTF8);
break;
}
else {
return FileType.Binary;
}
default:
if (IsUTF8(stream, (byte)firstByte, (byte)secondByte)) {
stream.Position = 0;
reader = new StreamReader(stream, Encoding.UTF8);
break;
}
else {
return FileType.Binary;
}
}
}
else {
return FileType.Binary;
}
// Now we got a StreamReader with the correct encoding
// Check for XML now
try {
XmlTextReader xmlReader = new XmlTextReader(reader);
xmlReader.XmlResolver = null;
xmlReader.MoveToContent();
return FileType.Xml;
}
catch (XmlException) {
return FileType.Text;
}
}
static bool IsUTF8(Stream fs, byte firstByte, byte secondByte) {
int max = (int)Math.Min(fs.Length, 500000); // look at max. 500 KB
const int ASCII = 0;
const int Error = 1;
const int UTF8 = 2;
const int UTF8Sequence = 3;
int state = ASCII;
int sequenceLength = 0;
byte b;
for (int i = 0; i < max; i++) {
if (i == 0) {
b = firstByte;
}
else if (i == 1) {
b = secondByte;
}
else {
b = (byte)fs.ReadByte();
}
if (b < 0x80) {
// normal ASCII character
if (state == UTF8Sequence) {
state = Error;
break;
}
}
else if (b < 0xc0) {
// 10xxxxxx : continues UTF8 byte sequence
if (state == UTF8Sequence) {
--sequenceLength;
if (sequenceLength < 0) {
state = Error;
break;
}
else if (sequenceLength == 0) {
state = UTF8;
}
}
else {
state = Error;
break;
}
}
else if (b >= 0xc2 && b < 0xf5) {
// beginning of byte sequence
if (state == UTF8 || state == ASCII) {
state = UTF8Sequence;
if (b < 0xe0) {
sequenceLength = 1; // one more byte following
}
else if (b < 0xf0) {
sequenceLength = 2; // two more bytes following
}
else {
sequenceLength = 3; // three more bytes following
}
}
else {
state = Error;
break;
}
}
else {
// 0xc0, 0xc1, 0xf5 to 0xff are invalid in UTF-8 (see RFC 3629)
state = Error;
break;
}
}
return state != Error;
}
}
enum FileType {
Binary,
Text,
Xml
}
}
| zuloloxi/dnSpy | dnSpy/GuessFileType.cs | C# | gpl-3.0 | 4,194 |
/*
* Copyright (C) 2014 Emil
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package freeWarOnTerror.cards;
import static freeWarOnTerror.Game.getCurrentPlayer;
import static freeWarOnTerror.Game.getMuslimCountries;
import static freeWarOnTerror.Game.getUS;
import freeWarOnTerror.MuslimCountry;
import freeWarOnTerror.abClasses.Card;
import freeWarOnTerror.helpers.CardLookup;
/**
*
* @author Emil
*/
public class IEDs extends Card {
public IEDs(){
super(CardLookup.IEDS);
}
@Override
public Boolean getPlayable(){
for (MuslimCountry c : getMuslimCountries()){
if (c.getRegimeChange() > 0 && c.hasCells()){
return true;
}
}
return false;
}
@Override
public void playEvent(){
getCurrentPlayer().discard(getUS().getRandomCard());
}
}
| wachsmuth/freeWarOnTerror | src/freeWarOnTerror/cards/IEDs.java | Java | gpl-3.0 | 1,521 |
function date(pub_date){
var date = new Date( Date.parse(pub_date+' UTC'));
return date.toLocaleString();
}
| donkeyxote/djangle | djangle/forum/static/forum/js/localTime.js | JavaScript | gpl-3.0 | 120 |
<div id="search" class="portfolio-search">
<div class="container">
<div class="row">
<div class="col-md-7">
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle language" data-toggle="dropdown">
Language <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" data-type="language">
<li><a href="<?= base_url('portfolio/search/0/12/javascript') ?>" data-value="javascript">Javascript</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/python') ?>" data-value="python">Python</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/php') ?>" data-value="php">PHP</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/sql') ?>" data-value="mysql">MySQL</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/c') ?>" data-value="c">C</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/c'.urldecode('++')) ?>" data-value="c++">C++</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/nodejs') ?>" data-value="nodejs">Nodejs</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/html5') ?>" data-value="html5">HTML5</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/') ?>" data-value="all">Language</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle company" data-toggle="dropdown">
Company <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" data-type="company">
<li><a href="<?= base_url('portfolio/search/0/12/shippingsoon') ?>" data-value="shippingsoon">Shippingsoon</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/vaden') ?>" data-value="vaden">Vaden</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/carcarepeople') ?>" data-value="carcarepeople">Carcarepeople</a></li>
<li><a href="<?= base_url('portfolio/search/0/12/') ?>" data-value="all">Company</a></li>
</ul>
</div>
<div class="btn-group">
<button type="button" class="btn btn-default dropdown-toggle year" data-toggle="dropdown">
Year <span class="caret"></span>
</button>
<ul class="dropdown-menu" role="menu" data-type="year">
<?php for ($i = 0; $i < 8; $i++): ?>
<li>
<a href="<?= base_url('portfolio/search/0/12/'.date('Y', strtotime("-$i year"))) ?>" data-value="<?= date('Y', strtotime("-$i year")) ?>"><?= date('Y', strtotime("-$i year")) ?></a>
</li>
<?php endfor ?>
<li><a href="<?= base_url('portfolio/search/0/12/') ?>" data-value="all">Year</a></li>
</ul>
</div>
</div> <!-- /.col-md-7 -->
<div class="col-md-4 col-md-offset-1">
<form class="pull-right" action="<?= base_url("project/search/$offset") ?>" method="post">
<input type="hidden" id="offset" value="<?= $offset ?>"/>
<input type="hidden" id="limit" value="<?= $limit ?>"/>
<input type="hidden" id="auto_complete" value="<?= $auto_complete ?>"/>
<div class="search-box">
<input type="text" class="search-query form-control transition" value="<?= $search_tags ?>" data-onpopstate="0" data-enabled="1">
<span class="glyphicon glyphicon-search"></span>
</div>
</form>
</div> <!-- /.col-md-5 -->
</div> <!-- /.row -->
</div> <!-- container -->
</div> <!-- /.portfolio-search -->
| shippingsoon/Shippingsoon | application/views/portfolio/search.php | PHP | gpl-3.0 | 3,554 |
"""Calculate exact solutions for the zero dimensional LLG as given by
[Mallinson2000]
"""
from __future__ import division
from __future__ import absolute_import
from math import sin, cos, tan, log, atan2, acos, pi, sqrt
import scipy as sp
import matplotlib.pyplot as plt
import functools as ft
import simpleode.core.utils as utils
def calculate_switching_time(magnetic_parameters, p_start, p_now):
"""Calculate the time taken to switch from polar angle p_start to p_now
with the magnetic parameters given.
"""
# Should never quite get to pi/2
# if p_now >= pi/2:
# return sp.inf
# Cache some things to simplify the expressions later
H = magnetic_parameters.H(None)
Hk = magnetic_parameters.Hk()
alpha = magnetic_parameters.alpha
gamma = magnetic_parameters.gamma
# Calculate the various parts of the expression
prefactor = ((alpha**2 + 1)/(gamma * alpha)) \
* (1.0 / (H**2 - Hk**2))
a = H * log(tan(p_now/2) / tan(p_start/2))
b = Hk * log((H - Hk*cos(p_start)) /
(H - Hk*cos(p_now)))
c = Hk * log(sin(p_now) / sin(p_start))
# Put everything together
return prefactor * (a + b + c)
def calculate_azimuthal(magnetic_parameters, p_start, p_now):
"""Calculate the azimuthal angle corresponding to switching from
p_start to p_now with the magnetic parameters given.
"""
def azi_into_range(azi):
a = azi % (2*pi)
if a < 0:
a += 2*pi
return a
alpha = magnetic_parameters.alpha
no_range_azi = (-1/alpha) * log(tan(p_now/2) / tan(p_start/2))
return azi_into_range(no_range_azi)
def generate_dynamics(magnetic_parameters,
start_angle=pi/18,
end_angle=17*pi/18,
steps=1000):
"""Generate a list of polar angles then return a list of corresponding
m directions (in spherical polar coordinates) and switching times.
"""
mag_params = magnetic_parameters
# Construct a set of solution positions
pols = sp.linspace(start_angle, end_angle, steps)
azis = [calculate_azimuthal(mag_params, start_angle, p) for p in pols]
sphs = [utils.SphPoint(1.0, azi, pol) for azi, pol in zip(azis, pols)]
# Calculate switching times for these positions
times = [calculate_switching_time(mag_params, start_angle, p)
for p in pols]
return (sphs, times)
def plot_dynamics(magnetic_parameters,
start_angle=pi/18,
end_angle=17*pi/18,
steps=1000):
"""Plot exact positions given start/finish angles and magnetic
parameters.
"""
sphs, times = generate_dynamics(magnetic_parameters, start_angle,
end_angle, steps)
sphstitle = "Path of m for " + str(magnetic_parameters) \
+ "\n (starting point is marked)."
utils.plot_sph_points(sphs, title=sphstitle)
timestitle = "Polar angle vs time for " + str(magnetic_parameters)
utils.plot_polar_vs_time(sphs, times, title=timestitle)
plt.show()
def calculate_equivalent_dynamics(magnetic_parameters, polars):
"""Given a list of polar angles (and some magnetic parameters)
calculate what the corresponding azimuthal angles and switching times
(from the first angle) should be.
"""
start_angle = polars[0]
f_times = ft.partial(calculate_switching_time, magnetic_parameters,
start_angle)
exact_times = [f_times(p) for p in polars]
f_azi = ft.partial(calculate_azimuthal, magnetic_parameters, start_angle)
exact_azis = [f_azi(p) for p in polars]
return exact_times, exact_azis
def plot_vs_exact(magnetic_parameters, ts, ms):
# Extract lists of the polar coordinates
m_as_sph_points = map(utils.array2sph, ms)
pols = [m.pol for m in m_as_sph_points]
azis = [m.azi for m in m_as_sph_points]
# Calculate the corresponding exact dynamics
exact_times, exact_azis = \
calculate_equivalent_dynamics(magnetic_parameters, pols)
# Plot
plt.figure()
plt.plot(ts, pols, '--',
exact_times, pols)
plt.figure()
plt.plot(pols, azis, '--',
pols, exact_azis)
plt.show()
| davidshepherd7/Landau-Lifshitz-Gilbert-ODE-model | llg/mallinson.py | Python | gpl-3.0 | 4,251 |
class Sbs:
def __init__(self, sbsFilename, sbc_filename, newSbsFilename):
import xml.etree.ElementTree as ET
import Sbc
self.mySbc = Sbc.Sbc(sbc_filename)
self.sbsTree = ET.parse(sbsFilename)
self.sbsRoot = self.sbsTree.getroot()
self.XSI_TYPE = "{http://www.w3.org/2001/XMLSchema-instance}type"
self.newSbsFilename = newSbsFilename
def findPlayerBySteamID(self, steam_id):
if (steam_id == 0):
return False
print("looking for player with steamID of %s" % steam_id)
ourPlayerDict = self.mySbc.getPlayerDict()
for player in ourPlayerDict:
# print playerDict[player]['steamID']
if ourPlayerDict[player]['steamID'] == steam_id:
return ourPlayerDict[player]
# if we don't find the user
return False
def giveReward(self, rewardOwner, rewardType, rewardAmount):
"""
This method will hunt down the first cargo container owned by
<Owner> matching their ingame ID, and with with "CustomName"
of "LOOT" and place the rewards in it
"""
import xml.etree.ElementTree as ET
print("trying to give %s %s units of %s" % (rewardOwner, rewardAmount, rewardType))
for sectorObjects in self.sbsRoot.iter('SectorObjects'):
for entityBase in sectorObjects.iter('MyObjectBuilder_EntityBase'):
# EntityId = entityBase.find('EntityId')
# print ("checking entityID %s" % EntityId.text)
gridSize = entityBase.find('GridSizeEnum')
# TODO+: some kind of warning if we have a reward to give, but can't find this user's LOOT container
if hasattr(gridSize, 'text'):
cubeBlocks = entityBase.find('CubeBlocks')
for myCubeBlock in cubeBlocks.iter('MyObjectBuilder_CubeBlock'):
owner = myCubeBlock.find("Owner")
EntityId = myCubeBlock.find('EntityId')
customName = myCubeBlock.find('CustomName')
if hasattr(owner, 'text') and owner.text == rewardOwner and myCubeBlock.get(self.XSI_TYPE) == "MyObjectBuilder_CargoContainer" and hasattr(customName, 'text'):
if "LOOT" in customName.text:
print("I found a cargo container owned by %s with entityID of %s and name of %s" % (owner.text, EntityId.text, customName.text))
componentContainer = myCubeBlock.find('ComponentContainer')
components = componentContainer.find('Components')
componentData = components.find('ComponentData')
component = componentData.find('Component')
items = component.find('Items')
itemCount = 0
for myInventoryItems in items.iter('MyObjectBuilder_InventoryItem'):
itemCount += 1
print("planning to add %s of %s into it as item %s" % (rewardAmount, rewardType, itemCount))
# <MyObjectBuilder_InventoryItem>
# <Amount>200</Amount>
# <PhysicalContent xsi:type="MyObjectBuilder_Ore">
# <SubtypeName>Uranium</SubtypeName> ## from rewardType
# </PhysicalContent>
# <ItemId>4</ItemId> ## from itemCount
# <AmountDecimal>200</AmountDecimal> ## from rewardAmount
# </MyObjectBuilder_InventoryItem>
# myCubeBlock.append((ET.fromstring('<MyObjectBuilder_InventoryItem><Amount>123456789</Amount></MyObjectBuilder_InventoryItem>')))
inventoryItem = ET.SubElement(items, 'MyObjectBuilder_InventoryItem')
amount = ET.SubElement(inventoryItem, 'Amount')
amount.text = str(rewardAmount)
physicalContent = ET.SubElement(inventoryItem, 'PhysicalContent')
physicalContent.set(self.XSI_TYPE, 'MyObjectBuilder_Ore')
subtypeName = ET.SubElement(physicalContent, 'SubtypeName')
subtypeName.text = rewardType
itemId = ET.SubElement(inventoryItem, 'ItemId')
itemId.text = str(itemCount)
amountDecimal = ET.SubElement(inventoryItem, 'AmountDecimal')
amountDecimal.text = str(rewardAmount)
nextItemId = component.find('nextItemId')
nextItemId.text = str(itemCount + 1)
# FIXME: this makes a mess of the html, figure out a way to clean it up?
def removeFloaters(self):
import xml.etree.ElementTree as ET
removedCount = 0
warnCount = 0
for sectorObjects in self.sbsRoot.iter('SectorObjects'):
for entityBase in sectorObjects.iter('MyObjectBuilder_EntityBase'):
cubeGridID = entityBase.find('EntityId')
gridSizeEnum = entityBase.find('GridSizeEnum')
objectType = entityBase.get(self.XSI_TYPE)
isStatic = entityBase.find('IsStatic') # FIXME: this does not do what I thought it did. Tested with simple station, and it isn't set as static when I build it from scratch.
# TODO: only way I can see to easily fix is check for <Forward x="-0" y="-0" z="-1" /> for static things
# print cubeGridID.text if hasattr(cubeGridID, 'text') else 'not defined'
if hasattr(cubeGridID, 'text'):
print("Grid EntityID: %s " % cubeGridID.text)
else:
print("FIXME: no gridID")
# print ("\t is objectType %s" % objectType )
if hasattr(isStatic, 'text'):
# this is a base, all of our checks are null and void. Bases don't float or cost me CPU
print("\t skipping trash checks because this IsStatic")
continue
if hasattr(gridSizeEnum, 'text'):
# is a grid, small or large
gridName = entityBase.find('DisplayName').text
print("\t is a grid size %s %s" % (gridSizeEnum.text, gridName))
# if the name contains DEL.WRN
if "[DEL.WRN]" in gridName:
print("\t ALREADY HAD DEL.WRN in the NAME, GOODBYE")
sectorObjects.remove(entityBase)
removedCount += 1
else:
# it doesn't have a DEL WRN yet, lets check for our rules
# TODO: look through the whole entityBase for 6 thrusters, a power supply, and at least one block not owned by pirates
thrusterCount = 0
powerSource = 0
controlSurface = 0
gyroCount = 0
turretCount = 0
ownerCount = 0
ownedThings = 0
ownerList = []
cubeBlocks = entityBase.find('CubeBlocks')
for myCubeBlock in cubeBlocks.iter('MyObjectBuilder_CubeBlock'):
owner = myCubeBlock.find("Owner")
# subtype = myCubeBlock.find('SubtypeName')
cubeType = myCubeBlock.get(self.XSI_TYPE)
entityID = myCubeBlock.find("EntityId")
# print ("\t\tTODO: cubeType of: %s" % cubeType)
if "Thrust" in cubeType:
thrusterCount += 1
elif "Cockpit" in cubeType:
controlSurface += 1
elif "Reactor" in cubeType:
powerSource += 1
elif "SolarPanel" in cubeType:
powerSource += 1
elif "RemoteControl" in cubeType:
controlSurface += 1
elif "Gyro" in cubeType:
gyroCount += 1
elif "Turret" in cubeType:
turretCount += 1
if hasattr(owner, 'text'):
# print ("\tOwner: %s" % owner.text)
if owner.text not in ownerList:
ownerList.append(owner.text)
ownerCount += 1
ownedThings += 1 # TODO: this is how many blocks have an owner, above is distinct owners of this grid
print("\t totals: %s %s %s %s %s %s %s" % (thrusterCount, powerSource, controlSurface, gyroCount, turretCount, ownerCount, len(ownerList)))
# TODO: if it fails all my tests,
# [CHECK] set name to [DEL.WRN]
# set ShowOnHUD to True ## can't, this is per cube. Ignore this.
if (thrusterCount < 6 or controlSurface < 1 or powerSource < 1 or gyroCount < 1 or ownerCount < 1):
print("\tWARNING: THIS GRID IS DUE TO DELETE")
gridNameToUpdate = entityBase.find('DisplayName')
gridNameToUpdate.text = "[DEL.WRN]" + gridNameToUpdate.text
print("\tname is now: %s" % gridNameToUpdate.text)
warnCount += 1
for myCubeBlock in cubeBlocks.iter('MyObjectBuilder_CubeBlock'):
# set all DeformationRatio to 1 (right up under owner) <DeformationRatio>0.5</DeformationRatio>
deformationElement = ET.SubElement(myCubeBlock, "DeformationRatio")
deformationElement.text = ".77"
# myCubeBlock.append('DeformationRatio', '.77')
else:
if (objectType == "MyObjectBuilder_FloatingObject"):
print("\t GOODBYE")
sectorObjects.remove(entityBase)
removedCount += 1
elif (objectType == "MyObjectBuilder_ReplicableEntity"):
# print ("\t Backpack!")
backPackName = entityBase.find('Name')
if hasattr(backPackName, 'text'):
print("\t Backpackname: %s" % backPackName.text)
print("\t GOODBYE")
sectorObjects.remove(entityBase)
removedCount += 1
elif (objectType == "MyObjectBuilder_VoxelMap"):
voxelStorageName = entityBase.find('StorageName')
if hasattr(voxelStorageName, 'text'):
print("\t voxelStorageName: %s" % voxelStorageName.text)
elif (objectType == "MyObjectBuilder_Character"):
# oops, someone was online
# entityID matches CharacterEntityId in the sbc
entityID = entityBase.find('EntityId').text # steamID
print("\t looking for %s entityID in playerDict" % entityID)
thisPlayersDict = self.findPlayerBySteamID(entityID) # returns False if we didn't have this players steamID in the sbc, meaning they weren't online
if (thisPlayersDict is not False and entityID is not False):
print("\t Sorry player: %s %s" % (entityID, thisPlayersDict["username"]))
else:
print("\tFIXME: this player was online, but I don't have their steamID of %s in the sbc" % entityID)
else:
print("\t ##### has no grid size")
# print ("writing tree out to %s" % newSbsFileName)
# tree = ET.ElementTree(sbsRoot)
# sbsRoot.attrib["xmlns:xsd"]="http://www.w3.org/2001/XMLSchema"
# tree.write(newSbsFileName, encoding='utf-8', xml_declaration=True)
return (removedCount, warnCount)
def writeFile(self):
import xml.etree.ElementTree as ET
print("writing tree out to %s" % self.newSbsFilename)
tree = ET.ElementTree(self.sbsRoot)
self.sbsRoot.attrib["xmlns:xsd"] = "http://www.w3.org/2001/XMLSchema"
tree.write(self.newSbsFilename, encoding='utf-8', xml_declaration=True)
| mccorkle/seds-utils | Sbs.py | Python | gpl-3.0 | 13,196 |
/*
Copyright 2019-2022 Michael Pozhidaev <msp@luwrain.org>
This file is part of LUWRAIN.
LUWRAIN 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.
LUWRAIN 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.
*/
Luwrain.addCommand("suspend", function(){
if (!Luwrain.popups.confirmDefaultYes(Luwrain.i18n.static.powerSuspendPopupName, Luwrain.i18n.static.powerSuspendPopupText))
return;
Luwrain.os.suspend();
});
| luwrain/extensions | js/pm.js | JavaScript | gpl-3.0 | 800 |
package com.pixelutilitys.commands;
import com.pixelmonmod.pixelmon.Pixelmon;
import com.pixelmonmod.pixelmon.enums.EnumGui;
import net.minecraft.command.CommandBase;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.ChatComponentTranslation;
public class PokecheckmeCommand extends CommandBase {
@Override
public String getCommandName() {
return "pokecheckme";
}
@Override
public int getRequiredPermissionLevel() {
return 2;
}
@Override
public String getCommandUsage(ICommandSender icommandsender) {
return "/pokecheckme";
}
@Override
public void processCommand(ICommandSender sender, String[] astring) {
// TODO Auto-generated method stub
EntityPlayer player = (EntityPlayer) sender;
player.openGui(Pixelmon.instance, EnumGui.PC.getIndex(), null, 0, 0, 0);
ChatComponentTranslation success = new ChatComponentTranslation("You have successfuly opened your pc files!");
sender.addChatMessage(success);
}
@Override
public int compareTo(Object arg0) {
// TODO Auto-generated method stub
return 0;
}
}
| AnDwHaT5/PixelUtilities | src/main/java/com/pixelutilitys/commands/PokecheckmeCommand.java | Java | gpl-3.0 | 1,217 |
/*
* _____ _ _ _____ _
* | __ \| | | | / ____| | |
* | |__) | | ___ | |_| (___ __ _ _ _ __ _ _ __ ___ __| |
* | ___/| |/ _ \| __|\___ \ / _` | | | |/ _` | '__/ _ \/ _` |
* | | | | (_) | |_ ____) | (_| | |_| | (_| | | | __/ (_| |
* |_| |_|\___/ \__|_____/ \__, |\__,_|\__,_|_| \___|\__,_|
* | |
* |_|
* PlotSquared plot management system for Minecraft
* Copyright (C) 2014 - 2022 IntellectualSites
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.plotsquared.core.events;
import com.plotsquared.core.player.PlotPlayer;
import com.plotsquared.core.plot.Plot;
import com.plotsquared.core.plot.PlotId;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.UUID;
public class PlotChangeOwnerEvent extends PlotEvent implements CancellablePlotEvent {
private final PlotPlayer<?> initiator;
@Nullable
private final UUID oldOwner;
private final boolean hasOldOwner;
@Nullable
private UUID newOwner;
private Result eventResult;
/**
* PlotChangeOwnerEvent: Called when a plot's owner is change.
*
* @param initiator The player attempting to set the plot's owner
* @param plot The plot having its owner changed
* @param oldOwner The old owner of the plot or null
* @param newOwner The new owner of the plot or null
* @param hasOldOwner If the plot has an old owner
*/
public PlotChangeOwnerEvent(
PlotPlayer<?> initiator, Plot plot, @Nullable UUID oldOwner,
@Nullable UUID newOwner, boolean hasOldOwner
) {
super(plot);
this.initiator = initiator;
this.newOwner = newOwner;
this.oldOwner = oldOwner;
this.hasOldOwner = hasOldOwner;
}
/**
* Get the PlotId.
*
* @return PlotId
*/
public PlotId getPlotId() {
return getPlot().getId();
}
/**
* Get the world name.
*
* @return String
*/
public String getWorld() {
return getPlot().getWorldName();
}
/**
* Get the change-owner initiator
*
* @return Player
*/
public PlotPlayer<?> getInitiator() {
return this.initiator;
}
/**
* Get the old owner of the plot. Null if not exists.
*
* @return UUID
*/
public @Nullable UUID getOldOwner() {
return this.oldOwner;
}
/**
* Get the new owner of the plot
*
* @return UUID
*/
public @Nullable UUID getNewOwner() {
return this.newOwner;
}
/**
* Set the new owner of the plot. Null for no owner.
*
* @param newOwner the new owner or null
*/
public void setNewOwner(@Nullable UUID newOwner) {
this.newOwner = newOwner;
}
/**
* Get if the plot had an old owner
*
* @return boolean
*/
public boolean hasOldOwner() {
return this.hasOldOwner;
}
@Override
public Result getEventResult() {
return eventResult;
}
@Override
public void setEventResult(Result e) {
this.eventResult = e;
}
}
| IntellectualSites/PlotSquared | Core/src/main/java/com/plotsquared/core/events/PlotChangeOwnerEvent.java | Java | gpl-3.0 | 3,957 |
/*
* Copyright (C) 2012-2015 Dominik Schürmann <dominik@dominikschuermann.de>
* Copyright (C) 2015 Adithya Abraham Philip <adithyaphilip@gmail.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.sufficientlysecure.keychain.ui;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Messenger;
import android.support.v4.app.Fragment;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import org.sufficientlysecure.keychain.R;
import org.sufficientlysecure.keychain.ui.dialog.AddEditKeyserverDialogFragment;
import org.sufficientlysecure.keychain.ui.util.FormattingUtils;
import org.sufficientlysecure.keychain.ui.util.Notify;
import org.sufficientlysecure.keychain.ui.util.recyclerview.ItemTouchHelperAdapter;
import org.sufficientlysecure.keychain.ui.util.recyclerview.ItemTouchHelperDragCallback;
import org.sufficientlysecure.keychain.ui.util.recyclerview.ItemTouchHelperViewHolder;
import org.sufficientlysecure.keychain.ui.util.recyclerview.RecyclerItemClickListener;
import org.sufficientlysecure.keychain.keyimport.ParcelableHkpKeyserver;
import org.sufficientlysecure.keychain.util.Preferences;
import java.util.ArrayList;
import java.util.Collections;
public class SettingsKeyserverFragment extends Fragment implements RecyclerItemClickListener.OnItemClickListener {
private static final String ARG_KEYSERVER_ARRAY = "arg_keyserver_array";
private ItemTouchHelper mItemTouchHelper;
private ArrayList<ParcelableHkpKeyserver> mKeyservers;
private KeyserverListAdapter mAdapter;
public static SettingsKeyserverFragment newInstance(ArrayList<ParcelableHkpKeyserver> keyservers) {
Bundle args = new Bundle();
args.putParcelableArrayList(ARG_KEYSERVER_ARRAY, keyservers);
SettingsKeyserverFragment fragment = new SettingsKeyserverFragment();
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle
savedInstanceState) {
return inflater.inflate(R.layout.settings_keyserver_fragment, null);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mKeyservers = getArguments().getParcelableArrayList(ARG_KEYSERVER_ARRAY);
mAdapter = new KeyserverListAdapter(mKeyservers);
RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.keyserver_recycler_view);
// recyclerView.setHasFixedSize(true); // the size of the first item changes
recyclerView.setAdapter(mAdapter);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
ItemTouchHelper.Callback callback = new ItemTouchHelperDragCallback(mAdapter);
mItemTouchHelper = new ItemTouchHelper(callback);
mItemTouchHelper.attachToRecyclerView(recyclerView);
// for clicks
recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), this));
// can't use item decoration because it doesn't move with drag and drop
// recyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), null));
// We have a menu item to show in action bar.
setHasOptionsMenu(true);
}
@Override
public void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) {
inflater.inflate(R.menu.keyserver_pref_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add_keyserver:
startAddKeyserverDialog();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void startAddKeyserverDialog() {
// keyserver and position have no meaning
startEditKeyserverDialog(AddEditKeyserverDialogFragment.DialogAction.ADD, null, -1);
}
private void startEditKeyserverDialog(AddEditKeyserverDialogFragment.DialogAction action,
ParcelableHkpKeyserver keyserver, final int position) {
Handler returnHandler = new Handler() {
@Override
public void handleMessage(Message message) {
Bundle data = message.getData();
switch (message.what) {
case AddEditKeyserverDialogFragment.MESSAGE_OKAY: {
boolean deleted =
data.getBoolean(AddEditKeyserverDialogFragment.MESSAGE_KEYSERVER_DELETED
, false);
if (deleted) {
Notify.create(getActivity(),
getActivity().getString(
R.string.keyserver_preference_deleted, mKeyservers.get(position)),
Notify.Style.OK)
.show();
deleteKeyserver(position);
return;
}
boolean verified =
data.getBoolean(AddEditKeyserverDialogFragment.MESSAGE_VERIFIED);
if (verified) {
Notify.create(getActivity(),
R.string.add_keyserver_connection_verified, Notify.Style.OK).show();
} else {
Notify.create(getActivity(),
R.string.add_keyserver_without_verification,
Notify.Style.WARN).show();
}
ParcelableHkpKeyserver keyserver = data.getParcelable(
AddEditKeyserverDialogFragment.MESSAGE_KEYSERVER);
AddEditKeyserverDialogFragment.DialogAction dialogAction
= (AddEditKeyserverDialogFragment.DialogAction) data.getSerializable(
AddEditKeyserverDialogFragment.MESSAGE_DIALOG_ACTION);
switch (dialogAction) {
case ADD:
addKeyserver(keyserver);
break;
case EDIT:
editKeyserver(keyserver, position);
break;
}
break;
}
}
}
};
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(returnHandler);
AddEditKeyserverDialogFragment dialogFragment = AddEditKeyserverDialogFragment
.newInstance(messenger, action, keyserver, position);
dialogFragment.show(getFragmentManager(), "addKeyserverDialog");
}
private void addKeyserver(ParcelableHkpKeyserver keyserver) {
mKeyservers.add(keyserver);
mAdapter.notifyItemInserted(mKeyservers.size() - 1);
saveKeyserverList();
}
private void editKeyserver(ParcelableHkpKeyserver newKeyserver, int position) {
mKeyservers.set(position, newKeyserver);
mAdapter.notifyItemChanged(position);
saveKeyserverList();
}
private void deleteKeyserver(int position) {
if (mKeyservers.size() == 1) {
Notify.create(getActivity(), R.string.keyserver_preference_cannot_delete_last,
Notify.Style.ERROR).show();
return;
}
mKeyservers.remove(position);
// we use this
mAdapter.notifyItemRemoved(position);
if (position == 0 && mKeyservers.size() > 0) {
// if we deleted the first item, we need the adapter to redraw the new first item
mAdapter.notifyItemChanged(0);
}
saveKeyserverList();
}
private void saveKeyserverList() {
Preferences.getPreferences(getActivity()).setKeyServers(mKeyservers);
}
@Override
public void onItemClick(View view, int position) {
startEditKeyserverDialog(AddEditKeyserverDialogFragment.DialogAction.EDIT,
mKeyservers.get(position), position);
}
public class KeyserverListAdapter extends RecyclerView.Adapter<KeyserverListAdapter.ViewHolder>
implements ItemTouchHelperAdapter {
private final ArrayList<ParcelableHkpKeyserver> mKeyservers;
public KeyserverListAdapter(ArrayList<ParcelableHkpKeyserver> keyservers) {
mKeyservers = keyservers;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.settings_keyserver_item, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.keyserverUrl.setText(mKeyservers.get(position).getUrl());
// Start a drag whenever the handle view it touched
holder.dragHandleView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
mItemTouchHelper.startDrag(holder);
}
return false;
}
});
selectUnselectKeyserver(holder, position);
}
private void selectUnselectKeyserver(ViewHolder holder, int position) {
if (position == 0) {
holder.showAsSelectedKeyserver();
} else {
holder.showAsUnselectedKeyserver();
}
}
@Override
public void onItemMove(RecyclerView.ViewHolder source, RecyclerView.ViewHolder target,
int fromPosition, int toPosition) {
Collections.swap(mKeyservers, fromPosition, toPosition);
saveKeyserverList();
selectUnselectKeyserver((ViewHolder) target, fromPosition);
// we don't want source to change color while dragging, therefore we just set
// isSelectedKeyserver instead of selectUnselectKeyserver
((ViewHolder) source).isSelectedKeyserver = toPosition == 0;
notifyItemMoved(fromPosition, toPosition);
}
@Override
public int getItemCount() {
return mKeyservers.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements
ItemTouchHelperViewHolder {
public final ViewGroup outerLayout;
public final TextView selectedServerLabel;
public final TextView keyserverUrl;
public final ImageView dragHandleView;
private boolean isSelectedKeyserver = false;
public ViewHolder(View itemView) {
super(itemView);
outerLayout = (ViewGroup) itemView.findViewById(R.id.outer_layout);
selectedServerLabel = (TextView) itemView.findViewById(
R.id.selected_keyserver_title);
keyserverUrl = (TextView) itemView.findViewById(R.id.keyserver_tv);
dragHandleView = (ImageView) itemView.findViewById(R.id.drag_handle);
itemView.setClickable(true);
}
public void showAsSelectedKeyserver() {
isSelectedKeyserver = true;
selectedServerLabel.setVisibility(View.VISIBLE);
outerLayout.setBackgroundColor(FormattingUtils.getColorFromAttr(getContext(), R.attr.colorPrimaryDark));
}
public void showAsUnselectedKeyserver() {
isSelectedKeyserver = false;
selectedServerLabel.setVisibility(View.GONE);
outerLayout.setBackgroundColor(0);
}
@Override
public void onItemSelected() {
selectedServerLabel.setVisibility(View.GONE);
itemView.setBackgroundColor(FormattingUtils.getColorFromAttr(getContext(), R.attr.colorBrightToolbar));
}
@Override
public void onItemClear() {
if (isSelectedKeyserver) {
showAsSelectedKeyserver();
} else {
showAsUnselectedKeyserver();
}
}
}
}
}
| tobiasschuelke/open-keychain | OpenKeychain/src/main/java/org/sufficientlysecure/keychain/ui/SettingsKeyserverFragment.java | Java | gpl-3.0 | 13,816 |
# -*- coding: utf-8 -*-
# Dioptas - GUI program for fast processing of 2D X-ray diffraction data
# Principal author: Clemens Prescher (clemens.prescher@gmail.com)
# Copyright (C) 2014-2019 GSECARS, University of Chicago, USA
# Copyright (C) 2015-2018 Institute for Geology and Mineralogy, University of Cologne, Germany
# Copyright (C) 2019-2020 DESY, Hamburg, Germany
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from ....model.util.HelperModule import get_partial_index
# imports for type hinting in PyCharm -- DO NOT DELETE
from ....model.DioptasModel import DioptasModel
from ....widgets.integration import IntegrationWidget
from ....widgets.plot_widgets.ImgWidget import IntegrationImgWidget
class PhaseInCakeController(object):
"""
PhaseInCakeController handles all the interaction between the phase controls and the plotted lines in the cake view.
"""
def __init__(self, integration_widget, dioptas_model):
"""
:param integration_widget: Reference to an IntegrationWidget
:param dioptas_model: reference to DioptasModel object
:type integration_widget: IntegrationWidget
:type dioptas_model: DioptasModel
"""
self.model = dioptas_model
self.phase_model = self.model.phase_model
self.integration_widget = integration_widget
self.cake_view_widget = integration_widget.integration_image_widget.cake_view # type: IntegrationImgWidget
self.connect()
def connect(self):
self.phase_model.phase_added.connect(self.add_phase_plot)
self.model.phase_model.phase_removed.connect(self.cake_view_widget.del_cake_phase)
self.phase_model.phase_changed.connect(self.update_phase_lines)
self.phase_model.phase_changed.connect(self.update_phase_color)
self.phase_model.phase_changed.connect(self.update_phase_visible)
self.phase_model.reflection_added.connect(self.reflection_added)
self.phase_model.reflection_deleted.connect(self.reflection_deleted)
def get_phase_position_and_intensities(self, ind, clip=True):
"""
Obtains the positions and intensities for lines of a phase with an index ind within the cake view.
No clipping is used for the first call to add the CakePhasePlot to the ImgWidget. Subsequent calls are used with
clipping. Thus, only lines within the cake_tth are returned. The visibility of each line is then estimated in
the ImgWidget based on the length of the clipped and not clipped lists.
:param ind: the index of the phase
:param clip: whether or not the lists should be clipped. Clipped means that lines which have positions larger
than the
:return: line_positions, line_intensities
"""
if self.model.cake_tth is None:
cake_tth = self.model.calibration_model.tth
else:
cake_tth = self.model.cake_tth
reflections_tth = self.phase_model.get_phase_line_positions(ind, 'tth',
self.model.calibration_model.wavelength * 1e10)
reflections_intensities = [reflex[1] for reflex in self.phase_model.reflections[ind]]
cake_line_positions = []
cake_line_intensities = []
for ind, tth in enumerate(reflections_tth):
pos_ind = get_partial_index(cake_tth, tth)
if pos_ind is not None:
cake_line_positions.append(pos_ind + 0.5)
cake_line_intensities.append(reflections_intensities[ind])
elif clip is False:
cake_line_positions.append(0)
cake_line_intensities.append(reflections_intensities[ind])
return cake_line_positions, cake_line_intensities
def add_phase_plot(self):
cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(-1, False)
self.cake_view_widget.add_cake_phase(cake_line_positions, cake_line_intensities,
self.phase_model.phase_colors[-1])
def update_phase_lines(self, ind):
cake_line_positions, cake_line_intensities = self.get_phase_position_and_intensities(ind)
self.cake_view_widget.update_phase_intensities(ind, cake_line_positions, cake_line_intensities)
def update_phase_color(self, ind):
self.cake_view_widget.set_cake_phase_color(ind, self.model.phase_model.phase_colors[ind])
def update_phase_visible(self, ind):
if self.phase_model.phase_visible[ind] and self.integration_widget.img_mode == 'Cake' and \
self.integration_widget.img_phases_btn.isChecked():
self.cake_view_widget.show_cake_phase(ind)
else:
self.cake_view_widget.hide_cake_phase(ind)
def reflection_added(self, ind):
self.cake_view_widget.phases[ind].add_line()
def reflection_deleted(self, phase_ind, reflection_ind):
self.cake_view_widget.phases[phase_ind].delete_line(reflection_ind)
| Dioptas/Dioptas | dioptas/controller/integration/phase/PhaseInCakeController.py | Python | gpl-3.0 | 5,615 |
/*
* Copyright (C) 2016-2022 phantombot.github.io/PhantomBot
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package tv.phantombot.event.discord.channel;
import discord4j.core.object.entity.User;
public class DiscordChannelPartEvent extends DiscordChannelEvent {
/**
* Class constructor.
*
* @param {IUser} user
*/
public DiscordChannelPartEvent(User user) {
super(user);
}
}
| PhantomBot/PhantomBot | source/tv/phantombot/event/discord/channel/DiscordChannelPartEvent.java | Java | gpl-3.0 | 1,025 |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.supportv7.app;
import com.example.android.supportv7.R;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Toast;
/**
* This demo shows how various action bar display option flags can be combined and their effects
* when used on a Toolbar-provided Action Bar
*/
public class ToolbarDisplayOptions extends ActionBarActivity
implements View.OnClickListener {
private View mCustomView;
private ActionBar.LayoutParams mCustomViewLayoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.toolbar_display_options);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
findViewById(R.id.toggle_home_as_up).setOnClickListener(this);
findViewById(R.id.toggle_show_home).setOnClickListener(this);
findViewById(R.id.toggle_use_logo).setOnClickListener(this);
findViewById(R.id.toggle_show_title).setOnClickListener(this);
findViewById(R.id.toggle_show_custom).setOnClickListener(this);
findViewById(R.id.cycle_custom_gravity).setOnClickListener(this);
findViewById(R.id.toggle_visibility).setOnClickListener(this);
// Configure several action bar elements that will be toggled by display options.
mCustomView = getLayoutInflater().inflate(R.layout.action_bar_display_options_custom, null);
mCustomViewLayoutParams = new ActionBar.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.display_options_actions, menu);
return true;
}
@Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
@Override
public void onClick(View v) {
final ActionBar bar = getSupportActionBar();
int flags = 0;
switch (v.getId()) {
case R.id.toggle_home_as_up:
flags = ActionBar.DISPLAY_HOME_AS_UP;
break;
case R.id.toggle_show_home:
flags = ActionBar.DISPLAY_SHOW_HOME;
break;
case R.id.toggle_use_logo:
flags = ActionBar.DISPLAY_USE_LOGO;
getSupportActionBar().setLogo(R.drawable.ic_media_play);
break;
case R.id.toggle_show_title:
flags = ActionBar.DISPLAY_SHOW_TITLE;
break;
case R.id.toggle_show_custom:
flags = ActionBar.DISPLAY_SHOW_CUSTOM;
break;
case R.id.cycle_custom_gravity: {
ActionBar.LayoutParams lp = mCustomViewLayoutParams;
int newGravity = 0;
switch (lp.gravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
case Gravity.LEFT:
newGravity = Gravity.CENTER_HORIZONTAL;
break;
case Gravity.CENTER_HORIZONTAL:
newGravity = Gravity.RIGHT;
break;
case Gravity.RIGHT:
newGravity = Gravity.LEFT;
break;
}
lp.gravity = lp.gravity & ~Gravity.HORIZONTAL_GRAVITY_MASK | newGravity;
bar.setCustomView(mCustomView, lp);
return;
}
case R.id.toggle_visibility:
if (bar.isShowing()) {
bar.hide();
} else {
bar.show();
}
return;
}
int change = bar.getDisplayOptions() ^ flags;
bar.setDisplayOptions(change, flags);
}
}
| MTK6580/walkie-talkie | ALPS.L1.MP6.V2_HEXING6580_WE_L/alps/development/samples/Support7Demos/src/com/example/android/supportv7/app/ToolbarDisplayOptions.java | Java | gpl-3.0 | 4,827 |
<?php if(!defined('__XE__')) exit();
$xml_info = (object)(array(
'author' =>
array (
0 =>
(object)(array(
'name' => 'NAVER',
'email_address' => 'developers@xpressengine.com',
'homepage' => 'http://xpressengine.com/',
)),
),
'extra_vars' =>
(object)(array(
)),
'component_name' => 'image_link',
'title' => 'イメージ追加',
'description' => 'エディターでイメージの追加、属性の変更が出来ます。',
'version' => '1.7',
'date' => '2013-11-27',
'homepage' => NULL,
'license' => NULL,
'license_link' => NULL,
)); | sazaam/oldworks | www/xe/test_xe/files/cache/editor/image_link.jp.php | PHP | gpl-3.0 | 607 |
namespace WOT.Stats
{
partial class ctxScreens
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.simpleButton1 = new DevExpress.XtraEditors.SimpleButton();
this.checkTabGlobal = new DevExpress.XtraEditors.CheckEdit();
this.checkTabTanks = new DevExpress.XtraEditors.CheckEdit();
this.checkTabKillCounts = new DevExpress.XtraEditors.CheckEdit();
this.checkTabTankInfo = new DevExpress.XtraEditors.CheckEdit();
this.checkTabKillSummary = new DevExpress.XtraEditors.CheckEdit();
this.checkTabCustomGroupings = new DevExpress.XtraEditors.CheckEdit();
this.checkTabLastGamesPlayed = new DevExpress.XtraEditors.CheckEdit();
this.checkTabGraph = new DevExpress.XtraEditors.CheckEdit();
((System.ComponentModel.ISupportInitialize)(this.checkTabGlobal.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabTanks.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabKillCounts.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabTankInfo.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabKillSummary.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabCustomGroupings.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabLastGamesPlayed.Properties)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabGraph.Properties)).BeginInit();
this.SuspendLayout();
//
// simpleButton1
//
this.simpleButton1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right)));
this.simpleButton1.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.simpleButton1.Appearance.Options.UseFont = true;
this.simpleButton1.Location = new System.Drawing.Point(146, 244);
this.simpleButton1.Name = "simpleButton1";
this.simpleButton1.Size = new System.Drawing.Size(75, 23);
this.simpleButton1.TabIndex = 0;
this.simpleButton1.Text = "Apply";
this.simpleButton1.Click += new System.EventHandler(this.simpleButton1_Click);
//
// checkTabGlobal
//
this.checkTabGlobal.Location = new System.Drawing.Point(4, 4);
this.checkTabGlobal.Name = "checkTabGlobal";
this.checkTabGlobal.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabGlobal.Properties.Appearance.Options.UseFont = true;
this.checkTabGlobal.Properties.Caption = "Display Overall";
this.checkTabGlobal.Size = new System.Drawing.Size(139, 21);
this.checkTabGlobal.TabIndex = 1;
//
// checkTabTanks
//
this.checkTabTanks.Location = new System.Drawing.Point(4, 31);
this.checkTabTanks.Name = "checkTabTanks";
this.checkTabTanks.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabTanks.Properties.Appearance.Options.UseFont = true;
this.checkTabTanks.Properties.Caption = "Display Tanks";
this.checkTabTanks.Size = new System.Drawing.Size(139, 21);
this.checkTabTanks.TabIndex = 2;
//
// checkTabKillCounts
//
this.checkTabKillCounts.Location = new System.Drawing.Point(4, 58);
this.checkTabKillCounts.Name = "checkTabKillCounts";
this.checkTabKillCounts.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabKillCounts.Properties.Appearance.Options.UseFont = true;
this.checkTabKillCounts.Properties.Caption = "Display Kill Counts";
this.checkTabKillCounts.Size = new System.Drawing.Size(139, 21);
this.checkTabKillCounts.TabIndex = 3;
//
// checkTabTankInfo
//
this.checkTabTankInfo.Location = new System.Drawing.Point(3, 85);
this.checkTabTankInfo.Name = "checkTabTankInfo";
this.checkTabTankInfo.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabTankInfo.Properties.Appearance.Options.UseFont = true;
this.checkTabTankInfo.Properties.Caption = "Display Tank Info";
this.checkTabTankInfo.Size = new System.Drawing.Size(139, 21);
this.checkTabTankInfo.TabIndex = 4;
//
// checkTabKillSummary
//
this.checkTabKillSummary.Location = new System.Drawing.Point(4, 112);
this.checkTabKillSummary.Name = "checkTabKillSummary";
this.checkTabKillSummary.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabKillSummary.Properties.Appearance.Options.UseFont = true;
this.checkTabKillSummary.Properties.Caption = "Display Kill Summary";
this.checkTabKillSummary.Size = new System.Drawing.Size(154, 21);
this.checkTabKillSummary.TabIndex = 5;
this.checkTabKillSummary.CheckedChanged += new System.EventHandler(this.checkEdit5_CheckedChanged);
//
// checkTabCustomGroupings
//
this.checkTabCustomGroupings.Location = new System.Drawing.Point(3, 139);
this.checkTabCustomGroupings.Name = "checkTabCustomGroupings";
this.checkTabCustomGroupings.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabCustomGroupings.Properties.Appearance.Options.UseFont = true;
this.checkTabCustomGroupings.Properties.Caption = "Display Custom Grouping";
this.checkTabCustomGroupings.Size = new System.Drawing.Size(180, 21);
this.checkTabCustomGroupings.TabIndex = 6;
//
// checkTabLastGamesPlayed
//
this.checkTabLastGamesPlayed.Location = new System.Drawing.Point(4, 166);
this.checkTabLastGamesPlayed.Name = "checkTabLastGamesPlayed";
this.checkTabLastGamesPlayed.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabLastGamesPlayed.Properties.Appearance.Options.UseFont = true;
this.checkTabLastGamesPlayed.Properties.Caption = "Display Last Played Games";
this.checkTabLastGamesPlayed.Size = new System.Drawing.Size(139, 21);
this.checkTabLastGamesPlayed.TabIndex = 7;
//
// checkTabGraph
//
this.checkTabGraph.Location = new System.Drawing.Point(4, 193);
this.checkTabGraph.Name = "checkTabGraph";
this.checkTabGraph.Properties.Appearance.Font = new System.Drawing.Font("Tahoma", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.checkTabGraph.Properties.Appearance.Options.UseFont = true;
this.checkTabGraph.Properties.Caption = "Display Charts";
this.checkTabGraph.Size = new System.Drawing.Size(139, 21);
this.checkTabGraph.TabIndex = 8;
//
// ctxScreens
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.checkTabGraph);
this.Controls.Add(this.checkTabLastGamesPlayed);
this.Controls.Add(this.checkTabCustomGroupings);
this.Controls.Add(this.checkTabKillSummary);
this.Controls.Add(this.checkTabTankInfo);
this.Controls.Add(this.checkTabKillCounts);
this.Controls.Add(this.checkTabTanks);
this.Controls.Add(this.checkTabGlobal);
this.Controls.Add(this.simpleButton1);
this.Name = "ctxScreens";
this.Size = new System.Drawing.Size(224, 270);
this.Load += new System.EventHandler(this.ctxScreens_Load);
((System.ComponentModel.ISupportInitialize)(this.checkTabGlobal.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabTanks.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabKillCounts.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabTankInfo.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabKillSummary.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabCustomGroupings.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabLastGamesPlayed.Properties)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.checkTabGraph.Properties)).EndInit();
this.ResumeLayout(false);
}
#endregion
private DevExpress.XtraEditors.SimpleButton simpleButton1;
private DevExpress.XtraEditors.CheckEdit checkTabGlobal;
private DevExpress.XtraEditors.CheckEdit checkTabTanks;
private DevExpress.XtraEditors.CheckEdit checkTabKillCounts;
private DevExpress.XtraEditors.CheckEdit checkTabTankInfo;
private DevExpress.XtraEditors.CheckEdit checkTabKillSummary;
private DevExpress.XtraEditors.CheckEdit checkTabCustomGroupings;
private DevExpress.XtraEditors.CheckEdit checkTabLastGamesPlayed;
private DevExpress.XtraEditors.CheckEdit checkTabGraph;
}
}
| Phalynx/WOT-Statistics | Solution/WOT.Stats/UserControls/ctxScreens.Designer.cs | C# | gpl-3.0 | 11,313 |
# -*- coding: utf-8 -*-
#
# MAVProxy documentation build configuration file, created by
# sphinx-quickstart on Wed Aug 19 05:17:36 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys
import os
import shlex
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.pngmath',
'sphinx.ext.ifconfig',
'sphinx.ext.viewcode',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'last_letter'
copyright = u'2014, George Zogopoulos - Papaliakos'
author = u'George Zogopoulos - Papaliakos'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.5'
# The full version, including alpha/beta/rc tags.
release = '0.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = []
# The reST default role (used for this markup: `text`) to use for all
# documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'sphinx_rtd_theme'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
html_theme_path = ["_static/themes", ]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#html_extra_path = []
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
html_domain_indices = False
# If false, no index is generated.
html_use_index = False
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
html_show_sourcelink = False
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
html_show_sphinx = False
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
html_show_copyright = False
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr'
#html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# Now only 'ja' uses this config value
#html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'last_letter_doc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
# Latex figure (float) alignment
#'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'last_letter.tex', u'last_letter Documentation',
u'George Zogopoulos - Papaliakos', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'last_letter', u'last_letter Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'last_letter', u'last_letter Documentation',
author, 'last_letter', 'A collection of ROS packages for UAV simulation and autopilot development.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# -- Options for Epub output ----------------------------------------------
# Bibliographic Dublin Core info.
epub_title = project
epub_author = author
epub_publisher = author
epub_copyright = copyright
# The basename for the epub file. It defaults to the project name.
#epub_basename = project
# The HTML theme for the epub output. Since the default themes are not optimized
# for small screen space, using the same theme for HTML and epub output is
# usually not wise. This defaults to 'epub', a theme designed to save visual
# space.
#epub_theme = 'epub'
# The language of the text. It defaults to the language option
# or 'en' if the language is not set.
#epub_language = ''
# The scheme of the identifier. Typical schemes are ISBN or URL.
#epub_scheme = ''
# The unique identifier of the text. This can be a ISBN number
# or the project homepage.
#epub_identifier = ''
# A unique identification for the text.
#epub_uid = ''
# A tuple containing the cover image and cover page html template filenames.
#epub_cover = ()
# A sequence of (type, uri, title) tuples for the guide element of content.opf.
#epub_guide = ()
# HTML files that should be inserted before the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_pre_files = []
# HTML files shat should be inserted after the pages created by sphinx.
# The format is a list of tuples containing the path and title.
#epub_post_files = []
# A list of files that should not be packed into the epub file.
epub_exclude_files = ['search.html']
# The depth of the table of contents in toc.ncx.
#epub_tocdepth = 3
# Allow duplicate toc entries.
#epub_tocdup = True
# Choose between 'default' and 'includehidden'.
#epub_tocscope = 'default'
# Fix unsupported image types using the Pillow.
#epub_fix_images = False
# Scale large images.
#epub_max_image_width = 0
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#epub_show_urls = 'inline'
# If false, no index is generated.
#epub_use_index = True
| Georacer/last_letter | documentation/source/conf.py | Python | gpl-3.0 | 11,461 |
/*
Color.cs
This file is part of Morgan's CLR Advanced Runtime (MCART)
Author(s):
César Andrés Morgan <xds_xps_ivx@hotmail.com>
Copyright © 2011 - 2021 César Andrés Morgan
Morgan's CLR Advanced Runtime (MCART) 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.
Morgan's CLR Advanced Runtime (MCART) is distributed in the hope that it will
be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.ComponentModel.DataAnnotations.Schema;
using TheXDS.MCART.Types.Base;
namespace TheXDS.MCART.Types.Entity
{
/// <summary>
/// Estructura universal que describe un color en sus componentes alfa,
/// rojo, verde y azul.
/// </summary>
[ComplexType]
public class Color : IColor, IEquatable<Color>
{
/// <summary>
/// Componente Alfa del color.
/// </summary>
public byte A { get; set; }
/// <summary>
/// Componente Azul del color.
/// </summary>
public byte B { get; set; }
/// <summary>
/// Componente Verde del color.
/// </summary>
public byte G { get; set; }
/// <summary>
/// Componente Rojo del color.
/// </summary>
public byte R { get; set; }
/// <summary>
/// Convierte implícitamente un <see cref="Types.Color"/> en un
/// <see cref="Color"/>.
/// </summary>
/// <param name="color">
/// <see cref="Types.Color"/> a convertir.
/// </param>
public static implicit operator Color(Types.Color color)
{
return new Color
{
A = color.A,
B = color.B,
G = color.G,
R = color.R,
};
}
/// <summary>
/// Convierte implícitamente un <see cref="Color"/> en un
/// <see cref="Types.Color"/>.
/// </summary>
/// <param name="color">
/// <see cref="Color"/> a convertir.
/// </param>
public static implicit operator Types.Color(Color color)
{
return new Types.Color(color.R, color.G, color.B, color.A);
}
/// <inheritdoc/>
public bool Equals(Color? other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return A == other.A && B == other.B && G == other.G && R == other.R;
}
/// <inheritdoc/>
public override bool Equals(object? obj)
{
if (obj is null) return false;
if (ReferenceEquals(this, obj)) return true;
return obj.GetType() == this.GetType() && Equals((Color)obj);
}
/// <inheritdoc/>
public override int GetHashCode()
{
return HashCode.Combine(A, B, G, R);
}
}
} | TheXDS/MCART | src/Extensions/ComplexTypes/Types/Entity/Color.cs | C# | gpl-3.0 | 3,305 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
An implementation of the time frequency phase misfit and adjoint source after
Fichtner et al. (2008).
:copyright:
Lion Krischer (krischer@geophysik.uni-muenchen.de), 2013
:license:
GNU General Public License, Version 3
(http://www.gnu.org/copyleft/gpl.html)
"""
import warnings
import numexpr as ne
import numpy as np
import obspy
from obspy.signal.interpolation import lanczos_interpolation
from lasif import LASIFAdjointSourceCalculationError
from lasif.adjoint_sources import time_frequency, utils
eps = np.spacing(1)
def adsrc_tf_phase_misfit(t, data, synthetic, min_period, max_period,
plot=False, max_criterion=7.0):
"""
:rtype: dictionary
:returns: Return a dictionary with three keys:
* adjoint_source: The calculated adjoint source as a numpy array
* misfit: The misfit value
* messages: A list of strings giving additional hints to what happened
in the calculation.
"""
# Assumes that t starts at 0. Pad your data if that is not the case -
# Parts with zeros are essentially skipped making it fairly efficient.
assert t[0] == 0
messages = []
# Internal sampling interval. Some explanations for this "magic" number.
# LASIF's preprocessing allows no frequency content with smaller periods
# than min_period / 2.2 (see function_templates/preprocesssing_function.py
# for details). Assuming most users don't change this, this is equal to
# the Nyquist frequency and the largest possible sampling interval to
# catch everything is min_period / 4.4.
#
# The current choice is historic as changing does (very slightly) chance
# the calculated misfit and we don't want to disturb inversions in
# progress. The difference is likely minimal in any case. We might have
# same aliasing into the lower frequencies but the filters coupled with
# the TF-domain weighting will get rid of them in essentially all
# realistically occurring cases.
dt_new = max(float(int(min_period / 3.0)), t[1] - t[0])
# New time axis
ti = utils.matlab_range(t[0], t[-1], dt_new)
# Make sure its odd - that avoid having to deal with some issues
# regarding frequency bin interpolation. Now positive and negative
# frequencies will always be all symmetric. Data is assumed to be
# tapered in any case so no problem are to be expected.
if not len(ti) % 2:
ti = ti[:-1]
# Interpolate both signals to the new time axis - this massively speeds
# up the whole procedure as most signals are highly oversampled. The
# adjoint source at the end is re-interpolated to the original sampling
# points.
original_data = data
original_synthetic = synthetic
data = lanczos_interpolation(
data=data, old_start=t[0], old_dt=t[1] - t[0], new_start=t[0],
new_dt=dt_new, new_npts=len(ti), a=8, window="blackmann")
synthetic = lanczos_interpolation(
data=synthetic, old_start=t[0], old_dt=t[1] - t[0], new_start=t[0],
new_dt=dt_new, new_npts=len(ti), a=8, window="blackmann")
original_time = t
t = ti
# -------------------------------------------------------------------------
# Compute time-frequency representations
# Window width is twice the minimal period.
width = 2.0 * min_period
# Compute time-frequency representation of the cross-correlation
_, _, tf_cc = time_frequency.time_frequency_cc_difference(
t, data, synthetic, width)
# Compute the time-frequency representation of the synthetic
tau, nu, tf_synth = time_frequency.time_frequency_transform(t, synthetic,
width)
# -------------------------------------------------------------------------
# compute tf window and weighting function
# noise taper: down-weight tf amplitudes that are very low
tf_cc_abs = np.abs(tf_cc)
m = tf_cc_abs.max() / 10.0 # NOQA
weight = ne.evaluate("1.0 - exp(-(tf_cc_abs ** 2) / (m ** 2))")
nu_t = nu.T
# highpass filter (periods longer than max_period are suppressed
# exponentially)
weight *= (1.0 - np.exp(-(nu_t * max_period) ** 2))
# lowpass filter (periods shorter than min_period are suppressed
# exponentially)
nu_t_large = np.zeros(nu_t.shape)
nu_t_small = np.zeros(nu_t.shape)
thres = (nu_t <= 1.0 / min_period)
nu_t_large[np.invert(thres)] = 1.0
nu_t_small[thres] = 1.0
weight *= (np.exp(-10.0 * np.abs(nu_t * min_period - 1.0)) * nu_t_large +
nu_t_small)
# normalisation
weight /= weight.max()
# computation of phase difference, make quality checks and misfit ---------
# Compute the phase difference.
# DP = np.imag(np.log(m + tf_cc / (2 * m + np.abs(tf_cc))))
DP = np.angle(tf_cc)
# Attempt to detect phase jumps by taking the derivatives in time and
# frequency direction. 0.7 is an emperical value.
abs_weighted_DP = np.abs(weight * DP)
_x = abs_weighted_DP.max() # NOQA
test_field = ne.evaluate("weight * DP / _x")
criterion_1 = np.sum([np.abs(np.diff(test_field, axis=0)) > 0.7])
criterion_2 = np.sum([np.abs(np.diff(test_field, axis=1)) > 0.7])
criterion = np.sum([criterion_1, criterion_2])
# Compute the phase misfit
dnu = nu[1] - nu[0]
i = ne.evaluate("sum(weight ** 2 * DP ** 2)")
# inserted by Nienke Blom, 22-11-2016
weighted_DP = ne.evaluate("weight * DP")
phasediff_integral = float(ne.evaluate("sum(weighted_DP * dnu * dt_new)"))
mean_delay = np.mean(weighted_DP)
wDP = weighted_DP.flatten()
wDP_thresh = wDP[abs(wDP) > 0.1 * max(wDP, key=lambda x: abs(x))]
median_delay = np.median(wDP_thresh)
max_delay = max(wDP, key=lambda x: abs(x))
phase_misfit = np.sqrt(i * dt_new * dnu)
# Sanity check. Should not occur.
if np.isnan(phase_misfit):
msg = "The phase misfit is NaN."
raise LASIFAdjointSourceCalculationError(msg)
# The misfit can still be computed, even if not adjoint source is
# available.
if criterion > max_criterion:
warning = ("Possible phase jump detected. Misfit included. No "
"adjoint source computed. Criterion: %.1f - Max allowed "
"criterion: %.1f" % (criterion, max_criterion))
warnings.warn(warning)
messages.append(warning)
ret_dict = {
"adjoint_source": None,
"misfit_value": phase_misfit,
"details": {"messages": messages,
#"weighted_DP": weighted_DP,
#"weight": weight,
#"DP": DP,
"mean_delay": mean_delay, # added NAB 30-8-2017
"phasediff_integral": phasediff_integral, # added NAB 22-11-2016, edited 30-8-2017
"median_delay": median_delay, # added NAB 22-11-2016, edited 30-8-2017
"max_delay": max_delay} # added NAB 31-8-2017
}
return ret_dict
# Make kernel for the inverse tf transform
idp = ne.evaluate(
"weight ** 2 * DP * tf_synth / (m + abs(tf_synth) ** 2)")
# Invert tf transform and make adjoint source
ad_src, it, I = time_frequency.itfa(tau, idp, width)
# Interpolate both signals to the new time axis
ad_src = lanczos_interpolation(
# Pad with a couple of zeros in case some where lost in all
# these resampling operations. The first sample should not
# change the time.
data=np.concatenate([ad_src.imag, np.zeros(100)]),
old_start=tau[0],
old_dt=tau[1] - tau[0],
new_start=original_time[0],
new_dt=original_time[1] - original_time[0],
new_npts=len(original_time), a=8, window="blackmann")
# Divide by the misfit and change sign.
ad_src /= (phase_misfit + eps)
ad_src = -1.0 * np.diff(ad_src) / (t[1] - t[0])
# Taper at both ends. Exploit ObsPy to not have to deal with all the
# nasty things.
ad_src = \
obspy.Trace(ad_src).taper(max_percentage=0.05, type="hann").data
# Reverse time and add a leading zero so the adjoint source has the
# same length as the input time series.
ad_src = ad_src[::-1]
ad_src = np.concatenate([[0.0], ad_src])
# Plot if requested. ------------------------------------------------------
if plot:
import matplotlib as mpl
import matplotlib.pyplot as plt
plt.style.use("seaborn-whitegrid")
from lasif.colors import get_colormap
if isinstance(plot, mpl.figure.Figure):
fig = plot
else:
fig = plt.gcf()
# Manually set-up the axes for full control.
l, b, w, h = 0.1, 0.05, 0.80, 0.22
rect = l, b + 3 * h, w, h
waveforms_axis = fig.add_axes(rect)
rect = l, b + h, w, 2 * h
tf_axis = fig.add_axes(rect)
rect = l, b, w, h
adj_src_axis = fig.add_axes(rect)
rect = l + w + 0.02, b, 1.0 - (l + w + 0.02) - 0.05, 4 * h
cm_axis = fig.add_axes(rect)
# Plot the weighted phase difference.
weighted_phase_difference = (DP * weight).transpose()
mappable = tf_axis.pcolormesh(
tau, nu, weighted_phase_difference, vmin=-1.0, vmax=1.0,
cmap=get_colormap("tomo_full_scale_linear_lightness_r"),
shading="gouraud", zorder=-10)
tf_axis.grid(True)
tf_axis.grid(True, which='minor', axis='both', linestyle='-',
color='k')
cm = fig.colorbar(mappable, cax=cm_axis)
cm.set_label("Phase difference in radian", fontsize="large")
# Various texts on the time frequency domain plot.
text = "Misfit: %.4f" % phase_misfit
tf_axis.text(x=0.99, y=0.02, s=text, transform=tf_axis.transAxes,
fontsize="large", color="#C25734", fontweight=900,
verticalalignment="bottom",
horizontalalignment="right")
txt = "Weighted Phase Difference - red is a phase advance of the " \
"synthetics"
tf_axis.text(x=0.99, y=0.95, s=txt,
fontsize="large", color="0.1",
transform=tf_axis.transAxes,
verticalalignment="top",
horizontalalignment="right")
if messages:
message = "\n".join(messages)
tf_axis.text(x=0.99, y=0.98, s=message,
transform=tf_axis.transAxes,
bbox=dict(facecolor='red', alpha=0.8),
verticalalignment="top",
horizontalalignment="right")
# Adjoint source.
adj_src_axis.plot(original_time, ad_src[::-1], color="0.1", lw=2,
label="Adjoint source (non-time-reversed)")
adj_src_axis.legend()
# Waveforms.
waveforms_axis.plot(original_time, original_data, color="0.1", lw=2,
label="Observed")
waveforms_axis.plot(original_time, original_synthetic,
color="#C11E11", lw=2, label="Synthetic")
waveforms_axis.legend()
# Set limits for all axes.
tf_axis.set_ylim(0, 2.0 / min_period)
tf_axis.set_xlim(0, tau[-1])
adj_src_axis.set_xlim(0, tau[-1])
waveforms_axis.set_xlim(0, tau[-1])
waveforms_axis.set_ylabel("Velocity [m/s]", fontsize="large")
tf_axis.set_ylabel("Period [s]", fontsize="large")
adj_src_axis.set_xlabel("Seconds since event", fontsize="large")
# Hack to keep ticklines but remove the ticks - there is probably a
# better way to do this.
waveforms_axis.set_xticklabels([
"" for _i in waveforms_axis.get_xticks()])
tf_axis.set_xticklabels(["" for _i in tf_axis.get_xticks()])
_l = tf_axis.get_ylim()
_r = _l[1] - _l[0]
_t = tf_axis.get_yticks()
_t = _t[(_l[0] + 0.1 * _r < _t) & (_t < _l[1] - 0.1 * _r)]
tf_axis.set_yticks(_t)
tf_axis.set_yticklabels(["%.1fs" % (1.0 / _i) for _i in _t])
waveforms_axis.get_yaxis().set_label_coords(-0.08, 0.5)
tf_axis.get_yaxis().set_label_coords(-0.08, 0.5)
fig.suptitle("Time Frequency Phase Misfit and Adjoint Source",
fontsize="xx-large")
ret_dict = {
"adjoint_source": ad_src,
"misfit_value": phase_misfit,
"details": {"messages": messages,
#"weighted_DP": weighted_DP,
#"weight": weight,
#"DP": DP,
"mean_delay": mean_delay, # added NAB 30-8-2017
"phasediff_integral": phasediff_integral, # added NAB 22-11-2016, edited 30-8-2017
"median_delay": median_delay, # added NAB 22-11-2016, edited 30-8-2017
"max_delay": max_delay} # added NAB 31-8-2017
}
# print "the phasedifference integral is "+str(ret_dict['details']['phasediff_integral'])
return ret_dict
| Phlos/LASIF_scripts | lasif_code/ad_src_tf_phase_misfit.py | Python | gpl-3.0 | 13,183 |
package compiler;
import checker.Checker;
import checker.SemanticException;
import encoder.Encoder;
import parser.Parser;
import parser.SyntacticException;
import scanner.LexicalException;
import util.FileException;
import util.AST.Programa;
/**
* Compiler driver
* @version 2010-september-04
* @discipline Compiladores
* @author Gustavo H P Carvalho
* @email gustavohpcarvalho@ecomp.poli.br
*/
public class Compiler {
/**
* Compiler start point
* @param args - none
* @throws Exception
*/
public static void main(String[] args) throws Exception {
try {
String location = Compiler.validateInput(args);
String[] file = location.split("/");
String out = location.split(".rec")[0];
Compiler.printHeader(file);
Parser p = new Parser(location);
Programa astRoot = null;
astRoot = p.parse();
System.out.println("\nAnálise Lexica - PASS");
System.out.println("Análise Sintatica - PASS");
if ( astRoot != null ) {
Checker c = new Checker();
astRoot = c.check(astRoot);
System.out.println("Análise Semantica - PASS");
out = out+".asm";
Encoder e = new Encoder(astRoot, location, out);
e.encode();
Compiler.printBody(astRoot, out);
}
}
catch (LexicalException e) {
System.out.println(e.toString());
} catch (SyntacticException e) {
System.out.println(e.toString());
} catch (SemanticException e) {
System.out.println(e.toString());
} catch (FileException e) {
System.out.println(e.toString());
}
}
public static String validateInput(String[] arg) throws FileException {
if (arg.length == 0) {
String message = "Path do codigo-fonte é inválido";
throw new FileException(message);
}
String location = arg[0];
String[] ext = location.split("[.]");
int i = ext.length;
try {
if (! ext[i-1].equals("rec")) {
String message = "Código-fonte não é da linguagem REC.";
throw new FileException(message);
}
} catch (ArrayIndexOutOfBoundsException e) {
String message = "Código-fonte não é da linguagem REC.";
throw new FileException(message);
}
return location;
}
public static void printHeader(String[] file) {
System.out.println("\nREC Compiler\nVersão 0.9 - 2017\nRubens Carneiro - rec2@ecomp.poli.br");
System.out.println("\nCompilando código-fonte [ " + file[file.length-1] + " ]\n");
System.out.println("-----------------------------------------------------------------------------------------");
}
public static void printBody(Programa astRoot, String out) {
System.out.println("Gerador de Código - PASS\n");
System.out.println("-----------------------------------------------------------------------------------------");
System.out.println("\n\t-- AST Decorada --\n");
System.out.println( astRoot.toString(0));
System.out.println("-----------------------------------------------------------------------------------------\n");
System.out.println("Código Assembly (NASM) criado em [ "+out+" ]\n");
System.out.println("-----------------------------------------------------------------------------------------\n");
}
}
| Drakmord2/rec-compiler | Compilador/src/compiler/Compiler.java | Java | gpl-3.0 | 3,268 |
package org.mariotaku.harmony.app;
import android.app.Application;
import android.content.Context;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.download.BaseImageDownloader;
import com.nostra13.universalimageloader.core.download.HttpClientImageDownloader;
import java.io.File;
import org.mariotaku.harmony.Constants;
import org.mariotaku.harmony.util.ImageLoaderWrapper;
import org.mariotaku.harmony.util.ImageMemoryCache;
import org.mariotaku.harmony.util.URLFileNameGenerator;
public class HarmonyApplication extends Application implements Constants {
private ImageLoaderWrapper mImageLoaderWrapper;
private ImageLoader mImageLoader;
public ImageLoader getImageLoader() {
if (mImageLoader != null) return mImageLoader;
final File cache_dir = new File(getCacheDir(), CACHE_DIR_NAME_ALBUMART);
if (!cache_dir.exists()) {
cache_dir.mkdirs();
}
final ImageLoader loader = ImageLoader.getInstance();
final ImageLoaderConfiguration.Builder cb = new ImageLoaderConfiguration.Builder(this);
cb.threadPoolSize(8);
cb.memoryCache(new ImageMemoryCache(40));
cb.discCache(new UnlimitedDiscCache(cache_dir, new URLFileNameGenerator()));
cb.imageDownloader(new BaseImageDownloader(this));
loader.init(cb.build());
return mImageLoader = loader;
}
public ImageLoaderWrapper getImageLoaderWrapper() {
if (mImageLoaderWrapper != null) return mImageLoaderWrapper;
return mImageLoaderWrapper = new ImageLoaderWrapper(getImageLoader());
}
public static HarmonyApplication getInstance(final Context context) {
final Context app = context != null ? context.getApplicationContext() : null;
return app instanceof HarmonyApplication ? (HarmonyApplication) app : null;
}
}
| mariotaku/harmony | src/org/mariotaku/harmony/app/HarmonyApplication.java | Java | gpl-3.0 | 1,908 |
package net.marevalo.flowsmanager;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class CollectionAdapter extends BaseAdapter {
// private static final String LOGTAG = "CollectionAdapter";
Context context;
ArrayList<Entity> collection;
public CollectionAdapter(Context context, ArrayList<Entity> list) {
this.context = context;
collection = list;
}
@Override
public int getCount() {
return collection.size();
}
@Override
public Object getItem(int position) {
return collection.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup arg2) {
//Log.d(LOGTAG, "Recreating view" );
Entity entity = collection.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.row_entity, null);
}
// Set the icon
ImageView ivIcon = (ImageView) convertView.findViewById(R.id.iconImageView );
ivIcon.setImageDrawable(
context.getResources().getDrawable(entity.getIconResource() ) );
// Set the name and ID
TextView tvName = (TextView) convertView.findViewById(R.id.tv_entity_name);
String name = entity.getDisplayName() ;
tvName.setText( name );
TextView tvId = (TextView) convertView.findViewById(R.id.tv_entity_id);
String id = entity.getIdName();
tvId.setText(((name == id) ? "" : id));
return convertView;
}
}
| marevalo/FlowsManager | app/src/main/java/net/marevalo/flowsmanager/CollectionAdapter.java | Java | gpl-3.0 | 1,955 |
<?php
/**
* @package Interspire eCommerce
* @copyright Copyright (C) 2015 Interspire Co.,Ltd. All rights reserved. (Interspire.vn)
* @credits See CREDITS.txt for credits and other copyright notices.
* @license GNU General Public License version 3; see LICENSE.txt
*/
// Heading
$_['heading_title'] = 'Interspire';
// Text
$_['text_order'] = 'Orders';
$_['text_order_status'] = 'Pending';
$_['text_complete_status'] = 'Completed';
$_['text_customer'] = 'Customers';
$_['text_online'] = 'Customers Online';
$_['text_approval'] = 'Pending approval';
$_['text_product'] = 'Products';
$_['text_stock'] = 'Out of stock';
$_['text_review'] = 'Reviews';
$_['text_return'] = 'Returns';
$_['text_affiliate'] = 'Affiliates';
$_['text_setting'] = 'Settings';
$_['text_store'] = 'Stores';
$_['text_front'] = 'Store Front';
$_['text_help'] = 'Help';
$_['text_homepage'] = 'Homepage';
$_['text_support'] = 'Support Forum';
$_['text_documentation'] = 'Documentation';
$_['text_logout'] = 'Logout';
$_['text_search_options'] = 'Search Options';
$_['text_update'] = 'Updates Available';
$_['text_new'] = 'New';
$_['text_new_category'] = 'Category';
$_['text_new_customer'] = 'Customer';
$_['text_new_download'] = 'Download';
$_['text_new_manufacturer']= 'Manufacturer';
$_['text_new_product'] = 'Product'; | interspiresource/interspire | admin/language/en-GB/common/header.php | PHP | gpl-3.0 | 1,475 |
package web;
import entities.User;
import services.UserService;
import javax.inject.Inject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.stream.Collectors;
@WebServlet("/")
public class HomeServlet extends HttpServlet {
private final UserService userService;
@Inject
public HomeServlet(UserService userService){
this.userService = userService;
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String html = getHtml();
resp.getWriter().write(html);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String body = req.getReader().lines()
.collect(Collectors.joining());
User user = new User();
Arrays.stream(body.split("&"))
.map(pairString -> pairString.split("="))
.forEach(pair -> {
switch (pair[0]){
case "name":
user.setName(pair[1].replace('+', ' ').trim());
break;
case "age":
user.setAge(pair[1].trim());
}
});
userService.add(user);
String result = getHtml();
resp.getWriter().write(result);
}
public String getUserList() {
return String.format("<ul>%s</ul>",
this.userService.getAllUsers().stream()
.map(user ->
String.format("<li>%s %s</li>", user.getName(), user.getAge())).collect(Collectors.joining(System.lineSeparator())));
}
public String getForm() {
return "<form action=\"/\" method=\"post\">\n" +
" <label for=\"name\">\n" +
" <input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Enter your name\" required>\n" +
" </label>\n" +
"<label for=\"age\">\n" +
" <input type=\"number\" id=\"age\" name=\"age\" placeholder=\"Enter your age\" required>\n" +
" </label>\n" +
" <button>Submit</button>\n" +
"</form>\n";
}
public String getHtml() {
String form = getForm();
String userList = getUserList();
return "<!DOCTYPE html>\n" +
" <html lang=\"en\">\n" +
" <head>\n" +
" <meta charset=\"UTF-8\">\n" +
" <title>Title</title>\n" +
" </head>\n" +
" <body>\n" +
form + "<br />" +
userList +
"</body>\n" +
"</html>";
}
}
| kostovhg/SoftUni | JavaWeb/JavaWebDevelopmentBasics/f_serverpages/demo/src/main/java/web/HomeServlet.java | Java | gpl-3.0 | 3,142 |
<?php
/*
Plugin Name: Like Buttons
Description: Adds Open Graph tags to your posts/pages/etc, adds a Facebook Like button to posts using simple Theme functions. Requires a Facebook Application ID (instructions are provided)
Author: Scott Taylor
Version: 0.4
Author URI: http://tsunamiorigami.com
*/
/**
* You must register you app with Facebook to have full-featured Like buttons
* If you don't want to register your app, you can use the <iframe> buttons (the_like_iframe( ) )
*
*/
define( 'FACEBOOK_APP_ID', 0 );
define( 'FACEBOOK_ADMINS', 0 );
function the_like_image() {
global $post;
if ( ! $post || ! $post->ID ) {
return;
}
$thumb_id = get_post_thumbnail_id( $post->ID );
$image = wp_get_attachment_image_src( $thumb_id );
if ( empty( $image[0] ) ) {
return;
}
?>
<meta property="og:image" content="<?php echo $image[0] ?>" />
<?php
}
function add_open_graph_atts( $value ) {
$append = array();
$append[] = $value;
if ( false === strpos( $value, 'xmlns=' ) ) {
$append[] = 'xmlns="http://www.w3.org/1999/xhtml"';
}
if ( false === strpos( $value, 'xmlns:og=' ) ) {
$append[] = 'xmlns:og="http://ogp.me/ns#"';
}
if ( false === strpos( $value, 'xmlns:fb=' ) ) {
$append[] = 'xmlns:fb="http://www.facebook.com/2008/fbml"';
}
return join( ' ', $append );
}
add_filter( 'language_attributes', 'add_open_graph_atts' );
function the_open_graph_meta_tags() {
if ( is_single( ) ):
global $post;
$content = strip_tags( apply_filters( 'the_excerpt', $post->post_excerpt ) );
if ( empty( $content ) ) {
$content = strip_tags(apply_filters( 'the_content', $post->post_content ) );
}
$content = str_replace( array( "\r\n", "\r", "\n", "\t" ), '', $content );
?>
<meta property="og:title" content="<?php echo esc_attr( apply_filters( 'the_title', $post->post_title ) ) ?>" />
<meta property="og:type" content="article" />
<?php the_like_image() ?>
<meta property="og:url" content="<?php echo esc_attr( get_permalink( $post->ID ) ) ?>" />
<meta property="og:site_name" content="<?php echo esc_attr(get_bloginfo( 'name' ) ) ?>" />
<meta property="og:description" content="<?php echo esc_attr(trim($content ) ) ?>" />
<?php else: ?>
<meta property="og:title" content="<?php echo esc_attr( get_bloginfo( 'name' ) ) ?>" />
<meta property="og:type" content="website" />
<?php the_like_image() ?>
<meta property="og:url" content="<?php echo esc_attr( home_url() ) ?>" />
<meta property="og:site_name" content="<?php echo esc_attr( get_bloginfo( 'name' ) ) ?>" />
<meta property="og:description" content="<?php echo esc_attr( trim( get_bloginfo( 'description' ) ) ) ?>" />
<?php endif; ?>
<?php if ( FACEBOOK_ADMINS ): ?>
<meta property="fb:admins" content="<?php echo esc_attr( trim( FACEBOOK_ADMINS ) ) ?>" />
<?php endif; ?>
<?php if ( FACEBOOK_APP_ID ): ?>
<meta property="fb:app_id" content="<?php echo esc_attr( trim( FACEBOOK_APP_ID ) ) ?>" />
<?php endif; ?>
<script type="text/javascript">window.FACEBOOK_APP_ID = <?php echo FACEBOOK_APP_ID ?>;</script>
<?php
}
add_action( 'wp_head', 'the_open_graph_meta_tags' );
function like_buttons_app_id() {
?>
<div id="like-buttons-warning" class="updated fade">
<p><strong>Warning!</strong> For Like Buttons to work properly, you need to register your site as a Facebook app <a href="http://www.facebook.com/developers/createapp.php" target="_blank">here</a>. Once you enter your Application Name and complete the security Captcha, select the Website tab on the left to obtain your Application ID and set Site URL to your site's root URL.</p>
</div>
<?php
}
function like_buttons_init() {
if ( 0 === (int) FACEBOOK_APP_ID ) {
add_action( 'admin_notices', 'like_buttons_app_id' );
}
}
add_action( 'admin_init', 'like_buttons_init' );
function init_like_button_js() {
wp_enqueue_script( 'like-buttons', plugins_url( 'like-buttons.js', __FILE__ ), array( 'jquery' ) );
}
add_action( 'template_redirect', 'init_like_button_js' );
/**
*
* Theme Functions
*
*/
function the_blog_like_button($height = 80, $width = 640) {
?><fb:like href="<?php echo home_url() ?>" action="like" layout="standard" colorscheme="light" show_faces="true" height="<?php echo $height ?>" width="<?php echo $width ?>"></fb:like><?php
}
function the_like_iframe() {
?><iframe src="http://www.facebook.com/plugins/like.php?href=<?php echo rawurlencode( get_permalink() ) ?>&layout=button_count&show_faces=false" scrolling="no" frameborder="0" style="border: none; overflow: hidden; width:85px; height: 21px" allowTransparency="true"></iframe><?php
}
function the_like_button() {
?><fb:like></fb:like><?php
} | wp-plugins/like-buttons | like-buttons.php | PHP | gpl-3.0 | 4,584 |
import json
import random
import requests
from plugin import create_plugin
from message import SteelyMessage
HELP_STR = """
Request your favourite bible quotes, right to the chat.
Usage:
/bible - Random quote
/bible Genesis 1:3 - Specific verse
/bible help - This help text
Verses are specified in the format {book} {chapter}:{verse}
TODO: Book acronyms, e.g. Gen -> Genesis
TODO: Verse ranges, e.g. Genesis 1:1-3
"""
BIBLE_FILE = "plugins/bible/en_kjv.json"
BIBLE_URL = 'https://raw.githubusercontent.com/thiagobodruk/bible/master/json/en_kjv.json'
plugin = create_plugin(name='bible', author='CianLR', help=HELP_STR)
bible = None
book_to_index = {}
def make_book_to_index(bible):
btoi = {}
for i, book in enumerate(bible):
btoi[book['name'].lower()] = i
return btoi
@plugin.setup()
def plugin_setup():
global bible, book_to_index
try:
bible = json.loads(open(BIBLE_FILE, encoding='utf-8-sig').read())
book_to_index = make_book_to_index(bible)
return
except BaseException as e:
pass
# We've tried nothing and we're all out of ideas, download a new bible.
try:
bible = json.loads(
requests.get(BIBLE_URL).content.decode('utf-8-sig'))
except BaseException as e:
return "Error loading bible: " + str(e)
book_to_index = make_book_to_index(bible)
with open(BIBLE_FILE, 'w') as f:
json.dump(bible, f)
@plugin.listen(command='bible help')
def help_command(bot, message: SteelyMessage, **kwargs):
bot.sendMessage(
HELP_STR,
thread_id=message.thread_id, thread_type=message.thread_type)
def is_valid_quote(book, chapter, verse):
return (0 <= book < len(bible) and
0 <= chapter < len(bible[book]['chapters']) and
0 <= verse < len(bible[book]['chapters'][chapter]))
def get_quote(book, chapter, verse):
return "{}\n - {} {}:{}".format(
bible[book]["chapters"][chapter][verse],
bible[book]["name"], chapter + 1, verse + 1)
def get_quote_from_ref(book_name, ref):
if book_name.lower() not in book_to_index:
return "Could not find book name: " + book_name
book_i = book_to_index[book_name.lower()]
if len(ref.split(':')) != 2:
return 'Reference not in form "Book Chapter:Passage"'
chapter, verse = ref.split(':')
if not chapter.isnumeric():
return "Chapter must be an int"
chapter_i = int(chapter) - 1
if not verse.isnumeric():
return "Passage must be an int"
verse_i = int(verse) - 1
if not is_valid_quote(book_i, chapter_i, verse_i):
return "Verse or chapter out of range"
return get_quote(book_i, chapter_i, verse_i)
@plugin.listen(command='bible [book] [passage]')
def passage_command(bot, message: SteelyMessage, **kwargs):
if 'passage' not in kwargs:
book = random.randrange(len(bible))
chapter = random.randrange(len(bible[book]["chapters"]))
verse = random.randrange(len(bible[book]["chapters"][chapter]))
bot.sendMessage(
get_quote(book, chapter, verse),
thread_id=message.thread_id, thread_type=message.thread_type)
else:
bot.sendMessage(
get_quote_from_ref(kwargs['book'], kwargs['passage']),
thread_id=message.thread_id, thread_type=message.thread_type)
| sentriz/steely | steely/plugins/bible/main.py | Python | gpl-3.0 | 3,384 |
<?php
return [
/*
|--------------------------------------------------------------------------
| Backpack\CRUD preferences
|--------------------------------------------------------------------------
*/
/*
|------------
| CREATE & UPDATE
|------------
*/
// Where do you want to redirect the user by default, after a CRUD entry is saved in the Add or Edit forms?
'default_save_action' => 'save_and_back', //options: save_and_back, save_and_edit, save_and_new
// When the user chooses "save and back" or "save and new", show a bubble
// for the fact that the default save action has been changed?
'show_save_action_change' => true, //options: true, false
// When using tabbed forms (create & update), what kind of tabs would you like?
'tabs_type' => 'horizontal', //options: horizontal, vertical
// How would you like the validation errors to be shown?
'show_grouped_errors' => true,
'show_inline_errors' => true,
// Here you may override the css-classes for the content section of the create view globally
// To override per view use $this->crud->setCreateContentClass('class-string')
//'create_content_class' => 'col-md-8 col-md-offset-2',
'create_content_class' => 'col-md-10 col-md-offset-1',
// Here you may override the css-classes for the content section of the edit view globally
// To override per view use $this->crud->setEditContentClass('class-string')
//'edit_content_class' => 'col-md-8 col-md-offset-2',
'edit_content_class' => 'col-md-10 col-md-offset-1',
// Here you may override the css-classes for the content section of the revisions timeline view globally
// To override per view use $this->crud->setRevisionsTimelineContentClass('class-string')
'revisions_timeline_content_class' => 'col-md-10 col-md-offset-1',
/*
|------------
| READ
|------------
*/
// LIST VIEW (table view)
// enable the datatables-responsive plugin, which hides columns if they don't fit?
// if not, a horizontal scrollbar will be shown instead
'responsive_table' => true,
// stores pagination and filters in localStorage for two hours
// whenever the user tries to see that page, backpack loads the previous pagination and filtration
'persistent_table' => false,
// How many items should be shown by default by the Datatable?
// This value can be overwritten on a specific CRUD by calling
// $this->crud->setDefaultPageLength(50);
'default_page_length' => 25,
// A 1D array of options which will be used for both the displayed option and the value, or
// A 2D array in which the first array is used to define the value options and the second array the displayed options
// If a 2D array is used, strings in the right hand array will be automatically run through trans()
'page_length_menu' => [[10, 25, 50, 100, -1], [10, 25, 50, 100, 'backpack::crud.all']],
// Here you may override the css-class for the content section of the list view globally
// To override per view use $this->crud->setListContentClass('class-string')
'list_content_class' => 'col-md-12',
// SHOW (PREVIEW)
// Here you may override the css-classes for the content section of the show view globally
// To override per view use $this->crud->setShowContentClass('class-string')
'show_content_class' => 'col-md-8 col-md-offset-2',
/*
|------------
| DELETE
|------------
*/
/*
|------------
| REORDER
|------------
*/
// Here you may override the css-classes for the content section of the reorder view globally
// To override per view use $this->crud->setReorderContentClass('class-string')
'reorder_content_class' => 'col-md-8 col-md-offset-2',
/*
|------------
| DETAILS ROW
|------------
*/
/*
|-------------------
| TRANSLATABLE CRUDS
|-------------------
*/
'show_translatable_field_icon' => true,
'translatable_field_icon_position' => 'right', // left or right
'locales' => [
// "af_NA" => "Afrikaans (Namibia)",
// "af_ZA" => "Afrikaans (South Africa)",
// "af" => "Afrikaans",
// "ak_GH" => "Akan (Ghana)",
// "ak" => "Akan",
// "sq_AL" => "Albanian (Albania)",
// "sq" => "Albanian",
// "am_ET" => "Amharic (Ethiopia)",
// "am" => "Amharic",
// "ar_DZ" => "Arabic (Algeria)",
// "ar_BH" => "Arabic (Bahrain)",
// "ar_EG" => "Arabic (Egypt)",
// "ar_IQ" => "Arabic (Iraq)",
// "ar_JO" => "Arabic (Jordan)",
// "ar_KW" => "Arabic (Kuwait)",
// "ar_LB" => "Arabic (Lebanon)",
// "ar_LY" => "Arabic (Libya)",
// "ar_MA" => "Arabic (Morocco)",
// "ar_OM" => "Arabic (Oman)",
// "ar_QA" => "Arabic (Qatar)",
// "ar_SA" => "Arabic (Saudi Arabia)",
// "ar_SD" => "Arabic (Sudan)",
// "ar_SY" => "Arabic (Syria)",
// "ar_TN" => "Arabic (Tunisia)",
// "ar_AE" => "Arabic (United Arab Emirates)",
// "ar_YE" => "Arabic (Yemen)",
// "ar" => "Arabic",
// "hy_AM" => "Armenian (Armenia)",
// "hy" => "Armenian",
// "as_IN" => "Assamese (India)",
// "as" => "Assamese",
// "asa_TZ" => "Asu (Tanzania)",
// "asa" => "Asu",
// "az_Cyrl" => "Azerbaijani (Cyrillic)",
// "az_Cyrl_AZ" => "Azerbaijani (Cyrillic, Azerbaijan)",
// "az_Latn" => "Azerbaijani (Latin)",
// "az_Latn_AZ" => "Azerbaijani (Latin, Azerbaijan)",
// "az" => "Azerbaijani",
// "bm_ML" => "Bambara (Mali)",
// "bm" => "Bambara",
// "eu_ES" => "Basque (Spain)",
// "eu" => "Basque",
// "be_BY" => "Belarusian (Belarus)",
// "be" => "Belarusian",
// "bem_ZM" => "Bemba (Zambia)",
// "bem" => "Bemba",
// "bez_TZ" => "Bena (Tanzania)",
// "bez" => "Bena",
// "bn_BD" => "Bengali (Bangladesh)",
// "bn_IN" => "Bengali (India)",
// "bn" => "Bengali",
// "bs_BA" => "Bosnian (Bosnia and Herzegovina)",
// "bs" => "Bosnian",
// "bg_BG" => "Bulgarian (Bulgaria)",
// "bg" => "Bulgarian",
// "my_MM" => "Burmese (Myanmar [Burma])",
// "my" => "Burmese",
// "ca_ES" => "Catalan (Spain)",
// "ca" => "Catalan",
// "tzm_Latn" => "Central Morocco Tamazight (Latin)",
// "tzm_Latn_MA" => "Central Morocco Tamazight (Latin, Morocco)",
// "tzm" => "Central Morocco Tamazight",
// "chr_US" => "Cherokee (United States)",
// "chr" => "Cherokee",
// "cgg_UG" => "Chiga (Uganda)",
// "cgg" => "Chiga",
// "zh_Hans" => "Chinese (Simplified Han)",
// "zh_Hans_CN" => "Chinese (Simplified Han, China)",
// "zh_Hans_HK" => "Chinese (Simplified Han, Hong Kong SAR China)",
// "zh_Hans_MO" => "Chinese (Simplified Han, Macau SAR China)",
// "zh_Hans_SG" => "Chinese (Simplified Han, Singapore)",
// "zh_Hant" => "Chinese (Traditional Han)",
// "zh_Hant_HK" => "Chinese (Traditional Han, Hong Kong SAR China)",
// "zh_Hant_MO" => "Chinese (Traditional Han, Macau SAR China)",
// "zh_Hant_TW" => "Chinese (Traditional Han, Taiwan)",
// "zh" => "Chinese",
// "kw_GB" => "Cornish (United Kingdom)",
// "kw" => "Cornish",
// "hr_HR" => "Croatian (Croatia)",
// "hr" => "Croatian",
// "cs_CZ" => "Czech (Czech Republic)",
// "cs" => "Czech",
// "da_DK" => "Danish (Denmark)",
// "da" => "Danish",
// "nl_BE" => "Dutch (Belgium)",
// "nl_NL" => "Dutch (Netherlands)",
// "nl" => "Dutch",
// "ebu_KE" => "Embu (Kenya)",
// "ebu" => "Embu",
// "en_AS" => "English (American Samoa)",
// "en_AU" => "English (Australia)",
// "en_BE" => "English (Belgium)",
// "en_BZ" => "English (Belize)",
// "en_BW" => "English (Botswana)",
// "en_CA" => "English (Canada)",
// "en_GU" => "English (Guam)",
// "en_HK" => "English (Hong Kong SAR China)",
// "en_IN" => "English (India)",
// "en_IE" => "English (Ireland)",
// "en_JM" => "English (Jamaica)",
// "en_MT" => "English (Malta)",
// "en_MH" => "English (Marshall Islands)",
// "en_MU" => "English (Mauritius)",
// "en_NA" => "English (Namibia)",
// "en_NZ" => "English (New Zealand)",
// "en_MP" => "English (Northern Mariana Islands)",
// "en_PK" => "English (Pakistan)",
// "en_PH" => "English (Philippines)",
// "en_SG" => "English (Singapore)",
// "en_ZA" => "English (South Africa)",
// "en_TT" => "English (Trinidad and Tobago)",
// "en_UM" => "English (U.S. Minor Outlying Islands)",
// "en_VI" => "English (U.S. Virgin Islands)",
// "en_GB" => "English (United Kingdom)",
// "en_US" => "English (United States)",
// "en_ZW" => "English (Zimbabwe)",
'en' => 'English',
// "eo" => "Esperanto",
// "et_EE" => "Estonian (Estonia)",
// "et" => "Estonian",
// "ee_GH" => "Ewe (Ghana)",
// "ee_TG" => "Ewe (Togo)",
// "ee" => "Ewe",
// "fo_FO" => "Faroese (Faroe Islands)",
// "fo" => "Faroese",
// "fil_PH" => "Filipino (Philippines)",
// "fil" => "Filipino",
// "fi_FI" => "Finnish (Finland)",
// "fi" => "Finnish",
// "fr_BE" => "French (Belgium)",
// "fr_BJ" => "French (Benin)",
// "fr_BF" => "French (Burkina Faso)",
// "fr_BI" => "French (Burundi)",
// "fr_CM" => "French (Cameroon)",
// "fr_CA" => "French (Canada)",
// "fr_CF" => "French (Central African Republic)",
// "fr_TD" => "French (Chad)",
// "fr_KM" => "French (Comoros)",
// "fr_CG" => "French (Congo - Brazzaville)",
// "fr_CD" => "French (Congo - Kinshasa)",
// "fr_CI" => "French (Côte d’Ivoire)",
// "fr_DJ" => "French (Djibouti)",
// "fr_GQ" => "French (Equatorial Guinea)",
// "fr_FR" => "French (France)",
// "fr_GA" => "French (Gabon)",
// "fr_GP" => "French (Guadeloupe)",
// "fr_GN" => "French (Guinea)",
// "fr_LU" => "French (Luxembourg)",
// "fr_MG" => "French (Madagascar)",
// "fr_ML" => "French (Mali)",
// "fr_MQ" => "French (Martinique)",
// "fr_MC" => "French (Monaco)",
// "fr_NE" => "French (Niger)",
// "fr_RW" => "French (Rwanda)",
// "fr_RE" => "French (Réunion)",
// "fr_BL" => "French (Saint Barthélemy)",
// "fr_MF" => "French (Saint Martin)",
// "fr_SN" => "French (Senegal)",
// "fr_CH" => "French (Switzerland)",
// "fr_TG" => "French (Togo)",
'fr' => 'French',
// "ff_SN" => "Fulah (Senegal)",
// "ff" => "Fulah",
// "gl_ES" => "Galician (Spain)",
// "gl" => "Galician",
// "lg_UG" => "Ganda (Uganda)",
// "lg" => "Ganda",
// "ka_GE" => "Georgian (Georgia)",
// "ka" => "Georgian",
// "de_AT" => "German (Austria)",
// "de_BE" => "German (Belgium)",
// "de_DE" => "German (Germany)",
// "de_LI" => "German (Liechtenstein)",
// "de_LU" => "German (Luxembourg)",
// "de_CH" => "German (Switzerland)",
// "de" => "German",
// "el_CY" => "Greek (Cyprus)",
// "el_GR" => "Greek (Greece)",
// "el" => "Greek",
// "gu_IN" => "Gujarati (India)",
// "gu" => "Gujarati",
// "guz_KE" => "Gusii (Kenya)",
// "guz" => "Gusii",
// "ha_Latn" => "Hausa (Latin)",
// "ha_Latn_GH" => "Hausa (Latin, Ghana)",
// "ha_Latn_NE" => "Hausa (Latin, Niger)",
// "ha_Latn_NG" => "Hausa (Latin, Nigeria)",
// "ha" => "Hausa",
// "haw_US" => "Hawaiian (United States)",
// "haw" => "Hawaiian",
// "he_IL" => "Hebrew (Israel)",
// "he" => "Hebrew",
// "hi_IN" => "Hindi (India)",
// "hi" => "Hindi",
// "hu_HU" => "Hungarian (Hungary)",
// "hu" => "Hungarian",
// "is_IS" => "Icelandic (Iceland)",
// "is" => "Icelandic",
// "ig_NG" => "Igbo (Nigeria)",
// "ig" => "Igbo",
// "id_ID" => "Indonesian (Indonesia)",
// "id" => "Indonesian",
// "ga_IE" => "Irish (Ireland)",
// "ga" => "Irish",
// "it_IT" => "Italian (Italy)",
// "it_CH" => "Italian (Switzerland)",
'it' => 'Italian',
// "ja_JP" => "Japanese (Japan)",
// "ja" => "Japanese",
// "kea_CV" => "Kabuverdianu (Cape Verde)",
// "kea" => "Kabuverdianu",
// "kab_DZ" => "Kabyle (Algeria)",
// "kab" => "Kabyle",
// "kl_GL" => "Kalaallisut (Greenland)",
// "kl" => "Kalaallisut",
// "kln_KE" => "Kalenjin (Kenya)",
// "kln" => "Kalenjin",
// "kam_KE" => "Kamba (Kenya)",
// "kam" => "Kamba",
// "kn_IN" => "Kannada (India)",
// "kn" => "Kannada",
// "kk_Cyrl" => "Kazakh (Cyrillic)",
// "kk_Cyrl_KZ" => "Kazakh (Cyrillic, Kazakhstan)",
// "kk" => "Kazakh",
// "km_KH" => "Khmer (Cambodia)",
// "km" => "Khmer",
// "ki_KE" => "Kikuyu (Kenya)",
// "ki" => "Kikuyu",
// "rw_RW" => "Kinyarwanda (Rwanda)",
// "rw" => "Kinyarwanda",
// "kok_IN" => "Konkani (India)",
// "kok" => "Konkani",
// "ko_KR" => "Korean (South Korea)",
// "ko" => "Korean",
// "khq_ML" => "Koyra Chiini (Mali)",
// "khq" => "Koyra Chiini",
// "ses_ML" => "Koyraboro Senni (Mali)",
// "ses" => "Koyraboro Senni",
// "lag_TZ" => "Langi (Tanzania)",
// "lag" => "Langi",
// "lv_LV" => "Latvian (Latvia)",
// "lv" => "Latvian",
// "lt_LT" => "Lithuanian (Lithuania)",
// "lt" => "Lithuanian",
// "luo_KE" => "Luo (Kenya)",
// "luo" => "Luo",
// "luy_KE" => "Luyia (Kenya)",
// "luy" => "Luyia",
// "mk_MK" => "Macedonian (Macedonia)",
// "mk" => "Macedonian",
// "jmc_TZ" => "Machame (Tanzania)",
// "jmc" => "Machame",
// "kde_TZ" => "Makonde (Tanzania)",
// "kde" => "Makonde",
// "mg_MG" => "Malagasy (Madagascar)",
// "mg" => "Malagasy",
// "ms_BN" => "Malay (Brunei)",
// "ms_MY" => "Malay (Malaysia)",
// "ms" => "Malay",
// "ml_IN" => "Malayalam (India)",
// "ml" => "Malayalam",
// "mt_MT" => "Maltese (Malta)",
// "mt" => "Maltese",
// "gv_GB" => "Manx (United Kingdom)",
// "gv" => "Manx",
// "mr_IN" => "Marathi (India)",
// "mr" => "Marathi",
// "mas_KE" => "Masai (Kenya)",
// "mas_TZ" => "Masai (Tanzania)",
// "mas" => "Masai",
// "mer_KE" => "Meru (Kenya)",
// "mer" => "Meru",
// "mfe_MU" => "Morisyen (Mauritius)",
// "mfe" => "Morisyen",
// "naq_NA" => "Nama (Namibia)",
// "naq" => "Nama",
// "ne_IN" => "Nepali (India)",
// "ne_NP" => "Nepali (Nepal)",
// "ne" => "Nepali",
// "nd_ZW" => "North Ndebele (Zimbabwe)",
// "nd" => "North Ndebele",
// "nb_NO" => "Norwegian Bokmål (Norway)",
// "nb" => "Norwegian Bokmål",
// "nn_NO" => "Norwegian Nynorsk (Norway)",
// "nn" => "Norwegian Nynorsk",
// "nyn_UG" => "Nyankole (Uganda)",
// "nyn" => "Nyankole",
// "or_IN" => "Oriya (India)",
// "or" => "Oriya",
// "om_ET" => "Oromo (Ethiopia)",
// "om_KE" => "Oromo (Kenya)",
// "om" => "Oromo",
// "ps_AF" => "Pashto (Afghanistan)",
// "ps" => "Pashto",
// "fa_AF" => "Persian (Afghanistan)",
// "fa_IR" => "Persian (Iran)",
// "fa" => "Persian",
// "pl_PL" => "Polish (Poland)",
// "pl" => "Polish",
// "pt_BR" => "Portuguese (Brazil)",
// "pt_GW" => "Portuguese (Guinea-Bissau)",
// "pt_MZ" => "Portuguese (Mozambique)",
// "pt_PT" => "Portuguese (Portugal)",
// "pt" => "Portuguese",
// "pa_Arab" => "Punjabi (Arabic)",
// "pa_Arab_PK" => "Punjabi (Arabic, Pakistan)",
// "pa_Guru" => "Punjabi (Gurmukhi)",
// "pa_Guru_IN" => "Punjabi (Gurmukhi, India)",
// "pa" => "Punjabi",
// "ro_MD" => "Romanian (Moldova)",
// "ro_RO" => "Romanian (Romania)",
'ro' => 'Romanian',
// "rm_CH" => "Romansh (Switzerland)",
// "rm" => "Romansh",
// "rof_TZ" => "Rombo (Tanzania)",
// "rof" => "Rombo",
// "ru_MD" => "Russian (Moldova)",
// "ru_RU" => "Russian (Russia)",
// "ru_UA" => "Russian (Ukraine)",
// "ru" => "Russian",
// "rwk_TZ" => "Rwa (Tanzania)",
// "rwk" => "Rwa",
// "saq_KE" => "Samburu (Kenya)",
// "saq" => "Samburu",
// "sg_CF" => "Sango (Central African Republic)",
// "sg" => "Sango",
// "seh_MZ" => "Sena (Mozambique)",
// "seh" => "Sena",
// "sr_Cyrl" => "Serbian (Cyrillic)",
// "sr_Cyrl_BA" => "Serbian (Cyrillic, Bosnia and Herzegovina)",
// "sr_Cyrl_ME" => "Serbian (Cyrillic, Montenegro)",
// "sr_Cyrl_RS" => "Serbian (Cyrillic, Serbia)",
// "sr_Latn" => "Serbian (Latin)",
// "sr_Latn_BA" => "Serbian (Latin, Bosnia and Herzegovina)",
// "sr_Latn_ME" => "Serbian (Latin, Montenegro)",
// "sr_Latn_RS" => "Serbian (Latin, Serbia)",
// "sr" => "Serbian",
// "sn_ZW" => "Shona (Zimbabwe)",
// "sn" => "Shona",
// "ii_CN" => "Sichuan Yi (China)",
// "ii" => "Sichuan Yi",
// "si_LK" => "Sinhala (Sri Lanka)",
// "si" => "Sinhala",
// "sk_SK" => "Slovak (Slovakia)",
// "sk" => "Slovak",
// "sl_SI" => "Slovenian (Slovenia)",
// "sl" => "Slovenian",
// "xog_UG" => "Soga (Uganda)",
// "xog" => "Soga",
// "so_DJ" => "Somali (Djibouti)",
// "so_ET" => "Somali (Ethiopia)",
// "so_KE" => "Somali (Kenya)",
// "so_SO" => "Somali (Somalia)",
// "so" => "Somali",
// "es_AR" => "Spanish (Argentina)",
// "es_BO" => "Spanish (Bolivia)",
// "es_CL" => "Spanish (Chile)",
// "es_CO" => "Spanish (Colombia)",
// "es_CR" => "Spanish (Costa Rica)",
// "es_DO" => "Spanish (Dominican Republic)",
// "es_EC" => "Spanish (Ecuador)",
// "es_SV" => "Spanish (El Salvador)",
// "es_GQ" => "Spanish (Equatorial Guinea)",
// "es_GT" => "Spanish (Guatemala)",
// "es_HN" => "Spanish (Honduras)",
// "es_419" => "Spanish (Latin America)",
// "es_MX" => "Spanish (Mexico)",
// "es_NI" => "Spanish (Nicaragua)",
// "es_PA" => "Spanish (Panama)",
// "es_PY" => "Spanish (Paraguay)",
// "es_PE" => "Spanish (Peru)",
// "es_PR" => "Spanish (Puerto Rico)",
// "es_ES" => "Spanish (Spain)",
// "es_US" => "Spanish (United States)",
// "es_UY" => "Spanish (Uruguay)",
// "es_VE" => "Spanish (Venezuela)",
// "es" => "Spanish",
// "sw_KE" => "Swahili (Kenya)",
// "sw_TZ" => "Swahili (Tanzania)",
// "sw" => "Swahili",
// "sv_FI" => "Swedish (Finland)",
// "sv_SE" => "Swedish (Sweden)",
// "sv" => "Swedish",
// "gsw_CH" => "Swiss German (Switzerland)",
// "gsw" => "Swiss German",
// "shi_Latn" => "Tachelhit (Latin)",
// "shi_Latn_MA" => "Tachelhit (Latin, Morocco)",
// "shi_Tfng" => "Tachelhit (Tifinagh)",
// "shi_Tfng_MA" => "Tachelhit (Tifinagh, Morocco)",
// "shi" => "Tachelhit",
// "dav_KE" => "Taita (Kenya)",
// "dav" => "Taita",
// "ta_IN" => "Tamil (India)",
// "ta_LK" => "Tamil (Sri Lanka)",
// "ta" => "Tamil",
// "te_IN" => "Telugu (India)",
// "te" => "Telugu",
// "teo_KE" => "Teso (Kenya)",
// "teo_UG" => "Teso (Uganda)",
// "teo" => "Teso",
// "th_TH" => "Thai (Thailand)",
// "th" => "Thai",
// "bo_CN" => "Tibetan (China)",
// "bo_IN" => "Tibetan (India)",
// "bo" => "Tibetan",
// "ti_ER" => "Tigrinya (Eritrea)",
// "ti_ET" => "Tigrinya (Ethiopia)",
// "ti" => "Tigrinya",
// "to_TO" => "Tonga (Tonga)",
// "to" => "Tonga",
// "tr_TR" => "Turkish (Turkey)",
// "tr" => "Turkish",
// "uk_UA" => "Ukrainian (Ukraine)",
// "uk" => "Ukrainian",
// "ur_IN" => "Urdu (India)",
// "ur_PK" => "Urdu (Pakistan)",
// "ur" => "Urdu",
// "uz_Arab" => "Uzbek (Arabic)",
// "uz_Arab_AF" => "Uzbek (Arabic, Afghanistan)",
// "uz_Cyrl" => "Uzbek (Cyrillic)",
// "uz_Cyrl_UZ" => "Uzbek (Cyrillic, Uzbekistan)",
// "uz_Latn" => "Uzbek (Latin)",
// "uz_Latn_UZ" => "Uzbek (Latin, Uzbekistan)",
// "uz" => "Uzbek",
// "vi_VN" => "Vietnamese (Vietnam)",
// "vi" => "Vietnamese",
// "vun_TZ" => "Vunjo (Tanzania)",
// "vun" => "Vunjo",
// "cy_GB" => "Welsh (United Kingdom)",
// "cy" => "Welsh",
// "yo_NG" => "Yoruba (Nigeria)",
// "yo" => "Yoruba",
// "zu_ZA" => "Zulu (South Africa)",
// "zu" => "Zulu"
],
];
| lejubila/piGardenWeb | config/backpack/crud.php | PHP | gpl-3.0 | 21,893 |
package yuuto.quantumelectronics.transport.routing;
import net.minecraft.item.ItemStack;
public interface IItemDestination extends IItemRouter{
ItemStack insertItem(ItemStack stack, boolean simulate, boolean supplier);
boolean isSupplier();
}
| AnimeniacYuuto/QuantumElectronics | src/main/java/yuuto/quantumelectronics/transport/routing/IItemDestination.java | Java | gpl-3.0 | 250 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package block_panopto
* @copyright Panopto 2009 - 2015 /With contributions from Spenser Jones (sjones@ambrose.edu)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
require_once(dirname(__FILE__) . '/../../config.php');
require_once($CFG->libdir . '/formslib.php');
require_once('lib/panopto_data.php');
global $courses;
// Populate list of servernames to select from.
$aserverarray = array();
$appkeyarray = array();
if (isset($_SESSION['numservers'])) {
$maxval = $_SESSION['numservers'];
} else {
$maxval = 1;
}
for ($x = 0; $x < $maxval; $x++) {
// Generate strings corresponding to potential servernames in $CFG.
$thisservername = 'block_panopto_server_name' . ($x + 1);
$thisappkey = 'block_panopto_application_key' . ($x + 1);
if ((isset($CFG->$thisservername) && !is_null_or_empty_string($CFG->$thisservername)) && (!is_null_or_empty_string($CFG->$thisappkey))) {
$aserverarray[$x] = $CFG->$thisservername;
$appkeyarray[$x] = $CFG->$thisappkey;
}
}
// If only one server, simply provision with that server. Setting these values will circumvent loading the selection form prior to provisioning.
if (count($aserverarray) == 1) {
// Get first element from associative array. aServerArray and appKeyArray will have same key values.
$key = array_keys($aserverarray);
$selectedserver = $aserverarray[$key[0]];
$selectedkey = $appkeyarray[$key[0]];
}
/**
* Create form for server selection.
*
* @package block_panopto
* @copyright Panopto 2009 - 2015
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class panopto_provision_form extends moodleform {
/**
* Defines a panopto provision form
*/
public function definition() {
global $DB;
global $aserverarray;
$mform = & $this->_form;
$serverselect = $mform->addElement('select', 'servers', 'Select a Panopto server', $aserverarray);
$this->add_action_buttons(true, 'Provision');
}
}
require_login();
// This page requires a course ID to be passed in as a param. If accessed directly without clicking on a link for the course,
// no id is passed and the script fails. Similarly if no ID is passed with via a link (should never happen) the script will fail.
$courseid = required_param('id', PARAM_INT);
// Course context.
$context = context_course::instance($courseid, MUST_EXIST);
$PAGE->set_context($context);
// Return URL is course page.
$returnurl = optional_param('return_url', $CFG->wwwroot . '/course/view.php?id=' . $courseid, PARAM_LOCALURL);
$urlparams['return_url'] = $returnurl;
$PAGE->set_url('/blocks/panopto/provision_course_internal.php?id=' . $courseid, $urlparams);
$PAGE->set_pagelayout('base');
$mform = new panopto_provision_form($PAGE->url);
if ($mform->is_cancelled()) {
redirect(new moodle_url($returnurl));
} else {
// Set Moodle page info.
$provisiontitle = get_string('provision_courses', 'block_panopto');
$PAGE->set_pagelayout('base');
$PAGE->set_title($provisiontitle);
$PAGE->set_heading($provisiontitle);
// Course context.
require_capability('block/panopto:provision_course', $context);
$editcourseurl = new moodle_url($returnurl);
$PAGE->navbar->add(get_string('pluginname', 'block_panopto'), $editcourseurl);
$data = $mform->get_data();
// If there is form data, use it to determine the server and app key to provision to.
if ($data) {
$selectedserver = $aserverarray[$data->servers];
$selectedkey = $appkeyarray[$data->servers];
$CFG->servername = $selectedserver;
$CFG->appkey = $selectedkey;
}
$manageblocks = new moodle_url('/admin/blocks.php');
$panoptosettings = new moodle_url('/admin/settings.php?section=blocksettingpanopto');
$PAGE->navbar->add(get_string('blocks'), $manageblocks);
$PAGE->navbar->add(get_string('pluginname', 'block_panopto'), $panoptosettings);
$PAGE->navbar->add($provisiontitle, new moodle_url($PAGE->url));
echo $OUTPUT->header();
// If there are no servers specified for provisioning, give a failure notice and allow user to return to course page.
if (count($aserverarray) < 1) {
echo "There are no servers set up for provisioning. Please contact system administrator.
<br/>
<a href='$returnurl'>Back to course</a>";
} else if (isset($selectedserver)) {
// If a $selected server is set, it means that a server has been chosen and that the provisioning should be done instead of
// loading the selection form.
$provisioned = array();
$panoptodata = new panopto_data(null);
// Set the current Moodle course to retrieve info for / provision.
$panoptodata->moodlecourseid = $courseid;
// If an application key and server name are pre-set (happens when provisioning from multi-select page) use those, otherwise retrieve
// values from the db.
if (isset($selectedserver)) {
$panoptodata->servername = $selectedserver;
} else {
$panoptodata->servername = $panoptodata->get_panopto_servername($panoptodata->moodlecourseid);
}
if (isset($selectedkey)) {
$panoptodata->applicationkey = $selectedkey;
} else {
$panoptodata->applicationkey = $panoptodata->get_panopto_app_key($panoptodata->moodlecourseid);
}
$provisioningdata = $panoptodata->get_provisioning_info();
$provisioneddata = $panoptodata->provision_course($provisioningdata);
include('views/provisioned_course.html.php');
echo "<a href='$returnurl'>Back to course</a>";
} else {
$mform->display();
}
echo $OUTPUT->footer();
}
/**
*Returns true if a string is null or empty, false otherwise
*/
function is_null_or_empty_string($name) {
return (!isset($name) || trim($name) === '');
}
/* End of file provision_course.php */
| lsuits/Moodle-2.0-Plugin-for-Panopto | provision_course_internal.php | PHP | gpl-3.0 | 6,665 |
<?php
/*
* This file is part of MedShakeEHR.
*
* Copyright (c) 2020
* Bertrand Boutillier <b.boutillier@gmail.com>
* http://www.medshake.net
*
* MedShakeEHR 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
* any later version.
*
* MedShakeEHR 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 MedShakeEHR. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Dropbox : les requêtes ajax
*
* @author Bertrand Boutillier <b.boutillier@gmail.com>
*/
$debug='';
$m=$match['params']['m'];
$acceptedModes=array(
'viewDoc', // Voir un doc
'getPatients', // Obtenir liste patients sur recherche
'delDoc',
'rotateDoc',
);
if (!in_array($m, $acceptedModes)) {
die;
}
include('inc-ajax-'.$m.'.php');
| MedShake/MedShakeEHR-base | controlers/dropbox/actions/dropboxAjax.php | PHP | gpl-3.0 | 1,145 |
package io.github.notsyncing.lightfur.integration.jdbc;
import io.github.notsyncing.lightfur.annotations.entity.Column;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;
public class ReflectDataMapper extends JdbcDataMapper
{
private <T> T mapCurrentRow(Class<T> clazz, ResultSet result) throws IllegalAccessException, InstantiationException, SQLException {
T instance = clazz.newInstance();
List<Field> fields = new ArrayList<>();
fields.addAll(Arrays.asList(clazz.getFields()));
if (clazz.getDeclaredFields().length > 0) {
Stream.of(clazz.getDeclaredFields())
.filter(f -> Modifier.isPrivate(f.getModifiers()))
.forEach(f -> {
f.setAccessible(true);
fields.add(f);
});
}
for (Field f : fields) {
if (!f.isAnnotationPresent(Column.class)) {
continue;
}
Column c = f.getAnnotation(Column.class);
int colIndex;
try {
colIndex = result.findColumn(c.value());
} catch (SQLException e) {
continue;
}
f.set(instance, valueToType(f.getType(), result.getObject(colIndex)));
}
return instance;
}
@Override
public <T> T map(Class<T> clazz, ResultSet results) throws IllegalAccessException, InstantiationException, SQLException {
if (!results.next()) {
return null;
}
return mapCurrentRow(clazz, results);
}
@Override
public <T> List<T> mapToList(Class<T> clazz, ResultSet results) throws InstantiationException, IllegalAccessException, SQLException {
List<T> list = new ArrayList<>();
while (results.next()) {
list.add(mapCurrentRow(clazz, results));
}
return list;
}
}
| notsyncing/lightfur | lightfur-integration-jdbc/src/main/java/io/github/notsyncing/lightfur/integration/jdbc/ReflectDataMapper.java | Java | gpl-3.0 | 2,099 |
package de.leif.ffmanagementsuite.service;
import de.leif.ffmanagementsuite.domain.Authority;
import de.leif.ffmanagementsuite.domain.User;
import de.leif.ffmanagementsuite.repository.AuthorityRepository;
import de.leif.ffmanagementsuite.config.Constants;
import de.leif.ffmanagementsuite.repository.UserRepository;
import de.leif.ffmanagementsuite.security.AuthoritiesConstants;
import de.leif.ffmanagementsuite.security.SecurityUtils;
import de.leif.ffmanagementsuite.service.util.RandomUtil;
import de.leif.ffmanagementsuite.service.dto.UserDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
/**
* Service class for managing users.
*/
@Service
@Transactional
public class UserService {
private final Logger log = LoggerFactory.getLogger(UserService.class);
private final UserRepository userRepository;
private final PasswordEncoder passwordEncoder;
private final AuthorityRepository authorityRepository;
private final CacheManager cacheManager;
public UserService(UserRepository userRepository, PasswordEncoder passwordEncoder, AuthorityRepository authorityRepository, CacheManager cacheManager) {
this.userRepository = userRepository;
this.passwordEncoder = passwordEncoder;
this.authorityRepository = authorityRepository;
this.cacheManager = cacheManager;
}
public Optional<User> activateRegistration(String key) {
log.debug("Activating user for activation key {}", key);
return userRepository.findOneByActivationKey(key)
.map(user -> {
// activate given user for the registration key.
user.setActivated(true);
user.setActivationKey(null);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Activated user: {}", user);
return user;
});
}
public Optional<User> completePasswordReset(String newPassword, String key) {
log.debug("Reset user password for reset key {}", key);
return userRepository.findOneByResetKey(key)
.filter(user -> user.getResetDate().isAfter(Instant.now().minusSeconds(86400)))
.map(user -> {
user.setPassword(passwordEncoder.encode(newPassword));
user.setResetKey(null);
user.setResetDate(null);
cacheManager.getCache("users").evict(user.getLogin());
return user;
});
}
public Optional<User> requestPasswordReset(String mail) {
return userRepository.findOneByEmailIgnoreCase(mail)
.filter(User::getActivated)
.map(user -> {
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
cacheManager.getCache("users").evict(user.getLogin());
return user;
});
}
public User createUser(String login, String password, String firstName, String lastName, String email,
String imageUrl, String langKey) {
User newUser = new User();
Authority authority = authorityRepository.findOne(AuthoritiesConstants.USER);
Set<Authority> authorities = new HashSet<>();
String encryptedPassword = passwordEncoder.encode(password);
newUser.setLogin(login);
// new user gets initially a generated password
newUser.setPassword(encryptedPassword);
newUser.setFirstName(firstName);
newUser.setLastName(lastName);
newUser.setEmail(email);
newUser.setImageUrl(imageUrl);
newUser.setLangKey(langKey);
// new user is not active
newUser.setActivated(false);
// new user gets registration key
newUser.setActivationKey(RandomUtil.generateActivationKey());
authorities.add(authority);
newUser.setAuthorities(authorities);
userRepository.save(newUser);
log.debug("Created Information for User: {}", newUser);
return newUser;
}
public User createUser(UserDTO userDTO) {
User user = new User();
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
if (userDTO.getLangKey() == null) {
user.setLangKey(Constants.DEFAULT_LANGUAGE); // default language
} else {
user.setLangKey(userDTO.getLangKey());
}
if (userDTO.getAuthorities() != null) {
Set<Authority> authorities = new HashSet<>();
userDTO.getAuthorities().forEach(
authority -> authorities.add(authorityRepository.findOne(authority))
);
user.setAuthorities(authorities);
}
String encryptedPassword = passwordEncoder.encode(RandomUtil.generatePassword());
user.setPassword(encryptedPassword);
user.setResetKey(RandomUtil.generateResetKey());
user.setResetDate(Instant.now());
user.setActivated(true);
userRepository.save(user);
log.debug("Created Information for User: {}", user);
return user;
}
/**
* Update basic information (first name, last name, email, language) for the current user.
*
* @param firstName first name of user
* @param lastName last name of user
* @param email email id of user
* @param langKey language key
* @param imageUrl image URL of user
*/
public void updateUser(String firstName, String lastName, String email, String langKey, String imageUrl) {
userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> {
user.setFirstName(firstName);
user.setLastName(lastName);
user.setEmail(email);
user.setLangKey(langKey);
user.setImageUrl(imageUrl);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Changed Information for User: {}", user);
});
}
/**
* Update all information for a specific user, and return the modified user.
*
* @param userDTO user to update
* @return updated user
*/
public Optional<UserDTO> updateUser(UserDTO userDTO) {
return Optional.of(userRepository
.findOne(userDTO.getId()))
.map(user -> {
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> managedAuthorities = user.getAuthorities();
managedAuthorities.clear();
userDTO.getAuthorities().stream()
.map(authorityRepository::findOne)
.forEach(managedAuthorities::add);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Changed Information for User: {}", user);
return user;
})
.map(UserDTO::new);
}
public void deleteUser(String login) {
userRepository.findOneByLogin(login).ifPresent(user -> {
userRepository.delete(user);
cacheManager.getCache("users").evict(login);
log.debug("Deleted User: {}", user);
});
}
public void changePassword(String password) {
userRepository.findOneByLogin(SecurityUtils.getCurrentUserLogin()).ifPresent(user -> {
String encryptedPassword = passwordEncoder.encode(password);
user.setPassword(encryptedPassword);
cacheManager.getCache("users").evict(user.getLogin());
log.debug("Changed password for User: {}", user);
});
}
@Transactional(readOnly = true)
public Page<UserDTO> getAllManagedUsers(Pageable pageable) {
return userRepository.findAllByLoginNot(pageable, Constants.ANONYMOUS_USER).map(UserDTO::new);
}
@Transactional(readOnly = true)
public Optional<User> getUserWithAuthoritiesByLogin(String login) {
return userRepository.findOneWithAuthoritiesByLogin(login);
}
@Transactional(readOnly = true)
public User getUserWithAuthorities(Long id) {
return userRepository.findOneWithAuthoritiesById(id);
}
@Transactional(readOnly = true)
public User getUserWithAuthorities() {
return userRepository.findOneWithAuthoritiesByLogin(SecurityUtils.getCurrentUserLogin()).orElse(null);
}
/**
* Not activated users should be automatically deleted after 3 days.
* <p>
* This is scheduled to get fired everyday, at 01:00 (am).
*/
@Scheduled(cron = "0 0 1 * * ?")
public void removeNotActivatedUsers() {
List<User> users = userRepository.findAllByActivatedIsFalseAndCreatedDateBefore(Instant.now().minus(3, ChronoUnit.DAYS));
for (User user : users) {
log.debug("Deleting not activated user {}", user.getLogin());
userRepository.delete(user);
cacheManager.getCache("users").evict(user.getLogin());
}
}
/**
* @return a list of all the authorities
*/
public List<String> getAuthorities() {
return authorityRepository.findAll().stream().map(Authority::getName).collect(Collectors.toList());
}
}
| t08094a/ffManagementSuite | src/main/java/de/leif/ffmanagementsuite/service/UserService.java | Java | gpl-3.0 | 10,089 |
#!/usr/bin/env python
"""
This program decodes the Motorola SmartNet II trunking protocol from the control channel
Tune it to the control channel center freq, and it'll spit out the decoded packets.
In what format? Who knows.
Based on your AIS decoding software, which is in turn based on the gr-pager code and the gr-air code.
"""
from gnuradio import gr, gru, blks2, optfir, digital
from gnuradio import audio
from gnuradio import eng_notation
from gnuradio import uhd
from fsk_demod import fsk_demod
from optparse import OptionParser
from gnuradio.eng_option import eng_option
from gnuradio import smartnet
import time
import gnuradio.gr.gr_threading as _threading
import csv
class top_block_runner(_threading.Thread):
def __init__(self, tb):
_threading.Thread.__init__(self)
self.setDaemon(1)
self.tb = tb
self.done = False
self.start()
def run(self):
self.tb.run()
self.done = True
class my_top_block(gr.top_block):
def __init__(self, options, queue):
gr.top_block.__init__(self)
if options.filename is not None:
self.fs = gr.file_source(gr.sizeof_gr_complex, options.filename)
self.rate = options.rate
else:
self.u = uhd.usrp_source(options.addr,
io_type=uhd.io_type.COMPLEX_FLOAT32,
num_channels=1)
if options.subdev is not None:
self.u.set_subdev_spec(options.subdev, 0)
self.u.set_samp_rate(options.rate)
self.rate = self.u.get_samp_rate()
# Set the antenna
if(options.antenna):
self.u.set_antenna(options.antenna, 0)
self.centerfreq = options.centerfreq
print "Tuning to: %fMHz" % (self.centerfreq - options.error)
if not(self.tune(options.centerfreq - options.error)):
print "Failed to set initial frequency"
if options.gain is None: #set to halfway
g = self.u.get_gain_range()
options.gain = (g.start()+g.stop()) / 2.0
print "Setting gain to %i" % options.gain
self.u.set_gain(options.gain)
self.u.set_bandwidth(options.bandwidth)
print "Samples per second is %i" % self.rate
self._syms_per_sec = 3600;
options.samples_per_second = self.rate
options.syms_per_sec = self._syms_per_sec
options.gain_mu = 0.01
options.mu=0.5
options.omega_relative_limit = 0.3
options.syms_per_sec = self._syms_per_sec
options.offset = options.centerfreq - options.freq
print "Control channel offset: %f" % options.offset
self.demod = fsk_demod(options)
self.start_correlator = gr.correlate_access_code_tag_bb("10101100",
0,
"smartnet_preamble") #should mark start of packet
self.smartnet_deinterleave = smartnet.deinterleave()
self.smartnet_crc = smartnet.crc(queue)
if options.filename is None:
self.connect(self.u, self.demod)
else:
self.connect(self.fs, self.demod)
self.connect(self.demod, self.start_correlator, self.smartnet_deinterleave, self.smartnet_crc)
#hook up the audio patch
if options.audio:
self.audiorate = 48000
self.audiotaps = gr.firdes.low_pass(1, self.rate, 8000, 2000, gr.firdes.WIN_HANN)
self.prefilter_decim = int(self.rate / self.audiorate) #might have to use a rational resampler for audio
print "Prefilter decimation: %i" % self.prefilter_decim
self.audio_prefilter = gr.freq_xlating_fir_filter_ccf(self.prefilter_decim, #decimation
self.audiotaps, #taps
0, #freq offset
self.rate) #sampling rate
#on a trunked network where you know you will have good signal, a carrier power squelch works well. real FM receviers use a noise squelch, where
#the received audio is high-passed above the cutoff and then fed to a reverse squelch. If the power is then BELOW a threshold, open the squelch.
self.squelch = gr.pwr_squelch_cc(options.squelch, #squelch point
alpha = 0.1, #wat
ramp = 10, #wat
gate = False)
self.audiodemod = blks2.fm_demod_cf(self.rate/self.prefilter_decim, #rate
1, #audio decimation
4000, #deviation
3000, #audio passband
4000, #audio stopband
1, #gain
75e-6) #deemphasis constant
#the filtering removes FSK data woobling from the subaudible channel (might be able to combine w/lpf above)
self.audiofilttaps = gr.firdes.high_pass(1, self.audiorate, 300, 50, gr.firdes.WIN_HANN)
self.audiofilt = gr.fir_filter_fff(1, self.audiofilttaps)
self.audiogain = gr.multiply_const_ff(options.volume)
self.audiosink = audio.sink (self.audiorate, "")
# self.audiosink = gr.wavfile_sink("test.wav", 1, self.audiorate, 8)
self.mute()
if options.filename is None:
self.connect(self.u, self.audio_prefilter)
else:
self.connect(self.fs, self.audio_prefilter)
# self.connect(self.audio_prefilter, self.squelch, self.audiodemod, self.audiofilt, self.audiogain, self.audioresamp, self.audiosink)
self.connect(self.audio_prefilter, self.squelch, self.audiodemod, self.audiofilt, self.audiogain, self.audiosink)
###########SUBCHANNEL DECODING EXPERIMENT###########
#here we set up the low-pass filter for audio subchannel data decoding. gain of 10, decimation of 10.
# self.subchannel_decimation = 50
# self.subchannel_gain = 10
# self.subchannelfilttaps = gr.firdes.low_pass(self.subchannel_gain, self.audiorate, 200, 40, firdes.WIN_HANN)
# self.subchannelfilt = gr.fir_filter_fff(self.subchannel_decimation, self.subchannelfilttaps)
# self.subchannel_syms_per_sec = 150
# self.subchannel_samples_per_symbol = (self.audiorate / self.subchannel_decimation) / self.subchannel_syms_per_sec
# print "Subchannel samples per symbol: %f" % self.subchannel_samples_per_symbol
# self.subchannel_clockrec = gr.clock_recovery_mm_ff(self.subchannel_samples_per_symbol,
# 0.25*0.01*0.01,
# 0.5,
# 0.01,
# 0.3)
# self.subchannel_slicer = gr.binary_slicer_fb()
# self.subchannel_correlator = gr.correlate_access_code_bb("01000",0)
# self.subchannel_framer = smartnet.subchannel_framer()
# self.subchannel_sink = gr.null_sink(1); #just so it doesn't bitch until we do something with it
# self.connect(self.audiodemod, self.subchannelfilt, self.subchannel_clockrec, self.subchannel_slicer, self.subchannel_correlator, self.subchannel_framer, self.subchannel_sink)
def tune(self, freq):
result = self.u.set_center_freq(freq)
return True
def tuneoffset(self, target_freq, rffreq):
#print "Setting offset; target freq is %f, Center freq is %f" % (target_freq, rffreq)
self.audio_prefilter.set_center_freq(rffreq-target_freq*1e6)
def setvolume(self, vol):
self.audiogain.set_k(vol)
def mute(self):
self.setvolume(0)
def unmute(self, volume):
self.setvolume(volume)
def getfreq(chanlist, cmd):
if chanlist is None:
if cmd < 0x2d0:
freq = float(cmd * 0.025 + 851.0125)
else:
freq = None
else:
if chanlist.get(str(cmd), None) is not None:
freq = float(chanlist[str(cmd)])
else:
freq = None
return freq
def parsefreq(s, chanlist):
retfreq = None
[address, groupflag, command] = s.split(",")
command = int(command)
address = int(address) & 0xFFF0
groupflag = bool(groupflag)
if chanlist is None:
if command < 0x2d0:
retfreq = getfreq(chanlist, command)
else:
if chanlist.get(str(command), None) is not None: #if it falls into the channel somewhere
retfreq = getfreq(chanlist, command)
return [retfreq, address] # mask so the squelch opens up on the entire group
def parse(s, shorttglist, longtglist, chanlist, elimdupes):
#this is the main parser. it takes in commands in the form "address,command" (no quotes of course) and outputs text via print
#it is also responsible for using the talkgroup list, if any
[address, groupflag, command] = s.split(",")
command = int(command)
address = int(address)
lookupaddr = address & 0xFFF0
groupflag = bool(groupflag)
# print "Command is",command
if longtglist is not None and longtglist.get(str(lookupaddr), None) is not None:
longname = longtglist[str(lookupaddr)] #the mask is to screen out extra status bits, which we can add in later (see the RadioReference.com wiki on SmartNet Type II)
else:
longname = None
if shorttglist is not None and shorttglist.get(str(lookupaddr), None) is not None:
shortname = shorttglist[str(lookupaddr)]
else:
shortname = None
retval = None
if command == 0x30B and groupflag is True and lastmsg.get("command", None) == 0x308 and address & 0x2000 and address & 0x0800:
retval = "SysID: Sys #" + hex(lastmsg["address"]) + " on " + str(getfreq(chanlist, address & 0x3FF))
else:
if getfreq(chanlist, command) is not None and dupes.get(command, None) != address:
retval = "Freq assignment: " + str(shortname) + " (" + str(address) + ")" + " @ " + str(getfreq(chanlist, command)) + " (" + str(longname) + ")"
if elimdupes is True:
dupes[command] = address
lastlastmsg = lastmsg
lastmsg["command"]=command
lastmsg["address"]=address
return retval
def main():
# Create Options Parser:
parser = OptionParser (option_class=eng_option, conflict_handler="resolve")
expert_grp = parser.add_option_group("Expert")
parser.add_option("-f", "--freq", type="eng_float", default=866.9625e6,
help="set control channel frequency to MHz [default=%default]", metavar="FREQ")
parser.add_option("-c", "--centerfreq", type="eng_float", default=867.5e6,
help="set center receive frequency to MHz [default=%default]. Set to center of 800MHz band for best results")
parser.add_option("-g", "--gain", type="int", default=None,
help="set RF gain", metavar="dB")
parser.add_option("-b", "--bandwidth", type="eng_float", default=3e6,
help="set bandwidth of DBS RX frond end [default=%default]")
parser.add_option("-F", "--filename", type="string", default=None,
help="read data from filename rather than USRP")
parser.add_option("-t", "--tgfile", type="string", default="sf_talkgroups.csv",
help="read in CSV-formatted talkgroup list for pretty printing of talkgroup names")
parser.add_option("-C", "--chanlistfile", type="string", default="motochan14.csv",
help="read in list of Motorola channel frequencies (improves accuracy of frequency decoding) [default=%default]")
parser.add_option("-e", "--allowdupes", action="store_false", default=True,
help="do not eliminate duplicate records (produces lots of noise)")
parser.add_option("-E", "--error", type="eng_float", default=0,
help="enter an offset error to compensate for USRP clock inaccuracy")
parser.add_option("-u", "--audio", action="store_true", default=False,
help="output audio on speaker")
parser.add_option("-m", "--monitor", type="int", default=None,
help="monitor a specific talkgroup")
parser.add_option("-v", "--volume", type="eng_float", default=0.2,
help="set volume gain for audio output [default=%default]")
parser.add_option("-s", "--squelch", type="eng_float", default=28,
help="set audio squelch level (default=%default, play with it)")
parser.add_option("-s", "--subdev", type="string",
help="UHD subdev spec", default=None)
parser.add_option("-A", "--antenna", type="string", default=None,
help="select Rx Antenna where appropriate")
parser.add_option("-r", "--rate", type="eng_float", default=64e6/18,
help="set sample rate [default=%default]")
parser.add_option("-a", "--addr", type="string", default="",
help="address options to pass to UHD")
#receive_path.add_options(parser, expert_grp)
(options, args) = parser.parse_args ()
if len(args) != 0:
parser.print_help(sys.stderr)
sys.exit(1)
if options.tgfile is not None:
tgreader=csv.DictReader(open(options.tgfile), quotechar='"')
shorttglist = {"0": 0}
longtglist = {"0": 0}
for record in tgreader:
# print record['tgnum']
shorttglist[record['tgnum']] = record['shortname']
longtglist[record['tgnum']] = record['longname']
else:
shorttglist = None
longtglist = None
if options.chanlistfile is not None:
clreader=csv.DictReader(open(options.chanlistfile), quotechar='"')
chanlist={"0": 0}
for record in clreader:
chanlist[record['channel']] = record['frequency']
else:
chanlist = None
# build the graph
queue = gr.msg_queue(10)
tb = my_top_block(options, queue)
runner = top_block_runner(tb)
global dupes
dupes = {0: 0}
global lastmsg
lastmsg = {"command": 0x0000, "address": 0x0000}
global lastlastmsg
lastlastmsg = lastmsg
currentoffset = 0
updaterate = 10
#tb.setvolume(options.volume)
#tb.mute()
try:
while 1:
if not queue.empty_p():
msg = queue.delete_head() # Blocking read
sentence = msg.to_string()
s = parse(sentence, shorttglist, longtglist, chanlist, options.allowdupes)
if s is not None:
print s
if options.audio:
[newfreq, newaddr] = parsefreq(sentence, chanlist)
if newfreq == currentoffset and newaddr != (options.monitor & 0xFFF0):
tb.mute()
if newaddr == (options.monitor & 0xFFF0): #the mask is to allow listening to all "flags" within a talkgroup: emergency, broadcast, etc.
tb.unmute(options.volume)
if newfreq is not None and newfreq != currentoffset:
print "Changing freq to %f" % newfreq
currentoffset = newfreq
tb.tuneoffset(newfreq, options.centerfreq)
elif runner.done:
break
else:
time.sleep(1.0/updaterate)
# tb.run()
except KeyboardInterrupt:
tb.stop()
runner = None
if __name__ == '__main__':
main()
| bistromath/gr-smartnet | src/python/smartnet2decode.py | Python | gpl-3.0 | 13,591 |
/*
* Copyright (c) 2014 Washington State Department of Transportation
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*
*/
package gov.wa.wsdot.mobile.client.activities.trafficmap.expresslanes;
import gov.wa.wsdot.mobile.shared.ExpressLaneItem;
import java.util.List;
import com.google.gwt.user.client.ui.IsWidget;
import com.googlecode.mgwt.ui.client.widget.base.HasRefresh;
import com.googlecode.mgwt.ui.client.widget.panel.pull.PullArrowWidget;
import com.googlecode.mgwt.ui.client.widget.panel.pull.PullPanel.Pullhandler;
public interface SeattleExpressLanesView extends IsWidget {
public void setPresenter(Presenter presenter);
public interface Presenter {
public void onDoneButtonPressed();
}
public void render(List<ExpressLaneItem> createPostList);
public void showProgressIndicator();
public void hideProgressIndicator();
public void refresh();
public void setHeaderPullHandler(Pullhandler pullHandler);
public PullArrowWidget getPullHeader();
public HasRefresh getPullPanel();
}
| chrxn/wsdot-mobile-app | src/main/java/gov/wa/wsdot/mobile/client/activities/trafficmap/expresslanes/SeattleExpressLanesView.java | Java | gpl-3.0 | 1,634 |
/**
*
*/
package org.javahispano.javaleague.client.event;
import org.javahispano.javaleague.shared.domain.TacticUser;
import com.google.gwt.event.shared.GwtEvent;
/**
* @author adou
*
*/
public class UpdateTacticEvent extends GwtEvent<UpdateTacticEventHandler> {
public static Type<UpdateTacticEventHandler> TYPE = new Type<UpdateTacticEventHandler>();
private final TacticUser userTactic;
public UpdateTacticEvent(TacticUser result) {
this.userTactic = result;
}
@Override
public com.google.gwt.event.shared.GwtEvent.Type<UpdateTacticEventHandler> getAssociatedType() {
return TYPE;
}
@Override
protected void dispatch(UpdateTacticEventHandler handler) {
handler.onUpdateTactic(this);
}
}
| alfonsodou/javaLeagueBootstrap | src/org/javahispano/javaleague/client/event/UpdateTacticEvent.java | Java | gpl-3.0 | 721 |
/*
* HawkEye Redux
* Copyright (C) 2012-2013 Cubeville <http://www.cubeville.org> and contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.cubeville.hawkeye.config;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Configuration implementation backed by a nested map
*/
public class ConfigurationNode implements Configuration {
protected Map<String, Object> root;
private boolean writeDefaults;
public ConfigurationNode(Map<String, Object> root) {
this(root, false);
}
public ConfigurationNode(Map<String, Object> root, boolean writeDefaults) {
this.root = root;
this.writeDefaults = writeDefaults;
}
/**
* Gets the configuration's backing map
*
* @return Map of keys and values
*/
public Map<String, Object> getRoot() {
return root;
}
@Override
public void clear() {
root.clear();
}
@SuppressWarnings("unchecked")
@Override
public Object get(String node) {
// Process dot notation
String[] path = node.split("\\.");
Object val = null;
Map<String, Object> tmp = root;
// Loop through map to get nested values
for (int i = 0; i < path.length; i++) {
val = tmp.get(path[i]);
// Path doesn't exist
if (val == null) return null;
// Last piece of path
if (i == path.length - 1) break;
try {
// Get next level of nested map
tmp = (Map<String, Object>) val;
} catch (ClassCastException ex) {
// Nested map doesn't exist
return null;
}
}
return val;
}
@Override
public Object get(String path, Object def) {
Object val = get(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@SuppressWarnings("unchecked")
@Override
public void set(String node, Object value) {
// Process dot notation
String[] path = node.split("\\.");
Map<String, Object> tmp = root;
for (int i = 0; i < path.length; i++) {
// Last level of nesting reached
if (i == path.length - 1) {
tmp.put(path[i], value);
return;
}
Object val = tmp.get(path[i]);
if (val == null || !(val instanceof Map)) {
// Create a map if it isn't already there
val = new HashMap<String, Object>();
tmp.put(path[i], val);
}
tmp = (Map<String, Object>) val;
}
}
@Override
public String getString(String path) {
Object val = get(path);
return val == null ? null : val.toString();
}
@Override
public String getString(String path, String def) {
String val = getString(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public Integer getInt(String path) {
Object val = get(path);
if (val instanceof Number) {
return ((Number) val).intValue();
} else {
return null;
}
}
@Override
public int getInt(String path, int def) {
Integer val = getInt(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public Double getDouble(String path) {
Object val = get(path);
if (val instanceof Number) {
return ((Number) val).doubleValue();
} else {
return null;
}
}
@Override
public double getDouble(String path, double def) {
Double val = getDouble(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public Boolean getBoolean(String path) {
Object val = get(path);
if (val instanceof Boolean) {
return (Boolean) val;
} else {
return null;
}
}
@Override
public boolean getBoolean(String path, boolean def) {
Boolean val = getBoolean(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public List<String> getStringList(String path) {
Object val = get(path);
List<String> list = new ArrayList<String>();
if (!(val instanceof List)) {
return list;
}
@SuppressWarnings("unchecked")
List<Object> raw = (List<Object>) val;
for (Object obj : raw) {
if (obj != null) list.add(obj.toString());
}
return list;
}
@Override
public List<String> getStringList(String path, List<String> def) {
List<String> val = getStringList(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public List<Integer> getIntList(String path) {
Object val = get(path);
List<Integer> list = new ArrayList<Integer>();
if (!(val instanceof List)) {
return list;
}
@SuppressWarnings("unchecked")
List<Object> raw = (List<Object>) val;
for (Object obj : raw) {
if (obj instanceof Number) list.add(((Number) obj).intValue());
}
return list;
}
@Override
public List<Integer> getIntList(String path, List<Integer> def) {
List<Integer> val = getIntList(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public List<Double> getDoubleList(String path) {
Object val = get(path);
List<Double> list = new ArrayList<Double>();
if (!(val instanceof List)) {
return list;
}
@SuppressWarnings("unchecked")
List<Object> raw = (List<Object>) val;
for (Object obj : raw) {
if (obj instanceof Number) list.add(((Number) obj).doubleValue());
}
return list;
}
@Override
public List<Double> getDoubleList(String path, List<Double> def) {
List<Double> val = getDoubleList(path);
if (val == null) {
if (writeDefaults) set(path, def);
val = def;
}
return val;
}
@Override
public boolean writeDefaults() {
return writeDefaults;
}
@Override
public void setWriteDefaults(boolean writeDefaults) {
this.writeDefaults = writeDefaults;
}
@Override public Object get(Variable path) { return get(path.getPath()); }
@Override public Object get(Variable path, Object def) { return get(path.getPath(), def); }
@Override public void set(Variable path, Object value) { set(path.getPath(), value); }
@Override public String getString(Variable path) { return getString(path.getPath()); }
@Override public String getString(Variable path, String def) { return getString(path.getPath(), def); }
@Override public Integer getInt(Variable path) { return getInt(path.getPath()); }
@Override public int getInt(Variable path, int def) { return getInt(path.getPath(), def); }
@Override public Double getDouble(Variable path) { return getDouble(path.getPath()); }
@Override public double getDouble(Variable path, double def) { return getDouble(path.getPath(), def); }
@Override public Boolean getBoolean(Variable path) { return getBoolean(path.getPath()); }
@Override public boolean getBoolean(Variable path, boolean def) { return getBoolean(path.getPath(), def); }
@Override public List<String> getStringList(Variable path) { return getStringList(path.getPath()); }
@Override public List<String> getStringList(Variable path, List<String> def) { return getStringList(path.getPath(), def); }
@Override public List<Integer> getIntList(Variable path) { return getIntList(path.getPath()); }
@Override public List<Integer> getIntList(Variable path, List<Integer> def) { return getIntList(path.getPath(), def); }
@Override public List<Double> getDoubleList(Variable path) { return getDoubleList(path.getPath()); }
@Override public List<Double> getDoubleList(Variable path, List<Double> def) { return getDoubleList(path.getPath(), def); }
}
| Cubeville/HawkEye-Redux | api/src/main/java/org/cubeville/hawkeye/config/ConfigurationNode.java | Java | gpl-3.0 | 7,970 |
# frozen_string_literal: true
FactoryBot.define do
factory :suite do
sequence(:number) { |n| "S#{n}" }
building
factory :suite_with_rooms do
transient do
rooms_count 1
end
after(:create) do |suite, e|
create_list(:single, e.rooms_count, suite: suite)
end
end
end
end
| YaleSTC/vesta | spec/factories/suites.rb | Ruby | gpl-3.0 | 330 |
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* TestSetEvent.java
* Copyright (C) 2002 Mark Hall
*
*/
package weka.gui.beans;
import java.util.EventObject;
import weka.core.Instances;
/**
* Event encapsulating a test set
*
* @author <a href="mailto:mhall@cs.waikato.ac.nz">Mark Hall</a>
* @version $Revision: 1.2 $
*/
public class TestSetEvent extends EventObject {
/**
* The test set instances
*/
protected Instances m_testSet;
private boolean m_structureOnly;
/**
* what number is this test set (ie fold 2 of 10 folds)
*/
protected int m_setNumber;
/**
* Maximum number of sets (ie 10 in a 10 fold)
*/
protected int m_maxSetNumber;
public TestSetEvent(Object source, Instances testSet) {
super(source);
m_testSet = testSet;
if (m_testSet != null && m_testSet.numInstances() == 0) {
m_structureOnly = true;
}
}
/**
* Get the test set instances
*
* @return an <code>Instances</code> value
*/
public Instances getTestSet() {
return m_testSet;
}
/**
* Get the test set number (eg. fold 2 of a 10 fold split)
*
* @return an <code>int</code> value
*/
public int getSetNumber() {
return m_setNumber;
}
/**
* Get the maximum set number
*
* @return an <code>int</code> value
*/
public int getMaxSetNumber() {
return m_maxSetNumber;
}
/**
* Returns true if the encapsulated instances
* contain just header information
*
* @return true if only header information is
* available in this DataSetEvent
*/
public boolean isStructureOnly() {
return m_structureOnly;
}
}
| paolopavan/cfr | src/weka/gui/BEANS/TestSetEvent.java | Java | gpl-3.0 | 2,331 |
<?php
/*
Copyright 2012 the app framework - slattman@gmail.com
This file is part of the app framework.
The app framework 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.
The app framework 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 the app framework. If not, see <http://www.gnu.org/licenses/>.
*/
/* start the session */
session_start();
/* load the configuration file */
require_once('../app/config.php');
/* instantiate the framework */
$app = new app();
/* shall we? */
class app {
function __construct($initialized = false) {
if (!$initialized) {
$this->initialize();
}
}
function app() {
global $app;
return $app;
}
private function initialize() {
$this->bind($_REQUEST, 'request');
$this->bind($_SESSION, 'session');
$method = isset($this->request->app) ? (string)$this->request->app : false;
if ($method and method_exists(__CLASS__, $method)) {
call_user_func_array(array($this, $method), array());
}
$this->load('core');
$this->load('controllers');
$this->load('models');
$this->load('plugins');
}
private function load($type = false) {
if ($type) {
$dir = '../app/' . $type . '/';
if (is_dir($dir)) {
if ($dh = opendir($dir)) {
while (($file = readdir($dh)) !== false) {
if (file_exists($dir.$file) and strstr($file, '.php') and substr_count($file, '.') == 2) {
$class = explode('.', $file);
$class = $class[0];
require_once($dir . $file);
if (in_array($class, get_declared_classes())) {
if ($type == 'core') {
$this->$class = new $class();
} else {
$this->$type->$class = new $class();
}
}
}
}
closedir($dh);
}
}
}
}
function bind($array = array(), $key = false) {
$object = new stdClass();
if (count($array)) {
foreach ($array as $k => $v) {
if (is_array($v)) {
$object->$k = $this->bind($v);
} else {
$object->$k = $v;
}
}
}
if ($key) {
$this->$key = (object)$object;
} else {
return (object)$object;
}
}
function view() {
global $routes;
$view = isset($this->request->app) ? $this->request->app : 'index';
if (array_key_exists($view, $routes)) {
$route = $routes[$view];
if (class_exists($route['controller'])) {
if (method_exists($this->app()->controllers->$route['controller'], $route['method'])) {
$method = new ReflectionMethod($route['controller'], $route['method']);
if (isset($route['args'])) {
if (!is_array($route['args'])) {
$route['args'] = array($route['args']);
}
$method->invokeArgs($this->app()->controllers->$route['controller'], $route['args']);
} else {
$method->invoke($this->app()->controllers->$route['controller']);
}
if ($route['view'] !== true) {
return;
}
}
}
}
if (file_exists('../app/views/' . $view . '.html')) {
require_once('../app/views/' . $view . '.html');
} elseif (is_dir('../app/views/' . $view) and file_exists('../app/views/' . $view . '/index.html')) {
require_once('../app/views/' . $view . '/index.html');
} else {
$this->go(ERROR_PAGE);
}
}
function set($key = false, $value = false) {
if ($key) {
$_SESSION[$key] = $value;
$this->bind($_SESSION, 'session');
}
}
function go($page = false) {
if ($page) {
header("Location: " . BASE_URL . $page);
exit;
}
}
function current_view() {
return isset($this->request->app) ? $this->request->app : 'index';
}
function error($error) {
die(htmlspecialchars($error));
}
function debug($die = false) {
echo "<pre>";
print_r($this);
echo "</pre>";
if ($die) die;
}
function shutdown() {
unset($app);
unset($this);
}
}
?> | slattman/app | app/app.php | PHP | gpl-3.0 | 4,152 |
/***************************************************************************
$Id: KVBase.cpp,v 1.57 2009/04/22 09:38:39 franklan Exp $
kvbase.cpp - description
-------------------
begin : Thu May 16 2002
copyright : (C) 2002 by J.D. Frankland
email : frankland@ganil.fr
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <cassert>
#include "Riostream.h"
#include "TMath.h"
#include "TFile.h"
#include "KVBase.h"
#include "TClass.h"
#include "KVString.h"
#include "TSystem.h"
#include "TInterpreter.h"
#include "TEnv.h"
#include "TPluginManager.h"
#include "KVNameValueList.h"
#include "TSystemDirectory.h"
#include "KVVersion.h"
#ifdef WITH_BZR_INFOS
#include "KVBzrInfo.h"
#endif
#ifdef WITH_GIT_INFOS
#include "KVGitInfo.h"
#endif
#include "TROOT.h"
#include "TDatime.h"
#include "THashList.h"
#include "TError.h"
#include "TGMimeTypes.h"
#include "TGClient.h"
#include "TContextMenu.h"
#include <TKey.h>
#include "TTree.h"
#ifdef WITH_GRULIB
#include "GNetClientRoot.h"
#endif
using namespace std;
ClassImp(KVBase)
////////////////////////////////////////////////////////////////////////////////
// BEGIN_HTML <!--
/* -->
<h2>KVBase</h2>
<h4>Base class for KaliVeda framework</h4>
This is the base class for many classes in the KaliVeda framework. Each
KVBase object has<br>
<ul>
<li>a name - Get/SetName()</li>
<li>a type - Get/SetType()</li>
<li>a number - Get/SetNumber()</li>
<li>a label - Get/SetLabel()<br>
</li>
</ul>
When objects are accessed through a TObject/TNamed base pointer, it is possible
to test whether an object is derived from KVBase, using the bit KVBase::kIsKaliVedaObject:
<code>
TObject* ob = (address of some object)
if( ob->TestBit( KVBase::kIsKaliVedaObject ) ){
</code>
This class also provides a number of general utilities, often as static
(stand-alone) methods.<br>
<h3>KaliVeda build/installation information</h3>
The static methods<br>
<pre>KVBase::GetKVSourceDir()<br>KVBase::GetKVBuildDate()<br>KVBase::GetKVBuildUser()<br></pre>
give info on the sources, when and where they were built, and by whom.<br>
The static methods<br>
<pre>KVBase::GetKVVersion()<br>KVBase::GetKVRoot()<br>KVBase::GetKVRootDir()<br>KVBase::GetKVBinDir()<br>KVBase::GetKVFilesDir()<br></pre>
give info on the version of KaliVeda, the environment variable $KVROOT,
and the paths to the installation directories.<br>
<h3>Initialisation</h3>
The entire KaliVeda framework is initialised by the static method<br>
<pre>KVBase::InitEnvironment()<br></pre>
<h3>Finding/opening files</h3>
Static methods for easily locating and/or opening files within the
KaliVeda installation tree (under $KVROOT) are given:<br>
<pre>KVBase::SearchKVFile(...)<br>KVBase::SearchAndOpenKVFile(...)<br></pre>
Note that in the second case, two methods exist: one for reading, the
other for writing the (ascii) files. A global function for searching
files is also defined:<br>
<pre>Bool_t SearchFile(const Char_t* name, TString& fullpath, int ndirs, ...)<br></pre>
This will search for a
file in an arbitrary number of locations, return kTRUE if file is found
and put full path to file in 'fullpath':<br>
<ul>
<li> 'name' is a filename (not an absolute pathname) i.e. "toto.dat"</li>
<li> 'fullpath' will contain the full path to the
file if it is found (if file not found, fullpath="")</li>
<li> 'ndirs' is the number of directories to
search in<br>
</li>
</ul>
The remaining arguments are the names of 'ndirs' paths to search in,
i.e.<br>
<pre>SearchFile("toto.dat", fullpath, 2, gSystem->pwd(), gSystem->HomeDirectory());</pre>
means: search for a file 'toto.dat' in current working directory, then
user's home directory.<br>
<pre>SearchFile("toto.dat", fullpath, 3, KVBase::GetKVFilesDir(), KVBase::GetKVRootDir(), gRootDir);</pre>
means: search for a file 'toto.dat' in $KVROOT/KVFiles, in $KVROOT, and
finally in $ROOTSYS.<br>
<h3>Finding class source files</h3>
Source files for a class can be found using static method<br>
<pre>KVBase::FindClassSourceFiles(...)<br></pre>
It will look for appropriately-named files corresponding to the header
& implementation file of a class, testing several popular suffixes
in each case.<br>
<h3>Finding executables</h3>
To find an executable in the current user's 'PATH' (or elsewhere), use
static method<br>
<pre>KVBase::FindExecutable(...)<br></pre>
<h3>Temporary files</h3>
The static methods<br>
<pre>KVBase::GetTempFileName(...)<br>KVBase::OpenTempFile(...)<br></pre>
can generate and handle uniquely-named temporary (ascii) files.<br>
<h3>Backing-up files</h3>
The static method<br>
<pre>KVBase::BackupFileWithDate(...)<br></pre>
can be used to create a dated backup of an existing file before it is
replaced with a new version.<br>
<h3>Handling plugins</h3>
As plugins are extensively used in the KaliVeda framework, a few
utilities for handling them are defined. They are static methods<br>
<pre>KVBase::LoadPlugin(...)<br>KVBase::GetPluginURI(...)<br></pre>
<!-- */
// --> END_HTML
////////////////////////////////////////////////////////////////////////////////
#define xstr(s) str(s)
#define str(s) #s
UInt_t KVBase::fNbObj = 0;
TString KVBase::fWorkingDirectory = "$(HOME)/.kaliveda";
Bool_t KVBase::fEnvIsInit = kFALSE;
const Char_t* KVBase::GetETCDIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", xstr(ETCDIR), namefile);
return Form("%s", xstr(ETCDIR));
}
const Char_t* KVBase::GetDATADIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", xstr(DATADIR), namefile);
return Form("%s", xstr(DATADIR));
}
const Char_t* KVBase::GetTEMPLATEDIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", xstr(TEMPLATEDIR), namefile);
return Form("%s", xstr(TEMPLATEDIR));
}
const Char_t* KVBase::GetDATABASEFilePath()
{
return Form("%s/db", fWorkingDirectory.Data());
}
const Char_t* KVBase::GetLIBDIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", xstr(LIBDIR), namefile);
return Form("%s", xstr(LIBDIR));
}
const Char_t* KVBase::GetINCDIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", xstr(INCDIR), namefile);
return Form("%s", xstr(INCDIR));
}
const Char_t* KVBase::GetBINDIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", xstr(BINDIR), namefile);
return Form("%s", xstr(BINDIR));
}
const Char_t* KVBase::GetWORKDIRFilePath(const Char_t* namefile)
{
if (strcmp(namefile, "")) return Form("%s/%s", fWorkingDirectory.Data(), namefile);
return fWorkingDirectory;
}
//_______________
void KVBase::init()
{
//Default initialisation
InitEnvironment();
fNumber = 0;
fNbObj++;
fLabel = "";
SetBit(kIsKaliVedaObject);
}
void KVBase::InitEnvironment()
{
// STATIC method to Initialise KaliVeda environment
// Reads config files in $(pkgdatadir)/etc and sets up environment
// (data repositories, datasets, etc. etc.)
// Adds directory where kaliveda shared libs are installed to the dynamic
// path - for finding and loading plugins (even those which are in libkaliveda.so)
// Resets the gRandom random number sequence using a clock-based seed
// (i.e. random sequences do not repeat).
#ifdef WITH_GNU_INSTALL
// Sets location of user's working directory which is by default
// $(HOME)/.kaliveda
// but can be changed with variable
// KaliVeda.WorkingDirectory: [directory]
// in configuration file. [directory] must be an absolute pathname,
// can use shell variables like $(HOME).
//
#endif
// Normally, the first object created which inherits from KVBase will
// perform this initialisation; if you need to set up the environment before
// creating a KVBase object, or if you just want to be absolutely sure that
// the environment has been initialised, you can call this method.
if (!fEnvIsInit) {//test if environment already initialised
// Add path to kaliveda libraries to dynamic loader path
// This is needed to find plugins
// and also to be able to compile with kaliveda in the interpreter
TString libdir = GetLIBDIRFilePath();
gSystem->AddDynamicPath(libdir);
// force re-reading of rootmap files in new dynamic path
gInterpreter->LoadLibraryMap();
// Add path to kaliveda header files
// This is needed to be able to compile with kaliveda in the interpreter
TString incdir = GetINCDIRFilePath();
incdir.Prepend("-I");
gSystem->AddIncludePath(incdir);
//set up environment using kvrootrc file
if (!gEnv->Defined("DataSet.DatabaseFile")) {
ReadConfigFiles();
}
#ifdef WITH_GNU_INSTALL
// set working directory & create if needed
fWorkingDirectory = gEnv->GetValue("KaliVeda.WorkingDirectory", "$(HOME)/.kaliveda");
gSystem->ExpandPathName(fWorkingDirectory);
gSystem->mkdir(fWorkingDirectory, kTRUE);
#else
// set environment variable used in database makefiles
fWorkingDirectory = KV_ROOT;
#endif
// set environment variable used in database makefiles
gSystem->Setenv("KV_WORK_DIR", fWorkingDirectory);
//generate new seed from system clock
gRandom->SetSeed(0);
// initialisation has been performed
fEnvIsInit = kTRUE;
}
}
void KVBase::ReadConfigFiles()
{
// Read all configuration files
// System config files are read first in the order they appear in file
// ${ETCDIR}/config.files
// Then we read any of the following files if they exist:
// ${HOME}/.kvrootrc
// ${PWD}/.kvrootrc
TString tmp = GetETCDIRFilePath("config.files");
ifstream conflist;
conflist.open(tmp.Data());
if (!conflist.good()) {
::Fatal("KVBase::ReadConfigFiles", "Cannot open %s", tmp.Data());
return;
}
KVString file;
file.ReadLine(conflist);
conflist.close();
file.Begin(";");
while (!file.End()) {
tmp = GetETCDIRFilePath(file.Next().Data());
//skip over any missing files - this is needed when installing from
//e.g. ubuntu packages if not all packages are installed
if (!gSystem->AccessPathName(tmp.Data())) gEnv->ReadFile(tmp.Data(), kEnvChange);
}
AssignAndDelete(tmp, gSystem->ConcatFileName(gSystem->Getenv("HOME"), ".kvrootrc"));
gEnv->ReadFile(tmp.Data(), kEnvChange);
tmp = "./.kvrootrc";
gEnv->ReadFile(tmp.Data(), kEnvChange);
// load plugin handlers
gROOT->GetPluginManager()->LoadHandlersFromEnv(gEnv);
// load mime types/icon definitions when not in batch (i.e. GUI-less) mode
if (!gROOT->IsBatch()) ReadGUIMimeTypes();
}
//_______________________________________________________________________________
KVBase::KVBase()
{
//Default constructor.
init();
}
//_______________________________________________________________________________
KVBase::KVBase(const Char_t* name, const Char_t* type): TNamed(name, type)
{
//Ctor for object with given name and type.
init();
}
//______________________
KVBase::KVBase(const KVBase& obj) : TNamed()
{
//copy ctor
init();
#if ROOT_VERSION_CODE >= ROOT_VERSION(3,4,0)
obj.Copy(*this);
#else
((KVBase&) obj).Copy(*this);
#endif
}
//_______________________________________________________________________________
KVBase::~KVBase()
{
fNbObj--;
}
//_______________________________________________________________________________
void KVBase::Clear(Option_t* opt)
{
//Clear object properties : name, type/title, number, label
TNamed::Clear(opt);
fNumber = 0;
fLabel = "";
}
//___________________________________________________________________________________
#if ROOT_VERSION_CODE >= ROOT_VERSION(3,4,0)
void KVBase::Copy(TObject& obj) const
#else
void KVBase::Copy(TObject& obj)
#endif
{
//Copy this to obj
//Redefinition of TObject::Copy
TNamed::Copy(obj);
((KVBase&) obj).SetNumber(fNumber);
((KVBase&) obj).SetLabel(fLabel);
}
//____________________________________________________________________________________
void KVBase::Print(Option_t*) const
{
cout << "KVBase object: Name=" << GetName() << " Type=" << GetType();
if (fLabel != "")
cout << " Label=" << GetLabel();
if (fNumber != 0)
cout << " Number=" << GetNumber();
cout << endl;
}
void KVBase::Streamer(TBuffer& R__b)
{
//Backwards compatible streamer for KVBase objects
//Needed to handle 'fLabel' char array in class version 1
//Objects written with version < 3 did not have kIsKaliVedaObject bit set,
//we set it here when reading object.
if (R__b.IsReading()) {
UInt_t R__s, R__c;
Version_t R__v = R__b.ReadVersion(&R__s, &R__c);
if (R__v > 1) {
if (R__v < 4) {
TNamed::Streamer(R__b);
R__b >> fNumber;
R__b >> fLabel;
if (R__v < 3) SetBit(kIsKaliVedaObject);
R__b.CheckByteCount(R__s, R__c, KVBase::IsA());
} else {
//AUTOMATIC STREAMER EVOLUTION FOR CLASS VERSION > 3
KVBase::Class()->ReadBuffer(R__b, this, R__v, R__s, R__c);
}
return;
}
//OLD STREAMER FOR CLASS VERSION 1
TNamed::Streamer(R__b);
R__b >> fNumber;
UInt_t LabelLength;
R__b >> LabelLength;
if (LabelLength) {
Char_t* Label = new Char_t[LabelLength];
R__b.ReadFastArray(Label, LabelLength);
fLabel = Label;
delete[]Label;
}
SetBit(kIsKaliVedaObject);
R__b.CheckByteCount(R__s, R__c, KVBase::IsA());
} else {
KVBase::Class()->WriteBuffer(R__b, this);
}
}
//________________________________________________________________________________//
Bool_t SearchFile(const Char_t* name, TString& fullpath, int ndirs, ...)
{
//Search for file in an arbitrary number of locations, return kTRUE if file found and put full path to file in 'fullpath"
//
//'name' is a filename (not an absolute pathname) i.e. "toto.dat"
//'fullpath" will contain the full path to the file if it is found (if file not found, fullpath="")
//'ndirs" is the number of directories to search in
//the remaining arguments are the names of 'ndirs' paths to search in, i.e.
//
// SearchFile("toto.dat", fullpath, 2, gSystem->pwd(), gSystem->HomeDirectory());
//
//means: search for a file 'toto.dat' in current working directory, then user's home directory.
if (ndirs <= 0)
return kFALSE;
va_list args;
va_start(args, ndirs);
for (; ndirs; ndirs--) { //loop over directories
AssignAndDelete(fullpath,
gSystem->ConcatFileName(va_arg(args, const char*),
name));
if (!gSystem->AccessPathName(fullpath.Data())) {
va_end(args);
return kTRUE;
}
}
va_end(args);
fullpath = ""; //clear fullpath string to avoid using it by mistake
return kFALSE;
}
Bool_t KVBase::SearchKVFile(const Char_t* name, TString& fullpath,
const Char_t* kvsubdir)
{
//search for files in the following order:
// if 'name' = absolute path the function returns kTRUE if the file exists
// if name != absolute path:
// 1. a. if 'kvsubdir'="" (default) look for file in $(pkgdatadir) directory
// 1. b. if 'kvsubdir'!="" look for file in $(pkgdatadir)/'kvsubdir'
// 2. look for file with this name in user's home directory
// 3. look for file with this name in working directory
//in all cases the function returns kTRUE if the file was found.
//'fullpath' then contains the absolute path to the file
if (gSystem->IsAbsoluteFileName(name)) {
//absolute path
fullpath = name;
return !gSystem->AccessPathName(name);
}
TString kvfile_dir;
if (strcmp(kvsubdir, "")) {
//subdirectory name given
kvfile_dir = GetDATADIRFilePath(kvsubdir);
} else
kvfile_dir = GetDATADIRFilePath();
return SearchFile(name, fullpath, 3, kvfile_dir.Data(),
gSystem->HomeDirectory(), gSystem->pwd());
}
//________________________________________________________________________________//
Bool_t KVBase::SearchAndOpenKVFile(const Char_t* name, ifstream& file, const Char_t* kvsubdir, KVLockfile* locks)
{
//Search and open for READING a file:
//
//search for ascii file (and open it, if found) in the following order:
// if 'name' = absolute path the function returns kTRUE if the file exists
// if name != absolute path:
// 1. a. if 'kvsubdir'="" (default) look for file in $(pkdatadir) directory
// 1. b. if 'kvsubdir'!="" look for file in $(pkdatadir)/'kvsubdir'
// 2. look for file with this name in user's home directory
// 3. look for file with this name in working directory
//if the file is not found, kFALSE is returned.
//if file is found and can be opened, file' is then an ifstream connected to the open (ascii) file
//
//LOCKFILE:
//If a KVLockfile pointer is given, we use it to get a lock on the file before opening it.
//If this lock is not successful, the file is not opened and we return an error message.
TString fullpath;
if (SearchKVFile(name, fullpath, kvsubdir)) {
//put lock on file if required
if (locks && !locks->Lock(fullpath.Data())) return kFALSE;
file.open(fullpath.Data());
if (file.good()) {
//cout << "Opened file : " << fullpath.Data() << endl;
return kTRUE;
}
//unlock file if not opened successfully
if (locks) locks->Release();
}
return kFALSE;
}
//________________________________________________________________________________//
Bool_t KVBase::SearchAndOpenKVFile(const Char_t* name, ofstream& file, const Char_t* kvsubdir, KVLockfile* locks)
{
//Search and CREATE i.e. open for WRITING a file:
//
//open for writing an ascii file in the location determined in the following way:
// if 'name' = absolute path we use the full path
// if name != absolute path:
// 1. a. if 'kvsubdir'="" (default) file will be in $(pkdatadir) directory
// 1. b. if 'kvsubdir'!="":
// if 'kvsubdir' is an absolute pathname, file in 'kvsubdir'
// if 'kvsubdir' is not an absolute pathname,
// file will be in '$(pkdatadir)/kvsubdir'
//if an existing file is found, a warning is printed and the existing file 'toto' is renamed
//"toto.date". where 'date' is created with TDatime::AsSQLDate
// file' is then an ofstream connected to the opened file
//
//LOCKFILE:
//If a KVLockfile pointer is given, we use it to get a lock on the file before opening it.
//If this lock is not successful, the file is not opened and we return an error message.
KVString fullpath;
if (gSystem->IsAbsoluteFileName(name)) {
fullpath = name;
} else if (gSystem->IsAbsoluteFileName(kvsubdir)) {
AssignAndDelete(fullpath,
gSystem->ConcatFileName(kvsubdir, name));
} else if (strcmp(kvsubdir, "")) {
KVString path = GetDATADIRFilePath(kvsubdir);
AssignAndDelete(fullpath,
gSystem->ConcatFileName(path.Data(), name));
} else {
fullpath = GetDATADIRFilePath(name);
}
//Backup file if necessary
BackupFileWithDate(fullpath.Data());
//put lock on file if required
if (locks && !locks->Lock(fullpath.Data())) return kFALSE;
file.open(fullpath.Data());
return kTRUE;
}
//________________________________________________________________________________//
void KVBase::BackupFileWithDate(const Char_t* path)
{
//'path' gives the full path (can include environment variables, special symbols)
//to a file which will be renamed with an extension containing the current date and time
//(in SQL format).
//Example:
// KVBase::BackupFileWithDate("$(HOME)/toto.txt")
//The file toto.txt will be renamed toto.txt.2007-05-02_16:22:37
//does the file exist ?
KVString fullpath = path;
gSystem->ExpandPathName(fullpath);
if (!gSystem->AccessPathName(fullpath.Data())) {
//backup file
TDatime now;
KVString date(now.AsSQLString());
date.ReplaceAll(' ', '_');
TString backup = fullpath + "." + date;
//lock both files
KVLockfile lf1(fullpath.Data()), lf2(backup.Data());
if (lf1.Lock() && lf2.Lock()) {
gSystem->Rename(fullpath.Data(), backup.Data());
printf("Info in <KVBase::BackupFileWithDate(const Char_t *)> : Existing file %s renamed %s\n",
fullpath.Data(), backup.Data());
}
}
}
//________________________________________________________________________________//
TPluginHandler* KVBase::LoadPlugin(const Char_t* base, const Char_t* uri)
{
//Load plugin library in order to extend capabilities of base class "base", depending on
//the given uri (these arguments are used to call TPluginManager::FindHandler).
//Returns pointer to TPluginHandler.
//Returns 0 in case of problems.
//does plugin exist for given name ?
TPluginHandler* ph =
(TPluginHandler*) gROOT->GetPluginManager()->FindHandler(base,
uri);
if (!ph)
return 0;
//check plugin library/macro is available
if (ph->CheckPlugin() != 0)
return 0;
//load plugin module
if (ph->LoadPlugin() != 0)
return 0;
return ph;
}
//__________________________________________________________________________________________________________________
void KVBase::OpenTempFile(TString& base, ofstream& fp)
{
//Opens a uniquely-named file in system temp directory (gSystem->TempDirectory)
//Name of file is "basexxxxxxxxxx" where "xxxxxxxxx" is current time as returned
//by gSystem->Now().
//After opening file, 'base' contains full path to file.
GetTempFileName(base);
fp.open(base.Data());
}
//__________________________________________________________________________________________________________________
void KVBase::GetTempFileName(TString& base)
{
//When called with base="toto.dat", the returned value of 'base' is
//"/full/path/to/temp/dir/toto.dat15930693"
//i.e. the full path to a file in the system temp directory (gSystem->TempDirectory)
//appended with the current time as returned by gSystem->Now() in order to make
//its name unique
TString tmp1;
AssignAndDelete(tmp1,
gSystem->ConcatFileName(gSystem->TempDirectory(),
base.Data()));
long lnow = (long) gSystem->Now();
base = tmp1 + lnow;
//make sure no existing file with same name
while (!gSystem->AccessPathName(base)) {
base = tmp1 + (++lnow);
}
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetKVVersion()
{
//Returns KaliVeda version string
static TString tmp(KV_VERSION);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetKVBuildUser()
{
// Returns username of person who performed build
static TString tmp(KV_BUILD_USER);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetKVBuildDate()
{
//Returns KaliVeda build date
static TString tmp(KV_BUILD_DATE);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetKVBuildType()
{
//Returns KaliVeda build type (cmake build: Release, Debug, RelWithDebInfo, ...)
static TString tmp(KV_BUILD_TYPE);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetKVSourceDir()
{
//Returns top-level directory of source tree used for build
static TString tmp(KV_SOURCE_DIR);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetKVBuildDir()
{
//Returns top-level directory used for build
static TString tmp(KV_BUILD_DIR);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
#ifdef WITH_GIT_INFOS
const Char_t* KVBase::gitBranch()
{
// Returns git branch of sources
static TString tmp(KV_GIT_BRANCH);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::gitCommit()
{
// Returns last git commit of sources
static TString tmp(KV_GIT_COMMIT);
return tmp.Data();
}
#endif
//__________________________________________________________________________________________________________________
#ifdef WITH_BZR_INFOS
const Char_t* KVBase::bzrRevisionId()
{
// Returns Bazaar branch revision-id of sources
static TString tmp(BZR_REVISION_ID);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::bzrRevisionDate()
{
// Returns date of Bazaar branch revision of sources
static TString tmp(BZR_REVISION_DATE);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::bzrBranchNick()
{
// Returns nickname of Bazaar branch of sources
static TString tmp(BZR_BRANCH_NICK);
return tmp.Data();
}
//__________________________________________________________________________________________________________________
Int_t KVBase::bzrIsBranchClean()
{
// Returns 1 if Bazaar branch of sources contained uncommitted
// changes at time of building; 0 if all changes had been committed.
// WARNING: this doesn't really work (ignore)
return BZR_BRANCH_IS_CLEAN;
}
//__________________________________________________________________________________________________________________
Int_t KVBase::bzrRevisionNumber()
{
// Returns Bazaar branch revision number of sources
return BZR_REVISION_NUMBER;
}
#endif
//__________________________________________________________________________________________________________________
Bool_t KVBase::FindExecutable(TString& exec, const Char_t* path)
{
//By default, FindExecutable(exec) will look for the executable named by 'exec'
//in the directories contained in the environment variable PATH. You can override
//this by giving your own search 'path' as second argument (remember to write
//environment variables as $(PATH), for cross-platform compatibility).
//
//If 'exec' is not found, and if it does not end with '.exe', we look for 'exec.exe'
//This is for compatibility with Windows/cygwin environments.
//
//If the executable is found, returns kTRUE and 'exec' then holds full path to executable.
//Returns kFALSE if exec not found in path.
//
//If 'exec' is an absolute pathname, we return kTRUE if the file exists
//(we do not use 'path').
TString spath(path), backup(exec), backup2(exec), expandexec(exec);
gSystem->ExpandPathName(expandexec);
if (gSystem->IsAbsoluteFileName(expandexec.Data())) {
//executable given as absolute path
//we check if it exists
if (!gSystem->AccessPathName(expandexec)) {
exec = expandexec;
return kTRUE;
} else {
//try with ".exe" in case of Windows system
if (!expandexec.EndsWith(".exe")) {
expandexec += ".exe";
if (!gSystem->AccessPathName(expandexec)) {
exec = expandexec;
return kTRUE;
}
}
}
exec = backup;
return kFALSE;
}
gSystem->ExpandPathName(spath);
if (KVBase::FindFile(spath.Data(), exec))
return kTRUE;
if (!backup.EndsWith(".exe")) {
backup += ".exe";
if (KVBase::FindFile(spath.Data(), backup)) {
exec = backup;
return kTRUE;
}
}
exec = backup2;
return kFALSE;
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::FindFile(const Char_t* search, TString& wfil)
{
//Backwards compatible fix for TSystem::FindFile which only exists from 5.12/00 onwards
//Use this method as a replacement for gSystem->FindFile (same arguments)
#ifdef __WITHOUT_TSYSTEM_FINDFILE
Char_t* result = gSystem->Which(search, wfil.Data());
if (result) {
wfil = result;
delete[]result;
} else {
wfil = "";
}
return wfil.Data();
#else
return gSystem->FindFile(search, wfil);
#endif
}
//__________________________________________________________________________________________________________________
Bool_t KVBase::FindClassSourceFiles(const Char_t* class_name, KVString& imp_file, KVString& dec_file, const Char_t* dir_name)
{
//Look for the source files corresponding to "class_name"
//i.e. taking class_name as a base, we look for one of
// [class_name.C,class_name.cpp,class_name.cxx]
//and one of
// [class_name.h,class_name.hh,class_name.H]
//By default we look in the current working directory, unless argument 'dir_name' is given
//If found, the names of the two files are written in 'imp_file' and 'dec_file'
KVNameValueList impl_alt;
int i = 0;
impl_alt.SetValue("%s.C", i);
impl_alt.SetValue("%s.cpp", i);
impl_alt.SetValue("%s.cxx", i);
KVNameValueList decl_alt;
decl_alt.SetValue("%s.h", i);
decl_alt.SetValue("%s.hh", i);
decl_alt.SetValue("%s.H", i);
TString _dir_name = dir_name;
gSystem->ExpandPathName(_dir_name);
TSystemDirectory dir("LocDir", _dir_name.Data());
TList* lf = dir.GetListOfFiles();
Bool_t ok_imp, ok_dec;
ok_imp = ok_dec = kFALSE;
//look for implementation file
for (i = 0; i < impl_alt.GetNpar(); i++) {
if (lf->FindObject(Form(impl_alt.GetParameter(i)->GetName(), class_name))) {
imp_file = Form(impl_alt.GetParameter(i)->GetName(), class_name);
ok_imp = kTRUE;
}
}
//look for header file
for (i = 0; i < decl_alt.GetNpar(); i++) {
if (lf->FindObject(Form(decl_alt.GetParameter(i)->GetName(), class_name))) {
dec_file = Form(decl_alt.GetParameter(i)->GetName(), class_name);
ok_dec = kTRUE;
}
}
delete lf;
return (ok_imp && ok_dec);
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetPluginURI(const Char_t* base, const Char_t* derived)
{
//Inverse of gPluginMgr->FindHandler(const Char_t* base, const Char_t* uri).
//Given a base class "base" and a derived class "derived", we search gEnv to find the
//URI corresponding to this plugin.
//
//Example: given a plugin such as
//
//Plugin.KVIDTelescope: ^PHOS$ KVIDPhoswich KVIndra "KVIDPhoswich()"
//
//then calling KVBase::GetPluginURI("KVIDTelescope", "KVIDPhoswich") will return "PHOS".
//
//Most of the code is copied from TPluginManager::LoadHandlersFromEnv
TIter next(gEnv->GetTable());
TEnvRec* er;
static TString tmp;
while ((er = (TEnvRec*) next())) {
const char* s;
if ((s = strstr(er->GetName(), "Plugin."))) {
// use s, i.e. skip possible OS and application prefix to Plugin.
// so that GetValue() takes properly care of returning the value
// for the specified OS and/or application
const char* val = gEnv->GetValue(s, (const char*)0);
if (val) {
Int_t cnt = 0;
s += 7;
//is it the right base class ?
if (strcmp(s, base)) continue; //skip to next env var if not right base
char* v = StrDup(val);
while (1) {
TString regexp = strtok(!cnt ? v : 0, "; ");
if (regexp.IsNull()) break;
TString clss = strtok(0, "; ");
if (clss.IsNull()) break;
TString plugin = strtok(0, "; ");
if (plugin.IsNull()) break;
TString ctor = strtok(0, ";\"");
if (!ctor.Contains("("))
ctor = strtok(0, ";\"");
if (clss == derived) {
//found the required plugin
//we remove the 'regexp' operator '^' from the beginning
//and '$' from the end of the URI, if necessary
if (regexp.MaybeRegexp()) {
regexp.Remove(TString::kBoth, '^');
regexp.Remove(TString::kBoth, '$');
}
tmp = regexp;
delete [] v;
return tmp.Data();
}
cnt++;
}
delete [] v;
}
}
}
tmp = "";
return tmp;
}
//__________________________________________________________________________________________________________________
const Char_t* KVBase::GetListOfPlugins(const Char_t* base)
{
// Return whitespace-separated list of all plugin classes defined for
// the given base class.
//
// Most of the code is copied from TPluginManager::LoadHandlersFromEnv
TIter next(gEnv->GetTable());
TEnvRec* er;
static TString tmp;
tmp = "";
while ((er = (TEnvRec*) next())) {
const char* s;
if ((s = strstr(er->GetName(), "Plugin."))) {
// use s, i.e. skip possible OS and application prefix to Plugin.
// so that GetValue() takes properly care of returning the value
// for the specified OS and/or application
const char* val = gEnv->GetValue(s, (const char*)0);
if (val) {
Int_t cnt = 0;
s += 7;
//is it the right base class ?
if (strcmp(s, base)) continue; //skip to next env var if not right base
char* v = StrDup(val);
while (1) {
TString regexp = strtok(!cnt ? v : 0, "; ");
if (regexp.IsNull()) break;
TString clss = strtok(0, "; ");
if (clss.IsNull()) break;
TString plugin = strtok(0, "; ");
if (plugin.IsNull()) break;
TString ctor = strtok(0, ";\"");
if (!ctor.Contains("("))
ctor = strtok(0, ";\"");
tmp += clss;
tmp += " ";
cnt++;
}
delete [] v;
}
}
}
//remove final trailing whitespace
tmp.Remove(TString::kTrailing, ' ');
return tmp;
}
//__________________________________________________________________________________________________________________
void KVBase::ReadGUIMimeTypes()
{
// Add to standard ROOT mime types some new ones defined in .kvrootrc
// for icons associated with graphs, runs, etc. by lines such as:
//
// KaliVeda.GUI.MimeTypes : KVIDMap
// KaliVeda.GUI.MimeTypes.KVIDMap.Icon : rootdb_t.xpm
// +KaliVeda.GUI.MimeTypes : KVIDZAGrid
// KaliVeda.GUI.MimeTypes.KVIDZAGrid.Icon : draw_t.xpm
//
// etc.
KVString mimetypes = gEnv->GetValue("KaliVeda.GUI.MimeTypes", "");
if (mimetypes != "") {
mimetypes.Begin(" ");
while (!mimetypes.End()) {
KVString classname = mimetypes.Next(kTRUE);
KVString icon = gEnv->GetValue(Form("KaliVeda.GUI.MimeTypes.%s.Icon", classname.Data()), "draw_t.xpm");
KVString type = classname;
type.ToLower();
if (gClient) gClient->GetMimeTypeList()->AddType(Form("[kaliveda/%s]", type.Data()),
classname.Data(), icon.Data(), icon.Data(), "");
}
}
}
//__________________________________________________________________________________________________________________
#ifdef WITH_GRULIB
Int_t KVBase::TestPorts(Int_t port)
{
// Test ports for availability. Start from 'port' and go up to port+2000 at most.
// Returns -1 if no ports available.
GNetClientRoot testnet((char*) "localhost");
Int_t ret;
ret = port;
for (int i = 0; i < 2000; i++) {
ret = testnet.TestPortFree(port, (char*) "localhost");
if (ret > 0)
break;
if ((ret <= 0))
port++;
}
return ret;
}
#endif
Bool_t KVBase::AreEqual(Double_t A, Double_t B, Long64_t maxdif)
{
// Comparison between two 64-bit floating-point values
// Returns kTRUE if the integer representations of the two values are within
// maxdif of each other.
// By default maxdif=1, which means that we consider that x==y if the
// difference between them is no greater than the precision of Double_t
// variables, i.e. 4.94065645841246544e-324
//
// Based on the function AlmostEqual2sComplement(float, float, int)
// by Bruce Dawson http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
union converter {
Double_t f;
Long64_t i;
} zero, val1, val2;
assert(maxdif > 0);
if (A == B) return true;
/* rustine to obtain the (64-bit) constant value 0x8000000000000000
even on 32-bit machines (there is probably an easier way!) */
zero.i = 1;
zero.f = -zero.f;
zero.i -= 1;
val1.f = A;
val2.f = B;
Long64_t Aint, Bint;
Aint = val1.i;
Bint = val2.i;
if (Aint < 0) Aint = zero.i - Aint;
if (Bint < 0) Bint = zero.i - Bint;
Long64_t intDiff = abs(val1.i - val2.i);
if (intDiff <= maxdif) return true;
return false;
}
Bool_t KVBase::OpenContextMenu(const char* method, TObject* obj, const char* alt_method_name)
{
// Open context menu for given method of object *obj.
// By default title of menu is 'obj->ClassName()::method'
// You can give an alternative method name in 'alt_method_name'
// Returns kFALSE if the given method is not defined for the class of object in question.
//
// WARNING: even if this method returns kTRUE, this is no guarantee that the method
// has indeed been executed. The user may have pressed the 'Cancel' button...
TMethod* m = obj->IsA()->GetMethodAllAny(method);
if (!m) {
obj->Warning("OpenContextMenu", "%s is not a method of %s", method, obj->ClassName());
return kFALSE;
}
TString Method = alt_method_name;
if (Method == "") Method = method;
TContextMenu* cm = new TContextMenu(Method, Form("%s::%s", obj->ClassName(), Method.Data()));
cm->Action(obj, m);
delete cm;
return kTRUE;
}
void KVBase::CombineFiles(const Char_t* file1, const Char_t* file2, const Char_t* newfilename, Bool_t keep)
{
// STATIC method which allows to combine the contents of two ROOT files
// (file1 and file2) into a new ROOT file (newfilename).
// All objects from the two files will be written in the new file.
//
// if keep=kFALSE, the two files will be deleted after the operation
::Info("KVBase::CombineFiles", "Copying all objects from %s and %s ===> into new file %s", file1, file2, newfilename);
TFile* f1 = TFile::Open(file1);
TList objL1;//list of objects in file 1
TList treeL1;//list of trees in file 1
TIter next(f1->GetListOfKeys());
TKey* key;
while ((key = (TKey*)next())) {
if (!TClass::GetClass(key->GetClassName(), kFALSE, kTRUE)->InheritsFrom("TDirectory")) {//avoid subdirectories!
if (!TClass::GetClass(key->GetClassName(), kFALSE, kTRUE)->InheritsFrom("TTree"))
objL1.Add(f1->Get(key->GetName()));
else
treeL1.Add(f1->Get(key->GetName()));
}
}
TFile* f2 = TFile::Open(file2);
TList objL2;//list of objects in file 2
TList treeL2;//list of trees in file 2
TIter next2(f2->GetListOfKeys());
while ((key = (TKey*)next2())) {
if (!TClass::GetClass(key->GetClassName(), kFALSE, kTRUE)->InheritsFrom("TDirectory")) {//avoid subdirectories!
if (!TClass::GetClass(key->GetClassName(), kFALSE, kTRUE)->InheritsFrom("TTree"))
objL2.Add(f2->Get(key->GetName()));
else
treeL2.Add(f2->Get(key->GetName()));
}
}
TFile* newfile = new TFile(newfilename, "recreate");
objL1.Execute("Write", "");
objL2.Execute("Write", "");
if (treeL1.GetEntries()) {
TIter nxtT(&treeL1);
TTree* t;
while ((t = (TTree*)nxtT())) t->CloneTree(-1, "fast")->Write();
}
if (treeL2.GetEntries()) {
TIter nxtT(&treeL2);
TTree* t;
while ((t = (TTree*)nxtT())) t->CloneTree(-1, "fast")->Write();
}
newfile->Close();
f1->Close();
f2->Close();
if (!keep) {
gSystem->Unlink(file1);
gSystem->Unlink(file2);
}
}
TObject* KVBase::GetObject() const
{
// Dummy method (returns NULL).
// This method may be used in 'container' classes used with KVListView.
// In order to open the context menu of the 'contained' object,
// GetLabel() should return the real class of the object,
// and this method should return its address.
// Then call KVListView::SetUseObjLabelAsRealClass(kTRUE).
return NULL;
}
const Char_t* KVBase::GetExampleFilePath(const Char_t* library, const Char_t* namefile)
{
// Return full path to example file for given library (="KVMultiDet", "BackTrack", etc.)
static TString path;
path = KVBase::GetDATADIRFilePath("examples/");
path += library;
path += "/";
path += namefile;
return path.Data();
}
void KVBase::PrintSplashScreen()
{
// Prints welcome message and infos on version etc.
cout << "***********************************************************" <<
endl;
cout << "* HI COQUINE !!! *" <<
endl;
cout << "* *" <<
endl;
cout << "* W E L C O M E to K A L I V E D A *" <<
endl;
cout << "* *" <<
endl;
printf("* Version: %-10s Built: %-10s *\n", KVBase::GetKVVersion(), KVBase::GetKVBuildDate());
#ifdef WITH_BZR_INFOS
TString bzrinfo;
bzrinfo.Form("%s@%d", bzrBranchNick(), bzrRevisionNumber());
printf("* bzr: %50s *\n", bzrinfo.Data());
#endif
#ifdef WITH_GIT_INFOS
TString gitinfo;
gitinfo.Form("%s@%s", gitBranch(), gitCommit());
printf("* git: %-50s *\n", gitinfo.Data());
#endif
cout << "* *" <<
endl;
cout << "* For help, read the doc on : *" <<
endl;
cout << "* http://indra.in2p3.fr/KaliVedaDoc *" <<
endl;
cout << "* *" <<
endl;
cout << "* ENJOY !!! *" <<
endl;
cout << "***********************************************************" <<
endl << endl;
}
| jdfrankland/kaliveda | KVMultiDet/base/KVBase.cpp | C++ | gpl-3.0 | 43,851 |
package it.unibas.lunatic.model.chase.chasede.operators.mainmemory;
import it.unibas.lunatic.Scenario;
import it.unibas.lunatic.model.chase.chasede.operators.IReplaceDatabase;
import java.util.Iterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import speedy.model.algebra.operators.ITupleIterator;
import speedy.model.algebra.operators.mainmemory.MainMemoryInsertTuple;
import speedy.model.database.Cell;
import speedy.model.database.IDatabase;
import speedy.model.database.Tuple;
import speedy.model.database.mainmemory.MainMemoryDB;
import speedy.model.database.mainmemory.MainMemoryTable;
import speedy.model.database.mainmemory.MainMemoryVirtualDB;
import speedy.model.database.mainmemory.MainMemoryVirtualTable;
public class MainMemoryReplaceDatabase implements IReplaceDatabase {
private final static Logger logger = LoggerFactory.getLogger(MainMemoryReplaceDatabase.class);
private final static MainMemoryInsertTuple insert = new MainMemoryInsertTuple();
public void replaceTargetDB(IDatabase newDatabase, Scenario scenario) {
if (newDatabase instanceof MainMemoryDB) {
scenario.setTarget(newDatabase);
return;
}
MainMemoryVirtualDB virtualDB = (MainMemoryVirtualDB) newDatabase;
if (logger.isDebugEnabled()) logger.debug("Copying virtual db\n" + newDatabase);
MainMemoryDB mainMemoryDB = new MainMemoryDB(virtualDB.getDataSource());
for (String tableName : mainMemoryDB.getTableNames()) {
MainMemoryTable table = (MainMemoryTable) mainMemoryDB.getTable(tableName);
emptyTable(table);
insertAllTuples(table, (MainMemoryVirtualTable) virtualDB.getTable(tableName));
}
if (logger.isDebugEnabled()) logger.debug("New db\n" + mainMemoryDB);
scenario.setTarget(mainMemoryDB);
}
private void emptyTable(MainMemoryTable table) {
table.getDataSource().getInstances().get(0).getChildren().clear();
}
private void insertAllTuples(MainMemoryTable table, MainMemoryVirtualTable mainMemoryVirtualTable) {
ITupleIterator it = mainMemoryVirtualTable.getTupleIterator();
while (it.hasNext()) {
Tuple tuple = it.next();
removeOID(tuple);
insert.execute(table, tuple, null, null);
}
}
private void removeOID(Tuple tuple) {
for (Iterator<Cell> it = tuple.getCells().iterator(); it.hasNext();) {
Cell cell = it.next();
if (cell.isOID()) {
it.remove();
}
}
}
}
| donatellosantoro/Llunatic | lunaticEngine/src/it/unibas/lunatic/model/chase/chasede/operators/mainmemory/MainMemoryReplaceDatabase.java | Java | gpl-3.0 | 2,579 |
<?php defined('SYSPATH') OR die('No direct access allowed.');
class Facebook {
protected static $table_prefix = '';
public static function install()
{
$db_config = Kohana::$config->load('database');
$default = $db_config->get('default');
self::$table_prefix = $default['table_prefix'];
self::_sql();
}
private static function _sql()
{
$db = Database::instance('default');
$create = "
CREATE TABLE IF NOT EXISTS `".self::$table_prefix."facebook_settings`
(
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`key` varchar(100) NOT NULL DEFAULT '',
`value` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_key` (`key`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
";
$db->query(NULL, $create, true);
// Insert Default Settings Keys
// Use ORM to prevent issues with unique keys
// Facebook Application ID / API Key
$setting = ORM::factory('facebook_setting')
->where('key', '=', 'application_id')
->find();
$setting->key = 'application_id';
$setting->save();
// Facebook Application Secret
$setting = ORM::factory('facebook_setting')
->where('key', '=', 'application_secret')
->find();
$setting->key = 'application_secret';
$setting->save();
// Access token for offline access to Facebook
$setting = ORM::factory('facebook_setting')
->where('key', '=', 'access_token')
->find();
$setting->key = 'access_token';
$setting->save();
// Unique ID on Facebook of the user Authorizing the Facebook Application
$setting = ORM::factory('facebook_setting')
->where('key', '=', 'access_user_id')
->find();
$setting->key = 'access_user_id';
$setting->save();
// Name of the user Authorizing the Facebook Application
$setting = ORM::factory('facebook_setting')
->where('key', '=', 'access_name')
->find();
$setting->key = 'access_name';
$setting->save();
}
} | ushahidi/Sweeper | plugins/facebook/classes/facebook.php | PHP | gpl-3.0 | 1,901 |
#include "network.h"
namespace network
{
bool can_reach_host (char const* host)
{
bool res = false;
if(SCNetworkReachabilityRef ref = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, host))
{
SCNetworkReachabilityFlags flags;
if(SCNetworkReachabilityGetFlags(ref, &flags))
{
if(flags & kSCNetworkReachabilityFlagsReachable)
res = true;
}
CFRelease(ref);
}
return res;
}
} /* network */ | aarongraham9/TextMate | Frameworks/network/src/network.cc | C++ | gpl-3.0 | 432 |
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
package ifc.sheet;
import lib.MultiMethodTest;
import lib.Status;
import lib.StatusException;
import com.sun.star.sheet.XDataPilotDescriptor;
import com.sun.star.sheet.XDataPilotTables;
import com.sun.star.sheet.XSpreadsheet;
import com.sun.star.table.CellAddress;
/**
* Testing <code>com.sun.star.sheet.XDataPilotTables</code>
* interface methods :
* <ul>
* <li><code> createDataPilotDescriptor()</code></li>
* <li><code> insertNewByName()</code></li>
* <li><code> removeByName()</code></li>
* </ul> <p>
* This test needs the following object relations :
* <ul>
* <li> <code>'SHEET'</code> (of type <code>XSpreadsheet</code>):
* to have a spreadsheet document for document content checking</li>
* <ul> <p>
* @see com.sun.star.sheet.XDataPilotTables
*/
public class _XDataPilotTables extends MultiMethodTest {
public XDataPilotTables oObj = null;
XDataPilotDescriptor DPDscr = null;
String name = "XDataPilotTables";
CellAddress CA = new CellAddress((short)0, 9, 8);
XSpreadsheet oSheet = null;
/**
* Retrieves object relations.
* @throws StatusException If one of relations not found.
*/
protected void before() {
oSheet = (XSpreadsheet)tEnv.getObjRelation("SHEET");
if (oSheet == null) throw new StatusException(Status.failed
("Relation 'SHEET' not found"));
}
/**
* Test calls the method, stores returned value and checks returned value.
* <p>Has <b> OK </b> status if returned value isn't null. <p>
*/
public void _createDataPilotDescriptor(){
DPDscr = oObj.createDataPilotDescriptor();
tRes.tested("createDataPilotDescriptor()", DPDscr != null);
}
/**
* Test calls the method inserting new table with new name and then calls
* the method inserting table with existent name. <p>
* Has <b> OK </b> status if the cell content where table was inserted is
* equal to 'Filter' after first call and exception was thrown during
* second call. <p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code> createDataPilotDescriptor() </code> : to have
* <code>XDataPilotDescriptor</code> created by this method</li>
* </ul>
*/
public void _insertNewByName(){
requiredMethod("createDataPilotDescriptor()");
boolean bResult = true;
log.println("Inserting new Table \"" + name + "\"");
try {
oObj.insertNewByName(name, CA, DPDscr);
bResult &= oSheet.getCellByPosition
(CA.Column, CA.Row).getFormula().equals("Filter");
} catch (com.sun.star.uno.Exception e) {
log.println("Exception occurred! " + e);
bResult = false;
}
log.println(bResult ? "OK" : "FAILED");
log.println("Trying to insert element with existent name");
try {
oObj.insertNewByName(name,new CellAddress((short)0, 7, 7), DPDscr);
log.println("No exception! - FAILED");
bResult = false;
} catch (com.sun.star.uno.RuntimeException e) {
log.println("Expected exception - OK " + e);
}
log.println("Inserting new table " + (bResult ? "OK" : "FAILED"));
tRes.tested("insertNewByName()", bResult);
}
/**
* Test calls the method for existent table and for unexistent table. <p>
* Has <b> OK </b> status if the cell where table was removed from is empty
* after first call and exception was thrown during second call. <p>
* The following method tests are to be completed successfully before :
* <ul>
* <li> <code>insertNewByName()</code>: to have name of existent table</li>
* </ul>
*/
public void _removeByName(){
requiredMethod("insertNewByName()");
boolean bResult = true;
log.println("Remove table with name " + name);
try {
oObj.removeByName(name);
bResult &= oSheet.getCellByPosition
(CA.Column, CA.Row).getFormula().equals("");
} catch (com.sun.star.uno.Exception e) {
log.println("Exception occurred ! " + e);
bResult = false;
}
log.println(bResult ? "OK" : "FAILED");
log.println("Removing unexistent element");
try {
oObj.removeByName(name);
log.println("No exception! - FAILED");
bResult = false;
} catch (com.sun.star.uno.RuntimeException e) {
log.println("Expected exception - OK " + e);
}
log.println("Removing a table " + (bResult ? "OK" : "FAILED"));
tRes.tested("removeByName()", bResult);
}
}
| qt-haiku/LibreOffice | qadevOOo/tests/java/ifc/sheet/_XDataPilotTables.java | Java | gpl-3.0 | 5,478 |
#include "RhythmComposerOS.h"
| onozuka/koblo_software | Products/Rythm_Composer/source/DigitalEcho.cpp | C++ | gpl-3.0 | 37 |
'use strict';
// Create the valorchat configuration
module.exports = function (io, socket) {
// Emit the status event when a new socket client is connected
io.emit('ValorchatMessage', {
type: 'status',
text: 'Is now connected',
created: Date.now(),
profileImageURL: socket.request.user.profileImageURL,
username: socket.request.user.username
});
// Send a valorchat messages to all connected sockets when a message is received
socket.on('ValorchatMessage', function (message) {
message.type = 'message';
message.created = Date.now();
message.profileImageURL = socket.request.user.profileImageURL;
message.username = socket.request.user.username;
// Emit the 'ValorchatMessage' event
io.emit('ValorchatMessage', message);
});
// Emit the status event when a socket client is disconnected
socket.on('disconnect', function () {
io.emit('ValorchatMessage', {
type: 'status',
text: 'disconnected',
created: Date.now(),
profileImageURL: socket.request.user.profileImageURL,
username: socket.request.user.username
});
});
};
| AnnaGenev/pokeapp-meanjs | modules/valorchat/server/sockets/valorchat.server.socket.config.js | JavaScript | gpl-3.0 | 1,122 |
/////////////////////////////////////////////////////////////////////////////////
//
// Jobbox WebGUI
// Copyright (C) 2014-2015 Komatsu Yuji(Zheng Chuyu)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
//
// Function:
//
// Purpose:
//
// Parameters:
//
// Return value:
//
// Author: Komatsu Yuji(Zheng Chuyu)
//
/////////////////////////////////////////////////////////////////////////////////
Ext.define('Jobbox.store.HistJobunit', {
extend: 'Ext.data.Store',
model: 'Jobbox.model.HistJobunit',
autoLoad: true,
autoDestroy: false,
autoSync: false,
remoteSort: true,
proxy: {
type: 'rest',
url: location.pathname + '/hist_jobunits',
appendId: true,
format: 'json',
reader: {
root: 'hist_jobunits',
totalProperty: 'total_count',
},
},
});
| komatsuyuji/jobbox | frontends/public/app/store/HistJobunit.js | JavaScript | gpl-3.0 | 1,563 |
<?php
/*=======================================================================
PHP-Nuke Titanium v3.0.0 : Enhanced PHP-Nuke Web Portal System
=======================================================================*/
/************************************************************************/
/* PHP-NUKE: Advanced Content Management System */
/* ============================================ */
/* */
/* Copyright (c) 2002 by Francisco Burzi */
/* http://phpnuke.org */
/* */
/* This program is free software. You can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 2 of the License. */
/************************************************************************/
/*****[CHANGES]**********************************************************
-=[Base]=-
Nuke Patched v3.1.0 06/26/2005
************************************************************************/
if (!defined('ADMIN_FILE')) {
die ('Illegal File Access');
}
switch($op) {
case "mod_authors":
case "modifyadmin":
case "UpdateAuthor":
case "AddAuthor":
case "deladmin2":
case "deladmin":
case "assignstories":
case "deladminconf":
include(NUKE_ADMIN_MODULE_DIR.'authors.php');
break;
}
?> | ernestbuffington/PHP-Nuke-Titanium | admin/case/case.authors.php | PHP | gpl-3.0 | 1,660 |
// @flow
import React from 'react';
import type { Trigger } from '../../Domain/Trigger';
import type { Maintenance } from '../../Domain/Maintenance';
import TriggerListItem from '../TriggerListItem/TriggerListItem';
import cn from './TriggerList.less';
type Props = {|
items: Array<Trigger>;
onChange?: (triggerId: string, maintenance: Maintenance, metric: string) => void;
onRemove?: (triggerId: string, metric: string) => void;
|};
export default function TriggerList(props: Props): React.Element<*> {
const { items, onChange, onRemove } = props;
return (
<div>
{items.length === 0
? <div className={cn('no-result')}>No results :-(</div>
: items.map(item =>
<div className={cn('item')} key={item.id}>
<TriggerListItem
data={item}
onChange={onChange && ((maintenance, metric) => onChange(item.id, maintenance, metric))}
onRemove={onRemove && (metric => onRemove(item.id, metric))}
/>
</div>
)}
</div>
);
}
| sashasushko/moira-front | src/Components/TriggerList/TriggerList.js | JavaScript | gpl-3.0 | 1,197 |
# coding: utf-8
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import UserPassesTestMixin
from django.views.generic import ListView
from django.views import View
from django.db.models import Q
import posgradmin.models as models
from posgradmin import authorization as auth
from django.conf import settings
from django.shortcuts import render, HttpResponseRedirect
import posgradmin.forms as forms
from dal import autocomplete
from django.urls import reverse
from django.forms.models import model_to_dict
from pdfrw import PdfReader, PdfWriter, PageMerge
from django.template.loader import render_to_string
from sh import pandoc, mkdir
from tempfile import NamedTemporaryFile
import datetime
from django.utils.text import slugify
from .settings import BASE_DIR, MEDIA_ROOT, MEDIA_URL
class AcademicoAutocomplete(LoginRequiredMixin, UserPassesTestMixin, autocomplete.Select2QuerySetView):
login_url = settings.APP_PREFIX + 'accounts/login/'
def test_func(self):
if auth.is_academico(self.request.user):
if self.request.user.academico.acreditacion in ['D', 'M', 'P', 'E',
'candidato profesor']:
return True
return False
def get_queryset(self):
qs = models.Academico.objects.filter(Q(acreditacion='candidato profesor')
| Q(acreditacion='P')
| Q(acreditacion='M')
| Q(acreditacion='D')
| Q(acreditacion='E'))
if self.q:
qs = qs.filter(Q(user__first_name__istartswith=self.q)
| Q(user__last_name__icontains=self.q))
return qs
class ProponerAsignatura(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = settings.APP_PREFIX + 'accounts/login/'
template = 'posgradmin/proponer_asignatura.html'
form_class = forms.AsignaturaModelForm
def test_func(self):
if auth.is_academico(self.request.user):
if self.request.user.academico.acreditacion in ['D', 'M', 'P',
'candidato profesor']:
return True
return False
def get(self, request, *args, **kwargs):
form = self.form_class(initial={'academicos': [request.user.academico, ]})
breadcrumbs = ((settings.APP_PREFIX + 'inicio/', 'Inicio'),
('', 'Proponer Asignatura')
)
return render(request,
self.template,
{
'title': 'Proponer Asignatura',
'breadcrumbs': breadcrumbs,
'form': form
})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
a = models.Asignatura(
asignatura=request.POST['asignatura'],
tipo='Optativa',
estado='propuesta',
programa=request.FILES['programa'])
a.save()
return HttpResponseRedirect(reverse('inicio'))
else:
print(form.errors)
class SolicitaCurso(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = settings.APP_PREFIX + 'accounts/login/'
template = 'posgradmin/solicita_curso.html'
form_class = forms.CursoModelForm
def test_func(self):
if auth.is_academico(self.request.user):
if self.request.user.academico.acreditacion in ['D', 'M', 'P', 'E',
'candidato profesor']:
return True
return False
def get(self, request, *args, **kwargs):
convocatoria = models.ConvocatoriaCurso.objects.get(pk=int(kwargs['pk']))
if convocatoria.status == 'cerrada':
return HttpResponseRedirect(reverse('mis_cursos'))
asignatura = models.Asignatura.objects.get(pk=int(kwargs['as_id']))
form = self.form_class(initial={'academicos': [request.user.academico, ]})
breadcrumbs = ((settings.APP_PREFIX + 'inicio/', 'Inicio'),
(reverse('elige_asignatura', args=[convocatoria.id,]),
"Convocatoria para cursos %s-%s" % (convocatoria.year, convocatoria.semestre))
)
return render(request,
self.template,
{
'title': 'Solicitar curso',
'breadcrumbs': breadcrumbs,
'convocatoria': convocatoria,
'asignatura': asignatura,
'form': form
})
def post(self, request, *args, **kwargs):
convocatoria = models.ConvocatoriaCurso.objects.get(pk=int(kwargs['pk']))
if convocatoria.status == 'cerrada':
return HttpResponseRedirect(reverse('mis_cursos'))
asignatura = models.Asignatura.objects.get(pk=int(kwargs['as_id']))
form = self.form_class(request.POST)
if form.is_valid():
curso = models.Curso(
convocatoria=convocatoria,
asignatura=asignatura,
year=convocatoria.year,
semestre=convocatoria.semestre,
sede=request.POST['sede'],
aula=request.POST['aula'],
horario=request.POST['horario'])
curso.save()
for ac_id in request.POST.getlist('academicos'):
ac = models.Academico.objects.get(pk=int(ac_id))
curso.academicos.add(ac)
curso.academicos.add(request.user.academico)
curso.save()
return HttpResponseRedirect(reverse('mis_cursos'))
class CursoView(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = settings.APP_PREFIX + 'accounts/login/'
template = 'posgradmin/solicita_curso.html'
form_class = forms.CursoModelForm
def test_func(self):
curso = models.Curso.objects.get(pk=int(self.kwargs['pk']))
if auth.is_academico(self.request.user):
if self.request.user.academico.acreditacion in ['D', 'M', 'P', 'E',
'candidato profesor']:
if self.request.user.academico in curso.academicos.all():
return True
return False
def get(self, request, *args, **kwargs):
curso = models.Curso.objects.get(pk=int(kwargs['pk']))
form = self.form_class(initial=model_to_dict(curso))
breadcrumbs = ((reverse('inicio'), 'Inicio'),
(reverse('mis_cursos'), "Mis cursos"))
return render(request,
self.template,
{
'title': 'Editar curso',
'breadcrumbs': breadcrumbs,
'convocatoria': curso.convocatoria,
'asignatura': curso.asignatura,
'form': form
})
def post(self, request, *args, **kwargs):
curso = models.Curso.objects.get(pk=int(kwargs['pk']))
convocatoria = curso.convocatoria
if convocatoria.status == 'cerrada':
return HttpResponseRedirect(reverse('mis_cursos'))
asignatura = curso.asignatura
form = self.form_class(request.POST)
if form.is_valid():
curso.sede = request.POST['sede']
curso.aula = request.POST['aula']
curso.horario = request.POST['horario']
curso.save()
curso.academicos.clear()
for ac_id in request.POST.getlist('academicos'):
ac = models.Academico.objects.get(pk=int(ac_id))
curso.academicos.add(ac)
curso.save()
return HttpResponseRedirect(reverse('mis_cursos'))
class CursoConstancia(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = settings.APP_PREFIX + 'accounts/login/'
template = 'posgradmin/curso_constancia.html'
form_class = forms.CursoConstancia
def test_func(self):
curso = models.Curso.objects.get(pk=int(self.kwargs['pk']))
if auth.is_academico(self.request.user):
if self.request.user.academico.acreditacion in ['D', 'M', 'P', 'E',
'candidato profesor']:
if self.request.user.academico in curso.academicos.all():
return True
return False
def get(self, request, *args, **kwargs):
curso = models.Curso.objects.get(pk=int(kwargs['pk']))
form = self.form_class(initial=model_to_dict(curso))
breadcrumbs = ((reverse('inicio'), 'Inicio'),
(reverse('mis_cursos'), "Mis cursos"))
return render(request,
self.template,
{
'title': 'Emitir constancia de participación',
'breadcrumbs': breadcrumbs,
'convocatoria': curso.convocatoria,
'asignatura': curso.asignatura,
'form': form
})
def post(self, request, *args, **kwargs):
curso = models.Curso.objects.get(pk=int(kwargs['pk']))
profesor_invitado = request.POST['profesor_invitado']
fecha_participacion = datetime.date(int(request.POST['fecha_de_participación_year']),
int(request.POST['fecha_de_participación_month']),
int(request.POST['fecha_de_participación_day']))
with NamedTemporaryFile(mode='r+', encoding='utf-8') as carta_md:
carta_md.write(
render_to_string('posgradmin/constancia_curso.md',
{'fecha': datetime.date.today(),
'profesor_invitado': profesor_invitado,
'tema': request.POST['tema'],
'curso': curso,
'fecha_participacion': fecha_participacion,
'profesor': request.user.get_full_name() }))
carta_md.seek(0)
outdir = '%s/perfil-academico/%s/' % (MEDIA_ROOT,
request.user.academico.id)
tmpname = 'cursoplain_%s_%s.pdf' % (curso.id,
slugify(profesor_invitado)
)
final_name = tmpname.replace('cursoplain', 'constancia_curso')
mkdir("-p", outdir)
pandoc(carta_md.name, output=outdir + tmpname)
C = PdfReader(outdir + tmpname)
M = PdfReader(BASE_DIR + '/docs/membrete_pcs.pdf')
w = PdfWriter()
merger = PageMerge(M.pages[0])
merger.add(C.pages[0]).render()
w.write(outdir + final_name, M)
return HttpResponseRedirect(MEDIA_URL+"perfil-academico/%s/%s" % (request.user.academico.id, final_name))
class CursoConstanciaEstudiante(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = settings.APP_PREFIX + 'accounts/login/'
template = 'posgradmin/curso_constancia.html'
form_class = forms.CursoConstanciaEstudiante
def test_func(self):
curso = models.Curso.objects.get(pk=int(self.kwargs['pk']))
if auth.is_academico(self.request.user):
if self.request.user.academico.acreditacion in ['D', 'M', 'P', 'E',
'candidato profesor']:
if self.request.user.academico in curso.academicos.all():
return True
return False
def get(self, request, *args, **kwargs):
curso = models.Curso.objects.get(pk=int(kwargs['pk']))
form = self.form_class(initial=model_to_dict(curso))
breadcrumbs = ((reverse('inicio'), 'Inicio'),
(reverse('mis_cursos'), "Mis cursos"))
return render(request,
self.template,
{
'title': 'Emitir constancia para estudiante',
'breadcrumbs': breadcrumbs,
'convocatoria': curso.convocatoria,
'asignatura': curso.asignatura,
'form': form
})
def post(self, request, *args, **kwargs):
curso = models.Curso.objects.get(pk=int(kwargs['pk']))
form = self.form_class(request.POST, request.FILES)
if form.is_valid():
estudiante_invitado = request.POST['estudiante_invitado']
calificacion = request.POST['calificacion']
with NamedTemporaryFile(mode='r+', encoding='utf-8') as carta_md:
carta_md.write(
render_to_string('posgradmin/constancia_curso_estudiante.md',
{'fecha': datetime.date.today(),
'estudiante_invitado': estudiante_invitado,
'calificacion': calificacion,
'curso': curso,
'profesor': request.user.get_full_name() }))
carta_md.seek(0)
outdir = '%s/perfil-academico/%s/' % (MEDIA_ROOT,
request.user.academico.id)
tmpname = 'cursoplain_%s_%s.pdf' % (curso.id,
slugify(estudiante_invitado)
)
final_name = tmpname.replace('cursoplain', 'constancia_curso')
mkdir("-p", outdir)
pandoc(carta_md.name, output=outdir + tmpname)
C = PdfReader(outdir + tmpname)
M = PdfReader(BASE_DIR + '/docs/membrete_pcs.pdf')
w = PdfWriter()
merger = PageMerge(M.pages[0])
merger.add(C.pages[0]).render()
w.write(outdir + final_name, M)
return HttpResponseRedirect(
MEDIA_URL + "perfil-academico/%s/%s" % (request.user.academico.id,
final_name))
else:
return render(request,
self.template,
{
'title': 'Emitir constancia para estudiante',
'breadcrumbs': breadcrumbs,
'convocatoria': curso.convocatoria,
'asignatura': curso.asignatura,
'form': form
})
class EligeAsignatura(LoginRequiredMixin, UserPassesTestMixin, View):
login_url = settings.APP_PREFIX + 'accounts/login/'
template = 'posgradmin/elige_asignatura.html'
def test_func(self):
return auth.is_academico(self.request.user)
def get(self, request, *args, **kwargs):
pk = int(kwargs['pk'])
convocatoria = models.ConvocatoriaCurso.objects.get(pk=pk)
asignaturas = models.Asignatura.objects.filter(
Q(tipo='Optativa') &
(Q(estado='aceptada') | Q(estado='propuesta')))
breadcrumbs = ((settings.APP_PREFIX + 'inicio/', 'Inicio'),
('', "Convocatoria para cursos %s-%s" % (convocatoria.year, convocatoria.semestre))
)
return render(request,
self.template,
{
'title': 'Asignaturas',
'breadcrumbs': breadcrumbs,
'asignaturas': asignaturas,
'convocatoria': convocatoria,
})
class MisEstudiantesView(LoginRequiredMixin, UserPassesTestMixin, ListView):
login_url = settings.APP_PREFIX + 'accounts/login/'
def test_func(self):
return auth.is_academico(self.request.user)
model = models.Estudiante
template_name = 'posgradmin/mis_estudiantes_list.html'
def get_queryset(self):
new_context = self.request.user.academico.estudiantes()
return new_context
class MisCursos(LoginRequiredMixin, UserPassesTestMixin, ListView):
login_url = settings.APP_PREFIX + 'accounts/login/'
def test_func(self):
return auth.is_academico(self.request.user)
model = models.Curso
template_name = 'posgradmin/mis_cursos_list.html'
def get_queryset(self):
return self.request.user.academico.curso_set.all()
def get_context_data(self, **kwargs):
ctxt = super(MisCursos, self).get_context_data(**kwargs)
ctxt['MEDIA_URL'] = MEDIA_URL
return ctxt
| sostenibilidad-unam/posgrado | posgradmin/posgradmin/views_academico.py | Python | gpl-3.0 | 17,170 |
#!/usr/bin/env ruby
#
require 'optparse'
module Roma
module Storage
end
Storage::autoload(:TCStorage,'roma/storage/tokyocabinet')
Storage::autoload(:DbmStorage,'roma/storage/dbm')
Storage::autoload(:SQLite3Storage,'roma/storage/sqlite3')
class KeyAccess
def initialize(argv)
options(argv)
each_hash(@path){|hname, dir|
puts "hash : #{hname}"
st = open_storage(dir)
vn, last, clk, expt, value = st.get_raw2(@key)
if vn
if @sv
puts "vnode: #{vn}"
puts "last : #{Time.at(last)}"
puts "clock: #{clk}"
puts "expt : #{Time.at(expt)}"
begin
puts "value #{Marshal.load(value)}"
rescue
puts "value: #{value}"
end
else
puts "exist"
end
st.closedb
return
end
st.closedb
}
puts "not exist"
end
def options(argv)
opts = OptionParser.new
opts.banner="usage:#{File.basename($0)} storage-path key"
@sv = false
opts.on("-v","--value","show value") { |v| @sv = true }
opts.parse!(argv)
raise OptionParser::ParseError.new if argv.length < 2
@path = argv[0]
@key = argv[1]
rescue OptionParser::ParseError => e
STDERR.puts opts.help
exit 1
end
def each_hash(path)
Dir::glob("#{path}/*").each{|dir|
next unless File::directory?(dir)
hname = dir[dir.rindex('/')+1..-1]
yield hname,dir
}
end
def open_storage(path)
unless File::directory?(path)
STDERR.puts "#{path} does not found."
return nil
end
# get a file extension
ext = File::extname(Dir::glob("#{path}/0.*")[0])[1..-1]
# count a number of divided files
divnum = Dir::glob("#{path}/*.#{ext}").length
st = new_storage(ext)
st.divnum = divnum
st.vn_list = []
st.storage_path = path
st.opendb
st
end
def new_storage(ext)
case(ext)
when 'tc'
return ::Roma::Storage::TCStorage.new
when 'dbm'
return Roma::Storage::DbmStorage.new
when 'sql3'
return Roma::Storage::SQLite3Storage.new
else
return nil
end
end
end
end
Roma::KeyAccess.new(ARGV)
| roma/roma | lib/roma/tools/key_access.rb | Ruby | gpl-3.0 | 2,341 |
// Copyright Alex Holehouse 2011
// Distributed under the terms of the GNU general public license - see COPYING.txt for more details
#include "sbml_confInput.h"
#include <stdio.h>
#include <fstream>
#include <iostream>
#include <sstream>
#include <time.h>
#include <string>
#include <cstdlib>
#include <cstring>
#include <sbml/SBMLTypes.h>
#include <sys/types.h>
#include <dirent.h>
#include <unistd.h>
// using namespace std;
// using delclarations, bit of namespace pollution, but if you're overriding cout, cin, endl or string you've got bigger problems...
using std::cout;
using std::cin;
using std::endl;
using std::string;
// assumes we won't go above 9999 items in a list.
const int MAX_NUMBER = 4;
// #############################################################################################
// CONSTRUCTOR
//
SBML_confInput::SBML_confInput(){
stream_set = false;
// set array elements to zero
for (int i = 0 ; i < 10 ; i++){
seek_locations[i] = 0;
}
// to indicate the fact that locations have not yet been identified
seek_locations[0] = -3;
ifstream conf_stream;
}
bool SBML_confInput::load_conf(){
return load_conf("");
}
// #############################################################################################
// LOAD integrate configuration file into conf_stream
//
bool SBML_confInput::load_conf(std::string conf_file)
{
// if stream is already loaded close and prepare to open a new file
if (stream_set){
conf_stream.close();
stream_set = false;
}
log_stream << endl << "---- OPENING CONF FILE ---------" << endl << endl;
char path_c[FILENAME_MAX];
// if no conf file specified, go for default
if (conf_file == ""){
conf_file.clear();
log_stream << "Default conf file used (integrate.conf)" << endl;
conf_file = "integrate.conf";
}
else
log_stream << "User defined conf file used (" << conf_file << ")" << endl;
// get current directory
if (!getcwd(path_c, sizeof(path_c)))
autoAbort("Fatal Error (line 223 in sbml_formatter.cpp) - unable to get current directory");
// set end to terminal character for proper formatting;
path_c[sizeof(path_c) - 1] = '\0';
DIR *dirp = NULL;
dirp = opendir(path_c);
string currentDir(path_c);
if (dirp)
{
struct dirent *dp = NULL;
log_stream << "Searching for configuration file;" << endl;
while ( (dp = readdir( dirp )) != NULL )
{
std::string file( dp->d_name );
log_stream << "filename: " << file << endl;
if (file == conf_file){
conf_stream.open(file.c_str(), ifstream::in);
stream_set = true;
log_stream << "Conf file loaded succesfully" << endl;
closedir(dirp);
return true;
}
}
cout << "#######################################################" << endl;
cerr << "ERROR - unable to find " << conf_file << " - files are;" << endl;
log_stream << "ERROR - unable to find " << conf_file << " - files are;" << endl;
cout << "You can explore the loaded models, but integration will not be possible" << endl;
any_key_to_continue();
closedir( dirp );
}
return false;
}
// #############################################################################################
//
//
//
bool SBML_confInput::import_data(const Model* modelNew, const Model* modelB, std::string conf_file){
// For now we're hardcoding in default integrate.conf - selectable filename to added
// TODO - add in "select filename functionality"
if (!load_conf("")){
cerr << "ERROR - problem with importing conf file." << endl;
log_stream << "ERROR - problem with importing conf file. Reselect conf file please" << endl;
return false;
}
log_stream << "About to import data from conf_file (";
if (conf_file != "")
log_stream << conf_file << "). Hold onto your hat!" << endl;
else
log_stream << "integrate.conf). Hold onto your hat!" << endl;
conf_preprocess();
set_import_list(modelB);
set_replace_or_integrate_list(modelNew, modelB, false);
set_replace_or_integrate_list(modelNew, modelB, true);
return true;
}
// #############################################################################################
// RESET_SEEK
// resets the seekg pointer in the loaded conf_file to the beginning, or gives a warning and
// returns false if the stream is broken
//
bool SBML_confInput::reset_seek(){
if (!stream_set){
cerr << "WARNING - Unlabe to reset_seek, no conf file currently loaded" << endl;
log_stream << "WARNING - Unlabe to reset_seek, no conf file currently loaded" << endl;
return false;
}
conf_stream.clear();
conf_stream.seekg(0);
return true;
}
// #############################################################################################
// CONF_PREPROCESS
// Analyses the conf_file, initializes the seek_location array (used by list_getter functions) and
// ensures file integrity is good for data read
//
void SBML_confInput::conf_preprocess(){
log_stream << "Preprocessing..." << endl;
char temp_char = ' ';
// Each of the seek_location array elements sets an int, which is infact a pointer location
// in the .conf file which specifies where a section (Species, FunctionDefinition etc) starts.
// These locations are then used as reference points to jump to to begin importing the specific
// section
seek_locations[0] = find_in_file("FunctionDefinitions:", true);
log_stream << "seek_locations[0] = " << seek_locations[0] << endl;
seek_locations[1] = find_in_file("UnitDefinitions:", true);
log_stream << "seek_locations[1] = " << seek_locations[1] << endl;
seek_locations[2] = find_in_file("Compartments:", true);
log_stream << "seek_locations[2] = " << seek_locations[2] << endl;
seek_locations[3] = find_in_file("Species:", true);
log_stream << "seek_locations[3] = " << seek_locations[3] << endl;
seek_locations[4] = find_in_file("Parameters:", true);
log_stream << "seek_locations[4] = " << seek_locations[4] << endl;
seek_locations[5] = find_in_file("InitialAssignments:", true);
log_stream << "seek_locations[5] = " << seek_locations[5] << endl;
seek_locations[6] = find_in_file("Rules:", true);
log_stream << "seek_locations[6] = " << seek_locations[6] << endl;
seek_locations[7] = find_in_file("Constraints:", true);
log_stream << "seek_locations[7] = " << seek_locations[7] << endl;
seek_locations[8] = find_in_file("Reactions:", true);
log_stream << "seek_locations[8] = " << seek_locations[8] << endl;
seek_locations[9] = find_in_file("Events:", true);
log_stream << "seek_locations[9] = " << seek_locations[9] << endl;
// checking conf stream for [], which indicates someone forgot to add data to the conf file!
while (conf_stream.good()){
conf_stream.get(temp_char);
if (temp_char == '['){
conf_stream.get(temp_char);
if (temp_char == ']'){
log_stream << "ERROR - in conf_preprocess() line 166, two [] back-to-back - this usually means there is missing data!" << endl;
autoAbort("Error in .conf file - two square brackets back to back ([]) - this usually indicates missing data! - Aborting...");
}
}
}
for (int i = 0 ; i < 10 ; i++){
if (seek_locations[i] == -1)
autoAbort("Error in .conf file - unable to find one of the ten sections");
if (seek_locations[i] == -2)
autoAbort("Error in .conf file - unspecified stream error on loading file");
}
log_stream << "Preprocessing finished successfully" << endl;
}
// #############################################################################################
// FIND_IN_FILE
// finds the pointer location in conf_file of the defined section.
// Returns -2 if stream is bad, and -1 if cannot be found.
//
// NB - on exit of this function, find_in_file resets the stream position and error flags to the
// beginning.
// However, on input it only resets if reset is true (allowing you to start searching where the
// position pointer is currently set to. If you're just searching the whole file make sure you
// include the reset variable to true.
int SBML_confInput::find_in_file(std::string section, bool reset){
// avoid a previously malformed pointer location/error state to disrup the search process
if (reset)
reset_seek();
char temp_char;
bool matching = false;
int position = conf_stream.tellg();
int location = 0;
int string_end = section.length();
// if conf_stream is dead
if (!conf_stream.good())
return -2;
// create cstring version of the string we've input
char* section_c = new char[section.length() + 1];
strcpy(section_c, section.c_str());
while (conf_stream.good()){
// reset at the start of each comparison
matching = false;
conf_stream.get(temp_char);
if (temp_char == section_c[location]){
matching = true;
// if we're at the end and have fully matched the string
if (location+1 == string_end){
delete [] section_c;
reset_seek();
return position-string_end;
}
location++;
}
// if temp_char and the current positin are not matching, but location in the cstring is not 0
// then reset to 0
if (!matching && location>0)
location = 0;
position++;
}
// If we get here then no match in the file!
delete [] section_c;
reset_seek();
return -1;
}
// #############################################################################################
// SET_REPLACE_OR_INTEGRATE_LISTS
//
// Define the import_lists (in the container member attributes) based on the data from the config file.
//
// Takes two const model pointers, modelA should be to the model you're building, while modelB is
// the one you're importing into modelA. So for replacement, the elements defined as modelA elemenst
// will be replaced by the modelB element defined in modelA.
//
// If replace is set, the function fills in the "replacement" lists, if not it does the integtrate
// lists
//
// ***Requires that conf_preprocess() has been run first***
// #############################################################################################
void SBML_confInput::set_replace_or_integrate_list(const Model* modelA, const Model* modelB, bool replace){
int* number_array;
int elements;
string search_term;
if (replace)
search_term = "Replace:";
else
search_term = "Integrate:";
// -3 means seek_locations array has not been set
if (seek_locations[0] == -3)
autoAbort("FATAL ERROR - conf_preprocess() *MUST* be run before set_replace_or_integrate_list(...)");
log_stream << endl << "--- Defining";
if (replace)
log_stream << " replace lists --" << endl;
else
log_stream << " integrate lists ---" << endl;
// -- Function Definitions ----------------------------------------------------------------
if (modelB->getNumFunctionDefinitions() > 0){
section_set(search_term, 0);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumFunctionDefinitions() || number_array[i] < 0){
log_stream << "WARNING - in loading functionDefinitions for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumFunctionDefinitions() || number_array[i+1] < 0){
log_stream << "WARNING - in loading functionDefinitions for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting function definitions modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
function_container.add_to_replace(modelA->getFunctionDefinition(number_array[i]), modelB->getFunctionDefinition(number_array[i+1]));
}
else{
log_stream << "Putting function definitions modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
function_container.add_to_integrate(modelA->getFunctionDefinition(number_array[i]), modelB->getFunctionDefinition(number_array[i+1]));
}
}
}
else
log_stream << "No function definitions in modelB" << endl;
// -- Unit Definitions ----------------------------------------------------------------
if (modelB->getNumUnitDefinitions() > 0){
section_set(search_term, 1);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumUnitDefinitions() || number_array[i] < 0){
log_stream << "WARNING - in loading unitDefinitions for replacement/integration from conf file, non-existant unitDef referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumUnitDefinitions() || number_array[i+1] < 0){
log_stream << "WARNING - in loading unitDefinitions for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting unit definitions modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
unit_container.add_to_replace(modelA->getUnitDefinition(number_array[i]), modelB->getUnitDefinition(number_array[i+1]));
}
else{
log_stream << "Putting unit definitions modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
unit_container.add_to_integrate(modelA->getUnitDefinition(number_array[i]), modelB->getUnitDefinition(number_array[i+1]));
}
}
}
else
log_stream << "No unit definitions in modelB" << endl;
// -- Compartments ----------------------------------------------------------------
if (modelB->getNumCompartments() > 0){
section_set(search_term, 2);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumCompartments() || number_array[i] < 0){
log_stream << "WARNING - in loading compartments for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumCompartments() || number_array[i+1] < 0){
log_stream << "WARNING - in loading compartment for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace) {
log_stream << "Putting compartment modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
compartment_container.add_to_replace(modelA->getCompartment(number_array[i]), modelB->getCompartment(number_array[i+1]));
}
else {
log_stream << "Putting compartment modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
compartment_container.add_to_integrate(modelA->getCompartment(number_array[i]), modelB->getCompartment(number_array[i+1]));
}
}
}
else
log_stream << "No compartments in modelB" << endl;
// -- Species ----------------------------------------------------------------
if (modelB->getNumSpecies() > 0){
section_set(search_term, 3);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumSpecies() || number_array[i] < 0){
log_stream << "WARNING - in loading species for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumSpecies() || number_array[i+1] < 0){
log_stream << "WARNING - in loading species for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting species modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
species_container.add_to_replace(modelA->getSpecies(number_array[i]), modelB->getSpecies(number_array[i+1]));
}
else {
log_stream << "Putting species modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
species_container.add_to_integrate(modelA->getSpecies(number_array[i]), modelB->getSpecies(number_array[i+1]));
}
}
}
else
log_stream << "No species in modelB" << endl;
// -- Parameters ----------------------------------------------------------------
if (modelB->getNumParameters() > 0){
section_set(search_term, 4);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumParameters() || number_array[i] < 0){
log_stream << "WARNING - in loading parameter for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumParameters() || number_array[i+1] < 0){
log_stream << "WARNING - in loading parameter for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting parameter modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
parameter_container.add_to_replace(modelA->getParameter(number_array[i]), modelB->getParameter(number_array[i+1]));
}
else{
log_stream << "Putting parameter modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
parameter_container.add_to_integrate(modelA->getParameter(number_array[i]), modelB->getParameter(number_array[i+1]));
}
}
}
else
log_stream << "No parameters in modelB" << endl;
// -- Initial Assignment ----------------------------------------------------------------
if (modelB->getNumInitialAssignments() > 0){
section_set(search_term, 5);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumInitialAssignments() || number_array[i] < 0){
log_stream << "WARNING - in loading initial assignment for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumInitialAssignments() || number_array[i+1] < 0){
log_stream << "WARNING - in loading initial assignment for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting initial assignment modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
initialAssignment_container.add_to_replace(modelA->getInitialAssignment(number_array[i]), modelB->getInitialAssignment(number_array[i+1]));
}
else{
log_stream << "Putting initial assignment modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
initialAssignment_container.add_to_integrate(modelA->getInitialAssignment(number_array[i]), modelB->getInitialAssignment(number_array[i+1]));
}
}
}
else
log_stream << "No initial assignments in modelB" << endl;
// -- Rules ----------------------------------------------------------------
if (modelB->getNumRules() > 0){
section_set(search_term, 6);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumRules() || number_array[i] < 0){
log_stream << "WARNING - in loading rule for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumRules() || number_array[i+1] < 0){
log_stream << "WARNING - in loading rule for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting rule modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
rule_container.add_to_replace(modelA->getRule(number_array[i]), modelB->getRule(number_array[i+1]));
}
else{
log_stream << "Putting rule modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
rule_container.add_to_integrate(modelA->getRule(number_array[i]), modelB->getRule(number_array[i+1]));
}
}
}
else
log_stream << "No rules in modelB" << endl;
// -- Constraints ----------------------------------------------------------------
if (modelB->getNumConstraints() > 0){
section_set(search_term, 7);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumConstraints() || number_array[i] < 0){
log_stream << "WARNING - in loading constraint for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumConstraints() || number_array[i+1] < 0){
log_stream << "WARNING - in loading constraint for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting constraint modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
constraint_container.add_to_replace(modelA->getConstraint(number_array[i]), modelB->getConstraint(number_array[i+1]));
}
else{
log_stream << "Putting constraint modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
constraint_container.add_to_integrate(modelA->getConstraint(number_array[i]), modelB->getConstraint(number_array[i+1]));
}
}
}
else
log_stream << "No constraints in modelB" << endl;
// -- Reaction ----------------------------------------------------------------
if (modelB->getNumReactions() > 0){
section_set(search_term, 8);
elements = get_number_list(number_array);
even_number(elements);
for (int i = 0 ; i < elements ; i=i+2){
if (number_array[i] >= (int)modelA->getNumReactions() || number_array[i] < 0){
log_stream << "WARNING - in loading reaction for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumReactions() || number_array[i+1] < 0){
log_stream << "WARNING - in loading reaction for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting reaction modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
reaction_container.add_to_replace(modelA->getReaction(number_array[i]), modelB->getReaction(number_array[i+1]));
}
else{
log_stream << "Putting reaction modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
reaction_container.add_to_integrate(modelA->getReaction(number_array[i]), modelB->getReaction(number_array[i+1]));
}
}
}
else
log_stream << "No reactions in modelB" << endl;
// -- Events ----------------------------------------------------------------
if (modelB->getNumEvents() > 0){
section_set(search_term, 9);
even_number(elements);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumEvents() || number_array[i] < 0){
log_stream << "WARNING - in loading events for replacement/integration from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
if (number_array[i+1] >= (int)modelB->getNumEvents() || number_array[i+1] < 0){
log_stream << "WARNING - in loading events for replacement/integration from conf file, non-existant functionDef referenced (" << number_array[i+1] << "). Ignoring..." << endl;
continue;
}
if (replace){
log_stream << "Putting events modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into replace list" << endl;
event_container.add_to_replace(modelA->getEvent(number_array[i]), modelB->getEvent(number_array[i+1]));
}
else{
log_stream << "Putting events modelA[" << number_array[i] << "] and modelB [" << number_array[i+1] << "] into integrate list" << endl;
event_container.add_to_integrate(modelA->getEvent(number_array[i]), modelB->getEvent(number_array[i+1]));
}
}
}
else
log_stream << "No events in modelB" << endl;
delete number_array;
}
// #############################################################################################
// SET_IMPORT_LIST
// define the import_lists (in the container member attributes) based on the data from the config file.
// ***Requires that conf_preprocess() has been run first***
//
//// #############################################################################################
void SBML_confInput::set_import_list(const Model* modelB){
int* number_array;
int elements;
log_stream << endl << "--- Defining import_list ---" << endl;
// -3 implies seek_locations array has not been set
if (seek_locations[0] == -3)
autoAbort("FATAL ERROR - conf_preprocess() *MUST* be run before set_import_list(...)");
log_stream << "Defining import_lists..." << endl << endl;
// -- Function Definitions ----------------------------------------------------------------
if (modelB->getNumFunctionDefinitions() > 0){
section_set("Import:", 0);
int num_function = modelB->getNumFunctionDefinitions();
log_stream << "num = " << num_function << endl;
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumFunctionDefinitions() || number_array[i] < 0){
log_stream << "WARNING - in loading functionDefinitions for import from conf file, non-existant functionDef referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting function definition [" << number_array[i] << "] into import list" << endl;
function_container.add_to_import( modelB->getFunctionDefinition(number_array[i]));
}
}
else
log_stream << "No function definitions in modelB" << endl;
// -- Unit Definitions ----------------------------------------------------------------
if (modelB->getNumUnitDefinitions() > 0){
section_set("Import:", 1);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumUnitDefinitions() || number_array[i] < 0){
log_stream << "WARNING - in loading unitDefinitions for import from conf file, non-existant unitDef referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting unit definition [" << number_array[i] << "] into import list" << endl;
unit_container.add_to_import( modelB->getUnitDefinition(number_array[i]));
}
}
else
log_stream << "No unit definitions in modelB" << endl;
// -- Compartments ----------------------------------------------------------------
if (modelB->getNumCompartments() > 0){
section_set("Import:", 2);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumCompartments() || number_array[i] < 0){
log_stream << "WARNING - in loading compartments for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting compartment [" << number_array[i] << "] into import list" << endl;
compartment_container.add_to_import( modelB->getCompartment(number_array[i]));
}
}
else
log_stream << "No compartments in modelB (WARNING - Suggests corrupt model)" << endl;
// -- Species ----------------------------------------------------------------
if (modelB->getNumSpecies() > 0){
section_set("Import:", 3);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumSpecies() || number_array[i] < 0){
log_stream << "WARNING - in loading compartments for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting species [" << number_array[i] << "] into import list" << endl;
species_container.add_to_import( modelB->getSpecies(number_array[i]));
}
}
else
log_stream << "No species in modelB" << endl;
// -- Parameters ----------------------------------------------------------------
if (modelB->getNumParameters() > 0){
section_set("Import:", 4);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumParameters() || number_array[i] < 0){
log_stream << "WARNING - in loading parameter for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting parameter [" << number_array[i] << "] into import list" << endl;
parameter_container.add_to_import(modelB->getParameter(number_array[i]));
}
}
else
log_stream << "No parameters in modelB" << endl;
// -- Initial Assignment ----------------------------------------------------------------
if (modelB->getNumInitialAssignments() > 0){
section_set("Import:", 5);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumInitialAssignments() || number_array[i] < 0){
log_stream << "WARNING - in loading assignment for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting initial assignment [" << number_array[i] << "] into import list" << endl;
initialAssignment_container.add_to_import(modelB->getInitialAssignment(number_array[i]));
}
}
else
log_stream << "No initial assignments in modelB" << endl;
// -- Rules ----------------------------------------------------------------
if (modelB->getNumRules() > 0){
section_set("Import:", 6);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumRules() || number_array[i] < 0){
log_stream << "WARNING - in loading rule for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting rule [" << number_array[i] << "] into import list" << endl;
rule_container.add_to_import(modelB->getRule(number_array[i]));
}
}
else
log_stream << "No rules in modelB" << endl;
// -- Constraints ----------------------------------------------------------------
if (modelB->getNumConstraints() > 0){
section_set("Import:", 7);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumConstraints() || number_array[i] < 0){
log_stream << "WARNING - in loading constraint for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting constraint [" << number_array[i] << "] into import list" << endl;
constraint_container.add_to_import(modelB->getConstraint(number_array[i]));
}
}
else
log_stream << "No constraints in modelB" << endl;
// -- Reaction ----------------------------------------------------------------
if (modelB->getNumReactions() > 0){
section_set("Import:", 8);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumReactions() || number_array[i] < 0){
log_stream << "WARNING - in loading reaction for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting reaction [" << number_array[i] << "] into import list" << endl;
reaction_container.add_to_import(modelB->getReaction(number_array[i]));
}
}
else
log_stream << "No reactions in modelB" << endl;
// -- Events ----------------------------------------------------------------
if (modelB->getNumEvents() > 0){
section_set("Import:", 9);
elements = get_number_list(number_array);
for (int i = 0 ; i < elements ; i++){
if (number_array[i] >= (int)modelB->getNumEvents() || number_array[i] < 0){
log_stream << "WARNING - in loading events for import from conf file, non-existant compartment referenced (" << number_array[i] << "). Ignoring..." << endl;
continue;
}
log_stream << "Putting event [" << number_array[i] << "] into import list" << endl;
event_container.add_to_import(modelB->getEvent(number_array[i]));
}
}
else
log_stream << "No events in modelB" << endl;
delete number_array;
}
// #############################################################################################
// SECTION_SET
// Sets the seekg pointer in conf_file to the position after element [0-9] defined by the string
// (typically "Import:", "Replace:" or "Integrate:"
//
void SBML_confInput::section_set(std::string section, int element){
reset_seek();
conf_stream.seekg(seek_locations[element]);
conf_stream.seekg(find_in_file(section.c_str(), false));
}
// #############################################################################################
// GET_NUMBER_LIST
// Build an array of values from the conf_file based on where the seekg pointer is currently located,
// with the caveat that
// a) Paired values are [1,2] [3,4] ... [n-1, n]
// b) List values are [1,2,3 ... n]
// (NB, the values are irrelevant, as is their order, this is simply to demonstrate structure
int SBML_confInput::get_number_list(int*& number_array){
int ret_val = 0, array_pos = 0, ref_num, input_pos = 0;
int original_seekpos = conf_stream.tellg();
char input[MAX_NUMBER];
char temp_char = ' ';
// set input_array to all ' '
reset_cstr(input, MAX_NUMBER);
while (temp_char != '\n'){
conf_stream.get(temp_char);
if (temp_char == ',' || temp_char == ']')
ret_val++;
}
// numer_array is an array of ints which is the size of the number of
// values we're importing from the conf file
number_array = new int[ret_val];
// reset the stream and temp_char so we're back where we were on function entry
conf_stream.clear();
conf_stream.seekg(original_seekpos);
temp_char = ' ';
while (temp_char != '\n'){
conf_stream.get(temp_char);
// entering the list of inport numbers
if (temp_char == '['){
// while you're not at the end of the list
while (temp_char != '\n'){
// get a character
conf_stream.get(temp_char);
// if we hit a comma or a ] we're at the end of a number
if (temp_char == ','|| temp_char == ']'){
ref_num = atoi(input);
// ref_num-1 as conf file indexes from 1 but all internal data
// structures reference from zero...
number_array[array_pos] = ref_num-1;
// increment the array position
array_pos++;
// reset input_array amd input_array position
reset_cstr(input, MAX_NUMBER);
input_pos = 0;
}
// else take the value and insert it into the input array
else if( static_cast<int>(temp_char) >= 48 && static_cast<int>(temp_char) <= 57){
input[input_pos] = temp_char;
input_pos++;
}
}
}
}
// used for debugging/analysis - left in for future work...
if (false){
log_stream << "Input array is : " ;
for (int i = 0; i < ret_val ;i++)
cout << number_array[i] << " ";
cout << endl;
}
return ret_val;
}
// i.e. move into .h file
void SBML_confInput::even_number(int elements){
if (2*(elements/2) != elements)
autoAbort("Fatal error - problem with conf_file formatting of pairs of elements for replacement or integration. Aborting");
}
// #############################################################################################
// #############################################################################################
// ## conf_file API (getters) ##
// #############################################################################################
// #############################################################################################
// While verbose, the below functioins provide an API for dealing with pathway viewer configuration
// files. The idea being that by defining two models and a file name, the user can then use these
// functions to get any information relating to the config file they may want, without dealing
// with any of the underlying logic, containers, file parsing or anything else. Return values are
// standard types (defined by the SBML documentation, or ints
//
int SBML_confInput::get_num_import_functionDefinitions(){ return (function_container.get_num_imports());}
int SBML_confInput::get_num_replace_functionDefinitions(){ return (function_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_functionDefinitions() { return (function_container.get_num_integrates());}
ListOfFunctionDefinitions* SBML_confInput::get_import_functionDefinitions()
{return function_container.get_import_list();}
ListOfFunctionDefinitions* SBML_confInput::get_replaceA_functionDefinitions()
{return function_container.get_replace_A_list();}
ListOfFunctionDefinitions* SBML_confInput::get_replaceB_functionDefinitions()
{return function_container.get_replace_B_list(); }
ListOfFunctionDefinitions* SBML_confInput::get_integrateA_functionDefinitions()
{return function_container.get_integrate_A_list(); }
ListOfFunctionDefinitions* SBML_confInput::get_integrateB_functionDefinitions()
{return function_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_unitDefinitions(){ return (unit_container.get_num_imports());}
int SBML_confInput::get_num_replace_unitDefinitions(){ return (unit_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_unitDefinitions(){ return (unit_container.get_num_integrates());}
ListOfUnitDefinitions* SBML_confInput::get_import_unitDefinitions()
{return unit_container.get_import_list();}
ListOfUnitDefinitions* SBML_confInput::get_replaceA_unitDefinitions()
{return unit_container.get_replace_A_list();}
ListOfUnitDefinitions* SBML_confInput::get_replaceB_unitDefinitions()
{return unit_container.get_replace_B_list(); }
ListOfUnitDefinitions* SBML_confInput::get_integrateA_unitDefinitions()
{return unit_container.get_integrate_A_list(); }
ListOfUnitDefinitions* SBML_confInput::get_integrateB_unitDefinitions()
{return unit_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_compartments(){ return (compartment_container.get_num_imports());}
int SBML_confInput::get_num_replace_compartments(){ return (compartment_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_compartments(){ return (compartment_container.get_num_integrates());}
ListOfCompartments* SBML_confInput::get_import_compartments()
{return compartment_container.get_import_list();}
ListOfCompartments* SBML_confInput::get_replaceA_compartments()
{return compartment_container.get_replace_A_list();}
ListOfCompartments* SBML_confInput::get_replaceB_compartments()
{return compartment_container.get_replace_B_list(); }
ListOfCompartments* SBML_confInput::get_integrateA_compartments()
{return compartment_container.get_integrate_A_list(); }
ListOfCompartments* SBML_confInput::get_integrateB_compartments()
{return compartment_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_species(){ return (species_container.get_num_imports());}
int SBML_confInput::get_num_replace_species(){ return (species_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_species(){ return (species_container.get_num_integrates());}
ListOfSpecies* SBML_confInput::get_import_species()
{return species_container.get_import_list();}
ListOfSpecies* SBML_confInput::get_replaceA_species()
{return species_container.get_replace_A_list();}
ListOfSpecies* SBML_confInput::get_replaceB_species()
{return species_container.get_replace_B_list(); }
ListOfSpecies* SBML_confInput::get_integrateA_species()
{return species_container.get_integrate_A_list(); }
ListOfSpecies* SBML_confInput::get_integrateB_species()
{return species_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_parameters(){ return (parameter_container.get_num_imports());}
int SBML_confInput::get_num_replace_parameters(){ return (parameter_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_parameters(){ return (parameter_container.get_num_integrates());}
ListOfParameters* SBML_confInput::get_import_parameters()
{return parameter_container.get_import_list();}
ListOfParameters* SBML_confInput::get_replaceA_parameters()
{return parameter_container.get_replace_A_list();}
ListOfParameters* SBML_confInput::get_replaceB_parameters()
{return parameter_container.get_replace_B_list(); }
ListOfParameters* SBML_confInput::get_integrateA_parameters()
{return parameter_container.get_integrate_A_list(); }
ListOfParameters* SBML_confInput::get_integrateB_parameters()
{return parameter_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_initialAssignments(){ return (initialAssignment_container.get_num_imports());}
int SBML_confInput::get_num_replace_initialAssignments(){ return (initialAssignment_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_initialAssignments(){ return (initialAssignment_container.get_num_integrates());}
ListOfInitialAssignments* SBML_confInput::get_import_initialAssignments()
{return initialAssignment_container.get_import_list();}
ListOfInitialAssignments* SBML_confInput::get_replaceA_initialAssignments()
{return initialAssignment_container.get_replace_A_list();}
ListOfInitialAssignments* SBML_confInput::get_replaceB_initialAssignments()
{return initialAssignment_container.get_replace_B_list(); }
ListOfInitialAssignments* SBML_confInput::get_integrateA_initialAssignments()
{return initialAssignment_container.get_integrate_A_list(); }
ListOfInitialAssignments* SBML_confInput::get_integrateB_initialAssignments()
{return initialAssignment_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_rules(){ return (rule_container.get_num_imports());}
int SBML_confInput::get_num_replace_rules(){ return (rule_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_rules(){ return (rule_container.get_num_integrates());}
ListOfRules* SBML_confInput::get_import_rules()
{return rule_container.get_import_list();}
ListOfRules* SBML_confInput::get_replaceA_rules()
{return rule_container.get_replace_A_list();}
ListOfRules* SBML_confInput::get_replaceB_rules()
{return rule_container.get_replace_B_list(); }
ListOfRules* SBML_confInput::get_integrateA_rules()
{return rule_container.get_integrate_A_list(); }
ListOfRules* SBML_confInput::get_integrateB_rules()
{return rule_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_constraints(){ return ( constraint_container.get_num_imports());}
int SBML_confInput::get_num_replace_constraints(){ return (constraint_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_constraints(){ return (constraint_container.get_num_integrates());}
ListOfConstraints* SBML_confInput::get_import_constraints()
{return constraint_container.get_import_list();}
ListOfConstraints* SBML_confInput::get_replaceA_constraints()
{return constraint_container.get_replace_A_list();}
ListOfConstraints* SBML_confInput::get_replaceB_constraints()
{return constraint_container.get_replace_B_list(); }
ListOfConstraints* SBML_confInput::get_integrateA_constraints()
{return constraint_container.get_integrate_A_list(); }
ListOfConstraints* SBML_confInput::get_integrateB_constraints()
{return constraint_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_reactions(){ return (reaction_container.get_num_imports());}
int SBML_confInput::get_num_replace_reactions(){ return (reaction_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_reactions(){ return (reaction_container.get_num_integrates());}
ListOfReactions* SBML_confInput::get_import_reactions()
{return reaction_container.get_import_list();}
ListOfReactions* SBML_confInput::get_replaceA_reactions()
{return reaction_container.get_replace_A_list();}
ListOfReactions* SBML_confInput::get_replaceB_reactions()
{return reaction_container.get_replace_B_list(); }
ListOfReactions* SBML_confInput::get_integrateA_reactions()
{return reaction_container.get_integrate_A_list(); }
ListOfReactions* SBML_confInput::get_integrateB_reactions()
{return reaction_container.get_integrate_B_list(); }
int SBML_confInput::get_num_import_events(){ return (event_container.get_num_imports());}
int SBML_confInput::get_num_replace_events(){ return (event_container.get_num_replacements());}
int SBML_confInput::get_num_integrate_events(){ return (event_container.get_num_integrates());}
ListOfEvents* SBML_confInput::get_import_events()
{return event_container.get_import_list();}
ListOfEvents* SBML_confInput::get_replaceA_events()
{return event_container.get_replace_A_list();}
ListOfEvents* SBML_confInput::get_replaceB_events()
{return event_container.get_replace_B_list(); }
ListOfEvents* SBML_confInput::get_integrateA_events()
{return event_container.get_integrate_A_list(); }
ListOfEvents* SBML_confInput::get_integrateB_events()
{return event_container.get_integrate_B_list(); }
| alexholehouse/SBMLIntegrator | src/sbml_confInput.cpp | C++ | gpl-3.0 | 47,810 |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'src/ui/mainwindow.ui'
#
# Created: Fri Feb 15 16:08:54 2013
# by: PyQt4 UI code generator 4.9.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
_fromUtf8 = lambda s: s
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(1024, 768)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setEnabled(True)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.centralwidget.sizePolicy().hasHeightForWidth())
self.centralwidget.setSizePolicy(sizePolicy)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.verticalLayout = QtGui.QVBoxLayout(self.centralwidget)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_3 = QtGui.QLabel(self.centralwidget)
self.label_3.setMaximumSize(QtCore.QSize(200, 200))
self.label_3.setText(_fromUtf8(""))
self.label_3.setPixmap(QtGui.QPixmap(_fromUtf8(":/logo/pixmaps/logo.jpg")))
self.label_3.setScaledContents(True)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_2.addWidget(self.label_3)
self.verticalLayout_2 = QtGui.QVBoxLayout()
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.label_2 = QtGui.QLabel(self.centralwidget)
font = QtGui.QFont()
font.setPointSize(20)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.verticalLayout_2.addWidget(self.label_2)
self.labelServerId = QtGui.QLabel(self.centralwidget)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush)
brush = QtGui.QBrush(QtGui.QColor(118, 116, 113))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(118, 116, 113))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush)
self.labelServerId.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(75)
self.labelServerId.setFont(font)
self.labelServerId.setAlignment(QtCore.Qt.AlignCenter)
self.labelServerId.setObjectName(_fromUtf8("labelServerId"))
self.verticalLayout_2.addWidget(self.labelServerId)
self.labelYear = QtGui.QLabel(self.centralwidget)
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(0, 0, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush)
brush = QtGui.QBrush(QtGui.QColor(118, 116, 113))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush)
self.labelYear.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(37)
font.setBold(True)
font.setWeight(75)
self.labelYear.setFont(font)
self.labelYear.setTextFormat(QtCore.Qt.PlainText)
self.labelYear.setAlignment(QtCore.Qt.AlignCenter)
self.labelYear.setObjectName(_fromUtf8("labelYear"))
self.verticalLayout_2.addWidget(self.labelYear)
self.horizontalLayout_2.addLayout(self.verticalLayout_2)
self.label = QtGui.QLabel(self.centralwidget)
self.label.setMaximumSize(QtCore.QSize(200, 200))
self.label.setText(_fromUtf8(""))
self.label.setPixmap(QtGui.QPixmap(_fromUtf8(":/logo/pixmaps/Stampa-silicone-tondo-fi55.png")))
self.label.setScaledContents(True)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_2.addWidget(self.label)
self.verticalLayout.addLayout(self.horizontalLayout_2)
self.line = QtGui.QFrame(self.centralwidget)
self.line.setFrameShadow(QtGui.QFrame.Raised)
self.line.setLineWidth(4)
self.line.setFrameShape(QtGui.QFrame.HLine)
self.line.setFrameShadow(QtGui.QFrame.Sunken)
self.line.setObjectName(_fromUtf8("line"))
self.verticalLayout.addWidget(self.line)
spacerItem = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.btnNewYear = QtGui.QToolButton(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(11)
sizePolicy.setHeightForWidth(self.btnNewYear.sizePolicy().hasHeightForWidth())
self.btnNewYear.setSizePolicy(sizePolicy)
self.btnNewYear.setMinimumSize(QtCore.QSize(0, 200))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.btnNewYear.setFont(font)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/img/pixmaps/planner.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btnNewYear.setIcon(icon)
self.btnNewYear.setIconSize(QtCore.QSize(128, 128))
self.btnNewYear.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.btnNewYear.setAutoRaise(False)
self.btnNewYear.setArrowType(QtCore.Qt.NoArrow)
self.btnNewYear.setObjectName(_fromUtf8("btnNewYear"))
self.horizontalLayout.addWidget(self.btnNewYear)
self.btnCloseYear = QtGui.QToolButton(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(11)
sizePolicy.setHeightForWidth(self.btnCloseYear.sizePolicy().hasHeightForWidth())
self.btnCloseYear.setSizePolicy(sizePolicy)
self.btnCloseYear.setMinimumSize(QtCore.QSize(0, 200))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.btnCloseYear.setFont(font)
self.btnCloseYear.setAutoFillBackground(False)
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8(":/img/pixmaps/save.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btnCloseYear.setIcon(icon1)
self.btnCloseYear.setIconSize(QtCore.QSize(128, 128))
self.btnCloseYear.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.btnCloseYear.setObjectName(_fromUtf8("btnCloseYear"))
self.horizontalLayout.addWidget(self.btnCloseYear)
self.btnTeachers = QtGui.QToolButton(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(11)
sizePolicy.setHeightForWidth(self.btnTeachers.sizePolicy().hasHeightForWidth())
self.btnTeachers.setSizePolicy(sizePolicy)
self.btnTeachers.setMinimumSize(QtCore.QSize(0, 200))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.btnTeachers.setFont(font)
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8(":/img/pixmaps/education.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btnTeachers.setIcon(icon2)
self.btnTeachers.setIconSize(QtCore.QSize(128, 128))
self.btnTeachers.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.btnTeachers.setObjectName(_fromUtf8("btnTeachers"))
self.horizontalLayout.addWidget(self.btnTeachers)
self.btnStudents = QtGui.QToolButton(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(11)
sizePolicy.setHeightForWidth(self.btnStudents.sizePolicy().hasHeightForWidth())
self.btnStudents.setSizePolicy(sizePolicy)
self.btnStudents.setMinimumSize(QtCore.QSize(0, 200))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.btnStudents.setFont(font)
self.btnStudents.setStyleSheet(_fromUtf8(""))
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8(":/img/pixmaps/System-users.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btnStudents.setIcon(icon3)
self.btnStudents.setIconSize(QtCore.QSize(128, 128))
self.btnStudents.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.btnStudents.setObjectName(_fromUtf8("btnStudents"))
self.horizontalLayout.addWidget(self.btnStudents)
self.btnAdvanced = QtGui.QToolButton(self.centralwidget)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Maximum)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(11)
sizePolicy.setHeightForWidth(self.btnAdvanced.sizePolicy().hasHeightForWidth())
self.btnAdvanced.setSizePolicy(sizePolicy)
self.btnAdvanced.setMinimumSize(QtCore.QSize(0, 200))
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.btnAdvanced.setFont(font)
icon4 = QtGui.QIcon()
icon4.addPixmap(QtGui.QPixmap(_fromUtf8(":/img/pixmaps/advanced_options.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.btnAdvanced.setIcon(icon4)
self.btnAdvanced.setIconSize(QtCore.QSize(128, 128))
self.btnAdvanced.setToolButtonStyle(QtCore.Qt.ToolButtonTextUnderIcon)
self.btnAdvanced.setObjectName(_fromUtf8("btnAdvanced"))
self.horizontalLayout.addWidget(self.btnAdvanced)
self.verticalLayout.addLayout(self.horizontalLayout)
spacerItem1 = QtGui.QSpacerItem(20, 40, QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Expanding)
self.verticalLayout.addItem(spacerItem1)
MainWindow.setCentralWidget(self.centralwidget)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1024, 29))
self.menubar.setObjectName(_fromUtf8("menubar"))
self.menuImpostazioni = QtGui.QMenu(self.menubar)
self.menuImpostazioni.setEnabled(False)
self.menuImpostazioni.setObjectName(_fromUtf8("menuImpostazioni"))
self.menuHelp = QtGui.QMenu(self.menubar)
self.menuHelp.setEnabled(False)
self.menuHelp.setObjectName(_fromUtf8("menuHelp"))
self.menuArchivi = QtGui.QMenu(self.menubar)
self.menuArchivi.setObjectName(_fromUtf8("menuArchivi"))
MainWindow.setMenuBar(self.menubar)
self.actionAbout = QtGui.QAction(MainWindow)
self.actionAbout.setObjectName(_fromUtf8("actionAbout"))
self.actionPreferenze = QtGui.QAction(MainWindow)
self.actionPreferenze.setObjectName(_fromUtf8("actionPreferenze"))
self.actionArchivioAnniPrec = QtGui.QAction(MainWindow)
self.actionArchivioAnniPrec.setObjectName(_fromUtf8("actionArchivioAnniPrec"))
self.menuImpostazioni.addAction(self.actionPreferenze)
self.menuHelp.addAction(self.actionAbout)
self.menuArchivi.addAction(self.actionArchivioAnniPrec)
self.menubar.addAction(self.menuArchivi.menuAction())
self.menubar.addAction(self.menuImpostazioni.menuAction())
self.menubar.addAction(self.menuHelp.menuAction())
self.retranslateUi(MainWindow)
QtCore.QObject.connect(self.btnAdvanced, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.execAdvancedUserManager)
QtCore.QObject.connect(self.btnCloseYear, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.execYearEnd)
QtCore.QObject.connect(self.btnNewYear, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.execYearNew)
QtCore.QObject.connect(self.actionArchivioAnniPrec, QtCore.SIGNAL(_fromUtf8("triggered()")), MainWindow.showArchBackup)
QtCore.QObject.connect(self.btnStudents, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.showStudentsManager)
QtCore.QObject.connect(self.btnTeachers, QtCore.SIGNAL(_fromUtf8("clicked()")), MainWindow.showTeachersManager)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
self.label_2.setText(QtGui.QApplication.translate("MainWindow", "Pannello di Amministrazione del Server", None, QtGui.QApplication.UnicodeUTF8))
self.labelServerId.setText(QtGui.QApplication.translate("MainWindow", "TextLabel", None, QtGui.QApplication.UnicodeUTF8))
self.labelYear.setText(QtGui.QApplication.translate("MainWindow", "Anno -", None, QtGui.QApplication.UnicodeUTF8))
self.btnNewYear.setText(QtGui.QApplication.translate("MainWindow", "Nuovo Anno", None, QtGui.QApplication.UnicodeUTF8))
self.btnCloseYear.setText(QtGui.QApplication.translate("MainWindow", "Chiusura Anno", None, QtGui.QApplication.UnicodeUTF8))
self.btnTeachers.setText(QtGui.QApplication.translate("MainWindow", "Gestione Insegnanti", None, QtGui.QApplication.UnicodeUTF8))
self.btnStudents.setText(QtGui.QApplication.translate("MainWindow", "Gestione Alunni", None, QtGui.QApplication.UnicodeUTF8))
self.btnAdvanced.setText(QtGui.QApplication.translate("MainWindow", "Gestione Avanzata", None, QtGui.QApplication.UnicodeUTF8))
self.menuImpostazioni.setTitle(QtGui.QApplication.translate("MainWindow", "Impostazioni", None, QtGui.QApplication.UnicodeUTF8))
self.menuHelp.setTitle(QtGui.QApplication.translate("MainWindow", "Help", None, QtGui.QApplication.UnicodeUTF8))
self.menuArchivi.setTitle(QtGui.QApplication.translate("MainWindow", "Archivi", None, QtGui.QApplication.UnicodeUTF8))
self.actionAbout.setText(QtGui.QApplication.translate("MainWindow", "About", None, QtGui.QApplication.UnicodeUTF8))
self.actionPreferenze.setText(QtGui.QApplication.translate("MainWindow", "Preferenze", None, QtGui.QApplication.UnicodeUTF8))
self.actionArchivioAnniPrec.setText(QtGui.QApplication.translate("MainWindow", "Archivio anni precedenti", None, QtGui.QApplication.UnicodeUTF8))
import classerman_rc
| itarozzi/classerman | src/ui/mainwindow_ui.py | Python | gpl-3.0 | 16,000 |
package com.autowp.canreader;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
/**
* Created by autow on 13.02.2016.
*/
public class UsbDeviceSpinnerAdapter extends ArrayAdapter<UsbDevice> {
public UsbDeviceSpinnerAdapter(Context context, int resource, List<UsbDevice> objects) {
super(context, resource, objects);
}
@Override
public View getDropDownView(int position, View convertView,
ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
return getCustomView(position, convertView, parent);
}
public View getCustomView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.usbdevice_spinner_item, null);
}
UsbDevice device = getItem(position);
if (device != null) {
TextView tvProductName = (TextView)v.findViewById(R.id.textViewProductName);
TextView tvDeviceInto = (TextView)v.findViewById(R.id.textViewDeviceInfo);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
tvProductName.setText(device.getProductName());
String deviceInfo = String.format(
"%s %04X/%04X, %s",
device.getManufacturerName(),
device.getVendorId(),
device.getProductId(),
device.getDeviceName()
);
tvDeviceInto.setText(deviceInfo);
} else {
tvProductName.setText(device.getDeviceName());
String deviceInfo = String.format(
"%04X/%04X",
device.getVendorId(),
device.getProductId()
);
tvDeviceInto.setText(deviceInfo);
}
}
return v;
}
}
| autowp/CANreader | app/src/main/java/com/autowp/canreader/UsbDeviceSpinnerAdapter.java | Java | gpl-3.0 | 2,360 |
/*
Copyright (C) 2009-2013 Bengt Martensson.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see http://www.gnu.org/licenses/.
*/
package org.harctoolbox.IrpMaster;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import javax.sound.sampled.AudioFileFormat;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import javax.sound.sampled.UnsupportedAudioFileException;
/**
* This class generates (or analyzes) a wave audio file that can be played
* on standard audio equipment and fed to a pair of anti-parallel double IR sending diodes,
* which can thus control IR equipment.
*
*
* @see <a href="http://www.lirc.org/html/audio.html">http://www.lirc.org/html/audio.html</a>
*/
public class Wave {
private static int debug = 0; // presently not used
private static int epsilon8Bit = 2;
private static int epsilon16Bit = 257;
private static JCommander argumentParser;
private static CommandLineArgs commandLineArgs = new CommandLineArgs();
/**
* Returns a line to the audio mixer on the local machine, suitable for sound with
* the parameter values given. When not needed, the user should close the line with its close()-function.
*
* @param audioFormat
* @return open audio line
* @throws LineUnavailableException
*/
public static SourceDataLine getLine(AudioFormat audioFormat) throws LineUnavailableException {
SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat);
line.open(audioFormat);
return line;
}
private static void usage(int exitcode) {
StringBuilder str = new StringBuilder(256);
argumentParser.usage(str);
str.append("\n"
+ "parameters: <protocol> <deviceno> [<subdevice_no>] commandno [<toggle>]\n"
+ " or <Pronto code>\n"
+ " or <importfile>");
(exitcode == IrpUtils.exitSuccess ? System.out : System.err).println(str);
IrpUtils.exit(exitcode);
}
/**
* Provides a command line interface to the export/import functions.
*
* <pre>
* Usage: Wave [options] [parameters]
* Options:
* -c, --config Path to IrpProtocols.ini
* Default: data/IrpProtocols.ini
* -h, --help, -? Display help message
* Default: false
* -m, --macrofile Macro filename
* -1, --nodivide Do not divide modulation frequency
* Default: false
* -t, --omittail Skip silence at end
* Default: false
* -o, --outfile Output filename
* Default: irpmaster.wav
* -p, --play Send the generated wave to the audio device of the
* local machine
* Default: false
* -r, --repeats Number of times to include the repeat sequence
* Default: 0
* -f, --samplefrequency Sample frequency in Hz
* Default: 44100
* -q, --square Modulate with square wave instead of sine
* Default: false
* -S, --stereo Generate two channels in anti-phase
* Default: false
* -v, --version Display version information
* Default: false
* -s, samplesize Sample size in bits
* Default: 8
*
* parameters: <em>protocol</em> <em>deviceno</em> [<em>subdevice_no</em>] <em>commandno</em> [<em>toggle</em>]
* or <em>ProntoCode</em>
* or <em>importfile</em>
* </pre>
* @param args
*/
public static void main(String[] args) {
argumentParser = new JCommander(commandLineArgs);
argumentParser.setProgramName("Wave");
try {
argumentParser.parse(args);
} catch (ParameterException ex) {
System.err.println(ex.getMessage());
usage(IrpUtils.exitUsageError);
}
if (commandLineArgs.helpRequensted)
usage(IrpUtils.exitSuccess);
if (commandLineArgs.versionRequested) {
System.out.println(Version.versionString);
System.out.println("JVM: " + System.getProperty("java.vendor") + " " + System.getProperty("java.version") + " " + System.getProperty("os.name") + "-" + System.getProperty("os.arch"));
System.out.println();
System.out.println(Version.licenseString);
System.exit(IrpUtils.exitSuccess);
}
if (commandLineArgs.macrofile == null && commandLineArgs.parameters.isEmpty()) {
System.err.println("Parameters missing");
usage(IrpUtils.exitUsageError);
}
try {
if (commandLineArgs.parameters.size() == 1) {
// Exactly one argument left -> input wave file
String inputfile = commandLineArgs.parameters.get(0);
Wave wave = new Wave(new File(inputfile));
ModulatedIrSequence seq = wave.analyze(!commandLineArgs.dontDivide);
//IrSignal irSignal = new
DecodeIR.invoke(seq);
wave.dump(new File(inputfile + ".tsv"));
if (commandLineArgs.play)
wave.play();
} else {
//if (commandLineArgs.macrofile != null) {
//IrSequence irSequence = IrSequence.parseMacro(commandLineArgs.irprotocolsIniFilename, commandLineArgs.macrofile);
//Wave wave = new Wave()
//}
IrSignal irSignal = new IrSignal(commandLineArgs.irprotocolsIniFilename, 0, commandLineArgs.parameters.toArray(new String[commandLineArgs.parameters.size()]));
File file = new File(commandLineArgs.outputfile);
Wave wave = new Wave(irSignal.toModulatedIrSequence(true, commandLineArgs.noRepeats, true), commandLineArgs.sampleFrequency, commandLineArgs.sampleSize,
commandLineArgs.stereo ? 2 : 1, false /* bigEndian */,
commandLineArgs.omitTail, commandLineArgs.square, !commandLineArgs.dontDivide);
wave.export(file);
if (commandLineArgs.play)
wave.play();
}
} catch (IOException | UnsupportedAudioFileException | LineUnavailableException | IrpMasterException ex) {
System.err.println(ex.getMessage());
System.exit(IrpUtils.exitFatalProgramFailure);
}
}
private int noFrames = -1;
private AudioFormat audioFormat;
private byte[] buf;
private Wave() {
}
/**
* Reads a wave file into a Wave object.
*
* @param file Wave file as input.
* @throws UnsupportedAudioFileException
* @throws IOException
*/
public Wave(File file) throws UnsupportedAudioFileException, IOException {
AudioInputStream af = AudioSystem.getAudioInputStream(file);
audioFormat = af.getFormat();
noFrames = (int) af.getFrameLength();
buf = new byte[noFrames*audioFormat.getFrameSize()];
int n = af.read(buf, 0, buf.length);
if (n != buf.length)
System.err.println("Too few bytes read: " + n + " < " + buf.length);
}
/**
* Generates a wave audio file from its arguments.
*
* @param freq Carrier frequency in Hz.
* @param data double array of durations in micro seconds.
* @param sampleFrequency Sample frequency of the generated wave file.
* @param sampleSize Sample size (8 or 16) in bits of the samples.
* @param channels If == 2, generates two channels in perfect anti-phase.
* @param bigEndian if true, use bigendian byte order for 16 bit samples.
* @param omitTail If true, the last trailing gap will be omitted.
* @param square if true, use a square wave for modulation, otherwise a sine.
* @param divide If true, divides the carrier frequency by 2, to be used with full-wave rectifiers, e.g. a pair of IR LEDs in anti-parallel.
* @throws IncompatibleArgumentException
*/
@SuppressWarnings("ValueOfIncrementOrDecrementUsed")
public Wave(double freq, double[] data,
int sampleFrequency, int sampleSize, int channels, boolean bigEndian,
boolean omitTail, boolean square, boolean divide)
throws IncompatibleArgumentException {
if (data == null || data.length == 0)
throw new IncompatibleArgumentException("Cannot create wave file from zero array.");
double sf = sampleFrequency/1000000.0;
int[] durationsInSamplePeriods = new int[omitTail ? data.length-1 : data.length];
int length = 0;
for (int i = 0; i < durationsInSamplePeriods.length; i++) {
durationsInSamplePeriods[i] = (int) Math.round(Math.abs(sf*data[i]));
length += durationsInSamplePeriods[i];
}
double c = sampleFrequency/freq;
buf = new byte[length*sampleSize/8*channels];
int index = 0;
for (int i = 0; i < data.length-1; i += 2) {
// Handle pulse, even index
for (int j = 0; j < durationsInSamplePeriods[i]; j++) {
double t = j/(divide ? 2*c : c);
double fraq = t - (int)t;
double s = square
? (fraq < 0.5 ? -1.0 : 1.0)
: Math.sin(2*Math.PI*(fraq));
if (sampleSize == 8) {
int val = (int) Math.round(Byte.MAX_VALUE*s);
buf[index++] = (byte) val;
if (channels == 2)
buf[index++] = (byte)-val;
} else {
int val = (int) Math.round(Short.MAX_VALUE*s);
byte low = (byte) (val & 0xFF);
byte high = (byte) (val >> 8);
buf[index++] = bigEndian ? high : low;
buf[index++] = bigEndian ? low : high;
if (channels == 2) {
val = -val;
low = (byte) (val & 0xFF);
high = (byte) (val >> 8);
buf[index++] = bigEndian ? high : low;
buf[index++] = bigEndian ? low : high;
}
}
}
// Gap, odd index
if (!omitTail || i < data.length - 2) {
for (int j = 0; j < durationsInSamplePeriods[i + 1]; j++) {
for (int ch = 0; ch < channels; ch++) {
buf[index++] = 0;
if (sampleSize == 16)
buf[index++] = 0;
}
}
}
}
audioFormat = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleFrequency, sampleSize, channels, sampleSize/8*channels, sampleFrequency, bigEndian);
}
/**
* Generates a wave audio file from its arguments.
*
* @param irSequence ModulatedIrSequence to be used.
* @param sampleFrequency Sample frequency of the generated wave file.
* @param sampleSize Sample size (8 or 16) in bits of the samples.
* @param channels If == 2, generates two channels in perfect anti-phase.
* @param bigEndian if true, use bigendian byte order for 16 bit samples.
* @param omitTail If true, the last trailing gap will be omitted.
* @param square if true, use a square wave for modulation, otherwise a sine.
* @param divide If true, divides the carrier frequency by 2, to be used with full-wave rectifiers, e.g. a pair of IR LEDs in anti-parallel.
* @throws IncompatibleArgumentException
*/
public Wave(ModulatedIrSequence irSequence,
int sampleFrequency, int sampleSize, int channels, boolean bigEndian,
boolean omitTail, boolean square, boolean divide)
throws IncompatibleArgumentException {
this(irSequence.getFrequency(), irSequence.toDoubles(),
sampleFrequency, sampleSize, channels, bigEndian,
omitTail, square, divide);
}
/**
* Generates a wave audio file from its arguments.
*
* @param irSequence ModulatedIrSequence to be used.
* @param audioFormat AudioFormat bundling sampleFrequency, sample size, channels, and bigEndian together.
* @param omitTail If true, the last trailing gap will be omitted.
* @param square if true, use a square wave for modulation, otherwise a sine.
* @param divide If true, divides the carrier frequency by 2, to be used with full-wave rectifiers, e.g. a pair of IR LEDs in anti-parallel.
* @throws IncompatibleArgumentException
*/
public Wave(ModulatedIrSequence irSequence,
AudioFormat audioFormat,
boolean omitTail,
boolean square, boolean divide)
throws IncompatibleArgumentException {
this(irSequence,
(int) audioFormat.getSampleRate(), audioFormat.getSampleSizeInBits(),
audioFormat.getChannels(),
audioFormat.isBigEndian(),
omitTail, square, divide);
}
// set up integer data (left and right channel) from the byte array.
private int[][] computeData() {
int channels = audioFormat.getChannels();
int sampleSize = audioFormat.getSampleSizeInBits();
AudioFormat.Encoding encoding = audioFormat.getEncoding();
boolean bigEndian = audioFormat.isBigEndian();
int[][] data = new int[noFrames][channels];
if (encoding == AudioFormat.Encoding.PCM_UNSIGNED && sampleSize != 8) {
System.err.println("Case not yet implemented");
return null;
}
for (int frame = 0; frame < noFrames; frame++) {
if (sampleSize == 8) {
for (int ch = 0; ch < channels; ch++) {
int val = buf[channels*frame + ch];
if (encoding == AudioFormat.Encoding.PCM_UNSIGNED)
val += (val < 0) ? 128 : -128;
data[frame][ch] = val;
}
} else {
// sampleSize == 16
for (int ch = 0; ch < channels; ch++) {
int baseIndex = 2*(channels*frame + ch);
int high = buf[bigEndian ? baseIndex : baseIndex+1]; // may be negative
int low = buf[bigEndian ? baseIndex+1 : baseIndex]; // consider as unsigned
if (low < 0)
low += 256;
int value = 256*high + low;
data[frame][ch] = value;
}
}
}
return data;
}
/**
* Analyzes the data and computes a ModulatedIrSequence. Generates some messages on stderr.
*
* @param divide consider the carrier as having its frequency halved or not?
* @return ModulatedIrSequence computed from the data.
*/
public ModulatedIrSequence analyze(boolean divide) {
double sampleFrequency = audioFormat.getSampleRate();
int channels = audioFormat.getChannels();
System.err.println("Format is: " + audioFormat.toString() + ".");
System.err.println(String.format("%d frames = %7.6f seconds.", noFrames, noFrames/sampleFrequency));
int[][] data = computeData();
if (channels == 2) {
int noDiffPhase = 0;
int noDiffAntiphase = 0;
int noNonNulls = 0;
for (int i = 0; i < noFrames; i++) {
if (data[i][0] != 0 || data[i][1] != 0) { // do not count nulls
noNonNulls++;
if (data[i][0] != data[i][1])
noDiffPhase++;
if (data[i][0] != -data[i][1])
noDiffAntiphase++;
}
}
System.err.println("This is a 2-channel file. Left and right channel are "
+ (noDiffPhase == 0 ? "perfectly in phase."
: noDiffAntiphase == 0 ? "perfectly in antiphase."
: "neither completely in nor out of phase. Pairs in-phase:"
+ (noNonNulls - noDiffPhase) + ", pairs anti-phase: " + (noNonNulls - noDiffAntiphase)
+ " (out of " + noNonNulls + ")."));
System.err.println("Subsequent analysis will be base on the left channel exclusively.");
}
// Search the largest block of oscillations
ArrayList<Integer> durations = new ArrayList<>(noFrames);
int bestLength = -1; // length of longest block this far
int bestStart = -1;
boolean isInInterestingBlock = true;
int last = -1111111;
int epsilon = audioFormat.getSampleSizeInBits() == 8 ? epsilon8Bit : epsilon16Bit;
int firstNonNullIndex = 0; // Ignore leading silence, it is silly.
while (data[firstNonNullIndex][0] == 0)
firstNonNullIndex++;
if (firstNonNullIndex > 0)
System.err.println("The first " + firstNonNullIndex + " sample(s) are 0, ignored.");
int beg = firstNonNullIndex; // start of current block
for (int i = firstNonNullIndex; i < noFrames; i++) {
int value = data[i][0];
// two consecutive zeros -> interesting block ends
if (((Math.abs(value) <= epsilon && Math.abs(last) <= epsilon) || (i == noFrames - 1)) && isInInterestingBlock) {
isInInterestingBlock = false;
// evaluate just ended block
int currentLength = i - 1 - beg;
if (currentLength > bestLength) {
// longest this far
bestLength = currentLength;
bestStart = beg;
}
durations.add((int)Math.round(currentLength/sampleFrequency*1000000.0));
beg = i;
} else if (Math.abs(value) > epsilon && !isInInterestingBlock) {
// Interesting block starts
isInInterestingBlock = true;
int currentLength = i - 1 - beg;
durations.add((int) Math.round(currentLength/sampleFrequency*1000000.0));
beg = i;
}
last = value;
}
if (!isInInterestingBlock && noFrames - beg > 1)
durations.add((int)Math.round((noFrames - beg)/sampleFrequency*1000000.0));
if (durations.size() % 2 == 1)
durations.add(0);
// Found the longest interesting block, now evaluate frequency
int signchanges = 0;
last = 0;
for (int i = 0; i < bestLength; i++) {
int indx = i + bestStart;
int value = data[indx][0];
if (value != 0) {
if (value*last < 0)
signchanges++;
last = value;
}
}
double carrierFrequency = (divide ? 2 : 1)*sampleFrequency * signchanges/(2*bestLength);
System.err.println("Carrier frequency estimated to " + Math.round(carrierFrequency) + " Hz.");
int arr[] = new int[durations.size()];
int ind = 0;
for (Integer val : durations) {
arr[ind] = val;
ind++;
if (debug > 0)
System.err.print(val + " ");
}
if (debug > 0)
System.err.println();
try {
//return new IrSignal(arr, arr.length/2, 0, (int) Math.round(carrierFrequency));
return new ModulatedIrSequence(arr, carrierFrequency);
} catch (IncompatibleArgumentException ex) {
// cannot happen, we have insured that the data has even size.
return null;
}
}
/**
* Print the channels to a tab separated text file, for example for debugging purposes.
* This file can be imported in a spreadsheet.
*
* @param dumpfile Output file.
* @throws FileNotFoundException
*/
public void dump(File dumpfile) throws FileNotFoundException {
int data[][] = computeData();
double sampleRate = audioFormat.getSampleRate();
int channels = audioFormat.getChannels();
try (PrintStream stream = new PrintStream(dumpfile, IrpUtils.dumbCharsetName)) {
for (int i = 0; i < noFrames; i++) {
stream.print(String.format("%d\t%8.6f\t", i, i / sampleRate));
for (int ch = 0; ch < channels; ch++)
stream.print(data[i][ch] + (ch < channels - 1 ? "\t" : "\n"));
}
} catch (UnsupportedEncodingException ex) {
throw new InternalError();
}
}
/**
* Write the signal to the file given as argument.
* @param file Output File.
*/
public void export(File file) {
ByteArrayInputStream bs = new ByteArrayInputStream(buf);
bs.reset();
AudioInputStream ais = new AudioInputStream(bs, audioFormat, (long) buf.length/audioFormat.getFrameSize());
try {
int result = AudioSystem.write(ais, AudioFileFormat.Type.WAVE, file);
if (result <= buf.length)
System.err.println("Wrong number of bytes written: " + result + " < " + buf.length);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}
/**
* Sends the generated wave to the line in argument, if possible.
* @param line Line to used. Should be open, and remains open. User must make sure AudioFormat is compatible.
* @throws LineUnavailableException
* @throws IOException
*/
public void play(SourceDataLine line) throws LineUnavailableException, IOException {
line.start();
int bytesWritten = line.write(buf, 0, buf.length);
if (bytesWritten != buf.length)
throw new IOException("Not all bytes written");
line.drain();
}
/**
* Sends the generated wave to the local machine's audio system, if possible.
* @throws LineUnavailableException
* @throws IOException
*/
public void play() throws LineUnavailableException, IOException {
try (SourceDataLine line = AudioSystem.getSourceDataLine(audioFormat)) {
line.open(audioFormat);
play(line);
}
}
private final static class CommandLineArgs {
@Parameter(names = {"-1", "--nodivide"}, description = "Do not divide modulation frequency")
boolean dontDivide = false;
@Parameter(names = {"-c", "--config"}, description = "Path to IrpProtocols.ini")
String irprotocolsIniFilename = "data/IrpProtocols.ini";
@Parameter(names = {"-h", "--help", "-?"}, description = "Display help message")
boolean helpRequensted = false;
@Parameter(names = {"-f", "--samplefrequency"}, description = "Sample frequency in Hz")
int sampleFrequency = 44100;
@Parameter(names = {"-m", "--macrofile"}, description = "Macro filename")
String macrofile = null;
@Parameter(names = {"-o", "--outfile"}, description = "Output filename")
String outputfile = "irpmaster.wav";
@Parameter(names = {"-p", "--play"}, description = "Send the generated wave to the audio device of the local machine")
boolean play = false;
@Parameter(names = {"-q", "--square"}, description = "Modulate with square wave instead of sine")
boolean square = false;
@Parameter(names = {"-r", "--repeats"}, description = "Number of times to include the repeat sequence")
int noRepeats = 0;
@Parameter(names = {"-s", "samplesize"}, description = "Sample size in bits")
int sampleSize = 8;
@Parameter(names = {"-S", "--stereo"}, description = "Generate two channels in anti-phase")
boolean stereo = false;
@Parameter(names = {"-t", "--omittail"}, description = "Skip silence at end")
boolean omitTail = false;
@Parameter(names = {"-v", "--version"}, description = "Display version information")
boolean versionRequested;
@Parameter(description = "[parameters]")
@SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
private ArrayList<String> parameters = new ArrayList<>(64);
}
}
| bengtmartensson/IrpMaster | src/main/java/org/harctoolbox/IrpMaster/Wave.java | Java | gpl-3.0 | 25,136 |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
import frappe
from frappe.model.document import Document
from frappe.website.utils import delete_page_cache
class Homepage(Document):
def validate(self):
if not self.description:
self.description = frappe._("This is an example website auto-generated from ERPNext")
delete_page_cache('home')
def setup_items(self):
for d in frappe.get_all('Item', fields=['name', 'item_name', 'description', 'image'],
filters={'show_in_website': 1}, limit=3):
doc = frappe.get_doc('Item', d.name)
if not doc.route:
# set missing route
doc.save()
self.append('products', dict(item_code=d.name,
item_name=d.item_name, description=d.description, image=d.image))
| mhbu50/erpnext | erpnext/portal/doctype/homepage/homepage.py | Python | gpl-3.0 | 801 |
/****************************************************************************
** Meta object code from reading C++ file 'stackencadenamientos.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.3.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "stackencadenamientos.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'stackencadenamientos.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.3.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_stackEncadenamientos_t {
QByteArrayData data[1];
char stringdata[21];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_stackEncadenamientos_t, stringdata) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_stackEncadenamientos_t qt_meta_stringdata_stackEncadenamientos = {
{
QT_MOC_LITERAL(0, 0, 20)
},
"stackEncadenamientos"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_stackEncadenamientos[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
0, 0, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
0 // eod
};
void stackEncadenamientos::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
Q_UNUSED(_o);
Q_UNUSED(_id);
Q_UNUSED(_c);
Q_UNUSED(_a);
}
const QMetaObject stackEncadenamientos::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_stackEncadenamientos.data,
qt_meta_data_stackEncadenamientos, qt_static_metacall, 0, 0}
};
const QMetaObject *stackEncadenamientos::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *stackEncadenamientos::qt_metacast(const char *_clname)
{
if (!_clname) return 0;
if (!strcmp(_clname, qt_meta_stringdata_stackEncadenamientos.stringdata))
return static_cast<void*>(const_cast< stackEncadenamientos*>(this));
return QWidget::qt_metacast(_clname);
}
int stackEncadenamientos::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
return _id;
}
QT_END_MOC_NAMESPACE
| rudmanmrrod/mmcs | moc_stackencadenamientos.cpp | C++ | gpl-3.0 | 2,747 |
# (void)walker hardware platform support
# Copyright (C) 2012-2013 David Holm <dholmster@gmail.com>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import abc
from ..utils import OrderedDict
from ..utils import enum
Architecture = enum('Test', 'X86', 'X8664', 'Mips', 'Arm', 'Generic',
enum_type='Architecture')
class Register(object):
_register_fmt = {16: '0x%032lX',
10: '0x%020lX',
8: '0x%016lX',
4: '0x%08lX',
2: '0x%04lX',
1: '0x%02lX'}
def __init__(self, name):
self._name = name
def name(self):
return self._name
def size(self):
raise NotImplementedError
def value(self):
raise NotImplementedError
def str(self):
if self.value() is not None:
return self._register_fmt[self.size()] % self.value()
chars_per_byte = 2
return ''.join(['-' * (self.size() * chars_per_byte)])
def create_static_register(register):
class StaticRegister(type(register), object):
def __init__(self, name):
super(StaticRegister, self).__init__(name)
self._size = register.size()
self._value = register.value()
def size(self):
return self._size
def value(self):
return self._value
return StaticRegister(register.name())
class Cpu(object):
__metaclass__ = abc.ABCMeta
def __init__(self, cpu_factory, registers):
self._registers = OrderedDict()
for group, register_list in registers.iteritems():
registers = OrderedDict([(x.name(),
cpu_factory.create_register(self, x))
for x in register_list])
self._registers[group] = registers
@classmethod
@abc.abstractmethod
def architecture(cls):
raise NotImplementedError
def register(self, name):
for register_dict in self._registers.itervalues():
if name in register_dict:
return register_dict[name]
return None
def registers(self):
return self._registers.iteritems()
@abc.abstractmethod
def stack_pointer(self):
raise NotImplementedError
@abc.abstractmethod
def program_counter(self):
raise NotImplementedError
class CpuFactory(object):
__metaclass__ = abc.ABCMeta
def create_cpu(self, architecture):
assert architecture in _cpu_map
return _cpu_map.get(architecture,
None)(self)
@abc.abstractmethod
def create_register(self, cpu, register):
raise NotImplementedError
class CpuRepository(object):
def __init__(self, cpu_factory):
self._cpu_factory = cpu_factory
self._cpus = {}
def get_cpu(self, architecture):
if architecture in self._cpus:
return self._cpus[architecture]
cpu = self._cpu_factory.create_cpu(architecture)
self._cpus[architecture] = cpu
return cpu
def register_cpu(cls):
_cpu_map[cls.architecture()] = cls
return cls
_cpu_map = {}
| dholm/voidwalker | voidwalker/framework/platform/cpu.py | Python | gpl-3.0 | 3,778 |
/*
* Copyright (c) 2018.
*
* This file is part of AvaIre.
*
* AvaIre 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.
*
* AvaIre 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 AvaIre. If not, see <https://www.gnu.org/licenses/>.
*
*
*/
package com.avairebot.imagegen.colors.ranks;
import com.avairebot.contracts.imagegen.BackgroundRankColors;
import javax.annotation.Nonnull;
import java.awt.*;
public class MountainRangeColors extends BackgroundRankColors {
@Nonnull
@Override
public Color getBackgroundColor() {
return makeColor(55, 55, 70);
}
@Nonnull
@Override
public Color getMainTextColor() {
return makeColor(226, 226, 229, 85);
}
@Nonnull
@Override
public Color getSecondaryTextColor() {
return makeColor(166, 166, 166, 85);
}
@Nonnull
@Override
public Color getExperienceBackgroundColor() {
return makeColor(38, 39, 59, 60);
}
@Nonnull
@Override
public Color getExperienceForegroundColor() {
return makeColor(96, 132, 186, 80);
}
@Nonnull
@Override
public Color getExperienceSeparatorColor() {
return makeColor(83, 180, 201, 65);
}
}
| avaire/orion | src/main/java/com/avairebot/imagegen/colors/ranks/MountainRangeColors.java | Java | gpl-3.0 | 1,664 |
// ========================================================================= //
// Fighting game framework (2D) with online multiplayer.
// Copyright(C) 2014 Jordan Sparks <unixunited@live.com>
//
// This program is free software; you can redistribute it and / or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 3
// of the License, or(at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ========================================================================= //
// File: LogImpl.hpp
// Author: Jordan Sparks <unixunited@live.com>
// ================================================ //
// Defines LogImpl Pimpl idiom class.
// ================================================ //
#ifndef __LOGIMPL_HPP__
#define __LOGIMPL_HPP__
// ================================================ //
#include "stdafx.hpp"
// ================================================ //
// Pimpl idiom class for Log.
class LogImpl
{
public:
// Opens a file handle for ExtMF.log and logs the date, time, and
// engine version.
explicit LogImpl(void);
// Closes the file handle.
~LogImpl(void);
void logMessage(const std::string& str);
void logTime(const bool time = true, const bool date = false);
private:
std::ofstream m_file;
};
// ================================================ //
#endif
// ================================================ // | unixunited/Fighting-Game-Framework-2D | LogImpl.hpp | C++ | gpl-3.0 | 1,798 |
# Copyright (c) 2010, Nathaniel Ritmeyer. All rights reserved.
#
# http://www.natontesting.com
#
# Save this in a file called 'unused.rb' in your 'features/support' directory. Then, to list
# all the unused steps in your project, run the following command:
#
# cucumber -d -f Cucumber::Formatter::Unused
#
# or...
#
# cucumber -d -f Unused
require 'cucumber/formatter/stepdefs'
class Unused < Cucumber::Formatter::Stepdefs
def print_summary(features)
add_unused_stepdefs
keys = @stepdef_to_match.keys.sort {|a,b| a.regexp_source <=> b.regexp_source}
puts "The following steps are unused...\n---------"
keys.each do |stepdef_key|
if @stepdef_to_match[stepdef_key].none?
puts "#{stepdef_key.regexp_source}\n#{stepdef_key.file_colon_line}\n---"
end
end
end
end | IntersectAustralia/anznn | features/support/unused.rb | Ruby | gpl-3.0 | 807 |
package com.tiketal.overwatch.util;
import org.bukkit.Bukkit;
import org.bukkit.boss.BarColor;
import org.bukkit.boss.BarStyle;
import org.bukkit.boss.BossBar;
import org.bukkit.entity.Player;
public class DisplayBar {
private BossBar bar;
public DisplayBar(String name, String color, String style) {
color = color.toUpperCase();
style = style.toUpperCase();
try {
bar = Bukkit.createBossBar(name, BarColor.valueOf(color), BarStyle.valueOf(style));
} catch (Exception e) {
bar = Bukkit.createBossBar(name, BarColor.WHITE, BarStyle.SOLID);
}
bar.setVisible(true);
}
public void show(Player player) {
bar.addPlayer(player);
}
public void hide(Player player) {
bar.removePlayer(player);
}
public void setTitle(String title) {
bar.setTitle(title);
}
public void setVisible(boolean visible) {
bar.setVisible(visible);
}
public void setColor(String color) {
try {
bar.setColor(BarColor.valueOf(color.toUpperCase()));
} catch (Exception e) {
bar.setColor(BarColor.WHITE);
}
}
public void setStyle(String style) {
try {
bar.setStyle(BarStyle.valueOf(style.toUpperCase()));
} catch (Exception e) {
bar.setStyle(BarStyle.SOLID);
}
}
public void progress(double amt) {
if (amt < 0) amt *= -1;
if (amt > 1) amt = 1;
bar.setProgress(amt);
}
public void reset() {
for (Player player : bar.getPlayers()) {
bar.removePlayer(player);
}
}
}
| Tiketal/Overwatch | src/com/tiketal/overwatch/util/DisplayBar.java | Java | gpl-3.0 | 1,427 |
package mapproject;
import static helpers.Artist.*;
import org.newdawn.slick.opengl.Texture;
/**
* Clase que representa una celda individual del mapa
*
* @author Alba Ríos
*/
public class Tile {
private float x, y, width, height;
private Texture texture;
/**
*
* @param x Coordenada x del pixel del mapa
* @param y Coordenada y del pixel del mapa
* @param width Ancho del tile
* @param height Alto del tile
* @param tex Textura del tile
*
* @author Alba Ríos
*/
public Tile(float x, float y, float width, float height, Texture tex){
this.x = x;
this.y = y;
this.height = height;
this.width = width;
this.texture = tex;
}
public void Draw(){
DrawQuadTex(texture, x, y, width, height);
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
public float getWidth() {
return width;
}
public void setWidth(float width) {
this.width = width;
}
public float getHeight() {
return height;
}
public void setHeight(float height) {
this.height = height;
}
public Texture getTexture() {
return texture;
}
public void setTexture(Texture texture) {
this.texture = texture;
}
}
| demiurgosoft/star-droids | StarDroids/src/mapproject/Tile.java | Java | gpl-3.0 | 1,477 |
class CreateRosters < ActiveRecord::Migration[4.2]
def change
create_table :rosters do |t|
t.belongs_to :roster_file
t.string :member_id
t.string :nam_first
t.string :nam_last
t.string :cp_pidsl
t.string :cp_name
t.string :aco_pidsl
t.string :aco_name
t.string :mco_pidsl
t.string :mco_name
t.string :sex
t.date :date_of_birth
t.string :mailing_address_1
t.string :mailing_address_2
t.string :mailing_city
t.string :mailing_state
t.string :mailing_zip
t.string :residential_address_1
t.string :residential_address_2
t.string :residential_city
t.string :residential_state
t.string :residential_zip
t.string :race
t.string :phone_number
t.string :primary_language_s
t.string :primary_language_w
t.string :sdh_nss7_score
t.string :sdh_homelessness
t.string :sdh_addresses_flag
t.string :sdh_other_disabled
t.string :sdh_spmi
t.string :raw_risk_score
t.string :normalized_risk_score
t.string :raw_dxcg_risk_score
t.date :last_office_visit
t.date :last_ed_visit
t.date :last_ip_visit
t.string :enrolled_flag
t.string :enrollment_status
t.date :cp_claim_dt
t.string :qualifying_hcpcs
t.string :qualifying_hcpcs_nm
t.string :qualifying_dsc
t.string :email
t.string :head_of_household
end
end
end
| greenriver/hmis-warehouse | db/health/migrate/20191107163343_create_rosters.rb | Ruby | gpl-3.0 | 1,472 |
package com.abm.mainet.agency.dao;
import com.abm.mainet.agency.dto.TPAgencyReqDTO;
import com.abm.mainet.agency.dto.TPAgencyResDTO;
import com.abm.mainet.common.domain.Employee;
/**
* @author Arun.Chavda
*
*/
public interface AgencyRegistrationProcessDao {
Employee saveAgnEmployeeDetails(Employee employee);
TPAgencyResDTO getAuthStatus(TPAgencyReqDTO requestDTO);
void updatedAuthStatus(Long empId, Long orgId, String flag);
}
| abmindiarepomanager/ABMOpenMainet | Mainet1.1/MainetServiceParent/MainetServiceAgency/src/main/java/com/abm/mainet/agency/dao/AgencyRegistrationProcessDao.java | Java | gpl-3.0 | 464 |
# Author: seedboy
# URL: https://github.com/seedboy
#
# This file is part of SickRage.
#
# SickRage 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.
#
# SickRage 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 SickRage. If not, see <http://www.gnu.org/licenses/>.
import re
import traceback
import datetime
import urlparse
import sickbeard
import generic
from sickbeard.common import Quality
from sickbeard import logger
from sickbeard import tvcache
from sickbeard import db
from sickbeard import classes
from sickbeard import helpers
from sickbeard import show_name_helpers
from sickbeard.exceptions import ex, AuthException
from sickbeard import clients
from lib import requests
from lib.requests import exceptions
from sickbeard.bs4_parser import BS4Parser
from lib.unidecode import unidecode
from sickbeard.helpers import sanitizeSceneName
from sickbeard.show_name_helpers import allPossibleShowNames
class IPTorrentsProvider(generic.TorrentProvider):
def __init__(self):
generic.TorrentProvider.__init__(self, "IPTorrents")
self.supportsBacklog = True
self.enabled = False
self.username = None
self.password = None
self.ratio = None
self.freeleech = False
self.cache = IPTorrentsCache(self)
self.urls = {'base_url': 'https://www.iptorrents.com',
'login': 'https://www.iptorrents.com/torrents/',
'search': 'https://www.iptorrents.com/torrents/?%s%s&q=%s&qf=ti',
}
self.url = self.urls['base_url']
self.categorie = 'l73=1&l78=1&l66=1&l65=1&l79=1&l5=1&l4=1'
def isEnabled(self):
return self.enabled
def imageName(self):
return 'iptorrents.png'
def getQuality(self, item, anime=False):
quality = Quality.sceneQuality(item[0], anime)
return quality
def _checkAuth(self):
if not self.username or not self.password:
raise AuthException("Your authentication credentials for " + self.name + " are missing, check your config.")
return True
def _doLogin(self):
login_params = {'username': self.username,
'password': self.password,
'login': 'submit',
}
try:
response = self.session.post(self.urls['login'], data=login_params, timeout=30, verify=False)
except (requests.exceptions.ConnectionError, requests.exceptions.HTTPError), e:
logger.log(u'Unable to connect to ' + self.name + ' provider: ' + ex(e), logger.ERROR)
return False
if re.search('tries left', response.text) \
or re.search('<title>IPT</title>', response.text) \
or response.status_code == 401:
logger.log(u'Invalid username or password for ' + self.name + ', Check your settings!', logger.ERROR)
return False
return True
def _get_season_search_strings(self, ep_obj):
search_string = {'Season': []}
for show_name in set(show_name_helpers.allPossibleShowNames(self.show)):
if ep_obj.show.air_by_date or ep_obj.show.sports:
ep_string = show_name + ' ' + str(ep_obj.airdate).split('-')[0]
elif ep_obj.show.anime:
ep_string = show_name + ' ' + "%d" % ep_obj.scene_absolute_number
else:
ep_string = show_name + ' S%02d' % int(ep_obj.scene_season) #1) showName SXX
search_string['Season'].append(ep_string)
return [search_string]
def _get_episode_search_strings(self, ep_obj, add_string=''):
search_string = {'Episode': []}
if not ep_obj:
return []
if self.show.air_by_date:
for show_name in set(allPossibleShowNames(self.show)):
ep_string = sanitizeSceneName(show_name) + ' ' + \
str(ep_obj.airdate).replace('-', '|')
search_string['Episode'].append(ep_string)
elif self.show.sports:
for show_name in set(allPossibleShowNames(self.show)):
ep_string = sanitizeSceneName(show_name) + ' ' + \
str(ep_obj.airdate).replace('-', '|') + '|' + \
ep_obj.airdate.strftime('%b')
search_string['Episode'].append(ep_string)
elif self.show.anime:
for show_name in set(show_name_helpers.allPossibleShowNames(self.show)):
ep_string = sanitizeSceneName(show_name) + ' ' + \
"%i" % int(ep_obj.scene_absolute_number)
search_string['Episode'].append(ep_string)
else:
for show_name in set(show_name_helpers.allPossibleShowNames(self.show)):
ep_string = show_name_helpers.sanitizeSceneName(show_name) + ' ' + \
sickbeard.config.naming_ep_type[2] % {'seasonnumber': ep_obj.scene_season,
'episodenumber': ep_obj.scene_episode} + ' %s' % add_string
search_string['Episode'].append(re.sub('\s+', ' ', ep_string))
return [search_string]
def _doSearch(self, search_params, search_mode='eponly', epcount=0, age=0):
results = []
items = {'Season': [], 'Episode': [], 'RSS': []}
freeleech = '&free=on' if self.freeleech else ''
if not self._doLogin():
return results
for mode in search_params.keys():
for search_string in search_params[mode]:
if isinstance(search_string, unicode):
search_string = unidecode(search_string)
# URL with 50 tv-show results, or max 150 if adjusted in IPTorrents profile
searchURL = self.urls['search'] % (self.categorie, freeleech, search_string)
searchURL += ';o=seeders' if mode != 'RSS' else ''
logger.log(u"" + self.name + " search page URL: " + searchURL, logger.DEBUG)
data = self.getURL(searchURL)
if not data:
continue
try:
data = re.sub(r'(?im)<button.+?<[\/]button>', '', data, 0)
with BS4Parser(data, features=["html5lib", "permissive"]) as html:
if not html:
logger.log(u"Invalid HTML data: " + str(data), logger.DEBUG)
continue
if html.find(text='No Torrents Found!'):
logger.log(u"No results found for: " + search_string + " (" + searchURL + ")", logger.DEBUG)
continue
torrent_table = html.find('table', attrs={'class': 'torrents'})
torrents = torrent_table.find_all('tr') if torrent_table else []
#Continue only if one Release is found
if len(torrents) < 2:
logger.log(u"The Data returned from " + self.name + " do not contains any torrent",
logger.WARNING)
continue
for result in torrents[1:]:
try:
torrent = result.find_all('td')[1].find('a')
torrent_name = torrent.string
torrent_download_url = self.urls['base_url'] + (result.find_all('td')[3].find('a'))['href']
torrent_details_url = self.urls['base_url'] + torrent['href']
torrent_seeders = int(result.find('td', attrs={'class': 'ac t_seeders'}).string)
## Not used, perhaps in the future ##
#torrent_id = int(torrent['href'].replace('/details.php?id=', ''))
#torrent_leechers = int(result.find('td', attrs = {'class' : 'ac t_leechers'}).string)
except (AttributeError, TypeError):
continue
# Filter unseeded torrent and torrents with no name/url
if mode != 'RSS' and torrent_seeders == 0:
continue
if not torrent_name or not torrent_download_url:
continue
item = torrent_name, torrent_download_url
logger.log(u"Found result: " + torrent_name + " (" + torrent_details_url + ")", logger.DEBUG)
items[mode].append(item)
except Exception, e:
logger.log(u"Failed parsing " + self.name + " Traceback: " + traceback.format_exc(), logger.ERROR)
results += items[mode]
return results
def _get_title_and_url(self, item):
title, url = item
if title:
title = u'' + title
title = title.replace(' ', '.')
if url:
url = str(url).replace('&', '&')
return (title, url)
def findPropers(self, search_date=datetime.datetime.today()):
results = []
myDB = db.DBConnection()
sqlResults = myDB.select(
'SELECT s.show_name, e.showid, e.season, e.episode, e.status, e.airdate FROM tv_episodes AS e' +
' INNER JOIN tv_shows AS s ON (e.showid = s.indexer_id)' +
' WHERE e.airdate >= ' + str(search_date.toordinal()) +
' AND (e.status IN (' + ','.join([str(x) for x in Quality.DOWNLOADED]) + ')' +
' OR (e.status IN (' + ','.join([str(x) for x in Quality.SNATCHED]) + ')))'
)
if not sqlResults:
return []
for sqlshow in sqlResults:
self.show = helpers.findCertainShow(sickbeard.showList, int(sqlshow["showid"]))
if self.show:
curEp = self.show.getEpisode(int(sqlshow["season"]), int(sqlshow["episode"]))
searchString = self._get_episode_search_strings(curEp, add_string='PROPER|REPACK')
for item in self._doSearch(searchString[0]):
title, url = self._get_title_and_url(item)
results.append(classes.Proper(title, url, datetime.datetime.today(), self.show))
return results
def seedRatio(self):
return self.ratio
class IPTorrentsCache(tvcache.TVCache):
def __init__(self, provider):
tvcache.TVCache.__init__(self, provider)
# Only poll IPTorrents every 10 minutes max
self.minTime = 10
def _getRSSData(self):
search_params = {'RSS': ['']}
return {'entries': self.provider._doSearch(search_params)}
provider = IPTorrentsProvider()
| bcorbet/SickRage | sickbeard/providers/iptorrents.py | Python | gpl-3.0 | 11,284 |
from collections import defaultdict
class Solution(object):
def minWindow(self, S, T):
"""
:type S: str
:type T: str
:rtype: str
"""
pre = defaultdict(list)
for i, c in enumerate(T, -1):
pre[c].append(i)
for val in pre.values():
val.reverse()
start_index = [None] * (len(T) + 1)
lo, hi = float('-inf'), 0
for i, c in enumerate(S):
start_index[-1] = i
for p in pre[c]:
if start_index[p] is not None:
start_index[p + 1] = start_index[p]
if (c == T[-1] and start_index[-2] is not None
and i - start_index[-2] < hi - lo):
lo, hi = start_index[-2], i
if lo < 0:
return ''
else:
return S[lo:hi+1]
# print(Solution().minWindow("abcdebdde", "bde"))
# print(Solution().minWindow("nkzcnhczmccqouqadqtmjjzltgdzthm", "bt"))
print(Solution().minWindow("cnhczmccqouqadqtmjjzl", "mm"))
| wufangjie/leetcode | 727. Minimum Window Subsequence.py | Python | gpl-3.0 | 1,035 |
#include "missile.h"
#include "../../ObjManager.h"
#include "../../autogen/sprites.h"
#include "../../caret.h"
#include "../../common/misc.h"
#include "../../game.h"
#include "../../player.h"
#include "../../sound/SoundManager.h"
#include "../../trig.h"
#include "weapons.h"
#define STATE_WAIT_RECOIL_OVER 1
#define STATE_RECOIL_OVER 2
#define STATE_MISSILE_CAN_EXPLODE 3
struct MissileSettings
{
int maxspeed; // max speed of missile
int hitrange; //
int lifetime; // number of boomflashes to create on impact
int boomrange; // max dist away to create the boomflashes
int boomdamage; // damage dealt by contact with a boomflash (AoE damage)
} missile_settings[] = {
// Level 1-3 regular missile
// maxspd hit, life, range, bmdmg
{0xA00, 16, 10, 16, 1},
{0xA00, 16, 15, 32, 1},
{0xA00, 16, 5, 40, 1},
// Level 1-3 super missile
// maxspd hit, life, range, bmdmg
{0x1400, 12, 10, 16, 2},
{0x1400, 12, 14, 32, 2},
{0x1400, 12, 6, 40, 2}};
INITFUNC(AIRoutines)
{
AFTERMOVE(OBJ_MISSILE_SHOT, ai_missile_shot);
AFTERMOVE(OBJ_SUPERMISSILE_SHOT, ai_missile_shot);
ONTICK(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner_tick);
AFTERMOVE(OBJ_MISSILE_BOOM_SPAWNER, ai_missile_boom_spawner);
}
/*
void c------------------------------() {}
*/
void ai_missile_shot(Object *o)
{
int index = o->shot.level + ((o->type == OBJ_SUPERMISSILE_SHOT) ? 3 : 0);
MissileSettings *settings = &missile_settings[index];
if (o->state == 0)
{
o->shot.damage = 0;
if (o->shot.level == 2)
{
// initilize wavey effect
o->xmark = o->x;
o->ymark = o->y;
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
// don't let it explode until the "recoil" effect is over.
o->state = STATE_WAIT_RECOIL_OVER;
// record position we were fired at (we won't explode until we pass it)
o->xmark2 = player->x;
o->ymark2 = player->y;
}
else
{
o->state = STATE_MISSILE_CAN_EXPLODE;
}
}
// accelerate according to current type and level of missile
// don't use LIMITX here as it can mess up recoil of level 3 super missiles
switch (o->shot.dir)
{
case RIGHT:
o->xinertia += o->shot.accel;
if (o->xinertia > settings->maxspeed)
o->xinertia = settings->maxspeed;
break;
case LEFT:
o->xinertia -= o->shot.accel;
if (o->xinertia < -settings->maxspeed)
o->xinertia = -settings->maxspeed;
break;
case UP:
o->yinertia -= o->shot.accel;
if (o->yinertia < -settings->maxspeed)
o->yinertia = -settings->maxspeed;
break;
case DOWN:
o->yinertia += o->shot.accel;
if (o->yinertia > settings->maxspeed)
o->yinertia = settings->maxspeed;
break;
}
// wavey effect for level 3
// (markx/y is used as a "speed" value here)
if (o->shot.level == 2)
{
if (o->shot.dir == LEFT || o->shot.dir == RIGHT)
{
if (o->y >= o->ymark)
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->yinertia += o->speed;
}
else
{
if (o->x >= o->xmark)
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? -64 : -32;
else
o->speed = (o->type == OBJ_SUPERMISSILE_SHOT) ? 64 : 32;
o->xinertia += o->speed;
}
}
// check if we hit an enemy
// level 3 missiles can not blow up while they are "recoiling"
// what we do is first wait until they're traveling in the direction
// they're pointing, then wait till they pass the player's original position.
switch (o->state)
{
case STATE_WAIT_RECOIL_OVER:
switch (o->shot.dir)
{
case LEFT:
if (o->xinertia <= 0)
o->state = STATE_RECOIL_OVER;
break;
case RIGHT:
if (o->xinertia >= 0)
o->state = STATE_RECOIL_OVER;
break;
case UP:
if (o->yinertia <= 0)
o->state = STATE_RECOIL_OVER;
break;
case DOWN:
if (o->yinertia >= 0)
o->state = STATE_RECOIL_OVER;
break;
}
if (o->state != STATE_RECOIL_OVER)
break;
case STATE_RECOIL_OVER:
switch (o->shot.dir)
{
case LEFT:
if (o->x <= o->xmark2 - (2 * CSFI))
o->state = STATE_MISSILE_CAN_EXPLODE;
break;
case RIGHT:
if (o->x >= o->xmark2 + (2 * CSFI))
o->state = STATE_MISSILE_CAN_EXPLODE;
break;
case UP:
if (o->y <= o->ymark2 - (2 * CSFI))
o->state = STATE_MISSILE_CAN_EXPLODE;
break;
case DOWN:
if (o->y >= o->ymark2 + (2 * CSFI))
o->state = STATE_MISSILE_CAN_EXPLODE;
break;
}
if (o->state != STATE_MISSILE_CAN_EXPLODE)
break;
case STATE_MISSILE_CAN_EXPLODE:
{
bool blow_up = false;
if (damage_enemies(o))
{
blow_up = true;
}
else
{ // check if we hit a wall
if (o->shot.dir == LEFT && o->blockl)
blow_up = true;
else if (o->shot.dir == RIGHT && o->blockr)
blow_up = true;
else if (o->shot.dir == UP && o->blocku)
blow_up = true;
else if (o->shot.dir == DOWN && o->blockd)
blow_up = true;
}
if (blow_up)
{
NXE::Sound::SoundManager::getInstance()->playSfx(NXE::Sound::SFX::SND_MISSILE_HIT);
if (!shot_destroy_blocks(o))
{
// create the boom-spawner object for the flashes, smoke, and AoE damage
int y = o->CenterY();
if (o->shot.dir == LEFT || o->shot.dir == RIGHT)
y -= 3 * CSFI;
Object *sp = CreateBullet(o->CenterX(), y, OBJ_MISSILE_BOOM_SPAWNER);
sp->shot.boomspawner.range = settings->hitrange;
sp->shot.boomspawner.booms_left = settings->lifetime;
sp->shot.damage = settings->boomdamage;
sp->shot.level = settings->boomdamage;
}
o->Delete();
return;
}
}
break;
}
if (--o->shot.ttl < 0)
shot_dissipate(o, EFFECT_STARPOOF);
// smoke trails
if (++o->timer > 2)
{
o->timer = 0;
Caret *trail = effect(o->CenterX() - o->xinertia, o->CenterY() - o->yinertia, EFFECT_SMOKETRAIL);
const int trailspd = 0x400;
switch (o->shot.dir)
{
case LEFT:
trail->xinertia = trailspd;
trail->y -= (2 * CSFI);
break;
case RIGHT:
trail->xinertia = -trailspd;
trail->y -= (2 * CSFI);
break;
case UP:
trail->yinertia = trailspd;
trail->x -= (1 * CSFI);
break;
case DOWN:
trail->yinertia = -trailspd;
trail->x -= (1 * CSFI);
break;
}
}
}
void ai_missile_boom_spawner(Object *o)
{
if (o->state == 0)
{
o->state = 1;
o->timer = 0;
o->xmark = o->x;
o->ymark = o->y;
// give us the same bounding box as the boomflash effects
o->sprite = SPR_BOOMFLASH;
o->invisible = true;
}
if (!(o->shot.boomspawner.booms_left % 3))
{
int range = 0;
switch (o->shot.level)
{
case 1:
range = 16;
break;
case 2:
range = 32;
break;
case 3:
range = 40;
break;
}
int x = o->CenterX() + (random(-range, range) * CSFI);
int y = o->CenterY() + (random(-range, range) * CSFI);
effect(x, y, EFFECT_BOOMFLASH);
missilehitsmoke(x, y, o->shot.boomspawner.range);
}
if (--o->shot.boomspawner.booms_left < 0)
o->Delete();
}
void ai_missile_boom_spawner_tick(Object *o)
{
damage_all_enemies_in_bb(o, FLAG_INVULNERABLE, o->CenterX(), o->CenterY(), o->shot.boomspawner.range);
}
static void missilehitsmoke(int x, int y, int range)
{
int smokex = x + (random(-range, range) * CSFI);
int smokey = y + (random(-range, range) * CSFI);
Object *smoke;
for (int i = 0; i < 2; i++)
{
smoke = CreateObject(smokex, smokey, OBJ_SMOKE_CLOUD);
smoke->sprite = SPR_MISSILEHITSMOKE;
vector_from_angle(random(0, 255), random(0x100, 0x3ff), &smoke->xinertia, &smoke->yinertia);
}
}
| isage/nxengine-evo | src/ai/weapons/missile.cpp | C++ | gpl-3.0 | 8,306 |
<?php defined('_JEXEC') or die('Restricted access'); // no direct access
//########## GET THE CSS NAME FOR SELECTED BULLET ##########//
if ($style == 3) $cssbullet = "bullet-trianglelight-jtmodule";
if ($style == 4) $cssbullet = "bullet-squarelight-jtmodule";
if ($style == 5) $cssbullet = "bullet-pluslight-jtmodule";
if ($style == 6) $cssbullet = "bullet-dotlight-jtmodule";
if ($style == 7) $cssbullet = "bullet-arrowlight-jtmodule";
if ($style == 8) $cssbullet = "bullet-triangledark-jtmodule";
if ($style == 9) $cssbullet = "bullet-squaredark-jtmodule";
if ($style == 10) $cssbullet = "bullet-plusdark-jtmodule";
if ($style == 11) $cssbullet = "bullet-dotdark-jtmodule";
if ($style == 12) $cssbullet = "bullet-arrowdark-jtmodule";
?>
<div id="main-cat-jtmodule">
<!--DOT seprated list (Horizontal)-->
<?php if ($style == 0):?>
<div style="text-align:center">
<?php foreach($items as $item):?>
<a href="<?php echo JRoute::_('index.php?option=com_jomtube&task=categories&catid='.$item->id.'&Itemid='.$jomtube_itemid) ?>"><?php echo $item->category_name?></a>
·
<?php endforeach;?>
</div>
<?php endif;?>
<!--Pipe seprated list (Horizontal)-->
<?php if ($style == 1):?>
<div style="text-align:center">
<?php foreach($items as $item):?>
<a href="<?php echo JRoute::_('index.php?option=com_jomtube&task=categories&catid='.$item->id.'&Itemid='.$jomtube_itemid) ?>"><?php echo $item->category_name?></a>
|
</div>
<?php endforeach;?>
<?php endif;?>
<!--Dash seprated list (Horizontal)-->
<?php if ($style == 2):?>
<div style="text-align:center">
<?php foreach($items as $item):?>
<a href="<?php echo JRoute::_('index.php?option=com_jomtube&task=categories&catid='.$item->id.'&Itemid='.$jomtube_itemid) ?>"><?php echo $item->category_name?></a>
-
</div>
<?php endforeach;?>
<?php endif;?>
<!--Bulleted list for Light Background(Vertical)-->
<?php if ($style == 3 || $style == 4 || $style == 5 || $style == 6 || $style == 7):?>
<ul class="<?php echo $cssbullet;?>">
<?php foreach($items as $item):?>
<li><a href="<?php echo JRoute::_('index.php?option=com_jomtube&task=categories&catid='.$item->id.'&Itemid='.$jomtube_itemid) ?>"><?php echo $item->category_name?></a></li>
<?php endforeach;?>
</ul>
<?php endif;?>
<!--Bulleted list for Dark Background(Vertical)-->
<?php if ($style == 8 || $style == 9 || $style == 10 || $style == 11 || $style == 12):?>
<ul class="<?php echo $cssbullet;?>">
<?php foreach($items as $item):?>
<li><a href="<?php echo JRoute::_('index.php?option=com_jomtube&task=categories&catid='.$item->id.'&Itemid='.$jomtube_itemid) ?>"><?php echo $item->category_name?></a></li>
<?php endforeach;?>
</ul>
<?php endif;?>
</div>
<!--DISPLAY OR HIDE VIEW MORE-->
<?php if ($show_morelink == 1):?>
<div id="cat-viewmore-jtmodule" style="text-align:<?php echo $textalign;?>">
<span><a href="<?php echo JRoute::_('index.php?option=com_jomtube&view=categories&Itemid='.$jomtube_itemid)?>">View More...</a></span>
</div>
<?php endif;?> | plexicloud/Plexicloud-Pleximedia | source/modules/mod_jomtube_categories/tmpl/default.php | PHP | gpl-3.0 | 3,243 |
// *****************************************************************************
// path3d.cpp Tao3D project
// *****************************************************************************
//
// File description:
//
// Representation of paths in 3D
//
//
//
//
//
//
//
//
// *****************************************************************************
// This software is licensed under the GNU General Public License v3
// (C) 2011-2013, Baptiste Soulisse <baptiste.soulisse@taodyne.com>
// (C) 2010, Catherine Burvelle <catherine@taodyne.com>
// (C) 2010-2015,2019, Christophe de Dinechin <christophe@dinechin.org>
// (C) 2010-2011,2013-2014, Jérôme Forissier <jerome@taodyne.com>
// (C) 2010-2011, Lionel Schaffhauser <lionel@taodyne.com>
// (C) 2011-2013, Baptiste Soulisse <baptiste.soulisse@taodyne.com>
// (C) 2010, Christophe de Dinechin <christophe@dinechin.org>
// *****************************************************************************
// This file is part of Tao3D
//
// Tao3D is free software: you can r 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.
//
// Tao3D 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 Tao3D, in a file named COPYING.
// If not, see <https://www.gnu.org/licenses/>.
// *****************************************************************************
#include "path3d.h"
#include "layout.h"
#include "manipulator.h"
#include "gl_keepers.h"
#include "tao_gl.h"
#include "tao_glu.h"
#include <QPainterPath>
#include <QPainterPathStroker>
#include <iostream>
TAO_BEGIN
typedef GraphicPath::VertexData VertexData;
typedef GraphicPath::PolygonData PolygonData;
typedef GraphicPath::Vertices Vertices;
typedef GraphicPath::DynamicVertices DynamicVertices;
typedef GraphicPath::EndpointStyle EndpointStyle;
scale GraphicPath::steps_min = 0;
scale GraphicPath::steps_increase = 2;
scale GraphicPath::steps_max = 25;
inline int pathSteps(scale length)
// ----------------------------------------------------------------------------
// Compute the number of polygon sides when converting a path
// ----------------------------------------------------------------------------
{
scale order = log2(length);
scale steps = GraphicPath::steps_min
+ order * GraphicPath::steps_increase;
if (steps > GraphicPath::steps_max)
steps = GraphicPath::steps_max;
if (steps < 1)
steps = 1;
return (int) ceil(steps);
}
#ifndef CALLBACK // Needed for Windows
#define CALLBACK
#endif
GraphicPath::GraphicPath()
// ----------------------------------------------------------------------------
// Constructor
// ----------------------------------------------------------------------------
: Shape(), startStyle(NONE), endStyle(NONE), lineStyle(Qt::SolidLine),
invert(false)
{}
GraphicPath::~GraphicPath()
// ----------------------------------------------------------------------------
// Destructor deletes all control points
// ----------------------------------------------------------------------------
{
clear();
}
GraphicPath::PolygonData::~PolygonData()
// ----------------------------------------------------------------------------
// Delete all the intersections we created
// ----------------------------------------------------------------------------
{
DynamicVertices::iterator i;
for (i = allocated.begin(); i != allocated.end(); i++)
delete *i;
}
static void drawArrays(GLenum mode, uint64 textureUnits, Vertices &data)
// ----------------------------------------------------------------------------
// Draw arrays
// ----------------------------------------------------------------------------
{
double *vdata = &data[0].vertex.x;
double *tdata = &data[0].texture.x;
double *ndata = &data[0].normal.x;
GLuint size = data.size();
GL.VertexPointer(3,GL_DOUBLE,sizeof(VertexData), vdata);
GL.NormalPointer(GL_DOUBLE, sizeof(VertexData), ndata);
GL.EnableClientState(GL_VERTEX_ARRAY);
GL.EnableClientState(GL_NORMAL_ARRAY);
// Activate texture coordinates for all used units
for(uint i = 0; i < GL.MaxTextureCoords() ; i++)
{
if(textureUnits & (1 << i))
{
GL.ClientActiveTexture( GL_TEXTURE0 + i );
GL.EnableClientState(GL_TEXTURE_COORD_ARRAY);
GL.TexCoordPointer(3, GL_DOUBLE, sizeof(VertexData), tdata);
}
}
GL.DrawArrays(mode, 0, size);
GL.DisableClientState(GL_VERTEX_ARRAY);
GL.DisableClientState(GL_NORMAL_ARRAY);
for(uint i = 0; i < GL.MaxTextureCoords() ; i++)
{
if(textureUnits & (1 << i))
{
GL.ClientActiveTexture( GL_TEXTURE0 + i );
GL.DisableClientState(GL_TEXTURE_COORD_ARRAY);
}
}
// Restore the client active texture
GL.ClientActiveTexture(GL_TEXTURE0);
}
static inline Vector3 swapXY(Vector3 v)
// ----------------------------------------------------------------------------
// Swap X and Y coordinates (rotate 90 degrees)
// ----------------------------------------------------------------------------
{
coord y = v.y;
v.y = -v.x;
v.x = y;
v.Normalize();
return v;
}
static inline void extrudeFacet(Vertices &side, VertexData &v,
Vector3 &orig, Vector3 &normal,
double r, double z, double sa, double ca)
// ----------------------------------------------------------------------------
// Push a facet during extrusion
// ----------------------------------------------------------------------------
// In practice, 'invert' is set for glyphs, which we have rendered with
// inverted y. So we also need to invert the normal here.
{
Vector3 vertex = orig + r * normal;
vertex.z = z;
Vector3 fn = normal;
fn.z = ca;
fn.x *= sa;
fn.y *= sa;
v.vertex = vertex;
v.normal = fn;
side.push_back(v);
}
#define ROUNDING_EPSILON 0.001
#define BACKSTEP_VALUE 0.9
static void extrudeSide(Vertices &data, bool invert, uint64 textureUnits,
double r1, double z1, double sa1, double ca1,
double r2, double z2, double sa2, double ca2)
// ----------------------------------------------------------------------------
// Extrude a side range
// ----------------------------------------------------------------------------
{
uint size = data.size();
Vertices side;
VertexData v;
Vector3 normal;
side.reserve(2*size+2);
for (uint s = 0; s <= size + 2; s++)
{
v = data[s%size];
uint n = (s+1)%size;
Vector3 delta = data[n].vertex - v.vertex;
if (delta.Dot(delta) <= ROUNDING_EPSILON)
continue;
Vector3 newNormal = swapXY(delta);
if (invert)
newNormal *= -1.0;
if (!s)
{
normal = newNormal;
continue;
}
Vector3 orig = v.vertex;
float dotProduct = newNormal.Dot(normal);
if (dotProduct < BACKSTEP_VALUE)
{
Vector3 oldPos = v.vertex + r2 * normal;
Vector3 newPos = v.vertex + r2 * newNormal;
float backstep = (newPos-oldPos).Dot(delta);
if (backstep < 0.0)
{
Vector3 mid = normal + newNormal;
mid.Normalize();
extrudeFacet(side, v, orig, mid, r1, z1, sa1, ca1);
extrudeFacet(side, v, orig, mid, r2, z2, sa2, ca2);
v.vertex = orig;
normal = newNormal;
continue;
}
else
{
// If we have a sharp angle, create additional face
// so that OpenGL does not interpolate normals
const uint MAX = 5;
for (uint a = 0; a <= MAX; a++)
{
Vector3 mid = normal * (MAX-a) + newNormal * a;
mid.Normalize();
extrudeFacet(side, v, orig, mid, r1, z1, sa1, ca1);
extrudeFacet(side, v, orig, mid, r2, z2, sa2, ca2);
v.vertex = orig;
}
}
}
normal = newNormal;
extrudeFacet(side, v, orig, normal, r1, z1, sa1, ca1);
extrudeFacet(side, v, orig, normal, r2, z2, sa2, ca2);
}
drawArrays(GL_TRIANGLE_STRIP, textureUnits, side);
}
static void extrude(PolygonData &poly, Vertices &data, scale depth)
// ----------------------------------------------------------------------------
// Extrude a given set of vertices
// ----------------------------------------------------------------------------
{
uint size = data.size();
if (!size)
return;
Layout *layout = poly.layout;
uint64 textureUnits = GL.ActiveTextureUnits();
scale radius = layout->extrudeRadius;
int count = layout->extrudeCount;
bool sharpEdges = count < 0;
if (sharpEdges)
count = -count;
// Check if we need to invert the normals on this contour
bool invert = poly.path->invert;
// Check if there is an extrude radius
if (radius != 0 && count > 0)
{
if (depth < 2 * radius)
radius = depth / 2;
// Loop on the number of extrusion facets
for (int c = 0; c < count; c++)
{
double a1 = M_PI/2 * c / count;
double ca1 = cos (a1);
double sa1 = sin (a1);
double a2 = M_PI/2 * (c+1) / count;
double ca2 = cos (a2);
double sa2 = sin (a2);
double z1 = -radius * (1 - ca1);
double z2 = -radius * (1 - ca2);
double r1 = radius * sa1;
double r2 = radius * sa2;
if (sharpEdges)
extrudeSide(data, invert, textureUnits,
r1, z1, sa2, ca2, r2, z2, sa2, ca2);
else
extrudeSide(data, invert, textureUnits,
r1, z1, sa1, ca1, r2, z2, sa2, ca2);
z1 = -depth - z1;
z2 = -depth - z2;
if (sharpEdges)
extrudeSide(data, invert, textureUnits,
r2, z2, sa2, -ca2, r1, z1, sa2, -ca2);
else
extrudeSide(data, invert, textureUnits,
r2, z2, sa2, -ca2, r1, z1, sa1, -ca1);
}
if (depth > 2 * radius)
extrudeSide(data, invert, textureUnits,
radius, -radius, 1, 0, radius, radius - depth, 1, 0);
}
else // Optimized case for 0 radius
{
Vertices side;
VertexData v;
Vector3 normal;
side.reserve(2*size);
for (uint s = 0; s <= size + 2; s++)
{
v = data[s%size];
uint n = (s+1) % size;
Vector3 delta = data[n].vertex - v.vertex;
if (delta.Dot(delta) <= ROUNDING_EPSILON)
continue;
Vector3 newNormal = swapXY(delta);
if (invert)
newNormal *= -1.0;
if (!s)
{
normal = newNormal;
continue;
}
coord origZ = v.vertex.z;
float dotProduct = newNormal.Dot(normal);
if (dotProduct < BACKSTEP_VALUE)
{
// If we have a sharp angle, create additional face
// so that OpenGL does not interpolate normals
v.normal = normal;
side.push_back(v);
v.vertex.z -= depth;
side.push_back(v);
v.vertex.z = origZ;
}
normal = newNormal;
v.normal = normal;
side.push_back(v);
v.vertex.z -= depth;
side.push_back(v);
}
drawArrays(GL_TRIANGLE_STRIP, textureUnits, side);
}
}
static void CALLBACK tessBegin(GLenum mode, PolygonData *poly)
// ----------------------------------------------------------------------------
// Callback for beginning of rendering
// ----------------------------------------------------------------------------
{
poly->mode = mode;
poly->vertices.clear();
}
static void CALLBACK tessVertex(VertexData *vertex, PolygonData *poly)
// ----------------------------------------------------------------------------
// Emit a vertex during tesselation
// ----------------------------------------------------------------------------
{
poly->vertices.push_back(*vertex);
VertexData &back = poly->vertices.back();
back.normal = Vector3(0, 0, 1);
}
static void CALLBACK tessEnd(PolygonData *poly)
// ----------------------------------------------------------------------------
// Callback for end of rendering
// ----------------------------------------------------------------------------
{
Vertices &data = poly->vertices;
uint size = data.size();
if (size)
{
Layout *layout = poly->layout;
uint64 textureUnits = GL.ActiveTextureUnits();
double depth = layout->extrudeDepth;
if (depth > 0.0)
{
bool invert = poly->path->invert;
GL.Sync();
// REVISIT: Replace pushMatrix/popMatrix by
// GL.Save() (Find why it occurs a bug with outline). Refs #3040.
glPushMatrix();
glTranslatef(0.0, 0.0, -depth);
glScalef(1, 1, -1);
GL.FrontFace(invert ? GL_CCW : GL_CW);
drawArrays(poly->mode, textureUnits, data);
GL.FrontFace(invert ? GL_CW : GL_CCW);
glPopMatrix();
}
drawArrays(poly->mode, textureUnits, data);
data.clear();
}
}
static void CALLBACK tessCombine(GLdouble coords[3],
VertexData *vertex[4],
GLfloat weight[4], VertexData **dataOut,
PolygonData *polygon)
// ----------------------------------------------------------------------------
// Combine vertex data when the polygon self-intersects
// ----------------------------------------------------------------------------
{
Point3 pos(coords[0], coords[1], coords[2]);
// The documentation states that all pointers are "valid", but valid
// seems to mean they can be NULL if we come from SpliceMergeVertices
Point3 tex = weight[0] * vertex[0]->texture;
if (vertex[1]) tex += weight[1] * vertex[1]->texture;
if (vertex[2]) tex += weight[2] * vertex[2]->texture;
if (vertex[3]) tex += weight[3] * vertex[3]->texture;
VertexData *result = new VertexData(pos, tex, -1);
polygon->allocated.push_back(result);
*dataOut = result;
}
void GraphicPath::Draw(Layout *where)
// ----------------------------------------------------------------------------
// Draw the graphic path using the current texture, fill and line color
// ----------------------------------------------------------------------------
{
Draw(where, 0);
}
static scale getShortenByStyle(EndpointStyle style, scale lw)
// ----------------------------------------------------------------------------
// Returns the length to remove from a path for a particular endpoint style
// ----------------------------------------------------------------------------
{
switch (style)
{
case GraphicPath::HOLLOW_CIRCLE:
case GraphicPath::HOLLOW_SQUARE:
return 3.5 * lw;
case GraphicPath::FLETCHING:
return 3.0 * lw;
case GraphicPath::ARROWHEAD:
case GraphicPath::TRIANGLE:
case GraphicPath::POINTER:
case GraphicPath::DIAMOND:
return 2.0 * lw;
case GraphicPath::CIRCLE:
case GraphicPath::SQUARE:
return 1.5 * lw;
case GraphicPath::CUP:
return 1.0 * lw;
case GraphicPath::ROUNDED:
case GraphicPath::BAR:
return 0.5 * lw;
case GraphicPath::NONE:
default:
return 0.0;
}
}
static void addEndpointToPath(EndpointStyle style,
Point3 endpoint, Vector3 heading,
GraphicPath &outline)
// ----------------------------------------------------------------------------
// Adds the slyle decoration to the outline path
// ----------------------------------------------------------------------------
{
switch (style)
{
case GraphicPath::ARROWHEAD:
{
Point3 p2 = endpoint + 2.0 * heading;
Point3 p3 = endpoint + 1.5 * heading;
Point3 p4 = p2;
p2.x += heading.y;
p2.y -= heading.x;
p4.x -= heading.y;
p4.y += heading.x;
outline.moveTo(endpoint);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(p4);
outline.lineTo(endpoint);
}
break;
case GraphicPath::TRIANGLE:
{
Point3 p2 = endpoint + 2.0 * heading;
Point3 p3 = p2;
p2.x += heading.y;
p2.y -= heading.x;
p3.x -= heading.y;
p3.y += heading.x;
outline.moveTo(endpoint);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(endpoint);
}
break;
case GraphicPath::POINTER:
{
Point3 p1 = endpoint + heading / 4.0;
Point3 p2 = endpoint + 7.0 / 4.0 * heading;
Point3 p3 = p2;
Point3 p4 = endpoint + heading;
p2.x += 3.0 / 4.0 * heading.y;
p2.y -= 3.0 / 4.0 * heading.x;
p3.x -= 3.0 / 4.0 * heading.y;
p3.y += 3.0 / 4.0 * heading.x;
QPainterPath pointer;
pointer.moveTo(p1.x, p1.y);
pointer.lineTo(p4.x, p4.y);
pointer.moveTo(p2.x, p2.y);
pointer.lineTo(p1.x, p1.y);
pointer.lineTo(p3.x, p3.y);
QPainterPathStroker stroker;
stroker.setWidth(heading.Length() / 2.0);
stroker.setCapStyle(Qt::FlatCap);
stroker.setJoinStyle(Qt::RoundJoin);
stroker.setDashPattern(Qt::SolidLine);
QPainterPath path = stroker.createStroke(pointer);
outline.addQtPath(path);
}
break;
case GraphicPath::DIAMOND:
{
Point3 p2 = endpoint + 1.0 * heading;
Point3 p3 = endpoint + 2.0 * heading;
Point3 p4 = p2;
p2.x += heading.y;
p2.y -= heading.x;
p4.x -= heading.y;
p4.y += heading.x;
outline.moveTo(endpoint);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(p4);
outline.lineTo(endpoint);
}
break;
case GraphicPath::CIRCLE:
{
Point3 c = endpoint + heading;
scale r = heading.Length();
QPainterPath circle;
circle.addEllipse(c.x-r, c.y-r, 2*r, 2*r);
outline.addQtPath(circle);
}
break;
case GraphicPath::SQUARE:
{
Point3 p1 = endpoint;
Point3 p2 = p1;
Point3 p3 = endpoint + 2.0 * heading;
Point3 p4 = p3;
p2.x += heading.y;
p2.y -= heading.x;
p1.x -= heading.y;
p1.y += heading.x;
p3.x += heading.y;
p3.y -= heading.x;
p4.x -= heading.y;
p4.y += heading.x;
outline.moveTo(endpoint);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(p4);
outline.lineTo(p1);
outline.lineTo(endpoint);
}
break;
case GraphicPath::BAR:
{
Point3 p1 = endpoint;
Point3 p2 = p1;
Point3 p3 = endpoint + 2.0 * heading;
Point3 p4 = p3;
p2.x += 4.0 * heading.y;
p2.y -= 4.0 * heading.x;
p1.x -= 4.0 * heading.y;
p1.y += 4.0 * heading.x;
p3.x += 4.0 * heading.y;
p3.y -= 4.0 * heading.x;
p4.x -= 4.0 * heading.y;
p4.y += 4.0 * heading.x;
outline.moveTo(endpoint);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(p4);
outline.lineTo(p1);
outline.lineTo(endpoint);
}
break;
case GraphicPath::CUP:
{
Point3 p2 = endpoint;
Point3 p3 = endpoint + 2.0 * heading;
Point3 p4 = p2;
p2.x += 2.0 * heading.y;
p2.y -= 2.0 * heading.x;
p4.x -= 2.0 * heading.y;
p4.y += 2.0 * heading.x;
outline.moveTo(endpoint);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(p4);
outline.lineTo(endpoint);
}
break;
case GraphicPath::FLETCHING:
{
Point3 p1 = endpoint + heading / 3.0;
Point3 p2 = endpoint;
Point3 p3 = endpoint + 4.0 / 3.0 * heading;
Point3 p4 = endpoint + 2.0 * heading;
Point3 p5 = p3;
Point3 p6 = p2;
p2.x += 2.0 / 3.0 * heading.y;
p2.y -= 2.0 / 3.0 * heading.x;
p3.x += 1.0 / 2.0 * heading.y;
p3.y -= 1.0 / 2.0 * heading.x;
p5.x -= 1.0 / 2.0 * heading.y;
p5.y += 1.0 / 2.0 * heading.x;
p6.x -= 2.0 / 3.0 * heading.y;
p6.y += 2.0 / 3.0 * heading.x;
outline.moveTo(p1);
outline.lineTo(p2);
outline.lineTo(p3);
outline.lineTo(p4);
outline.lineTo(p5);
outline.lineTo(p6);
outline.lineTo(p1);
}
break;
case GraphicPath::HOLLOW_CIRCLE:
{
Point3 c = endpoint + 4.0 / 7.0 * heading;
scale r = 3.0 / 7.0 * heading.Length();
QPainterPath circle;
circle.addEllipse(c.x-r, c.y-r, 2*r, 2*r);
QPainterPathStroker stroker;
stroker.setWidth(2.0 / 7.0 * heading.Length());
stroker.setCapStyle(Qt::FlatCap);
stroker.setJoinStyle(Qt::RoundJoin);
stroker.setDashPattern(Qt::SolidLine);
QPainterPath path = stroker.createStroke(circle);
outline.addQtPath(path);
}
break;
case GraphicPath::HOLLOW_SQUARE:
{
Point3 p1 = endpoint + 1.0 / 7.0 * heading;
Point3 p2 = p1;
Point3 p3 = endpoint + heading;
Point3 p4 = p3;
p2.x += 3.0 / 7.0 * heading.y;
p2.y -= 3.0 / 7.0 * heading.x;
p1.x -= 3.0 / 7.0 * heading.y;
p1.y += 3.0 / 7.0 * heading.x;
p3.x += 3.0 / 7.0 * heading.y;
p3.y -= 3.0 / 7.0 * heading.x;
p4.x -= 3.0 / 7.0 * heading.y;
p4.y += 3.0 / 7.0 * heading.x;
QPainterPath square;
square.moveTo(p1.x, p1.y);
square.lineTo(p2.x, p2.y);
square.lineTo(p3.x, p3.y);
square.lineTo(p4.x, p4.y);
square.lineTo(p1.x, p1.y);
QPainterPathStroker stroker;
stroker.setWidth(2.0 / 7.0 * heading.Length());
stroker.setCapStyle(Qt::FlatCap);
stroker.setJoinStyle(Qt::RoundJoin);
stroker.setDashPattern(Qt::SolidLine);
QPainterPath path = stroker.createStroke(square);
outline.addQtPath(path);
}
break;
case GraphicPath::ROUNDED:
{
Point3 c = endpoint + heading;
scale r = heading.Length();
QPainterPath circle;
circle.addEllipse(c.x-r, c.y-r, 2*r, 2*r);
outline.addQtPath(circle);
}
break;
case GraphicPath::NONE:
default:
break;
}
}
void GraphicPath::Draw(Layout *where, GLenum tessel)
// ----------------------------------------------------------------------------
// Draw the graphic path using the current texture, fill and line color
// ----------------------------------------------------------------------------
{
GLAllStateKeeper save;
// Sync lighting state only if we have lights or shaders
if(GL.LightsMask() || where->programId)
GL.Sync(STATE_lights);
GL.LoadMatrix();
// Do not bother setting up textures and programs if we are in selection
if (tessel != GL_SELECT)
setTexture(where);
else
tessel = 0;
if (where->extrudeDepth > 0.0)
{
bool hasFill = setFillColor(where);
if (hasFill)
Draw(where, where->offset, GL_POLYGON, tessel);
bool hasLine = setLineColor(where);
if (hasLine)
DrawOutline(where);
if (hasFill || hasLine)
Draw(where, where->offset, GL_POLYGON, GL_DEPTH);
}
else
{
if (setFillColor(where))
Draw(where, where->offset, GL_POLYGON, tessel);
if (setLineColor(where))
DrawOutline(where);
}
}
void GraphicPath::DrawOutline(Layout *where)
// ----------------------------------------------------------------------------
// Draw the outline for the current path
// ----------------------------------------------------------------------------
{
GraphicPath outline;
bool first = true;
bool last = true;
Kind endKind = MOVE_TO;
Point3 startPoint;
Point3 endPoint;
Point3* endPointPtr;
Vector3 startHeading;
Vector3 endHeading;
scale length;
scale shortenBy;
path_elements::iterator begin = elements.begin(), end = elements.end();
path_elements::iterator p;
for (path_elements::iterator i = begin; i != end; i++)
{
if (first)
{
shortenBy = getShortenByStyle(startStyle, where->lineWidth);
switch ((*i).kind)
{
case MOVE_TO:
startPoint = (*i).position;
break;
case LINE_TO:
case CURVE_TO:
// First line
startHeading = (*i).position - startPoint;
length = startHeading.Length();
if (length == 0)
{
startPoint = (*i).position;
}
else
{
startHeading.Normalize();
startHeading *= shortenBy;
if(length > shortenBy)
{
outline.moveTo(startPoint + startHeading);
}
else
{
outline.moveTo(startPoint);
startPoint -= startHeading;
}
p=i;
first = false;
}
break;
case CURVE_CONTROL:
// First curve
startHeading = (*i).position - startPoint;
length = startHeading.Length();
if (length == 0)
{
startPoint = (*i).position;
}
else
{
startHeading.Normalize();
startHeading *= shortenBy;
outline.moveTo(startPoint);
startPoint -= startHeading;
p = i;
first = false;
}
break;
}
}
else
{
if ((*p).position == (*i).position)
{
if ((*i).kind == CURVE_TO)
{
p=i;
}
}
else
{
outline.elements.push_back(*p);
p = i;
}
}
}
if (!first)
{
outline.elements.push_back(*p);
}
path_elements::reverse_iterator rbegin = outline.elements.rbegin();
path_elements::reverse_iterator rend = outline.elements.rend();
for (path_elements::reverse_iterator j, i = rbegin; i != rend; ++i)
{
j = i+1;
if (last)
{
shortenBy = getShortenByStyle(endStyle, where->lineWidth);
switch ((*i).kind)
{
case LINE_TO:
// Last line
endKind = LINE_TO;
break;
case CURVE_TO:
case CURVE_CONTROL:
// Last curve or line
if ((*j).kind == CURVE_CONTROL)
endKind = CURVE_TO;
else
endKind = LINE_TO;
break;
case MOVE_TO:
endKind = MOVE_TO;
break;
}
endPoint = (*i).position;
endPointPtr = &(*i).position;
endHeading = (*j).position - (*i).position;
length = endHeading.Length();
if (length == 0)
{
endKind = MOVE_TO;
}
else
{
endHeading.Normalize();
endHeading *= shortenBy;
if (endKind == LINE_TO && length > shortenBy)
{
*endPointPtr += endHeading;
}
else
{
endPoint -= endHeading;
}
}
if (endKind != MOVE_TO)
{
last = false;
}
}
}
// Draw outline of the path.
QPainterPath path;
if (extractQtPath(outline, path))
{
// Path is flat: use a QPainterPathStroker
QPainterPathStroker stroker;
stroker.setWidth(where->lineWidth);
stroker.setCapStyle(Qt::FlatCap);
stroker.setJoinStyle(Qt::RoundJoin);
stroker.setDashPattern(lineStyle);
QPainterPath stroke = stroker.createStroke(path);
outline.clear();
outline.addQtPath(stroke);
// Draw the endpoints
if (!first)
addEndpointToPath(startStyle,startPoint,startHeading,outline);
if (!last)
addEndpointToPath(endStyle, endPoint, endHeading, outline);
outline.Draw(where, where->offset,
GL_POLYGON, GLU_TESS_WINDING_POSITIVE);
}
else
{
// Path is not flat: use GL lines (temporarily)
Draw(where, where->offset, GL_LINE_STRIP, 0);
}
}
void GraphicPath::Draw(Layout *layout,
const Vector3 &offset,
GLenum mode, GLenum tesselation)
// ----------------------------------------------------------------------------
// Draw the graphic path using curves with the given mode and tesselation
// ----------------------------------------------------------------------------
{
PolygonData polygon (this); // Polygon information
Vertices &data = polygon.vertices;
Vertices control; // Control points
path_elements::iterator i, begin = elements.begin(), end = elements.end();
polygon.layout = layout;
uint textureUnits = GL.ActiveTextureUnits();
uint vertexIndex = 0;
scale depth = layout->extrudeDepth;
// Check if we need to tesselate polygon
static GLUtesselator *tess = 0;
if (tesselation && tesselation != GL_DEPTH)
{
if (!tess)
{
tess = gluNewTess();
typedef void CALLBACK (*fn)();
gluTessCallback(tess, GLU_TESS_BEGIN_DATA, fn(tessBegin));
gluTessCallback(tess, GLU_TESS_END_DATA, fn(tessEnd));
gluTessCallback(tess, GLU_TESS_VERTEX_DATA, fn(tessVertex));
gluTessCallback(tess, GLU_TESS_COMBINE_DATA, fn(tessCombine));
}
gluTessProperty(tess, GLU_TESS_WINDING_RULE, tesselation);
gluTessBeginPolygon(tess, &polygon);
}
for (i = begin; i != end; i++)
{
Element &e = *i;
Kind kind = e.kind;
Point3 pos = e.position + offset; // Geometry coordinates
Point3 tex = e.position / bounds; // Texture coordinates
VertexData here(pos, tex, vertexIndex++);
uint size;
switch (kind)
{
default:
std::cerr << "GraphicPath::Draw: Unexpected element kind\n";
break;
case LINE_TO:
data.push_back(here);
// Fall through
case MOVE_TO:
control.clear();
// Fall through
case CURVE_CONTROL:
control.push_back(here);
break;
case CURVE_TO:
control.push_back(here);
// Optimize common sizes, give up for the rest:
size = control.size();
switch (size)
{
case 1:
case 2:
// Simple line, just push the last point
std::cerr << "Got line in CURVE_TO\n";
data.push_back(here);
break;
case 3:
{
// Quadratic Bezier curve
Vector3& v0 = control[0].vertex;
Vector3& v1 = control[1].vertex;
Vector3& v2 = control[2].vertex;
Vector3& t0 = control[0].texture;
Vector3& t1 = control[1].texture;
Vector3& t2 = control[2].texture;
// REVISIT: Implement a true optimization of the interpolation
// Compute a good number of points for approximating the curve
scale length = (v2-v0).Length() + 1;
uint steps = pathSteps(length);
double dt = 1.0 / steps;
double lt = 1.0 + dt/2;
// Emit the points
for (double t = 0.0; t < lt; t += dt)
{
double tt = t*t;
double m = 1-t;
double mm = m*m;
Vector3 vd = mm * v0 + 2*m*t * v1 + tt * v2;
Vector3 td = mm * t0 + 2*m*t * t1 + tt * t2;
VertexData intermediate(vd, td, vertexIndex++);
data.push_back(intermediate);
}
break;
}
default:
std::cerr << "GraphicPath::Draw: Unimplemented Bezier"
<< " (order " << size << ")\n";
break;
case 4:
{
// Cubic Bezier curve
Vector3& v0 = control[0].vertex;
Vector3& v1 = control[1].vertex;
Vector3& v2 = control[2].vertex;
Vector3& v3 = control[3].vertex;
Vector3& t0 = control[0].texture;
Vector3& t1 = control[1].texture;
Vector3& t2 = control[2].texture;
Vector3& t3 = control[3].texture;
// Compute a good number of points for approximating the curve
scale length = (v2-v0).Length() + 1;
uint steps = pathSteps(length);
double dt = 1.0 / steps;
double lt = 1.0 + dt/2;
for (double t = 0.0; t < lt; t += dt)
{
double tt = t*t;
double ttt = t*tt;
double m = 1-t;
double mm = m*m;
double mmm = m*mm;
Vector3 vd = mmm*v0 + 3*mm*t*v1 + 3*m*tt*v2 + ttt*v3;
Vector3 td = mmm*t0 + 3*mm*t*t1 + 3*m*tt*t2 + ttt*t3;
VertexData intermediate(vd, td, vertexIndex++);
data.push_back(intermediate);
}
break;
}
} // switch(size)
control.clear();
control.push_back(here);
} // switch(kind)
// Check if we need to emit what existed before
if (i+1 == end || kind == MOVE_TO)
{
// Get size of previous elements
if (uint size = data.size())
{
if (depth > 0.0)
{
if (!tesselation)
{
// If no tesselation is required, draw back directly
GraphicSave* save = GL.Save();
GL.Translate(0.0, 0.0, -depth);
GL.Scale(1, 1, -1);
GL.FrontFace(GL_CW);
drawArrays(mode, textureUnits, data);
GL.FrontFace(GL_CCW);
GL.Restore(save);
}
extrude(polygon, data, depth);
}
// Pass the data we had so far to OpenGL and clear it
if (tesselation != GL_DEPTH)
{
if (tesselation)
{
gluTessBeginContour(tess);
for (uint j = 0; j < size; j++)
{
VertexData *dynv = new VertexData(data[j]);
polygon.allocated.push_back(dynv);
gluTessVertex(tess, &dynv->vertex.x, dynv);
}
gluTessEndContour(tess);
}
else
{
// If no tesselation is required, draw directly
drawArrays(mode, textureUnits, data);
}
}
data.clear();
}
data.push_back(here);
}
} // Loop on all elements
// End of tesselation
if (tesselation && tesselation != GL_DEPTH)
{
gluTessEndPolygon(tess);
}
}
GraphicPath& GraphicPath::moveTo(Point3 dst)
// ----------------------------------------------------------------------------
// Insert a 'move-to' into the path
// ----------------------------------------------------------------------------
{
elements.push_back(Element(MOVE_TO, dst));
start = dst;
position = dst;
bounds |= dst;
return *this;
}
GraphicPath& GraphicPath::lineTo(Point3 dst)
// ----------------------------------------------------------------------------
// Insert a 'line-to' into the path
// ----------------------------------------------------------------------------
{
if (!elements.size())
moveTo(dst);
elements.push_back(Element(LINE_TO, dst));
position = dst;
bounds |= dst;
return *this;
}
GraphicPath& GraphicPath::curveTo(Point3 control, Point3 dst)
// ----------------------------------------------------------------------------
// Insert a quadratic curve
// ----------------------------------------------------------------------------
{
if (!elements.size())
moveTo(start);
elements.push_back(Element(CURVE_CONTROL, control));
elements.push_back(Element(CURVE_TO, dst));
position = dst;
bounds |= control;
bounds |= dst;
return *this;
}
GraphicPath& GraphicPath::curveTo(Point3 c1, Point3 c2, Point3 dst)
// ----------------------------------------------------------------------------
// Insert a cubic curve
// ----------------------------------------------------------------------------
{
if (!elements.size())
moveTo(start);
elements.push_back(Element(CURVE_CONTROL, c1));
elements.push_back(Element(CURVE_CONTROL, c2));
elements.push_back(Element(CURVE_TO, dst));
position = dst;
bounds |= c1;
bounds |= c2;
bounds |= dst;
return *this;
}
GraphicPath& GraphicPath::close()
// ----------------------------------------------------------------------------
// Close a path by returning to the starting point
// ----------------------------------------------------------------------------
{
if (elements.size())
lineTo(start);
return *this;
}
GraphicPath& GraphicPath::addQtPath(QPainterPath &qt, scale sy)
// ----------------------------------------------------------------------------
// Add a QT path
// ----------------------------------------------------------------------------
{
// Check that Kind and QPainterPath::ElementType numerical values match
XL_CASSERT (int(QPainterPath::MoveToElement) == int(MOVE_TO) &&
int(QPainterPath::LineToElement) == int(LINE_TO) &&
int(QPainterPath::CurveToElement) == int(CURVE_TO) &&
int(QPainterPath::CurveToDataElement) == int(CURVE_CONTROL));
if (sy < 0)
invert = true;
// Loop on the Qt Path and insert elements
// Qt paths place CURVE_TO before control points, we place it last
uint i, max = qt.elementCount();
bool hadControl = false;
for (i = 0; i < max; i++)
{
const QPainterPath::Element &e = qt.elementAt(i);
Kind kind = Kind(e.type);
position = Point3(e.x, sy * e.y, 0);
if (kind == CURVE_CONTROL)
{
hadControl = true;
if (i+1 == max)
kind = CURVE_TO;
}
else
{
if (hadControl)
{
elements.back().kind = CURVE_TO;
hadControl = false;
}
if (kind == CURVE_TO)
kind = CURVE_CONTROL;
}
elements.push_back(Element(kind, position));
bounds |= position;
if (i == 0 && kind == MOVE_TO)
start = position;
}
return *this;
}
bool GraphicPath::extractQtPath(GraphicPath &in, QPainterPath &out)
// ----------------------------------------------------------------------------
// Extract a QT path from a graphic path. Returns true if path was flat
// ----------------------------------------------------------------------------
{
QPainterPath path;
bool flat = true;
// Check that Kind and QPainterPath::ElementType numerical values match
XL_CASSERT (int(QPainterPath::MoveToElement) == int(MOVE_TO) &&
int(QPainterPath::LineToElement) == int(LINE_TO) &&
int(QPainterPath::CurveToElement) == int(CURVE_TO) &&
int(QPainterPath::CurveToDataElement) == int(CURVE_CONTROL));
// Loop on the Graphic Path and insert elements in the QT Path
// Qt paths place CURVE_TO before control points, we place it last
uint i, max = in.elements.size();
Point3 p, c1, c2;
uint control = 0;
for (i = 0; i < max; i++)
{
const GraphicPath::Element &e = in.elements[i];
p = e.position;
switch(e.kind)
{
case GraphicPath::MOVE_TO:
path.moveTo(p.x, p.y);
if (p.z != 0.0)
flat = false;
break;
case GraphicPath::LINE_TO:
path.lineTo(p.x, p.y);
if (p.z != 0.0)
flat = false;
break;
case GraphicPath::CURVE_TO:
switch (control)
{
case 0:
path.lineTo(p.x, p.y);
break;
case 1:
path.quadTo(c1.x, c1.y, p.x, p.y);
break;
case 2:
default:
path.cubicTo(c1.x, c1.y, c2.x, c2.y, p.x, p.y);
break;
}
control = 0;
if (p.z != 0.0)
flat = false;
break;
case GraphicPath::CURVE_CONTROL:
switch (++control)
{
case 1:
c1 = p;
break;
case 2:
c2 = p;
break;
default:
assert(!"Curve should not exceed a cubic form");
}
break;
}
}
out = path;
return flat;
}
bool GraphicPath::extractQtPath(QPainterPath &out)
// ----------------------------------------------------------------------------
// Extract a QT path from the graphic path. Returns true if path was flat
// ----------------------------------------------------------------------------
{
return extractQtPath(*this, out);
}
void GraphicPath::Draw(Layout *where, QPainterPath &qtPath,
GLenum tessel, scale sy)
// ----------------------------------------------------------------------------
// Draw the graphic path using the current texture, fill and line color
// ----------------------------------------------------------------------------
{
GraphicPath path;
path.addQtPath(qtPath, sy);
path.Draw(where, tessel);
}
Box3 GraphicPath::Bounds(Layout *where)
// ----------------------------------------------------------------------------
// Return the bounding box, computed from all path elements
// ----------------------------------------------------------------------------
{
return bounds + where->offset;
}
void GraphicPath::clear()
// ----------------------------------------------------------------------------
// Clear a path
// ----------------------------------------------------------------------------
{
elements.clear();
start = position = Point3();
bounds = Box3();
// Delete the control points
control_points::iterator i;
for (i = controls.begin(); i != controls.end(); i++)
delete *i;
controls.clear();
}
void GraphicPath::AddControl(XL::Tree *self, bool onCurve,
Real *x, Real *y, Real *z)
// ----------------------------------------------------------------------------
// Add a control point to a path
// ----------------------------------------------------------------------------
{
controls.push_back(new ControlPoint(self, onCurve,
x, y, z, controls.size() + 1));
}
void GraphicPath::DrawSelection(Layout *layout)
// ----------------------------------------------------------------------------
// Draw the control points
// ----------------------------------------------------------------------------
{
Widget *widget = layout->Display();
uint sel = widget->selected(layout);
if (sel > 1)
{
// Show the control points
widget->selectionContainerPush();
control_points::iterator i;
for (i = controls.begin(); i != controls.end(); i++)
{
ControlPoint *child = *i;
child->DrawSelection(layout);
}
widget->selectionContainerPop();
}
else if (sel)
{
// Show bounding box
Drawing::DrawSelection(layout);
}
}
void GraphicPath::Identify(Layout *layout)
// ----------------------------------------------------------------------------
// Identify the control points
// ----------------------------------------------------------------------------
{
Draw(layout);
Widget *widget = layout->Display();
if (widget->selected(layout))
{
GL.PushName(layout->id);
control_points::iterator i;
for (i = controls.begin(); i != controls.end(); i++)
{
ControlPoint *child = *i;
child->Identify(layout);
}
GL.PopName();
}
}
GraphicPathInfo::GraphicPathInfo(GraphicPath *path)
// ----------------------------------------------------------------------------
// Store information about a GraphicPath
// ----------------------------------------------------------------------------
{
b0 = path->bounds;
GraphicPath::control_points::iterator i;
for (i = path->controls.begin(); i != path->controls.end(); i++)
{
ControlPoint *child = *i;
controls.push_back(Point3(child->x, child->y, child->z));
}
}
void TesselatedPath::Draw(Layout *where)
// ----------------------------------------------------------------------------
// Draw the graphic path using the current texture, fill and line color
// ----------------------------------------------------------------------------
{
GraphicPath::Draw(where, tesselation);
}
TAO_END
| c3d/tao-3D | app/path3d.cpp | C++ | gpl-3.0 | 47,696 |
package org.w3c.dom.svg;
public interface SVGUnitTypes {
// Unit Types
public static final short SVG_UNIT_TYPE_UNKNOWN = 0;
public static final short SVG_UNIT_TYPE_USERSPACEONUSE = 1;
public static final short SVG_UNIT_TYPE_OBJECTBOUNDINGBOX = 2;
}
| srnsw/xena | plugins/image/ext/src/w3c-svg/src/org/w3c/dom/svg/SVGUnitTypes.java | Java | gpl-3.0 | 281 |
<?php
/* Copyright (C) 2002-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
* Copyright (C) 2005 Simon TOSSER <simon@kornog-computing.com>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
/**
* \file htdocs/compta/ventilation/fournisseur/lignes.php
* \ingroup facture
* \brief Page de detail des lignes de ventilation d'une facture
*/
require '../../../main.inc.php';
$langs->load("bills");
if (!$user->rights->facture->supprimer) accessforbidden();
if (!$user->rights->compta->ventilation->creer) accessforbidden();
/*
* Securite acces client
*/
if ($user->societe_id > 0) accessforbidden();
llxHeader('');
/*
* Lignes de factures
*
*/
$page = $_GET["page"];
if ($page < 0) $page = 0;
$limit = $conf->liste_limit;
$offset = $limit * $page ;
$sql = "SELECT f.facnumber, f.rowid as facid, l.fk_product, l.description, l.total_ttc as price, l.qty, l.rowid, l.tva_tx, l.fk_code_ventilation, c.intitule, c.numero ";
$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn_det as l";
$sql .= " , ".MAIN_DB_PREFIX."facture_fourn as f";
$sql .= " , ".MAIN_DB_PREFIX."compta_compte_generaux as c";
$sql .= " WHERE f.rowid = l.fk_facture_fourn AND f.fk_statut = 1 AND l.fk_code_ventilation <> 0 ";
$sql .= " AND c.rowid = l.fk_code_ventilation";
if (dol_strlen(trim($_GET["search_facture"])))
{
$sql .= " AND f.facnumber like '%".$_GET["search_facture"]."%'";
}
$sql .= " ORDER BY l.rowid DESC";
$sql .= $db->plimit($limit+1,$offset);
$result = $db->query($sql);
if ($result)
{
$num_lignes = $db->num_rows($result);
$i = 0;
print_barre_liste("Lignes de facture ventilées",$page,"lignes.php","",$sortfield,$sortorder,'',$num_lignes);
print '<form method="GET" action="lignes.php">';
print '<table class="noborder" width="100%">';
print "<tr class=\"liste_titre\"><td>Facture</td>";
print '<td>'.$langs->trans("Description").'</td>';
print '<td align="right">'.$langs->trans("Montant").'</td>';
print '<td colspan="2" align="center">'.$langs->trans("Compte").'</td>';
print "</tr>\n";
print '<tr class="liste_titre"><td><input name="search_facture" size="8" value="'.$_GET["search_facture"].'"></td>';
print '<td><input type="submit"></td>';
print '<td align="right"> </td>';
print '<td align="center"> </td>';
print '<td align="center"> </td>';
print "</tr>\n";
$var=True;
while ($i < min($num_lignes, $limit))
{
$objp = $db->fetch_object($result);
$var=!$var;
print "<tr ".$bc[$var].">";
print '<td><a href="'.DOL_URL_ROOT.'/compta/facture.php?facid='.$objp->facid.'">'.$objp->facnumber.'</a></td>';
print '<td>'.stripslashes(nl2br($objp->description)).'</td>';
print '<td align="right">'.price($objp->price).'</td>';
print '<td align="right">'.$objp->numero.'</td>';
print '<td align="left">'.stripslashes($objp->intitule).'</td>';
print "</tr>";
$i++;
}
}
else
{
print $db->error();
}
print "</table></form>";
$db->close();
llxFooter();
?>
| ttingchan/MerchanDolibarr | htdocs/compta/ventilation/fournisseur/lignes.php | PHP | gpl-3.0 | 3,611 |
package org.se.lab;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
@WebServlet("/controller")
public class ControllerServlet extends HttpServlet
{
private final Logger LOG = Logger.getLogger(ControllerServlet.class);
private static final long serialVersionUID = 1L;
public ControllerServlet()
{
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
// Controller
String message = "";
String state = "";
String action = request.getParameter("action");
if(action == null)
{
// do nothing
}
else if(action.equals("Login"))
{
LOG.info("> login");
state = listToString(new ArrayList<Product>());
message = "You logged in successfully!";
}
else if(action.equals("Logout"))
{
LOG.info("> logout");
state = "";
message = "You logged out successfully!";
}
else if(action.equals("Add"))
{
String name = request.getParameter("name");
String quantity = request.getParameter("quantity");
ArrayList<Product> cart = listFromString(request.getParameter("state"));
Product product = new Product(name, quantity);
LOG.info("> add " + product);
cart.add(product);
state = listToString(cart);
message = "added: " + product.getQuantity() + " " + product.getName() + " to the cart";
LOG.info("> cart: " + cart);
}
// generate response page
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String html = generateWebPage(state, message);
out.println(html);
out.close();
}
private String generateWebPage(String state, String message)
{
StringBuilder html = new StringBuilder();
html.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n");
html.append("<html>\n");
html.append(" <head>\n");
html.append(" <title>Simple Shopping Cart</title>\n");
html.append(" </head>\n");
html.append(" <body>\n");
html.append(" <h2>Session Management</h2>\n");
html.append(" <form method=\"post\" action=\"controller\">");
html.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\"/>\n");
html.append(" <table border=\"0\" cellspacing=\"1\" cellpadding=\"5\">");
html.append(" <colgroup>");
html.append(" <col width=\"150\"> <col width=\"150\"> <col width=\"100\">");
html.append(" </colgroup>");
html.append(" <tr>");
html.append(" <th>");
html.append(" <input type=\"submit\" name=\"action\" value=\"Login\">");
html.append(" </th>");
html.append(" <th>");
html.append(" </th>");
html.append(" <th>");
html.append(" <input type=\"submit\" name=\"action\" value=\"Logout\">");
html.append(" </th>");
html.append(" </tr>");
html.append(" </table>");
html.append(" </form>");
html.append(" <p/>");
html.append(" <h2>Your Shopping Cart:</h2>\n");
html.append(" <form method=\"post\" action=\"controller\">");
html.append(" <input type=\"hidden\" name=\"state\" value=\"" + state + "\"/>\n");
html.append(" <table border=\"0\" cellspacing=\"1\" cellpadding=\"5\">");
html.append(" <colgroup>");
html.append(" <col width=\"150\"> <col width=\"150\"> <col width=\"100\">");
html.append(" </colgroup>");
html.append(" <tr>");
html.append(" <th>Product</th>");
html.append(" <th>Quantity</th>");
html.append(" <th></th>");
html.append(" </tr>");
html.append(" <tr>");
html.append(" <td><input type = \"text\" name = \"name\" /></td>");
html.append(" <td><input type = \"text\" name = \"quantity\" /></td>");
html.append(" <td><input type = \"submit\" name = \"action\" value = \"Add\" /></td>");
html.append(" </tr>");
html.append(" </table>");
html.append(" </form>");
html.append(" <p/>");
html.append(" <p style=\"color:blue\"><i>" + message + "</i></p>");
html.append(" <p/>");
Date now = new Date();
html.append(" <h6>" + now + "</h6>");
return html.toString();
}
private String listToString(ArrayList<Product> list)
{
LOG.debug("listToString() " + list);
try
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oos= new ObjectOutputStream(bout);
oos.writeObject(list);
oos.close();
byte[] bytes = bout.toByteArray();
// TODO: Encryption
return Base64.encodeBase64String(bytes);
}
catch (IOException e)
{
return "";
}
}
@SuppressWarnings("unchecked")
private ArrayList<Product> listFromString(String base64String)
{
LOG.debug("listFromString() " + base64String);
try
{
byte[] bytes = Base64.decodeBase64(base64String);
// Decrypt data
ArrayList<Product> list = new ArrayList<Product>();
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
ObjectInputStream ois;
ois = new ObjectInputStream(bin);
list = (ArrayList<Product>) ois.readObject();
ois.close();
return list;
}
catch (IOException | ClassNotFoundException e)
{
return new ArrayList<Product>();
}
}
}
| teiniker/teiniker-lectures-securedesign | web-applications/access-control/session-management/Servlet-SessionManagement-ViewState/src/main/java/org/se/lab/ControllerServlet.java | Java | gpl-3.0 | 6,040 |