repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
part-up/part-up
app/packages/partup-server/api.js
981
var url = Npm.require('url'); var apiRoot = process.env.API_ROOT_URL; var apiKey = process.env.API_KEY; var apiOpts = { headers: { apikey: apiKey } }; var apiSecure = apiRoot && url.parse(apiRoot).protocol === 'https'; // Check event endpoint config if (!apiRoot || !apiKey) { Log.warn('Partup API not configured, missing api root or api key.'); } /** * @ignore */ var _Api = function(document) { _.extend(this, document); }; _Api.prototype.available = apiRoot && apiKey; _Api.prototype.call = function(method, path, options, cb) { var reqOpts = options ? _.merge({}, apiOpts, options) : apiOpts; return HTTP.call(method, url.resolve(apiRoot, path), reqOpts, cb); }; _Api.prototype.get = function(path, options, cb) { return this.call('GET', path, options, cb); }; _Api.prototype.post = function(path, options, cb) { return this.call('POST', path, options, cb); }; _Api.prototype.isSecure = function() { return apiSecure; }; Api = new _Api();
agpl-3.0
peterkshultz/gradecraft-development
spec/controllers/analytics_controller_spec.rb
2976
#spec/controllers/analytics_controller_spec.rb require 'spec_helper' describe AnalyticsController do context "as a professor" do before do @course = create(:course_accepting_groups) @professor = create(:user) @professor.courses << @course @membership = CourseMembership.where(user: @professor, course: @course).first.update(role: "professor") @assignment_type = create(:assignment_type, course: @course) @assignment = create(:assignment, assignment_type: @assignment_type) @course.assignments << @assignment @student = create(:user) @student.courses << @course @students = [] @students << @student login_user(@professor) session[:course_id] = @course.id allow(Resque).to receive(:enqueue).and_return(true) end describe "GET index" do it "returns analytics page for the current course" do get :index expect(assigns(:title)).to eq("User Analytics") expect(response).to render_template(:index) end end describe "GET students" do it "returns the student analytics page for the current course" do get :students expect(assigns(:title)).to eq("Player Analytics") expect(response).to render_template(:students) end end describe "GET staff" do it "returns the staff analytics page for the current course" do get :staff expect(assigns(:title)).to eq("team leader Analytics") expect(response).to render_template(:staff) end end describe "GET top_10" do it "returns the Top 10/Bottom 10 page for the current course" do get :top_10 expect(assigns(:title)).to eq("Top 10/Bottom 10") expect(response).to render_template(:top_10) end end describe "GET per_assign" do it "returns the Assignment Analytics page for the current course" do get :per_assign expect(assigns(:title)).to eq("assignment Analytics") expect(response).to render_template(:per_assign) end end end context "as a student" do describe "protected routes" do [ :index, :students, :staff, :all_events, :top_10, :per_assign, :role_events, :assignment_events, :login_frequencies, :role_login_frequencies, :login_events, :login_role_events, :all_pageview_events, :all_role_pageview_events, :all_user_pageview_events, :pageview_events, :role_pageview_events, :user_pageview_events, :prediction_averages, :assignment_prediction_averages, :export ].each do |route| it "#{route} redirects to root" do expect(get route).to redirect_to(:root) end end end end end
agpl-3.0
tinkerinestudio/Tinkerine-Suite
TinkerineSuite/Cura/cura_sf/fabmetheus_utilities/geometry/geometry_utilities/boolean_geometry.py
7983
""" This page is in the table of contents. The xml.py script is an import translator plugin to get a carving from an Art of Illusion xml file. An import plugin is a script in the interpret_plugins folder which has the function getCarving. It is meant to be run from the interpret tool. To ensure that the plugin works on platforms which do not handle file capitalization properly, give the plugin a lower case name. The getCarving function takes the file name of an xml file and returns the carving. An xml file can be exported from Art of Illusion by going to the "File" menu, then going into the "Export" menu item, then picking the XML choice. This will bring up the XML file chooser window, choose a place to save the file then click "OK". Leave the "compressFile" checkbox unchecked. All the objects from the scene will be exported, this plugin will ignore the light and camera. If you want to fabricate more than one object at a time, you can have multiple objects in the Art of Illusion scene and they will all be carved, then fabricated together. """ from __future__ import absolute_import from fabmetheus_utilities.geometry.geometry_utilities.evaluate_elements import setting from fabmetheus_utilities.geometry.geometry_utilities import boolean_solid from fabmetheus_utilities.geometry.geometry_utilities import evaluate from fabmetheus_utilities.geometry.solids import triangle_mesh from fabmetheus_utilities.vector3 import Vector3 from fabmetheus_utilities import euclidean from fabmetheus_utilities import xml_simple_writer import math __author__ = 'Enrique Perez (perez_enrique@yahoo.com)' __credits__ = 'Nophead <http://hydraraptor.blogspot.com/>\nArt of Illusion <http://www.artofillusion.org/>' __date__ = '$Date: 2008/21/04 $' __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' def getEmptyZLoops(archivableObjects, importRadius, shouldPrintWarning, z, zoneArrangement): 'Get loops at empty z level.' emptyZ = zoneArrangement.getEmptyZ(z) visibleObjects = evaluate.getVisibleObjects(archivableObjects) visibleObjectLoopsList = boolean_solid.getVisibleObjectLoopsList(importRadius, visibleObjects, emptyZ) loops = euclidean.getConcatenatedList(visibleObjectLoopsList) if euclidean.isLoopListIntersecting(loops): loops = boolean_solid.getLoopsUnion(importRadius, visibleObjectLoopsList) if shouldPrintWarning: print('Warning, the triangle mesh slice intersects itself in getExtruderPaths in boolean_geometry.') print('Something will still be printed, but there is no guarantee that it will be the correct shape.') print('Once the gcode is saved, you should check over the layer with a z of:') print(z) return loops def getLoopLayers(archivableObjects, importRadius, layerHeight, maximumZ, shouldPrintWarning, z, zoneArrangement): 'Get loop layers.' loopLayers = [] while z <= maximumZ: triangle_mesh.getLoopLayerAppend(loopLayers, z).loops = getEmptyZLoops(archivableObjects, importRadius, True, z, zoneArrangement) z += layerHeight return loopLayers def getMinimumZ(geometryObject): 'Get the minimum of the minimum z of the archivableObjects and the object.' booleanGeometry = BooleanGeometry() booleanGeometry.archivableObjects = geometryObject.archivableObjects booleanGeometry.importRadius = setting.getImportRadius(geometryObject.elementNode) booleanGeometry.layerHeight = setting.getLayerHeight(geometryObject.elementNode) archivableMinimumZ = booleanGeometry.getMinimumZ() geometryMinimumZ = geometryObject.getMinimumZ() if archivableMinimumZ == None: return geometryMinimumZ if geometryMinimumZ == None: return archivableMinimumZ return min(archivableMinimumZ, geometryMinimumZ) class BooleanGeometry(object): 'A boolean geometry scene.' def __init__(self): 'Add empty lists.' self.archivableObjects = [] self.belowLoops = [] self.importRadius = 0.6 self.layerHeight = 0.4 self.loopLayers = [] def __repr__(self): 'Get the string representation of this carving.' elementNode = None if len(self.archivableObjects) > 0: elementNode = self.archivableObjects[0].elementNode output = xml_simple_writer.getBeginGeometryXMLOutput(elementNode) self.addXML( 1, output ) return xml_simple_writer.getEndGeometryXMLString(output) def addXML(self, depth, output): 'Add xml for this object.' xml_simple_writer.addXMLFromObjects( depth, self.archivableObjects, output ) def getCarveBoundaryLayers(self): 'Get the boundary layers.' if self.getMinimumZ() == None: return [] z = self.minimumZ + 0.5 * self.layerHeight self.loopLayers = getLoopLayers(self.archivableObjects, self.importRadius, self.layerHeight, self.maximumZ, True, z, self.zoneArrangement) self.cornerMaximum = Vector3(-912345678.0, -912345678.0, -912345678.0) self.cornerMinimum = Vector3(912345678.0, 912345678.0, 912345678.0) for loopLayer in self.loopLayers: for loop in loopLayer.loops: for point in loop: pointVector3 = Vector3(point.real, point.imag, loopLayer.z) self.cornerMaximum.maximize(pointVector3) self.cornerMinimum.minimize(pointVector3) self.cornerMaximum.z += self.halfHeight self.cornerMinimum.z -= self.halfHeight for loopLayerIndex in xrange(len(self.loopLayers) -1, -1, -1): loopLayer = self.loopLayers[loopLayerIndex] if len(loopLayer.loops) > 0: return self.loopLayers[: loopLayerIndex + 1] return [] def getCarveCornerMaximum(self): 'Get the corner maximum of the vertexes.' return self.cornerMaximum def getCarveCornerMinimum(self): 'Get the corner minimum of the vertexes.' return self.cornerMinimum def getCarveLayerHeight(self): 'Get the layer height.' return self.layerHeight def getFabmetheusXML(self): 'Return the fabmetheus XML.' if len(self.archivableObjects) > 0: return self.archivableObjects[0].elementNode.getOwnerDocument().getOriginalRoot() return None def getInterpretationSuffix(self): 'Return the suffix for a boolean carving.' return 'xml' def getMatrix4X4(self): 'Get the matrix4X4.' return None def getMatrixChainTetragrid(self): 'Get the matrix chain tetragrid.' return None def getMinimumZ(self): 'Get the minimum z.' vertexes = [] for visibleObject in evaluate.getVisibleObjects(self.archivableObjects): vertexes += visibleObject.getTransformedVertexes() if len(vertexes) < 1: return None self.maximumZ = -912345678.0 self.minimumZ = 912345678.0 for vertex in vertexes: self.maximumZ = max(self.maximumZ, vertex.z) self.minimumZ = min(self.minimumZ, vertex.z) self.zoneArrangement = triangle_mesh.ZoneArrangement(self.layerHeight, vertexes) self.halfHeight = 0.5 * self.layerHeight self.setActualMinimumZ() return self.minimumZ def getNumberOfEmptyZLoops(self, z): 'Get number of empty z loops.' return len(getEmptyZLoops(self.archivableObjects, self.importRadius, False, z, self.zoneArrangement)) def setActualMinimumZ(self): 'Get the actual minimum z at the lowest rotated boundary layer.' halfHeightOverMyriad = 0.0001 * self.halfHeight while self.minimumZ < self.maximumZ: if self.getNumberOfEmptyZLoops(self.minimumZ + halfHeightOverMyriad) > 0: if self.getNumberOfEmptyZLoops(self.minimumZ - halfHeightOverMyriad) < 1: return increment = -self.halfHeight while abs(increment) > halfHeightOverMyriad: self.minimumZ += increment increment = 0.5 * abs(increment) if self.getNumberOfEmptyZLoops(self.minimumZ) > 0: increment = -increment self.minimumZ = round(self.minimumZ, -int(round(math.log10(halfHeightOverMyriad) + 1.5))) return self.minimumZ += self.layerHeight def setCarveImportRadius( self, importRadius ): 'Set the import radius.' self.importRadius = importRadius def setCarveIsCorrectMesh( self, isCorrectMesh ): 'Set the is correct mesh flag.' self.isCorrectMesh = isCorrectMesh def setCarveLayerHeight( self, layerHeight ): 'Set the layer height.' self.layerHeight = layerHeight
agpl-3.0
prefeiturasp/SME-SGP
Src/GestaoEscolar/WebControls/GraficoAtendimento/UCGraficoAtendimento.ascx.cs
950
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace GestaoEscolar.WebControls.GraficoAtendimento { public partial class UCGraficoAtendimento : System.Web.UI.UserControl { public void Carregar(int gra_id, int esc_id, int uni_id, int cur_id, int crr_id, int crp_id, string gra_titulo, string cabecalho, string urlRetorno) { Session["gra_id_GraficoAtendimento"] = gra_id; Session["esc_id_GraficoAtendimento"] = esc_id; Session["uni_id_GraficoAtendimento"] = uni_id; Session["cur_id_GraficoAtendimento"] = cur_id; Session["crr_id_GraficoAtendimento"] = crr_id; Session["crp_id_GraficoAtendimento"] = crp_id; Session["gra_titulo_GraficoAtendimento"] = gra_titulo; Session["cabecalho_GraficoAtendimento"] = cabecalho; } } }
agpl-3.0
skylines-project/skylines
ember/app/routes/flight-upload.js
777
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; export default class FlightUploadRoute extends Route { @service ajax; @service account; @service session; beforeModel(transition) { this.session.requireAuthentication(transition, 'login'); } async model() { let ajax = this.ajax; let accountId = this.get('account.user.id'); let clubId = this.get('account.club.id'); let clubMembers = []; if (clubId) { let { users } = await ajax.request(`/api/users?club=${clubId}`); clubMembers = users.filter(user => user.id !== accountId); } return { clubMembers }; } setupController(controller) { super.setupController(...arguments); controller.set('result', null); } }
agpl-3.0
AdrianLxM/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/PumpDanaRS/comm/DanaRS_Packet_Notify_Alarm.java
2847
package info.nightscout.androidaps.plugins.PumpDanaRS.comm; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import info.nightscout.androidaps.Config; import info.nightscout.androidaps.MainApp; import info.nightscout.androidaps.R; import com.cozmo.danar.util.BleCommandUtil; import info.nightscout.utils.NSUpload; public class DanaRS_Packet_Notify_Alarm extends DanaRS_Packet { private static Logger log = LoggerFactory.getLogger(DanaRS_Packet_Notify_Alarm.class); private int alarmCode; public DanaRS_Packet_Notify_Alarm() { super(); type = BleCommandUtil.DANAR_PACKET__TYPE_NOTIFY; opCode = BleCommandUtil.DANAR_PACKET__OPCODE_NOTIFY__ALARM; } @Override public void handleMessage(byte[] data) { alarmCode = byteArrayToInt(getBytes(data, DATA_START, 1)); String errorString = ""; switch (alarmCode) { case 0x01: // Battery 0% Alarm errorString = MainApp.sResources.getString(R.string.batterydischarged); break; case 0x02: // Pump Error errorString = MainApp.sResources.getString(R.string.pumperror) + " " + alarmCode; break; case 0x03: // Occlusion errorString = MainApp.sResources.getString(R.string.occlusion); break; case 0x04: // LOW BATTERY errorString = MainApp.sResources.getString(R.string.lowbattery); break; case 0x05: // Shutdown errorString = MainApp.sResources.getString(R.string.lowbattery); break; case 0x06: // Basal Compare errorString = "BasalCompare ????"; break; case 0x09: // Empty Reservoir errorString = MainApp.sResources.getString(R.string.emptyreservoir); break; // BT case 0x07: case 0xFF: // Blood sugar measurement alert errorString = MainApp.sResources.getString(R.string.bloodsugarmeasurementalert); break; case 0x08: case 0xFE: // Remaining insulin level errorString = MainApp.sResources.getString(R.string.remaininsulinalert); break; case 0xFD: // Blood sugar check miss alarm errorString = "Blood sugar check miss alarm ???"; break; } if (Config.logDanaMessageDetail) log.debug("Error detected: " + errorString); NSUpload.uploadError(errorString); } @Override public String getFriendlyName() { return "NOTIFY__ALARM"; } }
agpl-3.0
Tesora/tesora-dve-pub
tesora-dve-message-api/src/main/java/com/tesora/dve/db/mysql/libmy/MyLoadDataResponse.java
1405
package com.tesora.dve.db.mysql.libmy; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ import io.netty.buffer.ByteBuf; import io.netty.util.CharsetUtil; import com.tesora.dve.exceptions.PECodingException; public class MyLoadDataResponse extends MyResponseMessage { String fileName; public MyLoadDataResponse(String fileName) { this.fileName = fileName; } @Override public void marshallMessage(ByteBuf cb) { cb.writeByte(0xFB); cb.writeBytes(fileName.getBytes(CharsetUtil.UTF_8)); } @Override public void unmarshallMessage(ByteBuf cb) { throw new PECodingException(getClass().getSimpleName()); } @Override public MyMessageType getMessageType() { return MyMessageType.LOCAL_INFILE_DATA; } }
agpl-3.0
MatthiasKainer/robbie-the-robot
test/public/javascript/src/ast/testLoopParser.ts
3828
import { LoopParser } from "../../../../../public/javascript/src/ast/availableParsers"; import { ParsingService, WordService } from "../../../../../public/javascript/src/ast/parser"; import { Comparator, Operator, SyntaxNode } from "../../../../../public/javascript/src/ast/node"; import { AssignmentNode, ComparingNode, ExpandVariableNode, ExportNode, ExportSequenceNode, LoopNode, NumberNode, OperationNode, StringNode, VariableNode, } from "../../../../../public/javascript/src/ast/availableNodes"; import { suite, test, slow, timeout, skip, only } from "mocha-typescript"; import chai = require("chai"); import * as sinon from "sinon"; const expect = chai.expect; const trigger = "while"; @suite("[LoopParser] When asking if the parser can parse word") class ShouldParseFunction { private parser: LoopParser = new LoopParser(new ParsingService([])); @test public "given the word should start the parser"() { expect(this.parser.activate(trigger)).to.be.true; } @test public "given the word should not start the parser"() { expect(this.parser.activate("anythingnotatrigger")).to.be.false; expect(this.parser.activate("")).to.be.false; } } @suite("[LoopParser] When trying to parse a for(from; until; do; too much; stuff) loop") class TestFromUntilDoAndErrorParser { private input = `while (the i is 0 & our i is < 10 & i is our i + 1 & export 1 & our robot) ( )`; @test public "validate expectation"() { const parser = new ParsingService(WordService.create(this.input)); let result = null; try { parser.parse(); } catch (err) { result = err; } expect(result).not.null; } } @suite("[LoopParser] When trying to parse a for(from; until; do) loop") class TestFromUntilDoParser { private input = `while (the i is 0&our i < 10 & i is our i+1) ( export i )`; private expect = new LoopNode(new ExportNode(new StringNode("i")), new ComparingNode(Comparator.Smaller, new ExpandVariableNode(new StringNode("i")), new NumberNode(10)), new ExportSequenceNode(new VariableNode(new StringNode("i")), new AssignmentNode(new StringNode("i"), new NumberNode(0)), new ExportNode(new StringNode("i"))), new AssignmentNode(new ExpandVariableNode(new StringNode("i")), new OperationNode(Operator.Add, new ExpandVariableNode(new StringNode("i")), new NumberNode(1)))); @test public "validate expectation"() { const parser = new ParsingService(WordService.create(this.input)); const result = parser.parse(); expect(expect).not.to.be.deep.eq(result); } } @suite("[LoopParser] When trying to parse a for(from; until) loop") class TestFromUntilParser { private input = `while (the i is 0 & our i<10) ( )`; private expect = new LoopNode(null, new ComparingNode(Comparator.Smaller, new ExpandVariableNode(new StringNode("i")), new NumberNode(10)), new ExportSequenceNode(new VariableNode(new StringNode("i")), new AssignmentNode(new StringNode("i"), new NumberNode(0)), new ExportNode(new StringNode("i")))); @test public "validate expectation"() { const parser = new ParsingService(WordService.create(this.input)); const result = parser.parse(); expect(expect).not.to.be.deep.eq(result); } } @suite("[LoopParser] When trying to parse a while(until) loop") class TestWhileParser { private input = `while (our i < 10) ()`; private expect = new LoopNode(null, new ComparingNode(Comparator.Smaller, new ExpandVariableNode(new StringNode("i")), new NumberNode(10))); @test public "validate expectation"() { const parser = new ParsingService(WordService.create(this.input)); const result = parser.parse(); expect(expect).not.to.be.deep.eq(result); } }
agpl-3.0
KadJ/amazon_new
cache/modules/Contacts/Contactvardefs.php
37615
<?php $GLOBALS["dictionary"]["Contact"]=array ( 'table' => 'contacts', 'audited' => true, 'unified_search' => true, 'full_text_search' => true, 'unified_search_default_enabled' => true, 'duplicate_merge' => true, 'fields' => array ( 'id' => array ( 'name' => 'id', 'vname' => 'LBL_ID', 'type' => 'id', 'required' => true, 'reportable' => true, 'comment' => 'Unique identifier', ), 'name' => array ( 'name' => 'name', 'rname' => 'name', 'vname' => 'LBL_NAME', 'type' => 'name', 'link' => true, 'fields' => array ( 0 => 'first_name', 1 => 'last_name', ), 'sort_on' => 'last_name', 'source' => 'non-db', 'group' => 'last_name', 'len' => '255', 'db_concat_fields' => array ( 0 => 'first_name', 1 => 'last_name', ), 'importable' => 'false', 'phone_search' => 1, ), 'date_entered' => array ( 'name' => 'date_entered', 'vname' => 'LBL_DATE_ENTERED', 'type' => 'datetime', 'group' => 'created_by_name', 'comment' => 'Date record created', 'enable_range_search' => true, 'options' => 'date_range_search_dom', ), 'date_modified' => array ( 'name' => 'date_modified', 'vname' => 'LBL_DATE_MODIFIED', 'type' => 'datetime', 'group' => 'modified_by_name', 'comment' => 'Date record last modified', 'enable_range_search' => true, 'options' => 'date_range_search_dom', ), 'modified_user_id' => array ( 'name' => 'modified_user_id', 'rname' => 'user_name', 'id_name' => 'modified_user_id', 'vname' => 'LBL_MODIFIED', 'type' => 'assigned_user_name', 'table' => 'users', 'isnull' => 'false', 'group' => 'modified_by_name', 'dbType' => 'id', 'reportable' => true, 'comment' => 'User who last modified record', 'massupdate' => false, ), 'modified_by_name' => array ( 'name' => 'modified_by_name', 'vname' => 'LBL_MODIFIED_NAME', 'type' => 'relate', 'reportable' => false, 'source' => 'non-db', 'rname' => 'user_name', 'table' => 'users', 'id_name' => 'modified_user_id', 'module' => 'Users', 'link' => 'modified_user_link', 'duplicate_merge' => 'disabled', 'massupdate' => false, ), 'created_by' => array ( 'name' => 'created_by', 'rname' => 'user_name', 'id_name' => 'modified_user_id', 'vname' => 'LBL_CREATED', 'type' => 'assigned_user_name', 'table' => 'users', 'isnull' => 'false', 'dbType' => 'id', 'group' => 'created_by_name', 'comment' => 'User who created record', 'massupdate' => false, ), 'created_by_name' => array ( 'name' => 'created_by_name', 'vname' => 'LBL_CREATED', 'type' => 'relate', 'reportable' => false, 'link' => 'created_by_link', 'rname' => 'user_name', 'source' => 'non-db', 'table' => 'users', 'id_name' => 'created_by', 'module' => 'Users', 'duplicate_merge' => 'disabled', 'importable' => 'false', 'massupdate' => false, ), 'description' => array ( 'name' => 'description', 'vname' => 'LBL_DESCRIPTION', 'type' => 'text', 'comment' => 'Full text of the note', 'rows' => 6, 'cols' => 80, ), 'deleted' => array ( 'name' => 'deleted', 'vname' => 'LBL_DELETED', 'type' => 'bool', 'default' => '0', 'reportable' => false, 'comment' => 'Record deletion indicator', ), 'created_by_link' => array ( 'name' => 'created_by_link', 'type' => 'link', 'relationship' => 'contacts_created_by', 'vname' => 'LBL_CREATED_BY_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', ), 'modified_user_link' => array ( 'name' => 'modified_user_link', 'type' => 'link', 'relationship' => 'contacts_modified_user', 'vname' => 'LBL_MODIFIED_BY_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', ), 'assigned_user_id' => array ( 'name' => 'assigned_user_id', 'rname' => 'user_name', 'id_name' => 'assigned_user_id', 'vname' => 'LBL_ASSIGNED_TO_ID', 'group' => 'assigned_user_name', 'type' => 'relate', 'table' => 'users', 'module' => 'Users', 'reportable' => true, 'isnull' => 'false', 'dbType' => 'id', 'audited' => true, 'comment' => 'User ID assigned to record', 'duplicate_merge' => 'disabled', ), 'assigned_user_name' => array ( 'name' => 'assigned_user_name', 'link' => 'assigned_user_link', 'vname' => 'LBL_ASSIGNED_TO_NAME', 'rname' => 'user_name', 'type' => 'relate', 'reportable' => false, 'source' => 'non-db', 'table' => 'users', 'id_name' => 'assigned_user_id', 'module' => 'Users', 'duplicate_merge' => 'disabled', ), 'assigned_user_link' => array ( 'name' => 'assigned_user_link', 'type' => 'link', 'relationship' => 'contacts_assigned_user', 'vname' => 'LBL_ASSIGNED_TO_USER', 'link_type' => 'one', 'module' => 'Users', 'bean_name' => 'User', 'source' => 'non-db', 'rname' => 'user_name', 'id_name' => 'assigned_user_id', 'table' => 'users', 'duplicate_merge' => 'enabled', ), 'salutation' => array ( 'name' => 'salutation', 'vname' => 'LBL_SALUTATION', 'type' => 'enum', 'options' => 'salutation_dom', 'massupdate' => false, 'len' => 100, 'comment' => 'Contact salutation (e.g., Mr, Ms)', 'comments' => 'Contact salutation (e.g., Mr, Ms)', 'merge_filter' => 'disabled', ), 'first_name' => array ( 'name' => 'first_name', 'vname' => 'LBL_FIRST_NAME', 'type' => 'varchar', 'len' => '100', 'unified_search' => true, 'full_text_search' => array ( 'boost' => 3, ), 'comment' => 'First name of the contact', 'merge_filter' => 'selected', ), 'last_name' => array ( 'name' => 'last_name', 'vname' => 'LBL_LAST_NAME', 'type' => 'varchar', 'len' => '100', 'unified_search' => true, 'full_text_search' => array ( 'boost' => 3, ), 'comment' => 'Last name of the contact', 'merge_filter' => 'selected', 'required' => true, 'importable' => 'required', ), 'full_name' => array ( 'name' => 'full_name', 'rname' => 'full_name', 'vname' => 'LBL_NAME', 'type' => 'fullname', 'fields' => array ( 0 => 'first_name', 1 => 'last_name', ), 'sort_on' => 'last_name', 'source' => 'non-db', 'group' => 'last_name', 'len' => '510', 'db_concat_fields' => array ( 0 => 'first_name', 1 => 'last_name', ), 'studio' => array ( 'listview' => false, ), ), 'title' => array ( 'name' => 'title', 'vname' => 'LBL_TITLE', 'type' => 'varchar', 'len' => '100', 'comment' => 'The title of the contact', ), 'department' => array ( 'name' => 'department', 'vname' => 'LBL_DEPARTMENT', 'type' => 'varchar', 'len' => '255', 'comment' => 'The department of the contact', 'merge_filter' => 'enabled', ), 'do_not_call' => array ( 'name' => 'do_not_call', 'vname' => 'LBL_DO_NOT_CALL', 'type' => 'bool', 'default' => '0', 'audited' => true, 'comment' => 'An indicator of whether contact can be called', ), 'phone_home' => array ( 'name' => 'phone_home', 'vname' => 'LBL_HOME_PHONE', 'type' => 'phone', 'dbType' => 'varchar', 'len' => 100, 'unified_search' => true, 'full_text_search' => array ( 'boost' => 1, ), 'comment' => 'Home phone number of the contact', 'merge_filter' => 'enabled', 'phone_search' => 7, ), 'email' => array ( 'name' => 'email', 'type' => 'email', 'query_type' => 'default', 'source' => 'non-db', 'operator' => 'subquery', 'subquery' => 'SELECT eabr.bean_id FROM email_addr_bean_rel eabr JOIN email_addresses ea ON (ea.id = eabr.email_address_id) WHERE eabr.deleted=0 AND ea.email_address LIKE', 'db_field' => array ( 0 => 'id', ), 'vname' => 'LBL_ANY_EMAIL', 'studio' => array ( 'visible' => false, 'searchview' => true, ), ), 'phone_mobile' => array ( 'name' => 'phone_mobile', 'vname' => 'LBL_MOBILE_PHONE', 'type' => 'phone', 'dbType' => 'varchar', 'len' => 100, 'unified_search' => true, 'full_text_search' => array ( 'boost' => 1, ), 'comment' => 'Mobile phone number of the contact', 'merge_filter' => 'enabled', 'phone_search' => 8, ), 'phone_work' => array ( 'name' => 'phone_work', 'vname' => 'LBL_OFFICE_PHONE', 'type' => 'phone', 'dbType' => 'varchar', 'len' => 100, 'audited' => true, 'unified_search' => true, 'full_text_search' => array ( 'boost' => 1, ), 'comment' => 'Work phone number of the contact', 'merge_filter' => 'enabled', 'phone_main' => true, 'phone_search' => 3, ), 'phone_other' => array ( 'name' => 'phone_other', 'vname' => 'LBL_OTHER_PHONE', 'type' => 'phone', 'dbType' => 'varchar', 'len' => 100, 'unified_search' => true, 'full_text_search' => array ( 'boost' => 1, ), 'comment' => 'Other phone number for the contact', 'merge_filter' => 'enabled', 'phone_search' => 4, ), 'phone_fax' => array ( 'name' => 'phone_fax', 'vname' => 'LBL_FAX_PHONE', 'type' => 'phone', 'dbType' => 'varchar', 'len' => 100, 'unified_search' => true, 'full_text_search' => array ( 'boost' => 1, ), 'comment' => 'Contact fax number', 'merge_filter' => 'enabled', 'phone_search' => 6, ), 'email1' => array ( 'name' => 'email1', 'vname' => 'LBL_EMAIL_ADDRESS', 'type' => 'varchar', 'function' => array ( 'name' => 'getEmailAddressWidget', 'returns' => 'html', ), 'source' => 'non-db', 'group' => 'email1', 'merge_filter' => 'enabled', 'studio' => array ( 'editview' => true, 'editField' => true, 'searchview' => false, 'popupsearch' => false, ), 'full_text_search' => array ( 'boost' => 3, 'index' => 'not_analyzed', ), ), 'email2' => array ( 'name' => 'email2', 'vname' => 'LBL_OTHER_EMAIL_ADDRESS', 'type' => 'varchar', 'function' => array ( 'name' => 'getEmailAddressWidget', 'returns' => 'html', ), 'source' => 'non-db', 'group' => 'email2', 'merge_filter' => 'enabled', 'studio' => 'false', ), 'invalid_email' => array ( 'name' => 'invalid_email', 'vname' => 'LBL_INVALID_EMAIL', 'source' => 'non-db', 'type' => 'bool', 'massupdate' => false, 'studio' => 'false', ), 'email_opt_out' => array ( 'name' => 'email_opt_out', 'vname' => 'LBL_EMAIL_OPT_OUT', 'source' => 'non-db', 'type' => 'bool', 'massupdate' => false, 'studio' => 'false', ), 'primary_address_street' => array ( 'name' => 'primary_address_street', 'vname' => 'LBL_PRIMARY_ADDRESS_STREET', 'type' => 'varchar', 'len' => '150', 'group' => 'primary_address', 'comment' => 'Street address for primary address', 'merge_filter' => 'enabled', ), 'primary_address_street_2' => array ( 'name' => 'primary_address_street_2', 'vname' => 'LBL_PRIMARY_ADDRESS_STREET_2', 'type' => 'varchar', 'len' => '150', 'source' => 'non-db', ), 'primary_address_street_3' => array ( 'name' => 'primary_address_street_3', 'vname' => 'LBL_PRIMARY_ADDRESS_STREET_3', 'type' => 'varchar', 'len' => '150', 'source' => 'non-db', ), 'primary_address_city' => array ( 'name' => 'primary_address_city', 'vname' => 'LBL_PRIMARY_ADDRESS_CITY', 'type' => 'varchar', 'len' => '100', 'group' => 'primary_address', 'comment' => 'City for primary address', 'merge_filter' => 'enabled', ), 'primary_address_state' => array ( 'name' => 'primary_address_state', 'vname' => 'LBL_PRIMARY_ADDRESS_STATE', 'type' => 'varchar', 'len' => '100', 'group' => 'primary_address', 'comment' => 'State for primary address', 'merge_filter' => 'enabled', ), 'primary_address_postalcode' => array ( 'name' => 'primary_address_postalcode', 'vname' => 'LBL_PRIMARY_ADDRESS_POSTALCODE', 'type' => 'varchar', 'len' => '20', 'group' => 'primary_address', 'comment' => 'Postal code for primary address', 'merge_filter' => 'enabled', ), 'primary_address_country' => array ( 'name' => 'primary_address_country', 'vname' => 'LBL_PRIMARY_ADDRESS_COUNTRY', 'type' => 'varchar', 'group' => 'primary_address', 'comment' => 'Country for primary address', 'merge_filter' => 'enabled', ), 'alt_address_street' => array ( 'name' => 'alt_address_street', 'vname' => 'LBL_ALT_ADDRESS_STREET', 'type' => 'varchar', 'len' => '150', 'group' => 'alt_address', 'comment' => 'Street address for alternate address', 'merge_filter' => 'enabled', ), 'alt_address_street_2' => array ( 'name' => 'alt_address_street_2', 'vname' => 'LBL_ALT_ADDRESS_STREET_2', 'type' => 'varchar', 'len' => '150', 'source' => 'non-db', ), 'alt_address_street_3' => array ( 'name' => 'alt_address_street_3', 'vname' => 'LBL_ALT_ADDRESS_STREET_3', 'type' => 'varchar', 'len' => '150', 'source' => 'non-db', ), 'alt_address_city' => array ( 'name' => 'alt_address_city', 'vname' => 'LBL_ALT_ADDRESS_CITY', 'type' => 'varchar', 'len' => '100', 'group' => 'alt_address', 'comment' => 'City for alternate address', 'merge_filter' => 'enabled', ), 'alt_address_state' => array ( 'name' => 'alt_address_state', 'vname' => 'LBL_ALT_ADDRESS_STATE', 'type' => 'varchar', 'len' => '100', 'group' => 'alt_address', 'comment' => 'State for alternate address', 'merge_filter' => 'enabled', ), 'alt_address_postalcode' => array ( 'name' => 'alt_address_postalcode', 'vname' => 'LBL_ALT_ADDRESS_POSTALCODE', 'type' => 'varchar', 'len' => '20', 'group' => 'alt_address', 'comment' => 'Postal code for alternate address', 'merge_filter' => 'enabled', ), 'alt_address_country' => array ( 'name' => 'alt_address_country', 'vname' => 'LBL_ALT_ADDRESS_COUNTRY', 'type' => 'varchar', 'group' => 'alt_address', 'comment' => 'Country for alternate address', 'merge_filter' => 'enabled', ), 'assistant' => array ( 'name' => 'assistant', 'vname' => 'LBL_ASSISTANT', 'type' => 'varchar', 'len' => '75', 'unified_search' => true, 'full_text_search' => array ( 'boost' => 2, ), 'comment' => 'Name of the assistant of the contact', 'merge_filter' => 'enabled', ), 'assistant_phone' => array ( 'name' => 'assistant_phone', 'vname' => 'LBL_ASSISTANT_PHONE', 'type' => 'phone', 'dbType' => 'varchar', 'len' => 100, 'group' => 'assistant', 'unified_search' => true, 'full_text_search' => array ( 'boost' => 1, ), 'comment' => 'Phone number of the assistant of the contact', 'merge_filter' => 'enabled', 'phone_search' => 5, ), 'email_addresses_primary' => array ( 'name' => 'email_addresses_primary', 'type' => 'link', 'relationship' => 'contacts_email_addresses_primary', 'source' => 'non-db', 'vname' => 'LBL_EMAIL_ADDRESS_PRIMARY', 'duplicate_merge' => 'disabled', ), 'email_addresses' => array ( 'name' => 'email_addresses', 'type' => 'link', 'relationship' => 'contacts_email_addresses', 'module' => 'EmailAddress', 'bean_name' => 'EmailAddress', 'source' => 'non-db', 'vname' => 'LBL_EMAIL_ADDRESSES', 'reportable' => false, 'rel_fields' => array ( 'primary_address' => array ( 'type' => 'bool', ), ), 'unified_search' => true, ), 'email_and_name1' => array ( 'name' => 'email_and_name1', 'rname' => 'email_and_name1', 'vname' => 'LBL_NAME', 'type' => 'varchar', 'source' => 'non-db', 'len' => '510', 'importable' => 'false', ), 'lead_source' => array ( 'name' => 'lead_source', 'vname' => 'LBL_LEAD_SOURCE', 'type' => 'enum', 'options' => 'lead_source_dom', 'len' => '255', 'comment' => 'How did the contact come about', ), 'account_name' => array ( 'name' => 'account_name', 'rname' => 'name', 'id_name' => 'account_id', 'vname' => 'LBL_ACCOUNT_NAME', 'join_name' => 'accounts', 'type' => 'relate', 'link' => 'accounts', 'table' => 'accounts', 'isnull' => 'true', 'module' => 'Accounts', 'dbType' => 'varchar', 'len' => '255', 'source' => 'non-db', 'unified_search' => true, 'phone_search' => 2, ), 'account_id' => array ( 'name' => 'account_id', 'rname' => 'id', 'id_name' => 'account_id', 'vname' => 'LBL_ACCOUNT_ID', 'type' => 'relate', 'table' => 'accounts', 'isnull' => 'true', 'module' => 'Accounts', 'dbType' => 'id', 'reportable' => false, 'source' => 'non-db', 'massupdate' => false, 'duplicate_merge' => 'disabled', 'hideacl' => true, ), 'opportunity_role_fields' => array ( 'name' => 'opportunity_role_fields', 'rname' => 'id', 'relationship_fields' => array ( 'id' => 'opportunity_role_id', 'contact_role' => 'opportunity_role', ), 'vname' => 'LBL_ACCOUNT_NAME', 'type' => 'relate', 'link' => 'opportunities', 'link_type' => 'relationship_info', 'join_link_name' => 'opportunities_contacts', 'source' => 'non-db', 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => false, ), 'opportunity_role_id' => array ( 'name' => 'opportunity_role_id', 'type' => 'varchar', 'source' => 'non-db', 'vname' => 'LBL_OPPORTUNITY_ROLE_ID', 'studio' => array ( 'listview' => false, ), ), 'opportunity_role' => array ( 'name' => 'opportunity_role', 'type' => 'enum', 'source' => 'non-db', 'vname' => 'LBL_OPPORTUNITY_ROLE', 'options' => 'opportunity_relationship_type_dom', ), 'reports_to_id' => array ( 'name' => 'reports_to_id', 'vname' => 'LBL_REPORTS_TO_ID', 'type' => 'id', 'required' => false, 'reportable' => false, 'comment' => 'The contact this contact reports to', ), 'report_to_name' => array ( 'name' => 'report_to_name', 'rname' => 'last_name', 'id_name' => 'reports_to_id', 'vname' => 'LBL_REPORTS_TO', 'type' => 'relate', 'link' => 'reports_to_link', 'table' => 'contacts', 'isnull' => 'true', 'module' => 'Contacts', 'dbType' => 'varchar', 'len' => 'id', 'reportable' => false, 'source' => 'non-db', ), 'birthdate' => array ( 'name' => 'birthdate', 'vname' => 'LBL_BIRTHDATE', 'massupdate' => false, 'type' => 'date', 'comment' => 'The birthdate of the contact', ), 'accounts' => array ( 'name' => 'accounts', 'type' => 'link', 'relationship' => 'accounts_contacts', 'link_type' => 'one', 'source' => 'non-db', 'vname' => 'LBL_ACCOUNT', 'duplicate_merge' => 'disabled', ), 'reports_to_link' => array ( 'name' => 'reports_to_link', 'type' => 'link', 'relationship' => 'contact_direct_reports', 'link_type' => 'one', 'side' => 'right', 'source' => 'non-db', 'vname' => 'LBL_REPORTS_TO', ), 'opportunities' => array ( 'name' => 'opportunities', 'type' => 'link', 'relationship' => 'opportunities_contacts', 'source' => 'non-db', 'module' => 'Opportunities', 'bean_name' => 'Opportunity', 'vname' => 'LBL_OPPORTUNITIES', ), 'bugs' => array ( 'name' => 'bugs', 'type' => 'link', 'relationship' => 'contacts_bugs', 'source' => 'non-db', 'vname' => 'LBL_BUGS', ), 'calls' => array ( 'name' => 'calls', 'type' => 'link', 'relationship' => 'calls_contacts', 'source' => 'non-db', 'vname' => 'LBL_CALLS', ), 'cases' => array ( 'name' => 'cases', 'type' => 'link', 'relationship' => 'contacts_cases', 'source' => 'non-db', 'vname' => 'LBL_CASES', ), 'direct_reports' => array ( 'name' => 'direct_reports', 'type' => 'link', 'relationship' => 'contact_direct_reports', 'source' => 'non-db', 'vname' => 'LBL_DIRECT_REPORTS', ), 'emails' => array ( 'name' => 'emails', 'type' => 'link', 'relationship' => 'emails_contacts_rel', 'source' => 'non-db', 'vname' => 'LBL_EMAILS', ), 'documents' => array ( 'name' => 'documents', 'type' => 'link', 'relationship' => 'documents_contacts', 'source' => 'non-db', 'vname' => 'LBL_DOCUMENTS_SUBPANEL_TITLE', ), 'leads' => array ( 'name' => 'leads', 'type' => 'link', 'relationship' => 'contact_leads', 'source' => 'non-db', 'vname' => 'LBL_LEADS', ), 'meetings' => array ( 'name' => 'meetings', 'type' => 'link', 'relationship' => 'meetings_contacts', 'source' => 'non-db', 'vname' => 'LBL_MEETINGS', ), 'notes' => array ( 'name' => 'notes', 'type' => 'link', 'relationship' => 'contact_notes', 'source' => 'non-db', 'vname' => 'LBL_NOTES', ), 'project' => array ( 'name' => 'project', 'type' => 'link', 'relationship' => 'projects_contacts', 'source' => 'non-db', 'vname' => 'LBL_PROJECTS', ), 'project_resource' => array ( 'name' => 'project_resource', 'type' => 'link', 'relationship' => 'projects_contacts_resources', 'source' => 'non-db', 'vname' => 'LBL_PROJECTS_RESOURCES', ), 'tasks' => array ( 'name' => 'tasks', 'type' => 'link', 'relationship' => 'contact_tasks', 'source' => 'non-db', 'vname' => 'LBL_TASKS', ), 'tasks_parent' => array ( 'name' => 'tasks_parent', 'type' => 'link', 'relationship' => 'contact_tasks_parent', 'source' => 'non-db', 'vname' => 'LBL_TASKS', 'reportable' => false, ), 'user_sync' => array ( 'name' => 'user_sync', 'type' => 'link', 'relationship' => 'contacts_users', 'source' => 'non-db', 'vname' => 'LBL_USER_SYNC', ), 'campaign_id' => array ( 'name' => 'campaign_id', 'comment' => 'Campaign that generated lead', 'vname' => 'LBL_CAMPAIGN_ID', 'rname' => 'id', 'id_name' => 'campaign_id', 'type' => 'id', 'table' => 'campaigns', 'isnull' => 'true', 'module' => 'Campaigns', 'massupdate' => false, 'duplicate_merge' => 'disabled', ), 'campaign_name' => array ( 'name' => 'campaign_name', 'rname' => 'name', 'vname' => 'LBL_CAMPAIGN', 'type' => 'relate', 'link' => 'campaign_contacts', 'isnull' => 'true', 'reportable' => false, 'source' => 'non-db', 'table' => 'campaigns', 'id_name' => 'campaign_id', 'module' => 'Campaigns', 'duplicate_merge' => 'disabled', 'comment' => 'The first campaign name for Contact (Meta-data only)', ), 'campaigns' => array ( 'name' => 'campaigns', 'type' => 'link', 'relationship' => 'contact_campaign_log', 'module' => 'CampaignLog', 'bean_name' => 'CampaignLog', 'source' => 'non-db', 'vname' => 'LBL_CAMPAIGNLOG', ), 'campaign_contacts' => array ( 'name' => 'campaign_contacts', 'type' => 'link', 'vname' => 'LBL_CAMPAIGN_CONTACT', 'relationship' => 'campaign_contacts', 'source' => 'non-db', ), 'c_accept_status_fields' => array ( 'name' => 'c_accept_status_fields', 'rname' => 'id', 'relationship_fields' => array ( 'id' => 'accept_status_id', 'accept_status' => 'accept_status_name', ), 'vname' => 'LBL_LIST_ACCEPT_STATUS', 'type' => 'relate', 'link' => 'calls', 'link_type' => 'relationship_info', 'source' => 'non-db', 'importable' => 'false', 'duplicate_merge' => 'disabled', 'studio' => false, ), 'm_accept_status_fields' => array ( 'name' => 'm_accept_status_fields', 'rname' => 'id', 'relationship_fields' => array ( 'id' => 'accept_status_id', 'accept_status' => 'accept_status_name', ), 'vname' => 'LBL_LIST_ACCEPT_STATUS', 'type' => 'relate', 'link' => 'meetings', 'link_type' => 'relationship_info', 'source' => 'non-db', 'importable' => 'false', 'hideacl' => true, 'duplicate_merge' => 'disabled', 'studio' => false, ), 'accept_status_id' => array ( 'name' => 'accept_status_id', 'type' => 'varchar', 'source' => 'non-db', 'vname' => 'LBL_LIST_ACCEPT_STATUS', 'studio' => array ( 'listview' => false, ), ), 'accept_status_name' => array ( 'massupdate' => false, 'name' => 'accept_status_name', 'type' => 'enum', 'studio' => 'false', 'source' => 'non-db', 'vname' => 'LBL_LIST_ACCEPT_STATUS', 'options' => 'dom_meeting_accept_status', 'importable' => 'false', ), 'prospect_lists' => array ( 'name' => 'prospect_lists', 'type' => 'link', 'relationship' => 'prospect_list_contacts', 'module' => 'ProspectLists', 'source' => 'non-db', 'vname' => 'LBL_PROSPECT_LIST', ), 'sync_contact' => array ( 'massupdate' => false, 'name' => 'sync_contact', 'vname' => 'LBL_SYNC_CONTACT', 'type' => 'bool', 'source' => 'non-db', 'comment' => 'Synch to outlook? (Meta-Data only)', 'studio' => 'true', ), 'aos_quotes' => array ( 'name' => 'aos_quotes', 'type' => 'link', 'relationship' => 'contact_aos_quotes', 'module' => 'AOS_Quotes', 'bean_name' => 'AOS_Quotes', 'source' => 'non-db', ), 'aos_invoices' => array ( 'name' => 'aos_invoices', 'type' => 'link', 'relationship' => 'contact_aos_invoices', 'module' => 'AOS_Invoices', 'bean_name' => 'AOS_Invoices', 'source' => 'non-db', ), 'aos_contracts' => array ( 'name' => 'aos_contracts', 'type' => 'link', 'relationship' => 'contact_aos_contracts', 'module' => 'AOS_Contracts', 'bean_name' => 'AOS_Contracts', 'source' => 'non-db', ), 'title_pdf_1_c' => array ( 'required' => false, 'source' => 'custom_fields', 'name' => 'title_pdf_1_c', 'vname' => 'LBL_TITLE_PDF_1', 'type' => 'varchar', 'massupdate' => '0', 'default' => '', 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '255', 'size' => '20', 'id' => 'Contactstitle_pdf_1_c', 'custom_module' => 'Contacts', ), 'title_pdf_2_c' => array ( 'required' => false, 'source' => 'custom_fields', 'name' => 'title_pdf_2_c', 'vname' => 'LBL_TITLE_PDF_2', 'type' => 'varchar', 'massupdate' => '0', 'default' => '', 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '255', 'size' => '20', 'id' => 'Contactstitle_pdf_2_c', 'custom_module' => 'Contacts', ), 'fio_assign_c' => array ( 'required' => false, 'source' => 'custom_fields', 'name' => 'fio_assign_c', 'vname' => 'LBL_FIO_ASSIGN', 'type' => 'varchar', 'massupdate' => '0', 'default' => NULL, 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '255', 'size' => '20', 'id' => 'Contactsfio_assign_c', 'custom_module' => 'Contacts', ), 'title_pdf_3_c' => array ( 'required' => false, 'source' => 'custom_fields', 'name' => 'title_pdf_3_c', 'vname' => 'LBL_TITLE_PDF_3', 'type' => 'varchar', 'massupdate' => '0', 'default' => '', 'no_default' => false, 'comments' => '', 'help' => '', 'importable' => 'true', 'duplicate_merge' => 'disabled', 'duplicate_merge_dom_value' => '0', 'audited' => true, 'reportable' => true, 'unified_search' => false, 'merge_filter' => 'disabled', 'len' => '255', 'size' => '20', 'id' => 'Contactstitle_pdf_3_c', 'custom_module' => 'Contacts', ), ), 'indices' => array ( 'id' => array ( 'name' => 'contactspk', 'type' => 'primary', 'fields' => array ( 0 => 'id', ), ), 0 => array ( 'name' => 'idx_cont_last_first', 'type' => 'index', 'fields' => array ( 0 => 'last_name', 1 => 'first_name', 2 => 'deleted', ), ), 1 => array ( 'name' => 'idx_contacts_del_last', 'type' => 'index', 'fields' => array ( 0 => 'deleted', 1 => 'last_name', ), ), 2 => array ( 'name' => 'idx_cont_del_reports', 'type' => 'index', 'fields' => array ( 0 => 'deleted', 1 => 'reports_to_id', 2 => 'last_name', ), ), 3 => array ( 'name' => 'idx_reports_to_id', 'type' => 'index', 'fields' => array ( 0 => 'reports_to_id', ), ), 4 => array ( 'name' => 'idx_del_id_user', 'type' => 'index', 'fields' => array ( 0 => 'deleted', 1 => 'id', 2 => 'assigned_user_id', ), ), 5 => array ( 'name' => 'idx_cont_assigned', 'type' => 'index', 'fields' => array ( 0 => 'assigned_user_id', ), ), ), 'relationships' => array ( 'contacts_modified_user' => array ( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'Contacts', 'rhs_table' => 'contacts', 'rhs_key' => 'modified_user_id', 'relationship_type' => 'one-to-many', ), 'contacts_created_by' => array ( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'Contacts', 'rhs_table' => 'contacts', 'rhs_key' => 'created_by', 'relationship_type' => 'one-to-many', ), 'contacts_assigned_user' => array ( 'lhs_module' => 'Users', 'lhs_table' => 'users', 'lhs_key' => 'id', 'rhs_module' => 'Contacts', 'rhs_table' => 'contacts', 'rhs_key' => 'assigned_user_id', 'relationship_type' => 'one-to-many', ), 'contacts_email_addresses' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'EmailAddresses', 'rhs_table' => 'email_addresses', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'email_addr_bean_rel', 'join_key_lhs' => 'bean_id', 'join_key_rhs' => 'email_address_id', 'relationship_role_column' => 'bean_module', 'relationship_role_column_value' => 'Contacts', ), 'contacts_email_addresses_primary' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'EmailAddresses', 'rhs_table' => 'email_addresses', 'rhs_key' => 'id', 'relationship_type' => 'many-to-many', 'join_table' => 'email_addr_bean_rel', 'join_key_lhs' => 'bean_id', 'join_key_rhs' => 'email_address_id', 'relationship_role_column' => 'primary_address', 'relationship_role_column_value' => '1', ), 'contact_direct_reports' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'Contacts', 'rhs_table' => 'contacts', 'rhs_key' => 'reports_to_id', 'relationship_type' => 'one-to-many', ), 'contact_leads' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'Leads', 'rhs_table' => 'leads', 'rhs_key' => 'contact_id', 'relationship_type' => 'one-to-many', ), 'contact_notes' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'Notes', 'rhs_table' => 'notes', 'rhs_key' => 'contact_id', 'relationship_type' => 'one-to-many', ), 'contact_tasks' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'Tasks', 'rhs_table' => 'tasks', 'rhs_key' => 'contact_id', 'relationship_type' => 'one-to-many', ), 'contact_tasks_parent' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'Tasks', 'rhs_table' => 'tasks', 'rhs_key' => 'parent_id', 'relationship_type' => 'one-to-many', 'relationship_role_column' => 'parent_type', 'relationship_role_column_value' => 'Contacts', ), 'contact_campaign_log' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'CampaignLog', 'rhs_table' => 'campaign_log', 'rhs_key' => 'target_id', 'relationship_type' => 'one-to-many', ), 'contact_aos_quotes' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'AOS_Quotes', 'rhs_table' => 'aos_quotes', 'rhs_key' => 'billing_contact_id', 'relationship_type' => 'one-to-many', ), 'contact_aos_invoices' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'AOS_Invoices', 'rhs_table' => 'aos_invoices', 'rhs_key' => 'billing_contact_id', 'relationship_type' => 'one-to-many', ), 'contact_aos_contracts' => array ( 'lhs_module' => 'Contacts', 'lhs_table' => 'contacts', 'lhs_key' => 'id', 'rhs_module' => 'AOS_Contracts', 'rhs_table' => 'aos_contracts', 'rhs_key' => 'contact_id', 'relationship_type' => 'one-to-many', ), ), 'optimistic_locking' => true, 'templates' => array ( 'person' => 'person', 'assignable' => 'assignable', 'basic' => 'basic', ), 'custom_fields' => true, );
agpl-3.0
JonathanxD/TextLexer
src/main/java/com/github/jonathanxd/textlexer/ext/constructor/structure/StructureConstructor.java
2881
/* * TextLexer - Lexical Analyzer API for Java! <https://github.com/JonathanxD/TextLexer> * Copyright (C) 2016 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <jonathan.scripter@programmer.net> * * GNU GPLv3 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.github.jonathanxd.textlexer.ext.constructor.structure; import com.github.jonathanxd.iutils.map.JwMap; import com.github.jonathanxd.textlexer.ext.common.TokenElementType; import com.github.jonathanxd.textlexer.ext.parser.holder.TokenHolder; import com.github.jonathanxd.textlexer.ext.parser.structure.StructuredTokens; import com.github.jonathanxd.textlexer.lexer.token.IToken; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Created by jonathan on 21/02/16. */ public class StructureConstructor { final PositionFactory positionFactory; private final StructuredTokens structuredTokens; public StructureConstructor(StructuredTokens structuredTokens, PositionFactory positionFactory) { this.structuredTokens = structuredTokens; this.positionFactory = positionFactory; } public byte[] construct() { StringBuilder sb = new StringBuilder(); recursive(structuredTokens.getTokenHolders(), sb); try { return sb.toString().getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { return sb.toString().getBytes(); } } private void recursive(List<TokenHolder> tokenHolderList, StringBuilder builder) { for (TokenHolder tokenHolder : tokenHolderList) { List<Runnable> runnable = new ArrayList<>(); List<IToken<?>> tokens = tokenHolder.getTokens(); JwMap<IToken<?>, Position> positions = positionFactory.getPositionOfToken(tokens, TokenElementType.HEAD); positions.forEach((token, position) -> { if (position == Position.START) { builder.append(token.mutableData().get()); } else { runnable.add(() -> builder.append(token.mutableData().get())); } }); recursive(tokenHolder.getChildTokens(), builder); runnable.forEach(Runnable::run); } } }
agpl-3.0
rgbconsulting/rgb-website
website_favicon/models/website_config.py
384
# -*- coding: utf-8 -*- # See README file for full copyright and licensing details. from openerp import fields, models, _ class Website(models.Model): _inherit = 'website' favicon = fields.Binary("Favicon ico") class WebsiteConfig(models.TransientModel): _inherit = 'website.config.settings' favicon = fields.Binary("Favicon ico", related="website_id.favicon")
agpl-3.0
ProtocolSupport/ProtocolSupportAntiBot
src/protocolsupportantibot/Settings.java
5157
package protocolsupportantibot; import java.io.File; import java.io.IOException; import org.bukkit.ChatColor; import org.bukkit.configuration.file.YamlConfiguration; public class Settings { public static int loginInterval = 50; public static String loginIntervalMessage = ChatColor.AQUA + "Your connection is currently queued. Please wait for your turn. There are {PLAYERS} players before you in a queue."; public static boolean protocolValidatorEnabled = true; public static int protocolValidatorMaxWait = 10; public static String protocolValidatorStartMessage = ChatColor.AQUA + "Basic antibot check in progress, please wait"; public static String protocolValidatorSuccessMessage = ChatColor.AQUA + "Basic bot check success"; public static String protocolValidatorFailMessage = ChatColor.RED + "Failed basic antibot check"; public static boolean captchaEnabled = true; public static int captchaMaxWait = 60; public static int captchaMaxTries = 3; public static int captchaColorId = 23; public static String captchaStartMessage = ChatColor.AQUA + "Please write a number you see on the map to chat"; public static String captchaSuccessMessage = ChatColor.AQUA + "Your captca code is valid"; public static String captchaFailMessage = ChatColor.RED + "You didn't solve captcha in time, your address is temportally banned, please try joining again later"; public static String captchaFailTryMessage = ChatColor.RED + "Wrong captcha, please try again"; public static String captchaFailTryBanMessage = ChatColor.RED + "You failed to input valid captcha in {MAXTRIES} tries, your address is temporally banned, please try joining again later"; public static long tempBanTime = 60; public static String tempBanMessage = ChatColor.RED + "Your address is temporally banned, please try again later"; public static void load() { YamlConfiguration config = YamlConfiguration.loadConfiguration(getMainConfigFile()); loginInterval = config.getInt("logininterval", loginInterval); protocolValidatorEnabled = config.getBoolean("protocolvalidator.enabled", protocolValidatorEnabled); protocolValidatorMaxWait = config.getInt("protocolvalidator.maxwait", protocolValidatorMaxWait); captchaEnabled = config.getBoolean("captcha.enabled", captchaEnabled); captchaMaxWait = config.getInt("captcha.maxwait", captchaMaxWait); captchaMaxTries = config.getInt("captcha.maxtries", captchaMaxTries); captchaColorId = config.getInt("captcha.colorid", captchaColorId); tempBanTime = config.getLong("tempban.time", tempBanTime); YamlConfiguration messages = YamlConfiguration.loadConfiguration(getMessagesConfigFile()); loginIntervalMessage = messages.getString("logininterval.start", loginIntervalMessage); protocolValidatorStartMessage = messages.getString("protocolvalidator.start", protocolValidatorStartMessage); protocolValidatorSuccessMessage = messages.getString("protocolvalidator.success", protocolValidatorSuccessMessage); protocolValidatorFailMessage = messages.getString("protocolvalidator.fail", protocolValidatorFailMessage); captchaStartMessage = messages.getString("captcha.start", captchaStartMessage); captchaSuccessMessage = messages.getString("captcha.success", captchaSuccessMessage); captchaFailMessage = messages.getString("captcha.fail", captchaFailMessage); captchaFailTryMessage = messages.getString("captcha.tryfail", captchaFailTryMessage); captchaFailTryBanMessage = messages.getString("captcha.tryfailban", captchaFailTryBanMessage); tempBanMessage = messages.getString("tempban", tempBanMessage); save(); } private static void save() { YamlConfiguration config = new YamlConfiguration(); config.set("logininterval", loginInterval); config.set("protocolvalidator.enabled", protocolValidatorEnabled); config.set("protocolvalidator.maxwait", protocolValidatorMaxWait); config.set("captcha.enabled", captchaEnabled); config.set("captcha.maxwait", captchaMaxWait); config.set("captcha.maxtries", captchaMaxTries); config.set("captcha.colorid", captchaColorId); config.set("tempban.time", tempBanTime); YamlConfiguration messages = new YamlConfiguration(); messages.set("logininterval.start", loginIntervalMessage); messages.set("protocolvalidator.start", protocolValidatorStartMessage); messages.set("protocolvalidator.success", protocolValidatorSuccessMessage); messages.set("protocolvalidator.fail", protocolValidatorFailMessage); messages.set("captcha.start", captchaStartMessage); messages.set("captcha.success", captchaSuccessMessage); messages.set("captcha.fail", captchaFailMessage); messages.set("captcha.tryfail", captchaFailTryMessage); messages.set("captcha.tryfailban", captchaFailTryBanMessage); messages.set("tempban", tempBanMessage); try { config.save(getMainConfigFile()); messages.save(getMessagesConfigFile()); } catch (IOException e) { } } private static File getMainConfigFile() { return new File(ProtocolSupportAntiBot.getInstance().getDataFolder(), "config.yml"); } private static File getMessagesConfigFile() { return new File(ProtocolSupportAntiBot.getInstance().getDataFolder(), "messages.yml"); } }
agpl-3.0
VibroAxe/athena
database/migrations/2015_04_19_123122_add_page_published_field.php
552
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class AddPagePublishedField extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::table('pages', function($table) { $table->integer('published') ->default(1) ->unsigned() ->after('position'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::table('pages', function($table) { $table->dropColumn('published'); }); } }
agpl-3.0
shanghaiscott/templatewrapper
src/main/java/com/swdouglass/velocity/AbstractTemplate.java
5913
/* * Copyright 2010, Scott Douglass <scott@swdouglass.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 * on the World Wide Web for more details: * http://www.fsf.org/licensing/licenses/gpl.txt */ package com.swdouglass.velocity; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.StringWriter; import java.net.MalformedURLException; import java.net.URL; import java.util.Iterator; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.velocity.VelocityContext; import org.apache.velocity.app.VelocityEngine; import org.apache.velocity.exception.MethodInvocationException; import org.apache.velocity.exception.ParseErrorException; import org.apache.velocity.exception.ResourceNotFoundException; /** * Base class for TemplateWrapper implementations. * * @author scott */ public abstract class AbstractTemplate implements TemplateWrapper { protected static final Logger LOG = Logger.getLogger(AbstractTemplate.class.getName()); // VelocityEngine is initialized on first getVelocityEngine or via injection private VelocityEngine velocityEngine; private VelocityContext velocityContext; /** Can be overridden by -Dtemplate.encoding=... */ private static final String P_ENCODING = "template.encoding"; private static final String D_ENCODING = System.getProperty(P_ENCODING, "UTF-8"); /** Can be overridden by -Dvelocity.properties=... */ private static final String P_PROPERTIES_FILE = "velocity.properties"; private static final String D_PROPERTIES_FILE = System.getProperty(P_PROPERTIES_FILE, "velocity.properties"); private String templatePath; private String templateEncoding = D_ENCODING; public void initVelocity() throws Exception { Properties velocityProperties = getPropertiesFromClasspath(D_PROPERTIES_FILE); Iterator vPropKeys = velocityProperties.keySet().iterator(); while (vPropKeys.hasNext()) { String key = (String)vPropKeys.next(); getVelocityEngine().setProperty(key, velocityProperties.get(key)); } try { URL testURL = new URL(getTemplatePath()); StringBuilder templateDirPath = new StringBuilder(); templateDirPath.append(testURL.getProtocol()); templateDirPath.append("://"); templateDirPath.append(testURL.getHost()); templateDirPath.append(":"); templateDirPath.append(testURL.getPort()); templateDirPath.append( testURL.getFile().substring(0, testURL.getFile().lastIndexOf("/"))); templateDirPath.append("/"); getVelocityEngine().setProperty( "url.resource.loader.root",templateDirPath.toString()); setTemplatePath ( testURL.getFile().substring(testURL.getFile().lastIndexOf("/") + 1)); } catch (MalformedURLException e) { LOG.log(Level.FINE, "Template path is not a valid URL", e); } getVelocityEngine().init(); setVelocityContext(new VelocityContext()); getVelocityEngine().getTemplate(getTemplatePath(), getTemplateEncoding()); } @Override public String merge() { LOG.log(Level.FINE, "Merging"); StringWriter stringWriter = new StringWriter(); try { getVelocityEngine().mergeTemplate( getTemplatePath(), getTemplateEncoding(), getVelocityContext(), stringWriter); } catch (MethodInvocationException | ParseErrorException | ResourceNotFoundException e) { LOG.log(Level.SEVERE, "Velocity merge failed", e); } LOG.log(Level.FINE, "merge result: {0}", stringWriter.toString()); return stringWriter.toString(); } private Properties getPropertiesFromClasspath(String propFileName) throws IOException { Properties props = new Properties(); InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(propFileName); if (inputStream == null) { throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath"); } props.load(inputStream); return props; } @Override public Boolean write() { return false; } /** * Initialize a new VelocityEngine if not previously initialized. * @return the velocityEngine */ public VelocityEngine getVelocityEngine() { if (velocityEngine == null) { velocityEngine = new VelocityEngine(); } return velocityEngine; } /** * @param velocityEngine the velocityEngine to set */ public void setVelocityEngine(VelocityEngine velocityEngine) { this.velocityEngine = velocityEngine; } /** * @return the velocityContext */ public VelocityContext getVelocityContext() { return velocityContext; } /** * @param velocityContext the velocityContext to set */ public void setVelocityContext(VelocityContext velocityContext) { this.velocityContext = velocityContext; } /** * @return the templatePath */ public final String getTemplatePath() { return templatePath; } /** * @param templatePath the templatePath to set */ public final void setTemplatePath(String templatePath) { this.templatePath = templatePath; } /** * @return the templateEncoding */ public final String getTemplateEncoding() { return templateEncoding; } /** * @param templateEncoding the templateEncoding to set */ public final void setTemplateEncoding(String templateEncoding) { this.templateEncoding = templateEncoding; } }
agpl-3.0
davecheney/juju
resource/api/helpers_test.go
11305
// Copyright 2015 Canonical Ltd. // Licensed under the AGPLv3, see LICENCE file for details. package api_test import ( "strings" "time" "github.com/juju/errors" "github.com/juju/names" "github.com/juju/testing" jc "github.com/juju/testing/checkers" gc "gopkg.in/check.v1" charmresource "gopkg.in/juju/charm.v6-unstable/resource" "github.com/juju/juju/apiserver/params" "github.com/juju/juju/resource" "github.com/juju/juju/resource/api" ) const fingerprint = "123456789012345678901234567890123456789012345678" func newFingerprint(c *gc.C, data string) charmresource.Fingerprint { fp, err := charmresource.GenerateFingerprint(strings.NewReader(data)) c.Assert(err, jc.ErrorIsNil) return fp } type helpersSuite struct { testing.IsolationSuite } var _ = gc.Suite(&helpersSuite{}) func (helpersSuite) TestResource2API(c *gc.C) { fp, err := charmresource.NewFingerprint([]byte(fingerprint)) c.Assert(err, jc.ErrorIsNil) now := time.Now() res := resource.Resource{ Resource: charmresource.Resource{ Meta: charmresource.Meta{ Name: "spam", Type: charmresource.TypeFile, Path: "spam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } err = res.Validate() c.Assert(err, jc.ErrorIsNil) apiRes := api.Resource2API(res) c.Check(apiRes, jc.DeepEquals, api.Resource{ CharmResource: api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, }) } func (helpersSuite) TestAPIResult2ServiceResourcesOkay(c *gc.C) { fp, err := charmresource.NewFingerprint([]byte(fingerprint)) c.Assert(err, jc.ErrorIsNil) now := time.Now() expected := resource.Resource{ Resource: charmresource.Resource{ Meta: charmresource.Meta{ Name: "spam", Type: charmresource.TypeFile, Path: "spam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } err = expected.Validate() c.Assert(err, jc.ErrorIsNil) unitExpected := resource.Resource{ Resource: charmresource.Resource{ Meta: charmresource.Meta{ Name: "unitspam", Type: charmresource.TypeFile, Path: "unitspam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } err = unitExpected.Validate() c.Assert(err, jc.ErrorIsNil) apiRes := api.Resource{ CharmResource: api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } unitRes := api.Resource{ CharmResource: api.CharmResource{ Name: "unitspam", Type: "file", Path: "unitspam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } resources, err := api.APIResult2ServiceResources(api.ResourcesResult{ Resources: []api.Resource{ apiRes, }, UnitResources: []api.UnitResources{ { Entity: params.Entity{ Tag: "unit-foo-0", }, Resources: []api.Resource{ unitRes, }, }, }, }) c.Assert(err, jc.ErrorIsNil) serviceResource := resource.ServiceResources{ Resources: []resource.Resource{ expected, }, UnitResources: []resource.UnitResources{ { Tag: names.NewUnitTag("foo/0"), Resources: []resource.Resource{ unitExpected, }, }, }, } c.Check(resources, jc.DeepEquals, serviceResource) } func (helpersSuite) TestAPIResult2ServiceResourcesBadUnitTag(c *gc.C) { fp, err := charmresource.NewFingerprint([]byte(fingerprint)) c.Assert(err, jc.ErrorIsNil) now := time.Now() expected := resource.Resource{ Resource: charmresource.Resource{ Meta: charmresource.Meta{ Name: "spam", Type: charmresource.TypeFile, Path: "spam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } err = expected.Validate() c.Assert(err, jc.ErrorIsNil) unitExpected := resource.Resource{ Resource: charmresource.Resource{ Meta: charmresource.Meta{ Name: "unitspam", Type: charmresource.TypeFile, Path: "unitspam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } err = unitExpected.Validate() c.Assert(err, jc.ErrorIsNil) apiRes := api.Resource{ CharmResource: api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } unitRes := api.Resource{ CharmResource: api.CharmResource{ Name: "unitspam", Type: "file", Path: "unitspam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } _, err = api.APIResult2ServiceResources(api.ResourcesResult{ Resources: []api.Resource{ apiRes, }, UnitResources: []api.UnitResources{ { Entity: params.Entity{ Tag: "THIS IS NOT A GOOD UNIT TAG", }, Resources: []api.Resource{ unitRes, }, }, }, }) c.Assert(err, gc.ErrorMatches, ".*got bad data from server.*") } func (helpersSuite) TestAPIResult2ServiceResourcesFailure(c *gc.C) { apiRes := api.Resource{ CharmResource: api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", ServiceID: "a-service", } failure := errors.New("<failure>") _, err := api.APIResult2ServiceResources(api.ResourcesResult{ ErrorResult: params.ErrorResult{ Error: &params.Error{ Message: failure.Error(), }, }, Resources: []api.Resource{ apiRes, }, }) c.Check(err, gc.ErrorMatches, "<failure>") c.Check(errors.Cause(err), gc.Not(gc.Equals), failure) } func (helpersSuite) TestAPIResult2ServiceResourcesNotFound(c *gc.C) { apiRes := api.Resource{ CharmResource: api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", ServiceID: "a-service", } _, err := api.APIResult2ServiceResources(api.ResourcesResult{ ErrorResult: params.ErrorResult{ Error: &params.Error{ Message: `service "a-service" not found`, Code: params.CodeNotFound, }, }, Resources: []api.Resource{ apiRes, }, }) c.Check(err, jc.Satisfies, errors.IsNotFound) } func (helpersSuite) TestAPI2Resource(c *gc.C) { now := time.Now() res, err := api.API2Resource(api.Resource{ CharmResource: api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, }) c.Assert(err, jc.ErrorIsNil) fp, err := charmresource.NewFingerprint([]byte(fingerprint)) c.Assert(err, jc.ErrorIsNil) expected := resource.Resource{ Resource: charmresource.Resource{ Meta: charmresource.Meta{ Name: "spam", Type: charmresource.TypeFile, Path: "spam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, }, ID: "a-service/spam", PendingID: "some-unique-ID", ServiceID: "a-service", Username: "a-user", Timestamp: now, } err = expected.Validate() c.Assert(err, jc.ErrorIsNil) c.Check(res, jc.DeepEquals, expected) } func (helpersSuite) TestCharmResource2API(c *gc.C) { fp, err := charmresource.NewFingerprint([]byte(fingerprint)) c.Assert(err, jc.ErrorIsNil) res := charmresource.Resource{ Meta: charmresource.Meta{ Name: "spam", Type: charmresource.TypeFile, Path: "spam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, } err = res.Validate() c.Assert(err, jc.ErrorIsNil) apiInfo := api.CharmResource2API(res) c.Check(apiInfo, jc.DeepEquals, api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }) } func (helpersSuite) TestAPI2CharmResource(c *gc.C) { res, err := api.API2CharmResource(api.CharmResource{ Name: "spam", Type: "file", Path: "spam.tgz", Description: "you need it", Origin: "upload", Revision: 1, Fingerprint: []byte(fingerprint), Size: 10, }) c.Assert(err, jc.ErrorIsNil) fp, err := charmresource.NewFingerprint([]byte(fingerprint)) c.Assert(err, jc.ErrorIsNil) expected := charmresource.Resource{ Meta: charmresource.Meta{ Name: "spam", Type: charmresource.TypeFile, Path: "spam.tgz", Description: "you need it", }, Origin: charmresource.OriginUpload, Revision: 1, Fingerprint: fp, Size: 10, } err = expected.Validate() c.Assert(err, jc.ErrorIsNil) c.Check(res, jc.DeepEquals, expected) }
agpl-3.0
kaltura/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/types/EventCuePointBaseFilter.java
3305
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2021 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.enums.EventType; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(EventCuePointBaseFilter.Tokenizer.class) public abstract class EventCuePointBaseFilter extends CuePointFilter { public interface Tokenizer extends CuePointFilter.Tokenizer { String eventTypeEqual(); String eventTypeIn(); } private EventType eventTypeEqual; private String eventTypeIn; // eventTypeEqual: public EventType getEventTypeEqual(){ return this.eventTypeEqual; } public void setEventTypeEqual(EventType eventTypeEqual){ this.eventTypeEqual = eventTypeEqual; } public void eventTypeEqual(String multirequestToken){ setToken("eventTypeEqual", multirequestToken); } // eventTypeIn: public String getEventTypeIn(){ return this.eventTypeIn; } public void setEventTypeIn(String eventTypeIn){ this.eventTypeIn = eventTypeIn; } public void eventTypeIn(String multirequestToken){ setToken("eventTypeIn", multirequestToken); } public EventCuePointBaseFilter() { super(); } public EventCuePointBaseFilter(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: eventTypeEqual = EventType.get(GsonParser.parseString(jsonObject.get("eventTypeEqual"))); eventTypeIn = GsonParser.parseString(jsonObject.get("eventTypeIn")); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaEventCuePointBaseFilter"); kparams.add("eventTypeEqual", this.eventTypeEqual); kparams.add("eventTypeIn", this.eventTypeIn); return kparams; } }
agpl-3.0
friendica/friendica
tests/src/Module/Api/ApiResponseTest.php
11595
<?php /** * @copyright Copyright (C) 2010-2022, the Friendica project * * @license GNU AGPL version 3 or any later version * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. * */ namespace Friendica\Test\src\Module\Api; use Friendica\App\Arguments; use Friendica\App\BaseURL; use Friendica\Core\L10n; use Friendica\Factory\Api\Twitter\User; use Friendica\Module\Api\ApiResponse; use Friendica\Test\MockedTest; use Psr\Log\NullLogger; class ApiResponseTest extends MockedTest { public function testErrorWithJson() { $l10n = \Mockery::mock(L10n::class); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response->error(200, 'OK', 'error_message', 'json'); self::assertEquals('{"error":"error_message","code":"200 OK","request":""}', $response->getContent()); } public function testErrorWithXml() { $l10n = \Mockery::mock(L10n::class); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response->error(200, 'OK', 'error_message', 'xml'); self::assertEquals(['Content-type' => 'text/xml', 'HTTP/1.1 200 OK'], $response->getHeaders()); self::assertEquals('<?xml version="1.0"?>' . "\n" . '<status xmlns="http://api.twitter.com" xmlns:statusnet="http://status.net/schema/api/1/" ' . 'xmlns:friendica="http://friendi.ca/schema/api/1/" ' . 'xmlns:georss="http://www.georss.org/georss">' . "\n" . ' <error>error_message</error>' . "\n" . ' <code>200 OK</code>' . "\n" . ' <request/>' . "\n" . '</status>' . "\n", $response->getContent()); } public function testErrorWithRss() { $l10n = \Mockery::mock(L10n::class); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response->error(200, 'OK', 'error_message', 'rss'); self::assertEquals(['Content-type' => 'application/rss+xml', 'HTTP/1.1 200 OK'], $response->getHeaders()); self::assertEquals( '<?xml version="1.0"?>' . "\n" . '<status xmlns="http://api.twitter.com" xmlns:statusnet="http://status.net/schema/api/1/" ' . 'xmlns:friendica="http://friendi.ca/schema/api/1/" ' . 'xmlns:georss="http://www.georss.org/georss">' . "\n" . ' <error>error_message</error>' . "\n" . ' <code>200 OK</code>' . "\n" . ' <request/>' . "\n" . '</status>' . "\n", $response->getContent()); } public function testErrorWithAtom() { $l10n = \Mockery::mock(L10n::class); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response->error(200, 'OK', 'error_message', 'atom'); self::assertEquals(['Content-type' => 'application/atom+xml', 'HTTP/1.1 200 OK'], $response->getHeaders()); self::assertEquals( '<?xml version="1.0"?>' . "\n" . '<status xmlns="http://api.twitter.com" xmlns:statusnet="http://status.net/schema/api/1/" ' . 'xmlns:friendica="http://friendi.ca/schema/api/1/" ' . 'xmlns:georss="http://www.georss.org/georss">' . "\n" . ' <error>error_message</error>' . "\n" . ' <code>200 OK</code>' . "\n" . ' <request/>' . "\n" . '</status>' . "\n", $response->getContent()); } public function testUnsupported() { $l10n = \Mockery::mock(L10n::class); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $response->unsupported(); self::assertEquals('{"error":"API endpoint %s %s is not implemented","error_description":"The API endpoint is currently not implemented but might be in the future."}', $response->getContent()); } /** * Test the BaseApi::reformatXML() function. * * @return void */ public function testApiReformatXml() { $item = true; $key = ''; self::assertTrue(ApiResponse::reformatXML($item, $key)); self::assertEquals('true', $item); } /** * Test the BaseApi::reformatXML() function with a statusnet_api key. * * @return void */ public function testApiReformatXmlWithStatusnetKey() { $item = ''; $key = 'statusnet_api'; self::assertTrue(ApiResponse::reformatXML($item, $key)); self::assertEquals('statusnet:api', $key); } /** * Test the BaseApi::reformatXML() function with a friendica_api key. * * @return void */ public function testApiReformatXmlWithFriendicaKey() { $item = ''; $key = 'friendica_api'; self::assertTrue(ApiResponse::reformatXML($item, $key)); self::assertEquals('friendica:api', $key); } /** * Test the BaseApi::createXML() function. * * @return void */ public function testApiCreateXml() { $l10n = \Mockery::mock(L10n::class); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); self::assertEquals( '<?xml version="1.0"?>' . "\n" . '<root_element xmlns="http://api.twitter.com" xmlns:statusnet="http://status.net/schema/api/1/" ' . 'xmlns:friendica="http://friendi.ca/schema/api/1/" ' . 'xmlns:georss="http://www.georss.org/georss">' . "\n" . ' <data>some_data</data>' . "\n" . '</root_element>' . "\n", $response->createXML(['data' => ['some_data']], 'root_element') ); } /** * Test the BaseApi::createXML() function without any XML namespace. * * @return void */ public function testApiCreateXmlWithoutNamespaces() { $l10n = \Mockery::mock(L10n::class); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); self::assertEquals( '<?xml version="1.0"?>' . "\n" . '<ok>' . "\n" . ' <data>some_data</data>' . "\n" . '</ok>' . "\n", $response->createXML(['data' => ['some_data']], 'ok') ); } /** * Test the BaseApi::formatData() function. * * @return void */ public function testApiFormatData() { $l10n = \Mockery::mock(L10n::class); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $data = ['some_data']; self::assertEquals($data, $response->formatData('root_element', 'json', $data)); } /** * Test the BaseApi::formatData() function with an XML result. * * @return void */ public function testApiFormatDataWithXml() { $l10n = \Mockery::mock(L10n::class); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $twitterUser = \Mockery::mock(User::class); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); self::assertEquals( '<?xml version="1.0"?>' . "\n" . '<root_element xmlns="http://api.twitter.com" xmlns:statusnet="http://status.net/schema/api/1/" ' . 'xmlns:friendica="http://friendi.ca/schema/api/1/" ' . 'xmlns:georss="http://www.georss.org/georss">' . "\n" . ' <data>some_data</data>' . "\n" . '</root_element>' . "\n", $response->formatData('root_element', 'xml', ['data' => ['some_data']]) ); } /** * Test the api_rss_extra() function. * * @return void */ public function testApiRssExtra() { self::markTestIncomplete('Cannot mock it yet.'); /* $user_info = ['url' => 'user_url', 'lang' => 'en']; $userMock = \Mockery::mock(\Friendica\Object\Api\Twitter\User::class); $userMock->shouldReceive('toArray')->andReturn($user_info); $l10n = \Mockery::mock(L10n::class); $l10n->shouldReceive('t')->andReturnUsing(function ($args) { return $args; }); $args = \Mockery::mock(Arguments::class); $args->shouldReceive('getQueryString')->andReturn(''); $baseUrl = \Mockery::mock(BaseURL::class); $baseUrl->shouldReceive('__toString')->andReturn('https://friendica.local'); $twitterUser = \Mockery::mock(User::class); $twitterUser->shouldReceive('createFromContactId')->with(1)->andReturn($userMock); $response = new ApiResponse($l10n, $args, new NullLogger(), $baseUrl, $twitterUser); $result = $response->formatData('root_element', 'rss', ['data' => ['some_data']], 1); print_r($result); self::assertEquals($user_info, $result['$user']); self::assertEquals($user_info['url'], $result['$rss']['alternate']); self::assertArrayHasKey('self', $result['$rss']); self::assertArrayHasKey('base', $result['$rss']); self::assertArrayHasKey('updated', $result['$rss']); self::assertArrayHasKey('atom_updated', $result['$rss']); self::assertArrayHasKey('language', $result['$rss']); self::assertArrayHasKey('logo', $result['$rss']); */ } /** * Test the api_rss_extra() function without any user info. * * @return void */ public function testApiRssExtraWithoutUserInfo() { self::markTestIncomplete('Cannot mock it yet.'); /* $result = api_rss_extra([], null); self::assertIsArray($result['$user']); self::assertArrayHasKey('alternate', $result['$rss']); self::assertArrayHasKey('self', $result['$rss']); self::assertArrayHasKey('base', $result['$rss']); self::assertArrayHasKey('updated', $result['$rss']); self::assertArrayHasKey('atom_updated', $result['$rss']); self::assertArrayHasKey('language', $result['$rss']); self::assertArrayHasKey('logo', $result['$rss']); */ } }
agpl-3.0
ONLYOFFICE/doc-builder-testing
asserts/js/docx/header/tables/add_table_in_header_right.js
475
builder.CreateFile("docx"); var oDocument = Api.GetDocument(); oDocument.CreateNewHistoryPoint(); var oTable, oTableRow, oCell, oCellContent, oRun, oDrawing; var oParagraph = Api.CreateParagraph(); var oFinalSection = oDocument.GetFinalSection(); var oDocContent = oFinalSection.GetHeader("default", true); oTable = Api.CreateTable(3, 3); oTable.SetJc("right"); oDocContent.Push(oTable); builder.SaveFile("docx", "add_table_in_header_right.docx"); builder.CloseFile();
agpl-3.0
LitusProject/Litus
module/LogisticsBundle/Hydrator/Article.php
1352
<?php namespace LogisticsBundle\Hydrator; use LogisticsBundle\Entity\Article as ArticleEntity; class Article extends \CommonBundle\Component\Hydrator\Hydrator { private static $stdKeys = array('name', 'additional_info', 'spot', 'amount_owned', 'amount_available', 'internal_comment', 'alertMail', 'location'); protected function doExtract($object = null) { if ($object === null) { return array(); } $data = $this->stdExtract($object, self::$stdKeys); $data['warranty'] = $object->getWarranty() / 100; $data['rent'] = $object->getRent() / 100; $data['visibility'] = $object->getVisibilityCode(); $data['status'] = $object->getStatusCode(); $data['category'] = $object->getCategoryCode(); return $data; } protected function doHydrate(array $data, $object = null) { if ($object === null) { $object = new ArticleEntity(); } $object->setWarranty($data['warranty'] !== null ? $data['warranty'] * 100 : 0); $object->setRent($data['rent'] !== null ? $data['rent'] * 100 : 0); $object->setVisibility($data['visibility']); $object->setStatus($data['status']); $object->setCategory($data['category']); return $this->stdHydrate($data, $object, self::$stdKeys); } }
agpl-3.0
liuning587/TCExam
shared/jscripts/vk/layouts/lithuanian.js
251
VirtualKeyboard.addLayout({code:'LT',name:'Lithuanian',normal:'`ąčęėįšųū90-ž\\qwertyuiop[]asdfghjkl;\'zxcvbnm,./',shift:{0:'~',9:'()_',13:'|',24:'{}',35:':"',44:'<>?'},alt:{1:'12345678',12:'=',16:'€'},shift_alt:{1:'!@#$%^&*',12:'+'}});
agpl-3.0
alejandro-du/acomersedijo
src/dpasoftware/acomersedijo/accesoDatos/dao/impl/DaoMenu.java
601
package dpasoftware.acomersedijo.accesoDatos.dao.impl; import java.util.List; import dpasoftware.acomersedijo.accesoDatos.dao.IDaoMenu; import dpasoftware.acomersedijo.accesoDatos.vo.Menu; /** * * @author Alejandro */ public class DaoMenu extends AbstractDao<Menu> implements IDaoMenu { private String listar; public List<Menu> listar(Menu menu) { return executeSelect(listar, new Object[]{"%" + menu.getNombre() + "%"}); } public String getListar() { return listar; } public void setListar(String listar) { this.listar = listar; } }
agpl-3.0
retest/recheck
src/main/java/de/retest/recheck/review/counter/IntCounter.java
468
package de.retest.recheck.review.counter; import java.util.function.IntConsumer; public class IntCounter implements Counter { private int count = 0; private final IntConsumer listener; public IntCounter( final IntConsumer listener ) { this.listener = listener; this.listener.accept( count ); } @Override public void add() { count += 1; listener.accept( count ); } @Override public void remove() { count -= 1; listener.accept( count ); } }
agpl-3.0
MiguelSMendoza/Kunagi
WEB-INF/classes/ilarkesto/gwt/client/AGwtDao.java
3882
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public * License for more details. * * You should have received a copy of the GNU General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package ilarkesto.gwt.client; import ilarkesto.core.logging.Log; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; public abstract class AGwtDao extends AComponent { private String entityIdBase; private int entityIdCounter; protected abstract Collection<Map<String, ? extends AGwtEntity>> getEntityMaps(); protected abstract AGwtEntity updateLocalEntity(String type, Map data); protected abstract void onEntityModifiedRemotely(AGwtEntity entity); protected abstract void onEntityDeletedRemotely(AGwtEntity entity); protected abstract void onEntityCreatedLocaly(AGwtEntity entity, Runnable successAction); protected abstract void onEntityDeletedLocaly(AGwtEntity entity); protected abstract void onEntityPropertyChangedLocaly(AGwtEntity entity, String property, Object value); public abstract Map<String, Integer> getEntityCounts(); public String getEntityIdBase() { return entityIdBase; } public int getEntityIdCounter() { return entityIdCounter; } String getNewEntityId() { if (entityIdBase == null) throw new RuntimeException("No entityIdBase received yet."); return entityIdBase + "-" + ++entityIdCounter; } public void handleDataFromServer(ADataTransferObject data) { if (data.entityIdBase != null) { entityIdBase = data.entityIdBase; log.debug("entityIdBase received:", data.entityIdBase); } List<AGwtEntity> modifiedEntities = null; if (data.containsEntities()) { modifiedEntities = new ArrayList<AGwtEntity>(data.getEntities().size()); for (Map entityData : data.getEntities()) { AGwtEntity entity = updateLocalEntity((String) entityData.get("@type"), entityData); modifiedEntities.add(entity); } } if (data.containsDeletedEntities()) { List<String> deletedEntities = new ArrayList<String>(data.getDeletedEntities()); for (Map<String, ? extends AGwtEntity> map : getEntityMaps()) { for (String entityId : new ArrayList<String>(deletedEntities)) { AGwtEntity entity = map.remove(entityId); if (entity != null) { deletedEntities.remove(entityId); Log.DEBUG("deleted:", entity.getEntityType() + ":", entity); onEntityDeletedRemotely(entity); entity.updateLocalModificationTime(); } } } } if (modifiedEntities != null) { for (AGwtEntity entity : modifiedEntities) { onEntityModifiedRemotely(entity); } } } protected final void entityCreated(AGwtEntity entity, Runnable successAction) { entity.setCreated(); onEntityCreatedLocaly(entity, successAction); } protected final void entityDeleted(AGwtEntity entity) { onEntityDeletedLocaly(entity); entity.updateLocalModificationTime(); } public final void entityPropertyChanged(AGwtEntity entity, String property, Object value) { onEntityPropertyChangedLocaly(entity, property, value); } public final AGwtEntity getEntity(String id) throws EntityDoesNotExistException { for (Map<String, ? extends AGwtEntity> entityMap : getEntityMaps()) { AGwtEntity entity = entityMap.get(id); if (entity != null) return entity; } throw new EntityDoesNotExistException(id); } }
agpl-3.0
arkivverket/arkade5
src/Arkivverket.Arkade.Core/Util/ArchivePart.cs
364
using Arkivverket.Arkade.Core.Resources; namespace Arkivverket.Arkade.Core.Util { public class ArchivePart { public string SystemId { get; set; } public string Name { get; set; } public override string ToString() { return string.Format(Noark5Messages.ArchivePartSystemId, SystemId, Name); } } }
agpl-3.0
PDI-DGS-Protolab/beta_program
register/models.py
677
from django.db import models from django.contrib import admin # Create your models here. class BetaTester(models.Model): email = models.EmailField(max_length=100, primary_key=True) desc = models.CharField(max_length=250) url = models.URLField(max_length=250, blank=True, null=True) def load_from_form(self, form): self.email = form.cleaned_data['email'] self.desc = form.cleaned_data['desc'] self.url = form.cleaned_data['url'] def __str__(self): return self.email class Meta: db_table = 'beta_tester' class BetaTesterAdmin(admin.ModelAdmin): pass admin.site.register(BetaTester, BetaTesterAdmin)
agpl-3.0
chain/chain
vendor/github.com/facebook/rocksdb/util/rate_limiter.cc
8398
// Copyright (c) 2011-present, Facebook, Inc. All rights reserved. // This source code is licensed under the BSD-style license found in the // LICENSE file in the root directory of this source tree. An additional grant // of patent rights can be found in the PATENTS file in the same directory. // // Copyright (c) 2011 The LevelDB Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. See the AUTHORS file for names of contributors. #include "util/rate_limiter.h" #include "monitoring/statistics.h" #include "port/port.h" #include "rocksdb/env.h" #include "util/sync_point.h" namespace rocksdb { // Pending request struct GenericRateLimiter::Req { explicit Req(int64_t _bytes, port::Mutex* _mu) : request_bytes(_bytes), bytes(_bytes), cv(_mu), granted(false) {} int64_t request_bytes; int64_t bytes; port::CondVar cv; bool granted; }; GenericRateLimiter::GenericRateLimiter(int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) : refill_period_us_(refill_period_us), refill_bytes_per_period_( CalculateRefillBytesPerPeriod(rate_bytes_per_sec)), env_(Env::Default()), stop_(false), exit_cv_(&request_mutex_), requests_to_wait_(0), available_bytes_(0), next_refill_us_(NowMicrosMonotonic(env_)), fairness_(fairness > 100 ? 100 : fairness), rnd_((uint32_t)time(nullptr)), leader_(nullptr) { total_requests_[0] = 0; total_requests_[1] = 0; total_bytes_through_[0] = 0; total_bytes_through_[1] = 0; } GenericRateLimiter::~GenericRateLimiter() { MutexLock g(&request_mutex_); stop_ = true; requests_to_wait_ = static_cast<int32_t>(queue_[Env::IO_LOW].size() + queue_[Env::IO_HIGH].size()); for (auto& r : queue_[Env::IO_HIGH]) { r->cv.Signal(); } for (auto& r : queue_[Env::IO_LOW]) { r->cv.Signal(); } while (requests_to_wait_ > 0) { exit_cv_.Wait(); } } // This API allows user to dynamically change rate limiter's bytes per second. void GenericRateLimiter::SetBytesPerSecond(int64_t bytes_per_second) { assert(bytes_per_second > 0); refill_bytes_per_period_.store( CalculateRefillBytesPerPeriod(bytes_per_second), std::memory_order_relaxed); } void GenericRateLimiter::Request(int64_t bytes, const Env::IOPriority pri, Statistics* stats) { assert(bytes <= refill_bytes_per_period_.load(std::memory_order_relaxed)); TEST_SYNC_POINT("GenericRateLimiter::Request"); MutexLock g(&request_mutex_); if (stop_) { return; } ++total_requests_[pri]; if (available_bytes_ >= bytes) { // Refill thread assigns quota and notifies requests waiting on // the queue under mutex. So if we get here, that means nobody // is waiting? available_bytes_ -= bytes; total_bytes_through_[pri] += bytes; return; } // Request cannot be satisfied at this moment, enqueue Req r(bytes, &request_mutex_); queue_[pri].push_back(&r); do { bool timedout = false; // Leader election, candidates can be: // (1) a new incoming request, // (2) a previous leader, whose quota has not been not assigned yet due // to lower priority // (3) a previous waiter at the front of queue, who got notified by // previous leader if (leader_ == nullptr && ((!queue_[Env::IO_HIGH].empty() && &r == queue_[Env::IO_HIGH].front()) || (!queue_[Env::IO_LOW].empty() && &r == queue_[Env::IO_LOW].front()))) { leader_ = &r; int64_t delta = next_refill_us_ - NowMicrosMonotonic(env_); delta = delta > 0 ? delta : 0; if (delta == 0) { timedout = true; } else { int64_t wait_until = env_->NowMicros() + delta; RecordTick(stats, NUMBER_RATE_LIMITER_DRAINS); timedout = r.cv.TimedWait(wait_until); } } else { // Not at the front of queue or an leader has already been elected r.cv.Wait(); } // request_mutex_ is held from now on if (stop_) { --requests_to_wait_; exit_cv_.Signal(); return; } // Make sure the waken up request is always the header of its queue assert(r.granted || (!queue_[Env::IO_HIGH].empty() && &r == queue_[Env::IO_HIGH].front()) || (!queue_[Env::IO_LOW].empty() && &r == queue_[Env::IO_LOW].front())); assert(leader_ == nullptr || (!queue_[Env::IO_HIGH].empty() && leader_ == queue_[Env::IO_HIGH].front()) || (!queue_[Env::IO_LOW].empty() && leader_ == queue_[Env::IO_LOW].front())); if (leader_ == &r) { // Waken up from TimedWait() if (timedout) { // Time to do refill! Refill(); // Re-elect a new leader regardless. This is to simplify the // election handling. leader_ = nullptr; // Notify the header of queue if current leader is going away if (r.granted) { // Current leader already got granted with quota. Notify header // of waiting queue to participate next round of election. assert((queue_[Env::IO_HIGH].empty() || &r != queue_[Env::IO_HIGH].front()) && (queue_[Env::IO_LOW].empty() || &r != queue_[Env::IO_LOW].front())); if (!queue_[Env::IO_HIGH].empty()) { queue_[Env::IO_HIGH].front()->cv.Signal(); } else if (!queue_[Env::IO_LOW].empty()) { queue_[Env::IO_LOW].front()->cv.Signal(); } // Done break; } } else { // Spontaneous wake up, need to continue to wait assert(!r.granted); leader_ = nullptr; } } else { // Waken up by previous leader: // (1) if requested quota is granted, it is done. // (2) if requested quota is not granted, this means current thread // was picked as a new leader candidate (previous leader got quota). // It needs to participate leader election because a new request may // come in before this thread gets waken up. So it may actually need // to do Wait() again. assert(!timedout); } } while (!r.granted); } void GenericRateLimiter::Refill() { TEST_SYNC_POINT("GenericRateLimiter::Refill"); next_refill_us_ = NowMicrosMonotonic(env_) + refill_period_us_; // Carry over the left over quota from the last period auto refill_bytes_per_period = refill_bytes_per_period_.load(std::memory_order_relaxed); if (available_bytes_ < refill_bytes_per_period) { available_bytes_ += refill_bytes_per_period; } int use_low_pri_first = rnd_.OneIn(fairness_) ? 0 : 1; for (int q = 0; q < 2; ++q) { auto use_pri = (use_low_pri_first == q) ? Env::IO_LOW : Env::IO_HIGH; auto* queue = &queue_[use_pri]; while (!queue->empty()) { auto* next_req = queue->front(); if (available_bytes_ < next_req->request_bytes) { // avoid starvation next_req->request_bytes -= available_bytes_; available_bytes_ = 0; break; } available_bytes_ -= next_req->request_bytes; next_req->request_bytes = 0; total_bytes_through_[use_pri] += next_req->bytes; queue->pop_front(); next_req->granted = true; if (next_req != leader_) { // Quota granted, signal the thread next_req->cv.Signal(); } } } } int64_t GenericRateLimiter::CalculateRefillBytesPerPeriod( int64_t rate_bytes_per_sec) { if (port::kMaxInt64 / rate_bytes_per_sec < refill_period_us_) { // Avoid unexpected result in the overflow case. The result now is still // inaccurate but is a number that is large enough. return port::kMaxInt64 / 1000000; } else { return std::max(kMinRefillBytesPerPeriod, rate_bytes_per_sec * refill_period_us_ / 1000000); } } RateLimiter* NewGenericRateLimiter( int64_t rate_bytes_per_sec, int64_t refill_period_us, int32_t fairness) { assert(rate_bytes_per_sec > 0); assert(refill_period_us > 0); assert(fairness > 0); return new GenericRateLimiter( rate_bytes_per_sec, refill_period_us, fairness); } } // namespace rocksdb
agpl-3.0
privacyidea/privacyidea
privacyidea/lib/privacyideaserver.py
8930
# -*- coding: utf-8 -*- # # 2017-08-24 Cornelius Kölbel <cornelius.koelbel@netknights.it> # Remote privacyIDEA server # # This code is free software; you can redistribute it and/or # modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE # License as published by the Free Software Foundation; either # version 3 of the License, or any later version. # # This code is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU AFFERO GENERAL PUBLIC LICENSE for more details. # # You should have received a copy of the GNU Affero General Public # License along with this program. If not, see <http://www.gnu.org/licenses/>. # # from privacyidea.models import PrivacyIDEAServer as PrivacyIDEAServerDB import logging from privacyidea.lib.log import log_with from privacyidea.lib.utils import fetch_one_resource, to_unicode from privacyidea.lib.error import ConfigAdminError from privacyidea.lib.utils.export import (register_import, register_export) import json import requests __doc__ = """ This is the library for creating, listing and deleting remote privacyIDEA server objects in the Database. It depends on the PrivacyIDEAServver in the database model models.py. This module can be tested standalone without any webservices. This module is tested in tests/test_lib_privacyideaserver.py """ log = logging.getLogger(__name__) class PrivacyIDEAServer(object): """ privacyIDEA Server object with configuration. The privacyIDEA Server object contains a test functionality so that the configuration can be tested. """ def __init__(self, db_privacyideaserver_object): """ Create a new PrivacyIDEA Server instance from a DB privacyIDEA object :param db_privacyideaserver_object: The database object :return: A privacyIDEA Server object """ self.config = db_privacyideaserver_object def validate_check(self, user, password, serial=None, realm=None, transaction_id=None, resolver=None): """ Perform an HTTP validate/check request to the remote privacyIDEA Server. :param serial: The serial number of a token :param user: The username :param password: The password :param realm: an optional realm, if it is not contained in the username :param transaction_id: an optional transaction_id. :return: Tuple (HTTP response object, JSON response content) """ data = {"pass": password} if user: data["user"] = user if serial: data["serial"] = serial if realm: data["realm"] = realm if transaction_id: data["transaction_id"] = transaction_id if resolver: data["resolver"] = resolver response = requests.post(self.config.url + "/validate/check", data=data, verify=self.config.tls) return response @staticmethod def request(config, user, password): """ Perform an HTTP test request to the privacyIDEA server. The privacyIDEA configuration contains the URL and the TLS verify. * config.url * config.tls :param config: The privacyIDEA configuration :type config: PrivacyIDEAServer Database Model :param user: the username to test :param password: the password/OTP to test :return: True or False. If any error occurs, an exception is raised. """ response = requests.post(config.url + "/validate/check", data={"user": user, "pass": password}, verify=config.tls ) log.debug("Sent request to privacyIDEA server. status code returned: " "{0!s}".format(response.status_code)) if response.status_code != 200: log.warning("The request to the remote privacyIDEA server {0!s} " "returned a status code: {1!s}".format(config.url, response.status_code)) return False j_response = json.loads(to_unicode(response.content)) result = j_response.get("result") return result.get("status") and result.get("value") @log_with(log) def list_privacyideaservers(identifier=None, id=None): res = {} server_list = get_privacyideaservers(identifier=identifier, id=id) for server in server_list: res[server.config.identifier] = {"id": server.config.id, "url": server.config.url, "tls": server.config.tls, "description": server.config.description} return res @log_with(log) def get_privacyideaserver(identifier=None, id=None): """ This returns the privacyIDEA Server object of the privacyIDEA Server definition "identifier". In case the identifier does not exist, an exception is raised. :param identifier: The name of the privacyIDEA Server definition :param id: The database ID of the privacyIDEA Server definition :return: A privacyIDEAServer Object """ server_list = get_privacyideaservers(identifier=identifier, id=id) if not server_list: raise ConfigAdminError("The specified privacyIDEA Server configuration " "does not exist.") return server_list[0] @log_with(log) def get_privacyideaservers(identifier=None, url=None, id=None): """ This returns a list of all privacyIDEA Servers matching the criterion. If no identifier or url is provided, it will return a list of all privacyIDEA server definitions. :param identifier: The identifier or the name of the privacyIDEA Server definition. As the identifier is unique, providing an identifier will return a list with either one or no privacyIDEA Server :type identifier: basestring :param url: The FQDN or IP address of the privacyIDEA Server :type url: basestring :param id: The database id of the server :type id: integer :return: list of privacyIDEA Server Objects. """ res = [] sql_query = PrivacyIDEAServerDB.query if id is not None: sql_query = sql_query.filter(PrivacyIDEAServerDB.id == id) elif identifier: sql_query = sql_query.filter(PrivacyIDEAServerDB.identifier == identifier) elif url: sql_query = sql_query.filter(PrivacyIDEAServerDB.server == url) for row in sql_query.all(): res.append(PrivacyIDEAServer(row)) return res @log_with(log) def add_privacyideaserver(identifier, url=None, tls=True, description=""): """ This adds a privacyIDEA server to the privacyideaserver database table. If the "identifier" already exists, the database entry is updated. :param identifier: The identifier or the name of the privacyIDEA Server definition. As the identifier is unique, providing an identifier will return a list with either one or no radius server :type identifier: basestring :param url: The url of the privacyIDEA server :type url: basestring :param tls: whether the certificate of the server should be checked :type tls: bool :param description: Human readable description of the RADIUS server definition :return: The Id of the database object """ r = PrivacyIDEAServerDB(identifier=identifier, url=url, tls=tls, description=description).save() return r @log_with(log) def delete_privacyideaserver(identifier): """ Delete the given server from the database. Raise ResourceNotFoundError if it couldn't be found. :param identifier: The identifier/name of the server :return: The ID of the database entry, that was deleted """ return fetch_one_resource(PrivacyIDEAServerDB, identifier=identifier).delete() @register_export('privacyideaserver') def export_privacyideaservers(name=None): """ Export given or all privacyideaservers configuration """ # remove the id from the resulting objects pids_list = list_privacyideaservers(identifier=name) for _, pids in pids_list.items(): pids.pop('id') return pids_list @register_import('privacyideaserver') def import_privacyideaservers(data, name=None): """Import privacyideaservers configuration""" log.debug('Import privacyideaservers config: {0!s}'.format(data)) for res_name, res_data in data.items(): if name and name != res_name: continue rid = add_privacyideaserver(res_name, **res_data) log.info('Import of privacyideaservers "{0!s}" finished,' ' id: {1!s}'.format(res_name, rid))
agpl-3.0
OxBRCInformatics/pedigree-editor-tool
js/queues.min.js
612
/*! pedigree-editor-tool - v1.3.1 - 2017-05-22 * https://github.com/OxBRCInformatics/pedigree-editor-tool#readme * Copyright (c) 2017 Licensed AGPL-3.0 */ Queue=function(){this.data=[]},Queue.prototype={setTo:function(list){this.data=list.slice()},push:function(v){this.data.push(v)},pop:function(v){return this.data.shift()},size:function(){return this.data.length},clear:function(){this.data=[]}},Stack=function(){this.data=[]},Stack.prototype={setTo:function(list){this.data=list.slice()},push:function(v){this.data.push(v)},pop:function(v){return this.data.pop()},size:function(){return this.data.length}};
agpl-3.0
decidim/decidim
decidim-elections/spec/system/voting_spec.rb
2102
# frozen_string_literal: true require "spec_helper" describe "Voting", type: :system do let!(:organization) { create(:organization) } let!(:voting) { create(:voting, :published, organization: organization) } let!(:user) { create :user, :confirmed, organization: organization } before do switch_to_host(organization.host) end it_behaves_like "editable content for admins" do let(:target_path) { decidim_votings.voting_path(voting) } end context "when requesting the voting path" do before do visit decidim_votings.voting_path(voting) end it "shows the basic voting data" do expect(page).to have_i18n_content(voting.title) expect(page).to have_i18n_content(voting.description) end context "when the voting is unpublished" do let!(:voting) do create(:voting, :unpublished, organization: organization) end before do switch_to_host(organization.host) end it "redirects to sign in path" do visit decidim_votings.voting_path(voting) expect(page).to have_current_path("/users/sign_in") end context "with signed in user" do let!(:user) { create(:user, :confirmed, organization: organization) } before do sign_in user, scope: :user end it "redirects to root path" do visit decidim_votings.voting_path(voting) expect(page).to have_current_path("/") end end end context "when the voting has census" do let!(:census) { create(:dataset, voting: voting) } before do switch_to_host(organization.host) visit decidim_votings.voting_path(voting) end it "shows 'Can I vote' tab" do expect(page).to have_link("Can I vote?") end end context "when the voting doesn't has a census" do before do switch_to_host(organization.host) visit decidim_votings.voting_path(voting) end it "doesn't has 'Can I vote' tab" do expect(page).not_to have_link("Can I vote?") end end end end
agpl-3.0
pyalot/WebGL-City-SSAO
glee/matrix.js
18128
/* :copyright: 2011 by Florian Boesch <pyalot@gmail.com>. :license: GNU AGPL3, see LICENSE for more details. */ (function(){ var fmt = function(value){ var str = value.toFixed(2); while(str.length < 7){ str = ' ' + str; } return str; } var pi = Math.PI; var tau = 2*pi; var deg = 360/tau var arc = tau/360 var Mat3 = Glee.prototype.Mat3 = function(other){ this.data = [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]; }; Mat3.prototype = { type: 'Mat3', set: function( a0, b0, c0, a1, b1, c1, a2, b2, c2 ){ this.data.splice(0, 16, a0, b0, c0, a1, b1, c1, a2, b2, c2 ); return this; }, ident: function(){ return this.set( 1, 0, 0, 0, 1, 0, 0, 0, 1 ); }, log: function(message){ var d = this.data; if(!message){ message = 'Mat3'; } console.group(message); console.log(fmt(d[0]), fmt(d[1]), fmt(d[2])); console.log(fmt(d[3]), fmt(d[4]), fmt(d[5])); console.log(fmt(d[6]), fmt(d[7]), fmt(d[8])); console.groupEnd(); return this; }, rotatex: function(angle){ var s = Math.sin(angle*arc); var c = Math.cos(angle*arc); return this.amul( 1, 0, 0, 0, c, s, 0, -s, c ); }, rotatey: function(angle){ var s = Math.sin(angle*arc); var c = Math.cos(angle*arc); return this.amul( c, 0, -s, 0, 1, 0, s, 0, c ); }, rotatez: function(angle){ var s = Math.sin(angle*arc); var c = Math.cos(angle*arc); return this.amul( c, s, 0, -s, c, 0, 0, 0, 1 ); }, updateFrom: function(other){ if(other.type == 'Mat4'){ tmp4.updateFrom(other); tmp4.invert().transpose(); var d = tmp4.data; var a0 = d[0], b0 = d[1], c0 = d[2]; var a1 = d[4], b1 = d[5], c1 = d[6]; var a2 = d[8], b2 = d[9], c2 = d[10]; } else{ var d = other.data; var a0 = d[0], b0 = d[1], c0 = d[2]; var a1 = d[3], b1 = d[4], c1 = d[5]; var a2 = d[6], b2 = d[7], c2 = d[8]; } return this.set( a0, b0, c0, a1, b1, c1, a2, b2, c2 ); return this; }, amul: function( b00, b10, b20, b01, b11, b21, b02, b12, b22, b03, b13, b23 ){ var a = this.data; var a00 = a[0]; var a10 = a[1]; var a20 = a[2]; var a01 = a[3]; var a11 = a[4]; var a21 = a[5]; var a02 = a[6]; var a12 = a[7]; var a22 = a[8]; a[0] = a00*b00 + a01*b10 + a02*b20; a[1] = a10*b00 + a11*b10 + a12*b20; a[2] = a20*b00 + a21*b10 + a22*b20; a[3] = a00*b01 + a01*b11 + a02*b21; a[4] = a10*b01 + a11*b11 + a12*b21; a[5] = a20*b01 + a21*b11 + a22*b21; a[6] = a00*b02 + a01*b12 + a02*b22; a[7] = a10*b02 + a11*b12 + a12*b22; a[8] = a20*b02 + a21*b12 + a22*b22; return this; } } var Mat4 = Glee.prototype.Mat4 = function(other){ this.data = [ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ]; }; Mat4.prototype = { type: 'Mat4', set: function( a0, b0, c0, d0, a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 ){ this.data.splice(0, 16, a0, b0, c0, d0, a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 ); return this; }, updateFrom: function(other){ var d = other.data; if(other.type == 'Mat4'){ var a0 = d[0], b0 = d[1], c0 = d[2], d0 = d[3]; var a1 = d[4], b1 = d[5], c1 = d[6], d1 = d[7]; var a2 = d[8], b2 = d[9], c2 = d[10], d2 = d[11]; var a3 = d[12], b3 = d[13], c3 = d[14], d3 = d[15]; } else{ var a0 = d[0], b0 = d[1], c0 = d[2], d0 = 0; var a1 = d[3], b1 = d[4], c1 = d[5], d1 = 0; var a2 = d[6], b2 = d[7], c2 = d[8], d2 = 0; var a3 = 0, b3 = 0, c3 = 0, d3 = 1; } return this.set( a0, b0, c0, d0, a1, b1, c1, d1, a2, b2, c2, d2, a3, b3, c3, d3 ); }, det: function(){ var d = this.data; var a11 = d[0], a12 = d[1], a13 = d[2], a14 = d[3]; var a21 = d[4], a22 = d[5], a23 = d[6], a24 = d[7]; var a31 = d[8], a32 = d[9], a33 = d[10], a34 = d[11]; var a41 = d[12], a42 = d[13], a43 = d[14], a44 = d[15]; return ( + a11*a22*a33*a44 + a11*a23*a34*a42 + a11*a24*a32*a43 + a12*a21*a34*a33 + a12*a23*a31*a44 + a12*a24*a33*a41 + a13*a21*a32*a44 + a13*a22*a34*a41 + a13*a24*a31*a42 + a14*a21*a33*a42 + a14*a22*a31*a43 + a14*a23*a31*a41 - a11*a22*a34*a43 - a11*a23*a32*a44 - a11*a24*a33*a42 - a12*a21*a33*a44 - a12*a23*a34*a41 - a12*a24*a31*a43 - a13*a21*a34*a42 - a13*a22*a31*a44 - a13*a24*a32*a41 - a14*a21*a32*a43 - a14*a22*a33*a41 - a14*a23*a31*a42 ) }, invert: function(){ var det = this.det(); if(det == 0){ return this.ident(); } else{ var d = this.data; var a11 = d[0], a12 = d[1], a13 = d[2], a14 = d[3]; var a21 = d[4], a22 = d[5], a23 = d[6], a24 = d[7]; var a31 = d[8], a32 = d[9], a33 = d[10], a34 = d[11]; var a41 = d[12], a42 = d[13], a43 = d[14], a44 = d[15]; return this.set( (a22*a33*a44 + a23*a34*a42 + a24*a32*a43 - a22*a34*a43 - a23*a32*a44 - a24*a33*a42)/det, (a12*a34*a43 + a13*a32*a44 + a14*a33*a42 - a12*a33*a44 - a13*a34*a42 - a14*a32*a43)/det, (a12*a23*a44 + a13*a24*a42 + a14*a22*a43 - a12*a24*a43 - a13*a22*a44 - a14*a23*a42)/det, (a12*a24*a33 + a13*a22*a34 + a14*a23*a32 - a12*a23*a34 - a13*a24*a32 - a14*a22*a33)/det, (a21*a34*a43 + a23*a31*a44 + a24*a33*a41 - a21*a33*a44 - a23*a34*a41 - a24*a31*a43)/det, (a11*a33*a44 + a13*a34*a41 + a14*a31*a43 - a11*a34*a43 - a13*a31*a44 - a14*a33*a41)/det, (a11*a24*a43 + a13*a21*a44 + a14*a23*a41 - a11*a23*a44 - a13*a24*a41 - a14*a21*a43)/det, (a11*a23*a34 + a13*a24*a31 + a14*a21*a33 - a11*a24*a33 - a13*a21*a34 - a14*a23*a31)/det, (a21*a32*a44 + a22*a34*a41 + a24*a31*a42 - a21*a34*a42 - a22*a31*a44 - a24*a32*a41)/det, (a11*a34*a42 + a12*a31*a44 + a14*a32*a41 - a11*a32*a44 - a12*a34*a41 - a14*a31*a42)/det, (a11*a22*a44 + a12*a24*a41 + a14*a21*a42 - a11*a24*a42 - a12*a21*a44 - a14*a22*a41)/det, (a11*a24*a32 + a12*a21*a34 + a14*a22*a31 - a11*a22*a34 - a12*a24*a31 - a14*a21*a32)/det, (a21*a33*a42 + a22*a31*a43 + a23*a32*a41 - a21*a32*a43 - a22*a33*a41 - a23*a31*a42)/det, (a11*a32*a43 + a12*a33*a41 + a13*a31*a42 - a11*a33*a42 - a12*a31*a43 - a13*a32*a41)/det, (a11*a23*a42 + a12*a21*a43 + a13*a22*a41 - a11*a22*a43 - a12*a23*a41 - a13*a21*a42)/det, (a11*a22*a33 + a12*a23*a31 + a13*a21*a32 - a11*a23*a32 - a12*a21*a33 - a13*a22*a31)/det ) } }, ident: function(){ return this.set( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); }, perspective: function(params){ var args = Glee.defaults(params, {fov:60, near:1, far:100}); var near = args.near; var far = args.far; var angle = (args.fov/360)*Math.PI; var aspect = args.width/args.height; var top = near * Math.tan(angle); var bottom = -top; var right = top * aspect; var left = -right; var a = (2*near)/(right-left); var b = (right+left)/(right-left); var c = (2*near)/(top-bottom); var d = (top+bottom)/(top-bottom); var e = -(far+near)/(far-near); var f = -(2*far*near)/(far-near); var g = -1; return this.set( a, 0, b, 0, 0, c, d, 0, 0, 0, e, f, 0, 0, g, 0 ).transpose(); }, inverse_perspective: function(params){ var args = Glee.defaults(params, {fov:60, near:1, far:100}); var near = args.near; var far = args.far; var aspect = args.width/args.height; var top = near * Math.tan((args.fov*Math.PI)/360.0); var bottom = -top; var right = top * aspect; var left = -right; var a = (right-left)/(2*near) var b = (right+left)/(2*near) var c = (top-bottom)/(2*near) var d = (top+bottom)/(2*near) var e = -1 var f = -(far-near)/(2*far*near) var g = (far+near)/(2*far*near) return this.set( a, 0, 0, b, 0, c, 0, d, 0, 0, 0, e, 0, 0, f, g ).transpose(); }, ortho: function(params){ var args = Glee.defaults(params, {near:-1, far:1, top:-1, bottom:1, left:-1, right:1}); var near = args.near; var far = args.far; var bottom = args.bottom; var top = args.top; var right = args.right; var left = args.left; var a = 2/(right-left) var b = -((right+left)/(right-left)) var c = 2/(top-bottom) var d = -((top+bottom)/(top-bottom)) var e = -2/(far-near) var f = -((far+near)/(far-near)) var g = 1 return this.set( a, 0, 0, b, 0, c, 0, d, 0, 0, e, f, 0, 0, 0, g ).transpose() }, inverse_ortho: function(params){ var args = Glee.defaults(params, {near:-1, far:1, top:-1, bottom:1, left:-1, right:1}); var near = args.near; var far = args.far; var bottom = args.bottom; var top = args.top; var right = args.right; var left = args.left; var a = (right-left)/2 var b = (right+left)/2 var c = (top-bottom)/2 var d = (top+bottom)/2 var e = (far-near)/-2 var f = (near+far)/2 var g = 1 return this.set( a, 0, 0, b, 0, c, 0, d, 0, 0, e, f, 0, 0, 0, g ).transpose() }, log: function(message){ var d = this.data; if(!message){ message = 'Mat4'; } console.group(message); console.log(fmt(d[0]), fmt(d[1]), fmt(d[2]), fmt(d[3])); console.log(fmt(d[4]), fmt(d[5]), fmt(d[6]), fmt(d[7])); console.log(fmt(d[8]), fmt(d[9]), fmt(d[10]), fmt(d[11])); console.log(fmt(d[12]), fmt(d[13]), fmt(d[14]), fmt(d[15])); console.groupEnd(); return this; }, // operations translate: function(x, y, z){ return this.amul( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 ); }, rotatex: function(angle){ var s = Math.sin(angle*arc); var c = Math.cos(angle*arc); return this.amul( 1, 0, 0, 0, 0, c, s, 0, 0, -s, c, 0, 0, 0, 0, 1 ); }, rotatey: function(angle){ var s = Math.sin(angle*arc); var c = Math.cos(angle*arc); return this.amul( c, 0, -s, 0, 0, 1, 0, 0, s, 0, c, 0, 0, 0, 0, 1 ); }, rotatez: function(angle){ var s = Math.sin(angle*arc); var c = Math.cos(angle*arc); return this.amul( c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ); }, mul: function(b){ return this.lmul(b.data); }, amul: function( b00, b10, b20, b30, b01, b11, b21, b31, b02, b12, b22, b32, b03, b13, b23, b33 ){ var a = this.data; var a00 = a[0]; var a10 = a[1]; var a20 = a[2]; var a30 = a[3]; var a01 = a[4]; var a11 = a[5]; var a21 = a[6]; var a31 = a[7]; var a02 = a[8]; var a12 = a[9]; var a22 = a[10]; var a32 = a[11]; var a03 = a[12]; var a13 = a[13]; var a23 = a[14]; var a33 = a[15]; a[0] = a00*b00 + a01*b10 + a02*b20 + a03*b30; a[1] = a10*b00 + a11*b10 + a12*b20 + a13*b30; a[2] = a20*b00 + a21*b10 + a22*b20 + a23*b30; a[3] = a30*b00 + a31*b10 + a32*b20 + a33*b30; a[4] = a00*b01 + a01*b11 + a02*b21 + a03*b31; a[5] = a10*b01 + a11*b11 + a12*b21 + a13*b31; a[6] = a20*b01 + a21*b11 + a22*b21 + a23*b31; a[7] = a30*b01 + a31*b11 + a32*b21 + a33*b31; a[8] = a00*b02 + a01*b12 + a02*b22 + a03*b32; a[9] = a10*b02 + a11*b12 + a12*b22 + a13*b32; a[10] = a20*b02 + a21*b12 + a22*b22 + a23*b32; a[11] = a30*b02 + a31*b12 + a32*b22 + a33*b32; a[12] = a00*b03 + a01*b13 + a02*b23 + a03*b33; a[13] = a10*b03 + a11*b13 + a12*b23 + a13*b33; a[14] = a20*b03 + a21*b13 + a22*b23 + a23*b33; a[15] = a30*b03 + a31*b13 + a32*b23 + a33*b33; return this; }, lmul: function(b){ var a = this.data; var a00 = a[0]; var a10 = a[1]; var a20 = a[2]; var a30 = a[3]; var a01 = a[4]; var a11 = a[5]; var a21 = a[6]; var a31 = a[7]; var a02 = a[8]; var a12 = a[9]; var a22 = a[10]; var a32 = a[11]; var a03 = a[12]; var a13 = a[13]; var a23 = a[14]; var a33 = a[15]; var b00 = b[0]; var b10 = b[1]; var b20 = b[2]; var b30 = b[3]; var b01 = b[4]; var b11 = b[5]; var b21 = b[6]; var b31 = b[7]; var b02 = b[8]; var b12 = b[9]; var b22 = b[10]; var b32 = b[11]; var b03 = b[12]; var b13 = b[13]; var b23 = b[14]; var b33 = b[15]; a[0] = a00*b00 + a01*b10 + a02*b20 + a03*b30; a[1] = a10*b00 + a11*b10 + a12*b20 + a13*b30; a[2] = a20*b00 + a21*b10 + a22*b20 + a23*b30; a[3] = a30*b00 + a31*b10 + a32*b20 + a33*b30; a[4] = a00*b01 + a01*b11 + a02*b21 + a03*b31; a[5] = a10*b01 + a11*b11 + a12*b21 + a13*b31; a[6] = a20*b01 + a21*b11 + a22*b21 + a23*b31; a[7] = a30*b01 + a31*b11 + a32*b21 + a33*b31; a[8] = a00*b02 + a01*b12 + a02*b22 + a03*b32; a[9] = a10*b02 + a11*b12 + a12*b22 + a13*b32; a[10] = a20*b02 + a21*b12 + a22*b22 + a23*b32; a[11] = a30*b02 + a31*b12 + a32*b22 + a33*b32; a[12] = a00*b03 + a01*b13 + a02*b23 + a03*b33; a[13] = a10*b03 + a11*b13 + a12*b23 + a13*b33; a[14] = a20*b03 + a21*b13 + a22*b23 + a23*b33; a[15] = a30*b03 + a31*b13 + a32*b23 + a33*b33; return this; }, transpose: function(){ var d = this.data; return this.set( d[0], d[4], d[8], d[12], d[1], d[5], d[9], d[13], d[2], d[6], d[10], d[14], d[3], d[7], d[11], d[15] ); } }; var tmp4 = new Mat4(); var tmp3 = new Mat3(); })();
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/impl/IfcProjectOrderImpl.java
5576
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.bimserver.models.ifc4.impl; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ import org.bimserver.models.ifc4.Ifc4Package; import org.bimserver.models.ifc4.IfcProjectOrder; import org.bimserver.models.ifc4.IfcProjectOrderTypeEnum; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Project Order</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.bimserver.models.ifc4.impl.IfcProjectOrderImpl#getPredefinedType <em>Predefined Type</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcProjectOrderImpl#getStatus <em>Status</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcProjectOrderImpl#getLongDescription <em>Long Description</em>}</li> * </ul> * * @generated */ public class IfcProjectOrderImpl extends IfcControlImpl implements IfcProjectOrder { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcProjectOrderImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_PROJECT_ORDER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public IfcProjectOrderTypeEnum getPredefinedType() { return (IfcProjectOrderTypeEnum) eGet(Ifc4Package.Literals.IFC_PROJECT_ORDER__PREDEFINED_TYPE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setPredefinedType(IfcProjectOrderTypeEnum newPredefinedType) { eSet(Ifc4Package.Literals.IFC_PROJECT_ORDER__PREDEFINED_TYPE, newPredefinedType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetPredefinedType() { eUnset(Ifc4Package.Literals.IFC_PROJECT_ORDER__PREDEFINED_TYPE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetPredefinedType() { return eIsSet(Ifc4Package.Literals.IFC_PROJECT_ORDER__PREDEFINED_TYPE); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getStatus() { return (String) eGet(Ifc4Package.Literals.IFC_PROJECT_ORDER__STATUS, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setStatus(String newStatus) { eSet(Ifc4Package.Literals.IFC_PROJECT_ORDER__STATUS, newStatus); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetStatus() { eUnset(Ifc4Package.Literals.IFC_PROJECT_ORDER__STATUS); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetStatus() { return eIsSet(Ifc4Package.Literals.IFC_PROJECT_ORDER__STATUS); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getLongDescription() { return (String) eGet(Ifc4Package.Literals.IFC_PROJECT_ORDER__LONG_DESCRIPTION, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setLongDescription(String newLongDescription) { eSet(Ifc4Package.Literals.IFC_PROJECT_ORDER__LONG_DESCRIPTION, newLongDescription); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetLongDescription() { eUnset(Ifc4Package.Literals.IFC_PROJECT_ORDER__LONG_DESCRIPTION); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetLongDescription() { return eIsSet(Ifc4Package.Literals.IFC_PROJECT_ORDER__LONG_DESCRIPTION); } } //IfcProjectOrderImpl
agpl-3.0
Gebesa-Dev/Addons-gebesa
mrp_gebesa/__openerp__.py
964
# -*- coding: utf-8 -*- # © <2016> <César Barrón Bautista> # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html). { "name": "Gebesa MRP", "summary": "Modify MRP's default behavior to adapt it to Gebesa", "version": "9.0.1.0.0", "category": "Uncategorized", "website": "https://odoo-community.org/", "author": "<Cesar Barrón Bautista>, Odoo Community Association (OCA)", "license": "AGPL-3", "application": False, "installable": True, "external_dependencies": { "python": [], "bin": [], }, "depends": [ "base", "mrp", "mrp_cut_detail", "stock_warehouse_analytic_id", "sale_order_gebesa", ], "data": [ "views/mrp_bom_view.xml", "views/sale_order_view.xml", "views/procurement_view.xml", ], "demo": [ # "demo/res_partner_demo.xml", ], "qweb": [ # "static/src/xml/module_name.xml", ] }
agpl-3.0
espona/ckanext-composite
ckanext/composite/tests/test_plugin.py
97
"""Tests for plugin.py.""" import ckanext.composite.plugin as plugin def test_plugin(): pass
agpl-3.0
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/coa/businessobject/options/AccountTypeCodeComparator.java
1651
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ // This class is a comparator for sorting AccountType with Code name. package org.kuali.kfs.coa.businessobject.options; import java.util.Comparator; import org.kuali.kfs.coa.businessobject.AccountType; /** * This class is a comparator for Account Type Codes */ public class AccountTypeCodeComparator implements Comparator { /** * If these two account type codes are the same codes * * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(Object o1, Object o2) { AccountType acctType1 = (AccountType) o1; AccountType acctType2 = (AccountType) o2; int acctTypeComp = acctType1.getAccountTypeCode().compareTo(acctType2.getAccountTypeCode()); return acctTypeComp; } }
agpl-3.0
detrout/chwala
lib/file_locks.php
9352
<?php /* +--------------------------------------------------------------------------+ | This file is part of the Kolab File API | | | | Copyright (C) 2012-2013, Kolab Systems AG | | | | This program is free software: you can redistribute it and/or modify | | it under the terms of the GNU Affero General Public License as published | | by the Free Software Foundation, either version 3 of the License, or | | (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public License | | along with this program. If not, see <http://www.gnu.org/licenses/> | +--------------------------------------------------------------------------+ | Author: Aleksander Machniak <machniak@kolabsys.com> | +--------------------------------------------------------------------------+ */ /** * The Lock manager allows you to handle all file-locks centrally. * It stores all its data in a sql database. Derived from SabreDAV's * PDO Lock manager. */ class file_locks { const SHARED = 1; const EXCLUSIVE = 2; const INFINITE = -1; /** * The database connection object * * @var rcube_db */ private $db; /** * The tablename this backend uses. * * @var string */ protected $table; /** * Internal cache * * @var array */ protected $icache = array(); /** * Constructor * * @param string $table Table name */ public function __construct($table = 'chwala_locks') { $rcube = rcube::get_instance(); $this->db = $rcube->get_dbh(); $this->table = $this->db->table_name($table); if ($rcube->session) { $rcube->session->register_gc_handler(array($this, 'gc')); } else { // run garbage collector with probability based on // session settings if session does not exist. $probability = (int) ini_get('session.gc_probability'); $divisor = (int) ini_get('session.gc_divisor'); if ($divisor > 0 && $probability > 0) { $random = mt_rand(1, $divisor); if ($random <= $probability) { $this->gc(); } } } } /** * Returns a list of locks * * This method should return all the locks for a particular URI, including * locks that might be set on a parent URI. * * If child_locks is set to true, this method should also look for * any locks in the subtree of the URI for locks. * * @param string $uri URI * @param bool $child_locks Enables subtree checks * * @return array List of locks */ public function lock_list($uri, $child_locks = false) { if ($this->icache['uri'] == $uri && $this->icache['child'] == $child_locks) { return $this->icache['list']; } $query = "SELECT * FROM " . $this->db->quote_identifier($this->table) . " WHERE (uri = ?"; $params = array($uri); if ($child_locks) { $query .= " OR uri LIKE ?"; $params[] = $uri . '/%'; } $path = ''; $key = $uri; $list = array(); // in case uri contains protocol/host specification e.g. imap://user@host/ // handle prefix separately if (preg_match('~^([a-z]+://[^/]+/)~i', $uri, $matches)) { $path = $matches[1]; $uri = substr($uri, strlen($matches[1])); } // We need to check locks for every part in the path $path_parts = explode('/', $uri); // We already covered the last part of the uri array_pop($path_parts); if (!empty($path_parts)) { $root_path = $path . implode('/', $path_parts); // this path is already cached, extract locks from cached result // we do this because it is a common scenario to request // for lock on every file/folder in specified location if ($this->icache['root_path'] == $root_path) { $length = strlen($root_path); foreach ($this->icache['list'] as $lock) { if ($lock['depth'] != 0 && strlen($lock['token']) <= $length) { $list[] = $lock; } } } else { foreach ($path_parts as $part) { $path .= $part; $params[] = $path; $path .= '/'; } $query .= " OR (uri IN (" . implode(',', array_pad(array(), count($path_parts), '?')) . ") AND depth <> 0)"; } } // finally, skip expired locks $query .= ") AND expires > " . $this->db->now(); // run the query and parse result $result = $this->db->query($query, $params); while ($row = $this->db->fetch_assoc($result)) { $created = strtotime($row['expires']) - $row['timeout']; $list[] = array( 'uri' => $row['uri'], 'owner' => $row['owner'], 'token' => $row['token'], 'timeout' => (int) $row['timeout'], 'created' => (int) $created, 'scope' => $row['scope'] == self::EXCLUSIVE ? file_storage::LOCK_EXCLUSIVE : file_storage::LOCK_SHARED, 'depth' => $row['depth'] == self::INFINITE ? file_storage::LOCK_INFINITE : (int) $row['depth'], ); } // remember last result in memory, sometimes we need it (or part of it) again $this->icache['list'] = $list; $this->icache['uri'] = $key; $this->icache['root_path'] = $root_path; $this->icache['child_locks'] = $child_locks; return $list; } /** * Locks a uri * * @param string $uri URI * @param array $lock Lock data * * @return bool */ public function lock($uri, $lock) { // We're making the lock timeout max. 30 minutes $timeout = min($lock['timeout'], 30*60); $data = array( $this->db->quote_identifier('uri') => $uri, $this->db->quote_identifier('owner') => $lock['owner'], $this->db->quote_identifier('scope') => $lock['scope'] == file_storage::LOCK_EXCLUSIVE ? self::EXCLUSIVE : self::SHARED, $this->db->quote_identifier('depth') => $lock['depth'] == file_storage::LOCK_INFINITE ? self::INFINITE : 0, $this->db->quote_identifier('timeout') => $timeout, ); // check if lock exists $locks = $this->lock_list($uri, false); $exists = false; foreach ($locks as $l) { if ($l['token'] == $lock['token']) { $exists = true; break; } } if ($exists) { foreach (array_keys($data) as $key) { $update_cols[] = "$key = ?"; } $result = $this->db->query("UPDATE " . $this->db->quote_identifier($this->table) . " SET " . implode(', ', $update_cols) . ", " . $this->db->quote_identifier('expires') . " = " . $this->db->now($timeout) . " WHERE token = ?", array_merge(array_values($data), array($lock['token'])) ); } else { $data[$this->db->quote_identifier('token')] = $lock['token']; $result = $this->db->query("INSERT INTO " . $this->db->quote_identifier($this->table) . " (".join(', ', array_keys($data)) . ", " . $this->db->quote_identifier('expires') . ")" . " VALUES (" . str_repeat('?, ', count($data)) . $this->db->now($timeout) . ")", array_values($data) ); } return $this->db->affected_rows(); } /** * Removes a lock from a URI * * @param string $path URI * @param array $lock Lock data * * @return bool */ public function unlock($uri, $lock) { $stmt = $this->db->query("DELETE FROM " . $this->db->quote_identifier($this->table) . " WHERE uri = ? AND token = ?", $uri, $lock['token']); return $this->db->affected_rows(); } /** * Remove expired locks */ public function gc() { $this->db->query("DELETE FROM " . $this->db->quote_identifier($this->table) . " WHERE expires < " . $this->db->now()); } }
agpl-3.0
pol-is/polisClientParticipation
js/views/conversation-stats-header.js
1248
// Copyright (C) 2012-present, The Authors. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License, version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. var eb = require("../eventBus"); var template = require("../tmpl/conversation-stats-header"); var Handlebones = require("handlebones"); module.exports = Handlebones.View.extend({ name: "conversation-stats-header-view", template: template, initialize: function(options) { var that = this; eb.on(eb.participantCount, function(count) { that.participantCount = count; that.render(); }); eb.on(eb.commentCount, function(count) { that.commentCount = count; that.render(); }); eb.on(eb.voteCount, function(count) { that.voteCount = count; that.render(); }); } });
agpl-3.0
gabrys/wikidot
lib/ozone/php/core/Action.php
1055
<?php /** * Wikidot - free wiki collaboration software * Copyright (c) 2008, Wikidot Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * For more information about licensing visit: * http://www.wikidot.org/license * * @category Ozone * @package Ozone_Web * @version $Id$ * @copyright Copyright (c) 2008, Wikidot Inc. * @license http://www.gnu.org/licenses/agpl-3.0.html GNU Affero General Public License */ /** * Action class. * */ abstract class Action { public function isAllowed($runData){ return true; } public abstract function perform($runData); }
agpl-3.0
coorasse/Airesis
app/models/proposal_comment_search.rb
3299
class ProposalCommentSearch attr_reader :section def initialize(params, proposal, current_user = nil) @proposal = proposal @all = params[:all] @view = params[:view] @page = params[:page] @comment_id = params[:comment_id].to_i @section_id = params[:section_id] @section = Section.find(@section_id) if @section_id.present? @contributes = params[:contributes] @limit = params[:disable_limit] ? 9_999_999 : COMMENTS_PER_PAGE @current_user = current_user end def random_order? @view == SearchProposal::ORDER_RANDOM end def rank_order? @view == SearchProposal::ORDER_BY_RANK end def show_more? @total_pages > @current_page end # return a list of ids of already evaluated contributes by the current_user def evaluated_ids return @evaluated_ids if @evaluated_ids @evaluated_ids = if @current_user ProposalComment.joins(:rankings). where(proposal_comment_rankings: { user_id: @current_user.id }, proposal_comments: { proposal_id: @proposal.id }).distinct.pluck(:id) else [] end @evaluated_ids.delete(@comment_id) if @comment_id @evaluated_ids end def order_clause 'random()' unless @comment_id "CASE proposal_comments.id WHEN #{@comment_id.to_i} THEN 1 ELSE 5 END, random()" end def proposal_comments return @proposal_comments if @proposal_comments proposal_comments_t = ProposalComment.arel_table if @section.present? paragraphs_ids = @section.paragraph_ids conditions_arel = proposal_comments_t[:paragraph_id].in(paragraphs_ids) elsif @all.present? conditions_arel = Arel::Nodes::SqlLiteral.new('1').eq(1) else conditions_arel = proposal_comments_t[:paragraph_id].eq(nil) end if random_order? # remove already shown contributes conditions_arel = conditions_arel.and(proposal_comments_t[:id].not_in @contributes) if @contributes left = @limit tmp_comments = [] # extract not evaluated contributes tmp_comments += @proposal.contributes.listable. where(conditions_arel.and(proposal_comments_t[:id].not_in(evaluated_ids))). order(Arel.sql(order_clause)).take(left) left -= tmp_comments.count if left > 0 && !evaluated_ids.empty? # extract the evaluated ones tmp_comments += @proposal.contributes.listable. where(conditions_arel.and(proposal_comments_t[:id].in(evaluated_ids))). order('rank desc').take(left) end @proposal_comments = tmp_comments @total_pages = (@proposal.contributes.listable.where(conditions_arel).count.to_f / COMMENTS_PER_PAGE).ceil @current_page = (@page || 1).to_i else order = if rank_order? [proposal_comments_t[:j_value].desc, proposal_comments_t[:id].desc] else proposal_comments_t[:updated_at].desc end @proposal_comments = @proposal.contributes.listable.where(conditions_arel).order(order).page(@page).per(@limit) @total_pages = @proposal_comments.total_pages @current_page = @proposal_comments.current_page end @proposal_comments end end
agpl-3.0
Comunitea/CMNT_004_15
project-addons/mrp_repair_custom/__init__.py
983
############################################################################## # # Copyright (C) 2015 Comunitea Servicios Tecnológicos All Rights Reserved # $Omar Castiñeira Saaevdra <omar@comunitea.com>$ # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ##############################################################################
agpl-3.0
asm-helpful/helpful-web
db/migrate/20140626180318_drop_respond_laters_table.rb
109
class DropRespondLatersTable < ActiveRecord::Migration def change drop_table :respond_laters end end
agpl-3.0
uniteddiversity/mycollab
mycollab-services/src/main/java/com/esofthead/mycollab/module/crm/dao/LeadMapper.java
5377
/** * This file is part of mycollab-services. * * mycollab-services 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. * * mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.crm.dao; import com.esofthead.mycollab.core.persistence.ICrudGenericDAO; import com.esofthead.mycollab.module.crm.domain.Lead; import com.esofthead.mycollab.module.crm.domain.LeadExample; import java.util.List; import org.apache.ibatis.annotations.Param; @SuppressWarnings({ "ucd", "rawtypes" }) public interface LeadMapper extends ICrudGenericDAO { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int countByExample(LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int deleteByExample(LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int deleteByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int insert(Lead record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int insertSelective(Lead record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ List<Lead> selectByExampleWithBLOBs(LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ List<Lead> selectByExample(LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ Lead selectByPrimaryKey(Integer id); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int updateByExampleSelective(@Param("record") Lead record, @Param("example") LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int updateByExampleWithBLOBs(@Param("record") Lead record, @Param("example") LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int updateByExample(@Param("record") Lead record, @Param("example") LeadExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int updateByPrimaryKeySelective(Lead record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int updateByPrimaryKeyWithBLOBs(Lead record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ int updateByPrimaryKey(Lead record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ Integer insertAndReturnKey(Lead value); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ void removeKeysWithSession(List primaryKeys); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_crm_lead * * @mbggenerated Thu Jul 16 10:50:10 ICT 2015 */ void massUpdateWithSession(@Param("record") Lead record, @Param("primaryKeys") List primaryKeys); }
agpl-3.0
Extentsoftware/Quest
src/Quest.LAS/Model/PermissionGroup.cs
654
#pragma warning disable 0649 using System; namespace Quest.LAS.Model.Processor { internal class PermissionGroup { public DateTime? DateAdded; public DateTime? DateUpdated; public string Description; public bool HasChangeMaxRecords; public bool HasCrew; public bool HasEocLog; public bool HasLocations; public bool HasMedical; public bool HasOverView; public bool HasPatient; public bool HasPrfs; public bool HasValidation; public bool HasVehicles; public int ID; public bool IsPrimary; public string Name; } }
agpl-3.0
melisamx/melisa-kernel
third_party/melisa-kernel/release/events/core.input.inyect_php.php
201
<?php Event()->listen('core.input.inyect_php', function($field, &$value) { return get_instance()->app->load()->libraries('Melisa\core\input\Inyect') ->init($field, $value); });
agpl-3.0
monicahq/monica
tests/cypress/integration/contacts/debts_spec.js
1652
describe('Debts', function () { beforeEach(function () { cy.login(); cy.createContact('John', 'Doe', 'Man'); }); it('lets you manage a debt', function () { cy.url().should('include', '/people/h:'); cy.get('[cy-name=debt-blank-state]').should('be.visible'); // add a debt cy.get('[cy-name=add-debt-button]').should('be.visible'); cy.get('[cy-name=add-debt-button]').click(); cy.url().should('include', '/debts/create'); cy.get('[name=amount]').type('123'); cy.get('[cy-name=save-debt-button]').click(); cy.url().should('include', '/people/h:'); cy.get('[cy-name=debt-blank-state]').should('not.be.visible'); cy.get('[cy-name=debts-body]').should('be.visible') .invoke('attr', 'cy-items').then(function (item) { cy.get('[cy-name=debt-item-'+item+']').should('exist'); cy.get('[cy-name=debt-item-'+item+']').should('contain', '123'); // edit a debt cy.get('[cy-name=edit-debt-button-'+item+']').click(); cy.url().should('include', '/edit'); cy.get('[name=amount]').clear(); cy.get('[name=amount]').type('234'); cy.get('[cy-name=save-debt-button]').click(); cy.get('[cy-name=debt-item-'+item+']').should('exist'); cy.get('[cy-name=debt-item-'+item+']').should('contain', '234'); // delete a debt cy.get('[cy-name=delete-debt-button-'+item+']').click(); cy.get('[cy-name=confirm-delete-debt]').should('be.visible').click(); cy.get('[cy-name=debt-blank-state]').should('be.visible'); cy.get('[cy-name=debt-item-'+item+']').should('not.exist'); }); }); });
agpl-3.0
YellowDi/Sandbox
app/libraries/Captcha.php
2570
<?php class Captcha { var $width='60'; var $num='4'; var $height='20'; var $name='randcode'; public function __construct($conf="") { if($conf!="") { foreach($conf as $key=>$value) { $this->$key=$value; } } } function show() { $CI = & get_instance(); $CI->load->library('session'); //Header("Content-type: image/gif"); /* * 初始化 */ $border = 0; //是否要边框 1要:0不要 $how = $this->num; //验证码位数 $w = $this->width; //图片宽度 $h = $this->height; //图片高度 $fontsize = 5; //字体大小 $alpha = "abcdefghijkmnpqrstuvwxyz"; //验证码内容1:字母 $number = "23456789"; //验证码内容2:数字 $randcode = ""; //验证码字符串初始化 srand((double)microtime()*1000000); //初始化随机数种子 $im = imagecreate($w,$h); //创建验证图片 /* * 绘制基本框架 */ $bgcolor = imagecolorallocate($im, 255, 255, 255); //设置背景颜色 ImageFill($im, 0, 0, $bgcolor); //填充背景色 if($border) { $black = ImageColorAllocate($im, 0, 0, 0); //设置边框颜色 ImageRectangle($im, 0, 0, $w-1, $h-1, $black);//绘制边框 } /* * 逐位产生随机字符 */ for($i=0; $i<$how; $i++) { $alpha_or_number = mt_rand(0, 1); //字母还是数字 $str = $alpha_or_number ? $alpha : $number; $which = mt_rand(0, strlen($str)-1); //取哪个字符 $code = substr($str, $which, 1); //取字符 $j = !$i ? 4 : $j+15; //绘字符位置 $color3 = ImageColorAllocate($im, mt_rand(0,100), mt_rand(0,100), mt_rand(0,100)); //字符随即颜色 ImageChar($im, $fontsize, $j, 3, $code, $color3); //绘字符 $randcode .= $code; //逐位加入验证码字符串 } /* * 添加干扰 */ /* for($i=0; $i<5; $i++)//绘背景干扰线 { $color1 = ImageColorAllocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); //干扰线颜色 ImageArc($im, mt_rand(-5,$w), mt_rand(-5,$h), mt_rand(20,300), mt_rand(20,200), 55, 44, $color1); //干扰线 } */ for($i=0; $i<$how*5; $i++)//绘背景干扰点 { $color2 = ImageColorAllocate($im, mt_rand(0,255), mt_rand(0,255), mt_rand(0,255)); //干扰点颜色 ImageSetPixel($im, mt_rand(0,$w), mt_rand(0,$h), $color2); //干扰点 } //$_SESSION[$this->name]=$randcode; $CI->session->set_userdata($this->name, $randcode); //ob_clean(); /*绘图结束*/ Imagegif($im); ImageDestroy($im); /*绘图结束*/ } } ?>
agpl-3.0
m-sc/yamcs
yamcs-xtce/src/main/java/org/yamcs/xtce/AggregateDataType.java
11048
package org.yamcs.xtce; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.yamcs.protobuf.Yamcs.Value; import org.yamcs.protobuf.Yamcs.Value.Type; import org.yamcs.xtce.util.AggregateMemberNames; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.google.gson.JsonParser; public class AggregateDataType extends NameDescription implements DataType { private static final long serialVersionUID = 1L; List<Member> memberList = new ArrayList<>(); transient AggregateMemberNames memberNames; public AggregateDataType(Builder<?> builder) { super(builder); this.memberList = builder.memberList; } public AggregateDataType(String name) { super(name); } protected AggregateDataType(AggregateDataType t) { super(t); this.memberList = t.memberList; this.memberNames = t.memberNames; } @Override public String getTypeAsString() { return "aggregate"; } /** * Returns a member on the given name. If no such member is present return null * * @param name * the name of the member to be returned * @return the member with the given name */ public Member getMember(String name) { for (Member m : memberList) { if (name.equals(m.getName())) { return m; } } return null; } public List<Member> getMemberList() { return memberList; } @Override public Type getValueType() { return Value.Type.AGGREGATE; } /** * Returns a member in a hierarchical aggregate. It is equivalent with a chained call of {@link #getMember(String)}: * * <pre> * getMember(path[0]).getMember(path[1])...getMember(path[n]) * </pre> * * assuming that all the elements on the path exist. * * * @param path * - the path to be traversed. Its length has to be at least 1 - otherwise an * {@link IllegalArgumentException} will be thrown. * @return the member obtained by traversing the path or null if not such member exist. */ public Member getMember(String[] path) { if (path.length == 0) { throw new IllegalArgumentException("path cannot be empty"); } Member m = getMember(path[0]); for (int i = 1; i < path.length; i++) { if (m == null) { return null; } DataType ptype = m.getType(); if (ptype instanceof AggregateParameterType) { m = ((AggregateParameterType) ptype).getMember(path[i]); } else { return null; } m = getMember(path[i]); } return m; } /** * * @return the (unique) object encoding the member names * */ public AggregateMemberNames getMemberNames() { if (memberNames == null) { String[] n = memberList.stream().map(m -> m.getName()).toArray(String[]::new); memberNames = AggregateMemberNames.get(n); } return memberNames; } public int numMembers() { return memberList.size(); } public Member getMember(int idx) { return memberList.get(idx); } /** * Parse the initial value as a JSON string. * <p> * This allows to specify only partially the values, the rest are copied from the member initial value or the type * definition (an exception is thrown if there is any member for which the value cannot be determined). * * @return a map containing the values for all members. * @throws IllegalArgumentException * if the string cannot be parsed or if values cannot be determined for all members */ @Override @SuppressWarnings("unchecked") public Map<String, Object> convertType(Object value) { if (value instanceof String) { // Parse as JSON try { JsonElement je = new JsonParser().parse((String) value); if (je instanceof JsonObject) { return fromJson((JsonObject) je); } else { throw new IllegalArgumentException("Expected JSON object but found " + je.getClass()); } } catch (JsonParseException jpe) { throw new IllegalArgumentException(jpe.toString()); } } else if (value instanceof Map) { return fromMap((Map<String, Object>) value); } else { throw new IllegalArgumentException("Cannot convert value of type '" + value.getClass() + "'"); } } private Map<String, Object> fromJson(JsonObject jobj) { Map<String, Object> r = new HashMap<>(); for (Member memb : memberList) { if (jobj.has(memb.getName())) { JsonElement jsel = jobj.remove(memb.getName()); String v; if (jsel.isJsonPrimitive() && jsel.getAsJsonPrimitive().isString()) { v = jsel.getAsString(); } else { v = jsel.toString(); } r.put(memb.getName(), memb.getType().convertType(v)); } else { Object v = memb.getInitialValue(); if (v == null) { v = memb.getType().getInitialValue(); } if (v == null) { throw new IllegalArgumentException("No value could be determined for member '" + memb.getName() + "' (its corresponding type does not have an initial value)"); } r.put(memb.getName(), v); } } if (jobj.size() > 0) { throw new IllegalArgumentException("Unknown members " + jobj.entrySet().stream().map(e -> e.getKey()).collect(Collectors.toList())); } return r; } private Map<String, Object> fromMap(Map<String, Object> map) { // Provided map may be immutable. So make a copy where we can remove. Map<String, Object> input = new HashMap<>(map); Map<String, Object> r = new HashMap<>(input.size()); for (Member memb : memberList) { if (input.containsKey(memb.getName())) { Object el = input.remove(memb.getName()); r.put(memb.getName(), memb.getType().convertType(el)); } else { Object v = memb.getInitialValue(); if (v == null) { v = memb.getType().getInitialValue(); } if (v == null) { throw new IllegalArgumentException("No value could be determined for member '" + memb.getName() + "' (its corresponding type does not have an initial value)"); } r.put(memb.getName(), v); } } if (input.size() > 0) { throw new IllegalArgumentException("Unknown members " + input.keySet()); } return r; } @Override public Object parseStringForRawValue(String stringValue) { // parse it as json try { JsonElement je = new JsonParser().parse(stringValue); if (je instanceof JsonObject) { return fromJsonRaw((JsonObject) je); } else { throw new IllegalArgumentException("Expected JSON object but found " + je.getClass()); } } catch (JsonParseException jpe) { throw new IllegalArgumentException(jpe.toString()); } } private Map<String, Object> fromJsonRaw(JsonObject jobj) { Map<String, Object> r = new HashMap<>(); for (Member memb : memberList) { if (jobj.has(memb.getName())) { JsonElement jsel = jobj.remove(memb.getName()); String v; if (jsel.isJsonPrimitive() && jsel.getAsJsonPrimitive().isString()) { v = jsel.getAsString(); } else { v = jsel.toString(); } r.put(memb.getName(), memb.getType().parseStringForRawValue(v)); } else { throw new IllegalArgumentException("No value for member '" + memb.getName() + "'"); } } if (jobj.size() > 0) { throw new IllegalArgumentException("Unknown members " + jobj.entrySet().stream().map(e -> e.getKey()).collect(Collectors.toList())); } return r; } @Override public Map<String, Object> getInitialValue() { Map<String, Object> r = new HashMap<>(); for (Member memb : memberList) { Object v = memb.getInitialValue(); if (v == null) { DataType dt = memb.getType(); if (dt != null) { v = dt.getInitialValue(); } } if (v == null) { return null; } r.put(memb.getName(), v); } return r; } @Override public String toString(Object v) { if (v instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> m1 = (Map<String, Object>) v; Map<String, Object> m2 = new HashMap<>(); for (Member memb : memberList) { Object v2 = m1.get(memb.getName()); if (v != null) { DataType dt = memb.getType(); m2.put(memb.getName(), dt.toString(v2)); } } Gson gson = new Gson(); return gson.toJson(m2); } else { throw new IllegalArgumentException("Can only convert maps"); } } public abstract static class Builder<T extends Builder<T>> extends NameDescription.Builder<T> implements DataType.Builder<T> { List<Member> memberList = new ArrayList<>(); public Builder() { } public Builder(AggregateDataType dataType) { super(dataType); this.memberList = dataType.memberList; } @Override public T setInitialValue(String initialValue) { throw new UnsupportedOperationException( "Cannot set initial value; please send individual initial values for the members"); } public T addMember(Member member) { memberList.add(member); return self(); } public T addMembers(List<Member> memberList) { this.memberList.addAll(memberList); return self(); } public List<Member> getMemberList() { return memberList; } } }
agpl-3.0
cgi-eoss/fstep
fs-tep-worker/src/test/java/com/cgi/eoss/fstep/worker/worker/FstepWorkerIT.java
3795
package com.cgi.eoss.fstep.worker.worker; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; import static org.junit.Assume.assumeTrue; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.UUID; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestPropertySource; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.cgi.eoss.fstep.io.ServiceInputOutputManager; import com.cgi.eoss.fstep.io.download.DownloaderFacade; import com.cgi.eoss.fstep.rpc.Job; import com.cgi.eoss.fstep.rpc.worker.FstepWorkerGrpc; import com.cgi.eoss.fstep.rpc.worker.JobDockerConfig; import com.cgi.eoss.fstep.worker.WorkerConfig; import com.cgi.eoss.fstep.worker.WorkerTestConfig; import io.grpc.ManagedChannelBuilder; import io.grpc.Server; import io.grpc.inprocess.InProcessServerBuilder; import shadow.dockerjava.com.github.dockerjava.api.DockerClient; import shadow.dockerjava.com.github.dockerjava.core.command.PullImageResultCallback; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = {WorkerConfig.class, WorkerTestConfig.class}) @TestPropertySource("classpath:test-worker.properties") public class FstepWorkerIT { @MockBean private ServiceInputOutputManager ioManager; @MockBean private DownloaderFacade downloaderFacade; @Autowired private InProcessServerBuilder serverBuilder; @Autowired private ManagedChannelBuilder channelBuilder; @Autowired private DockerClient dockerClient; @Autowired private FstepWorker worker; private Server server; private FstepWorkerGrpc.FstepWorkerBlockingStub workerClient; @BeforeClass public static void precondition() { // Shortcut if docker socket is not accessible to the current user assumeTrue("Unable to write to Docker socket; disabling docker tests", Files.isWritable(Paths.get("/var/run/docker.sock"))); // TODO Pass in a DOCKER_HOST env var to allow remote docker engine use } @Before public void setUp() throws IOException { serverBuilder.addService(worker); server = serverBuilder.build().start(); workerClient = FstepWorkerGrpc.newBlockingStub(channelBuilder.build()); // Ensure the test base image is available before testing dockerClient.pullImageCmd("hello-world:latest").exec(new PullImageResultCallback()).awaitSuccess(); } @After public void tearDown() { server.shutdownNow(); } @Test public void testLaunchContainer() throws Exception { Mockito.when(ioManager.getServiceContext("service1")).thenReturn(Paths.get("src/test/resources/service1").toAbsolutePath()); String tag = UUID.randomUUID().toString(); worker.getJobClientsCache().put("jobid-1", dockerClient); JobDockerConfig request = JobDockerConfig.newBuilder() .setServiceName("service1") .setJob(Job.newBuilder().setId("jobid-1")) .setDockerImage(tag) .build(); try { assertThat(dockerClient.listImagesCmd().withImageNameFilter(tag).exec().size(), is(0)); workerClient.launchContainer(request); assertThat(dockerClient.listImagesCmd().withImageNameFilter(tag).exec().size(), is(1)); } finally { dockerClient.removeImageCmd(tag).exec(); } } }
agpl-3.0
KWZwickau/KREDA-Sphere
Sphere/Common/Extension/Faker/Provider/cs_CZ/Internet.php
1911
<?php namespace Faker\Provider\cs_CZ; class Internet extends \Faker\Provider\Internet { protected static $freeEmailDomain = array( 'gmail.com', 'yahoo.com', 'seznam.cz', 'atlas.cz', 'centrum.cz', 'email.cz', 'post.cz' ); protected static $tld = array( 'cz', 'cz', 'cz', 'cz', 'cz', 'cz', 'com', 'info', 'net', 'org' ); public function email() { return $this->toAscii( parent::email() ); } /** * Converts czech characters to their ASCII representation * * @return string */ private function toAscii( $string ) { $from = array( 'Ě', 'ě', 'Š', 'š', 'Č', 'č', 'Ř', 'ř', 'Ž', 'ž', 'Ý', 'ý', 'Á', 'á', 'Í', 'í', 'É', 'é', 'Ó', 'ó', 'Ú', 'ú', 'Ů', 'ů', 'Ď', 'ď', 'Ť', 'ť', 'Ň', 'ň' ); $to = array( 'E', 'e', 'S', 's', 'C', 'c', 'R', 'r', 'Z', 'z', 'Y', 'y', 'A', 'a', 'I', 'i', 'E', 'e', 'O', 'o', 'U', 'u', 'U', 'u', 'D', 'd', 'T', 't', 'N', 'n' ); return str_replace( $from, $to, $string ); } public function userName() { return $this->toAscii( parent::userName() ); } }
agpl-3.0
SCUEvals/scuevals-api
db/alembic/versions/20171012150636_add_university_id_to_major.py
531
"""Add university id to Major Revision ID: 3c13dfa66a11 Revises: 8e798b2a2354 Create Date: 2017-10-12 15:06:36.201364 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '3c13dfa66a11' down_revision = '8e798b2a2354' branch_labels = None depends_on = None def upgrade(): op.add_column( 'majors', sa.Column('university_id', sa.Integer, sa.ForeignKey('universities.id'), nullable=False) ) def downgrade(): op.drop_column('majors', 'university_id')
agpl-3.0
spyrosg/VISION-Cloud-Monitoring
vismo-core/src/main/java/gr/ntua/vision/monitoring/metrics/HostMemoryMetric.java
176
package gr.ntua.vision.monitoring.metrics; /** * */ public interface HostMemoryMetric { /** * @return the memory usage of the host. */ HostMemory get(); }
agpl-3.0
B3Partners/geo-ov
src/main/webapp/openlayers/lib/OpenLayers/Format/WFST/v1.js
16760
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Format/XML.js * @requires OpenLayers/Format/WFST.js */ /** * Class: OpenLayers.Format.WFST.v1 * Superclass for WFST parsers. * * Inherits from: * - <OpenLayers.Format.XML> */ OpenLayers.Format.WFST.v1 = OpenLayers.Class(OpenLayers.Format.XML, { /** * Property: namespaces * {Object} Mapping of namespace aliases to namespace URIs. */ namespaces: { xlink: "http://www.w3.org/1999/xlink", xsi: "http://www.w3.org/2001/XMLSchema-instance", wfs: "http://www.opengis.net/wfs", gml: "http://www.opengis.net/gml", ogc: "http://www.opengis.net/ogc", ows: "http://www.opengis.net/ows" }, /** * Property: defaultPrefix */ defaultPrefix: "wfs", /** * Property: version * {String} WFS version number. */ version: null, /** * Property: schemaLocation * {String} Schema location for a particular minor version. */ schemaLocations: null, /** * APIProperty: srsName * {String} URI for spatial reference system. */ srsName: null, /** * APIProperty: extractAttributes * {Boolean} Extract attributes from GML. Default is true. */ extractAttributes: true, /** * APIProperty: xy * {Boolean} Order of the GML coordinate true:(x,y) or false:(y,x) * Changing is not recommended, a new Format should be instantiated. */ xy: true, /** * Property: stateName * {Object} Maps feature states to node names. */ stateName: null, /** * Constructor: OpenLayers.Format.WFST.v1 * Instances of this class are not created directly. Use the * <OpenLayers.Format.WFST.v1_0_0> or <OpenLayers.Format.WFST.v1_1_0> * constructor instead. * * Parameters: * options - {Object} An optional object whose properties will be set on * this instance. */ initialize: function(options) { // set state name mapping this.stateName = {}; this.stateName[OpenLayers.State.INSERT] = "wfs:Insert"; this.stateName[OpenLayers.State.UPDATE] = "wfs:Update"; this.stateName[OpenLayers.State.DELETE] = "wfs:Delete"; OpenLayers.Format.XML.prototype.initialize.apply(this, [options]); }, /** * Method: getSrsName */ getSrsName: function(feature, options) { var srsName = options && options.srsName; if(!srsName) { if(feature && feature.layer) { srsName = feature.layer.projection.getCode(); } else { srsName = this.srsName; } } return srsName; }, /** * APIMethod: read * Parse the response from a transaction. Because WFS is split into * Transaction requests (create, update, and delete) and GetFeature * requests (read), this method handles parsing of both types of * responses. * * Parameters: * data - {String | Document} The WFST document to read * options - {Object} Options for the reader * * Valid options properties: * output - {String} either "features" or "object". The default is * "features", which means that the method will return an array of * features. If set to "object", an object with a "features" property * and other properties read by the parser will be returned. * * Returns: * {Array | Object} Output depending on the output option. */ read: function(data, options) { options = options || {}; OpenLayers.Util.applyDefaults(options, { output: "features" }); if(typeof data == "string") { data = OpenLayers.Format.XML.prototype.read.apply(this, [data]); } if(data && data.nodeType == 9) { data = data.documentElement; } var obj = {}; if(data) { this.readNode(data, obj, true); } if(obj.features && options.output === "features") { obj = obj.features; } return obj; }, /** * Property: readers * Contains public functions, grouped by namespace prefix, that will * be applied when a namespaced node is found matching the function * name. The function will be applied in the scope of this parser * with two arguments: the node being read and a context object passed * from the parent. */ readers: { "wfs": { "FeatureCollection": function(node, obj) { obj.features = []; this.readChildNodes(node, obj); } } }, /** * Method: write * Given an array of features, write a WFS transaction. This assumes * the features have a state property that determines the operation * type - insert, update, or delete. * * Parameters: * features - {Array(<OpenLayers.Feature.Vector>)} A list of features. See * below for a more detailed description of the influence of the * feature's *modified* property. * options - {Object} * * feature.modified rules: * If a feature has a modified property set, the following checks will be * made before a feature's geometry or attribute is included in an Update * transaction: * - *modified* is not set at all: The geometry and all attributes will be * included. * - *modified.geometry* is set (null or a geometry): The geometry will be * included. If *modified.attributes* is not set, all attributes will * be included. * - *modified.attributes* is set: Only the attributes set (i.e. to null or * a value) in *modified.attributes* will be included. * If *modified.geometry* is not set, the geometry will not be included. * * Valid options include: * - *multi* {Boolean} If set to true, geometries will be casted to * Multi geometries before writing. * * Returns: * {String} A serialized WFS transaction. */ write: function(features, options) { var node = this.writeNode("wfs:Transaction", { features:features, options: options }); var value = this.schemaLocationAttr(); if(value) { this.setAttributeNS( node, this.namespaces["xsi"], "xsi:schemaLocation", value ); } return OpenLayers.Format.XML.prototype.write.apply(this, [node]); }, /** * Property: writers * As a compliment to the readers property, this structure contains public * writing functions grouped by namespace alias and named like the * node names they produce. */ writers: { "wfs": { "GetFeature": function(options) { var node = this.createElementNSPlus("wfs:GetFeature", { attributes: { service: "WFS", version: this.version, handle: options && options.handle, outputFormat: options && options.outputFormat, maxFeatures: options && options.maxFeatures, "xsi:schemaLocation": this.schemaLocationAttr(options) } }); if (typeof this.featureType == "string") { this.writeNode("Query", options, node); } else { for (var i=0,len = this.featureType.length; i<len; i++) { options.featureType = this.featureType[i]; this.writeNode("Query", options, node); } } return node; }, "Transaction": function(obj) { obj = obj || {}; var options = obj.options || {}; var node = this.createElementNSPlus("wfs:Transaction", { attributes: { service: "WFS", version: this.version, handle: options.handle } }); var i, len; var features = obj.features; if(features) { // temporarily re-assigning geometry types if (options.multi === true) { OpenLayers.Util.extend(this.geometryTypes, { "OpenLayers.Geometry.Point": "MultiPoint", "OpenLayers.Geometry.LineString": (this.multiCurve === true) ? "MultiCurve": "MultiLineString", "OpenLayers.Geometry.Polygon": (this.multiSurface === true) ? "MultiSurface" : "MultiPolygon" }); } var name, feature; for(i=0, len=features.length; i<len; ++i) { feature = features[i]; name = this.stateName[feature.state]; if(name) { this.writeNode(name, { feature: feature, options: options }, node); } } // switch back to original geometry types assignment if (options.multi === true) { this.setGeometryTypes(); } } if (options.nativeElements) { for (i=0, len=options.nativeElements.length; i<len; ++i) { this.writeNode("wfs:Native", options.nativeElements[i], node); } } return node; }, "Native": function(nativeElement) { var node = this.createElementNSPlus("wfs:Native", { attributes: { vendorId: nativeElement.vendorId, safeToIgnore: nativeElement.safeToIgnore }, value: nativeElement.value }); return node; }, "Insert": function(obj) { var feature = obj.feature; var options = obj.options; var node = this.createElementNSPlus("wfs:Insert", { attributes: { handle: options && options.handle } }); this.srsName = this.getSrsName(feature); this.writeNode("feature:_typeName", feature, node); return node; }, "Update": function(obj) { var feature = obj.feature; var options = obj.options; var node = this.createElementNSPlus("wfs:Update", { attributes: { handle: options && options.handle, typeName: (this.featureNS ? this.featurePrefix + ":" : "") + this.featureType } }); if(this.featureNS) { node.setAttribute("xmlns:" + this.featurePrefix, this.featureNS); } // add in geometry var modified = feature.modified; if (this.geometryName !== null && (!modified || modified.geometry !== undefined)) { this.srsName = this.getSrsName(feature); this.writeNode( "Property", {name: this.geometryName, value: feature.geometry}, node ); } // add in attributes for(var key in feature.attributes) { if(feature.attributes[key] !== undefined && (!modified || !modified.attributes || (modified.attributes && modified.attributes[key] !== undefined))) { this.writeNode( "Property", {name: key, value: feature.attributes[key]}, node ); } } // add feature id filter this.writeNode("ogc:Filter", new OpenLayers.Filter.FeatureId({ fids: [feature.fid] }), node); return node; }, "Property": function(obj) { var node = this.createElementNSPlus("wfs:Property"); this.writeNode("Name", obj.name, node); if(obj.value !== null) { this.writeNode("Value", obj.value, node); } return node; }, "Name": function(name) { return this.createElementNSPlus("wfs:Name", {value: name}); }, "Value": function(obj) { var node; if(obj instanceof OpenLayers.Geometry) { node = this.createElementNSPlus("wfs:Value"); var geom = this.writeNode("feature:_geometry", obj).firstChild; node.appendChild(geom); } else { node = this.createElementNSPlus("wfs:Value", {value: obj}); } return node; }, "Delete": function(obj) { var feature = obj.feature; var options = obj.options; var node = this.createElementNSPlus("wfs:Delete", { attributes: { handle: options && options.handle, typeName: (this.featureNS ? this.featurePrefix + ":" : "") + this.featureType } }); if(this.featureNS) { node.setAttribute("xmlns:" + this.featurePrefix, this.featureNS); } this.writeNode("ogc:Filter", new OpenLayers.Filter.FeatureId({ fids: [feature.fid] }), node); return node; } } }, /** * Method: schemaLocationAttr * Generate the xsi:schemaLocation attribute value. * * Returns: * {String} The xsi:schemaLocation attribute or undefined if none. */ schemaLocationAttr: function(options) { options = OpenLayers.Util.extend({ featurePrefix: this.featurePrefix, schema: this.schema }, options); var schemaLocations = OpenLayers.Util.extend({}, this.schemaLocations); if(options.schema) { schemaLocations[options.featurePrefix] = options.schema; } var parts = []; var uri; for(var key in schemaLocations) { uri = this.namespaces[key]; if(uri) { parts.push(uri + " " + schemaLocations[key]); } } var value = parts.join(" ") || undefined; return value; }, /** * Method: setFilterProperty * Set the property of each spatial filter. * * Parameters: * filter - {<OpenLayers.Filter>} */ setFilterProperty: function(filter) { if(filter.filters) { for(var i=0, len=filter.filters.length; i<len; ++i) { OpenLayers.Format.WFST.v1.prototype.setFilterProperty.call(this, filter.filters[i]); } } else { if(filter instanceof OpenLayers.Filter.Spatial && !filter.property) { // got a spatial filter without property, so set it filter.property = this.geometryName; } } }, CLASS_NAME: "OpenLayers.Format.WFST.v1" });
agpl-3.0
akuhtz/serial-communication-manager
tests/test57-list-usb-ports/src/test57/Test57.java
4389
/* * This file is part of SerialPundit. * * Copyright (C) 2014-2018, Rishi Gupta. All rights reserved. * * The SerialPundit is DUAL LICENSED. It is made available under the terms of the GNU Affero * General Public License (AGPL) v3.0 for non-commercial use and under the terms of a commercial * license for commercial use of this software. * * The SerialPundit is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. */ package test57; import com.serialpundit.usb.SerialComUSB; import com.serialpundit.usb.SerialComUSBdevice; public class Test57 { public static void main(String[] args) { try { SerialComUSB scusb = new SerialComUSB(null, null); SerialComUSBdevice[] usbDevices = scusb.listUSBdevicesWithInfo(SerialComUSB.V_ALL); for(int x=0; x< usbDevices.length; x++) { usbDevices[x].dumpDeviceInfo(); } }catch (Exception e) { e.printStackTrace(); } try { SerialComUSB scusb = new SerialComUSB(null, null); SerialComUSBdevice[] usbDevices; usbDevices = scusb.listUSBdevicesWithInfo(SerialComUSB.V_FTDI); for(int x=0; x< usbDevices.length; x++) { usbDevices[x].dumpDeviceInfo(); } }catch (Exception e) { e.printStackTrace(); } try { SerialComUSB scusb = new SerialComUSB(null, null); SerialComUSBdevice[] usbDevices; usbDevices = scusb.listUSBdevicesWithInfo(SerialComUSB.V_PL); for(int x=0; x< usbDevices.length; x++) { usbDevices[x].dumpDeviceInfo(); } }catch (Exception e) { e.printStackTrace(); } try { SerialComUSB scusb = new SerialComUSB(null, null); for(long a=0; a<50000; a++) { scusb.listUSBdevicesWithInfo(SerialComUSB.V_ALL); } }catch (Exception e) { e.printStackTrace(); } System.out.println("done"); } } /* Vendor id : 0x0403 Product id : 0x6001 Serial number : A7036479 Product : FT232R USB UART Manufacturer : FTDI Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(3)#USB(3)-Port_#0003.Hub_#0002 Vendor id : 0x04CA Product id : 0x0061 Serial number : 5&2768E75C&0&4 Product : USB Optical Mouse Manufacturer : (Standard system devices) Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(4)-Port_#0004.Hub_#0001 Vendor id : 0x04D8 Product id : 0x00DF Serial number : 0000980371 Product : MCP2200 USB Serial Port Emulator Manufacturer : (Standard USB Host Controller) Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(2)-Port_#0002.Hub_#0001 Vendor id : 0x067B Product id : 0x2303 Serial number : 6&3A94452&0&2 Product : USB-Serial Controller C Manufacturer : Prolific Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(3)#USB(2)-Port_#0002.Hub_#0002 Vendor id : 0x105B Product id : 0xE065 Serial number : 1C3E84E539E2 Product : BCM43142A0 Manufacturer : Broadcom Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(7)-Port_#0007.Hub_#0001 Vendor id : 0x10C4 Product id : 0xEA60 Serial number : 0001 Product : CP2102 USB to UART Bridge Controller Manufacturer : Silicon Laboratories Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(3)#USB(1)-Port_#0001.Hub_#0002 Vendor id : 0x174F Product id : 0x1474 Serial number : LENOVO_EASYCAMERA Product : Lenovo EasyCamera Manufacturer : (Standard USB Host Controller) Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(1)-Port_#0001.Hub_#0001 Vendor id : 0x4348 Product id : 0x5523 Serial number : 6&3A94452&0&4 Product : USB-SER! Manufacturer : wch.cn Location : PCIROOT(0)#PCI(1400)#USBROOT(0)#USB(3)#USB(4)-Port_#0004.Hub_#0002 */ /* * Vendor id : 0x174f Product id : 0x1474 Serial number : Lenovo EasyCamera Product : Lenovo EasyCamera Manufacturer : Lenovo EasyCamera Location : /devices/pci0000:00/0000:00:14.0/usb3/3-1 Vendor id : 0x0403 Product id : 0x6001 Serial number : A602RDCH Product : FT232R USB UART Manufacturer : FTDI Location : /devices/pci0000:00/0000:00:14.0/usb3/3-2 Vendor id : 0x0403 Product id : 0x6001 Serial number : A70362A3 Product : FT232R USB UART Manufacturer : FTDI Location : /devices/pci0000:00/0000:00:14.0/usb3/3-3 Vendor id : 0x04ca Product id : 0x0061 Serial number : --- Product : USB Optical Mouse Manufacturer : PixArt Location : /devices/pci0000:00/0000:00:14.0/usb3/3-4 Vendor id : 0x105b Product id : 0xe065 Serial number : 1C3E84E539E2 Product : BCM43142A0 Manufacturer : Broadcom Corp Location : /devices/pci0000:00/0000:00:14.0/usb3/3-7 done */
agpl-3.0
PeerBay/PeerSocial
web/bower_components/blob-util/bin/dev-server.js
1493
#!/usr/bin/env node 'use strict'; var HTTP_PORT = 8001; var Promise = require('bluebird'); var request = require('request'); var http_server = require("http-server"); var fs = require('fs'); var indexfile = "./test/test.js"; var dotfile = "./test/.test-bundle.js"; var outfile = "./test/test-bundle.js"; var watchify = require("watchify"); var w = watchify(indexfile); w.on('update', bundle); bundle(); var filesWritten = false; var serverStarted = false; var readyCallback; function bundle() { var wb = w.bundle(); wb.on('error', function (err) { console.error(String(err)); }); wb.on("end", end); wb.pipe(fs.createWriteStream(dotfile)); function end() { fs.rename(dotfile, outfile, function (err) { if (err) { return console.error(err); } console.log('Updated:', outfile); filesWritten = true; checkReady(); }); } } function startServers(callback) { readyCallback = callback; Promise.resolve().then(function () { return http_server.createServer().listen(HTTP_PORT); }).then(function () { console.log('Tests: http://127.0.0.1:' + HTTP_PORT + '/test/index.html'); serverStarted = true; checkReady(); }).catch(function (err) { if (err) { console.log(err); process.exit(1); } }); } function checkReady() { if (filesWritten && serverStarted && readyCallback) { readyCallback(); } } if (require.main === module) { startServers(); } else { module.exports.start = startServers; }
agpl-3.0
dzc34/Asqatasun
rules/rules-seo1.0/src/main/java/org/asqatasun/rules/seo/SeoRule05011.java
2245
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.seo; import org.asqatasun.entity.audit.TestSolution; import org.asqatasun.ruleimplementation.link.AbstractLinkRuleImplementation; import org.asqatasun.rules.elementchecker.link.LinkPertinenceChecker; import org.asqatasun.rules.elementselector.LinkElementSelector; import static org.asqatasun.rules.keystore.AttributeStore.TITLE_ATTR; import static org.asqatasun.rules.keystore.HtmlElementStore.TEXT_ELEMENT2; import static org.asqatasun.rules.keystore.RemarkMessageStore.CHECK_LINK_PERTINENCE_MSG; import static org.asqatasun.rules.keystore.RemarkMessageStore.UNEXPLICIT_LINK_MSG; /** * Is each text of a text link explicit out of context (except in special cases)? * * @author jkowalczyk */ public class SeoRule05011 extends AbstractLinkRuleImplementation { /** * Default constructor */ public SeoRule05011 () { // context is not taken into consideration super(new LinkElementSelector(false), new LinkPertinenceChecker( // not pertinent solution TestSolution.FAILED, // not pertinent message UNEXPLICIT_LINK_MSG, // manual check message CHECK_LINK_PERTINENCE_MSG, // evidence elements TEXT_ELEMENT2, TITLE_ATTR ), null); } }
agpl-3.0
NicolasEYSSERIC/Silverpeas-Components
kmelia/kmelia-ejb/src/main/java/com/silverpeas/kmelia/dao/TopicSearchDaoImpl.java
3603
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.kmelia.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import javax.inject.Named; import org.springframework.jdbc.core.PreparedStatementCreator; import org.springframework.jdbc.core.simple.ParameterizedRowMapper; import org.springframework.jdbc.core.support.JdbcDaoSupport; import com.silverpeas.kmelia.model.MostInterestedQueryVO; import com.stratelia.webactiv.util.ResourceLocator; /** * This class is the Jdbc Dao implementation of TopicSearchDao * @author ebonnet */ @Named("topicSearchDao") public class TopicSearchDaoImpl extends JdbcDaoSupport implements TopicSearchDao { private static final String QUERY_GET_LIST_MOST_INTERESTED_QUERY = "SELECT count(*) as nb, query FROM sc_kmelia_search WHERE instanceid = ? GROUP BY query, language ORDER BY nb DESC, query"; private static ResourceLocator settings = new ResourceLocator("com.stratelia.webactiv.kmelia.settings.kmeliaSettings", "fr"); @Override public List<MostInterestedQueryVO> getMostInterestedSearch(String instanceId) { // Set the max number of result to retrieve getJdbcTemplate().setMaxRows( settings.getInteger("kmelia.stats.most.interested.query.limit", 10)); return getJdbcTemplate().query(new MyPreparedStatementCreator(instanceId), new MostInterestedQueryRowMapper()); } private static class MostInterestedQueryRowMapper implements ParameterizedRowMapper<MostInterestedQueryVO> { @Override public MostInterestedQueryVO mapRow(ResultSet rs, int rowNum) throws SQLException { MostInterestedQueryVO interestedQuery = new MostInterestedQueryVO(rs.getString("query"), rs.getInt("nb")); return interestedQuery; } } /** * Inner class to create a Spring PreparedStatementCreator object */ class MyPreparedStatementCreator implements PreparedStatementCreator { private String instanceId; public MyPreparedStatementCreator(String instanceId) { this.instanceId = instanceId; } public PreparedStatement createPreparedStatement(Connection connection) throws SQLException { PreparedStatement ps = connection.prepareStatement(QUERY_GET_LIST_MOST_INTERESTED_QUERY); ps.setString(1, getInstanceId()); return ps; } /** * @return the instanceId */ public String getInstanceId() { return instanceId; } } }
agpl-3.0
David-Development/ownCloud-Account-Importer
src/main/java/com/nextcloud/android/sso/api/NextcloudRetrofitServiceMethod.java
14852
package com.nextcloud.android.sso.api; import android.util.Log; import androidx.annotation.Nullable; import com.nextcloud.android.sso.aidl.NextcloudRequest; import com.nextcloud.android.sso.helper.Okhttp3Helper; import com.nextcloud.android.sso.helper.ReactivexHelper; import com.nextcloud.android.sso.helper.Retrofit2Helper; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.lang.annotation.Annotation; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.security.InvalidParameterException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.reactivex.Completable; import io.reactivex.Observable; import okhttp3.Headers; import okhttp3.MediaType; import okhttp3.MultipartBody; import okhttp3.RequestBody; import okhttp3.ResponseBody; import okio.Buffer; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.DELETE; import retrofit2.http.Field; import retrofit2.http.FieldMap; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.HEAD; import retrofit2.http.HTTP; import retrofit2.http.Header; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.Streaming; public class NextcloudRetrofitServiceMethod<T> { private static String TAG = NextcloudRetrofitServiceMethod.class.getCanonicalName(); private final Annotation[][] parameterAnnotationsArray; // Upper and lower characters, digits, underscores, and hyphens, starting with a character. private static final String PARAM = "[a-zA-Z][a-zA-Z0-9_-]*"; private static final Pattern PARAM_URL_REGEX = Pattern.compile("\\{(" + PARAM + ")\\}"); private Method method; private String httpMethod; private @Nullable String relativeUrl; private @Nullable Headers headers; private Type returnType; private boolean followRedirects = false; private Map<String, String> queryParameters; private final NextcloudRequest.Builder requestBuilder; private boolean isMultipart = false; private boolean isFormEncoded = false; public NextcloudRetrofitServiceMethod(String apiEndpoint, Method method) { this.method = method; this.returnType = method.getGenericReturnType(); Annotation[] methodAnnotations = method.getAnnotations(); this.parameterAnnotationsArray = method.getParameterAnnotations(); for (Annotation annotation : methodAnnotations) { parseMethodAnnotation(annotation); } this.queryParameters = parsePathParameters(); if(headers == null) { headers = new Headers.Builder().build(); } requestBuilder = new NextcloudRequest.Builder() .setMethod(httpMethod) .setHeader(headers.toMultimap()) .setFollowRedirects(followRedirects) .setUrl(new File(apiEndpoint, relativeUrl).toString()); Log.d(TAG, "NextcloudRetrofitServiceMethod() called with: apiEndpoint = [" + apiEndpoint + "], method = [" + method + "]"); } public T invoke(NextcloudAPI nextcloudAPI, Object[] args) throws Exception { if(parameterAnnotationsArray.length != args.length) { throw new InvalidParameterException("Expected: " + parameterAnnotationsArray.length + " params - were: " + args.length); } NextcloudRequest.Builder rBuilder = new NextcloudRequest.Builder(requestBuilder); Map<String, String> parameters = new HashMap<>(); // Copy all static query params into parameters array parameters.putAll(this.queryParameters); MultipartBody.Builder multipartBuilder = null; if (isMultipart) { multipartBuilder = new MultipartBody.Builder(); } // Build/parse dynamic parameters for(int i = 0; i < parameterAnnotationsArray.length; i++) { Annotation annotation = parameterAnnotationsArray[i][0]; if(annotation instanceof Query) { parameters.put(((Query)annotation).value(), String.valueOf(args[i])); } else if(annotation instanceof Body) { rBuilder.setRequestBody(nextcloudAPI.getGson().toJson(args[i])); } else if(annotation instanceof Path) { String varName = "{" + ((Path)annotation).value() + "}"; String url = rBuilder.build().getUrl(); rBuilder.setUrl(url.replace(varName, String.valueOf(args[i]))); } else if(annotation instanceof Header) { Object value = args[i]; String key =((Header) annotation).value(); addHeader(rBuilder, key, value); } else if(annotation instanceof FieldMap) { if(args[i] != null) { Map<String, Object> fieldMap = (HashMap<String, Object>) args[i]; for (String key : fieldMap.keySet()) { parameters.put(key, fieldMap.get(key).toString()); } } } else if(annotation instanceof Field) { if(args[i] != null) { String field = args[i].toString(); parameters.put(((Field)annotation).value(), field); } } else if(annotation instanceof Part) { if (args[i] instanceof MultipartBody.Part){ multipartBuilder.addPart((MultipartBody.Part) args[i]); } else { throw new IllegalArgumentException("Only MultipartBody.Part type is supported as a @Part"); } } else { throw new UnsupportedOperationException("don't know this type yet.. [" + annotation + "]"); } } // include multipart body as stream, set header if (isMultipart) { MultipartBody multipartBody = multipartBuilder.build(); addHeader(rBuilder, "Content-Type", MultipartBody.FORM+"; boundary="+multipartBody.boundary()); rBuilder.setRequestBodyAsStream(bodyToStream(multipartBody)); } NextcloudRequest request = rBuilder .setParameter(parameters) .build(); if(this.returnType instanceof ParameterizedType) { ParameterizedType type = (ParameterizedType) returnType; Type ownerType = type.getRawType(); if(ownerType == Observable.class) { Type typeArgument = type.getActualTypeArguments()[0]; Log.d(TAG, "invoke call to api using observable " + typeArgument); // Streaming if(typeArgument == ResponseBody.class) { return (T) Observable.just(Okhttp3Helper.getResponseBodyFromRequest(nextcloudAPI, request)); } else if (typeArgument instanceof ParameterizedType) { ParameterizedType innerType = (ParameterizedType) typeArgument; Type innerOwnerType = innerType.getRawType(); if(innerOwnerType == ParsedResponse.class) { return (T) nextcloudAPI.performRequestObservableV2(innerType.getActualTypeArguments()[0], request); } } //fallback return (T) nextcloudAPI.performRequestObservableV2(typeArgument, request).map(r -> r.getResponse()); } else if(ownerType == Call.class) { Type typeArgument = type.getActualTypeArguments()[0]; return (T) Retrofit2Helper.WrapInCall(nextcloudAPI, request, typeArgument); } } else if(this.returnType == Observable.class) { return (T) nextcloudAPI.performRequestObservableV2(Object.class, request).map(r -> r.getResponse()); } else if (this.returnType == Completable.class) { return (T) ReactivexHelper.wrapInCompletable(nextcloudAPI, request); } return nextcloudAPI.performRequestV2(this.returnType, request); } private void addHeader(NextcloudRequest.Builder rBuilder, String key, Object value) { if (key == null || value == null) { Log.d(TAG, "WARNING: Header not set - key or value missing! Key: " + key + " | Value: " + value); return; } Map<String, List<String>> headers = rBuilder.build().getHeader(); List<String> arg = new ArrayList<>(); arg.add(String.valueOf(value)); headers.put(key, arg); rBuilder.setHeader(headers); } private static InputStream bodyToStream(final RequestBody request){ try { final RequestBody copy = request; final Buffer buffer = new Buffer(); copy.writeTo(buffer); return buffer.inputStream(); } catch (final IOException e) { throw new IllegalStateException("failed to build request-body", e); } } private void parseMethodAnnotation(Annotation annotation) { if (annotation instanceof DELETE) { parseHttpMethodAndPath("DELETE", ((DELETE) annotation).value(), false); } else if (annotation instanceof GET) { parseHttpMethodAndPath("GET", ((GET) annotation).value(), false); } else if (annotation instanceof POST) { parseHttpMethodAndPath("POST", ((POST) annotation).value(), true); } else if (annotation instanceof PUT) { parseHttpMethodAndPath("PUT", ((PUT) annotation).value(), true); } else if (annotation instanceof HEAD) { parseHttpMethodAndPath("HEAD", ((HEAD) annotation).value(), false); } else if (annotation instanceof HTTP) { HTTP http = (HTTP) annotation; parseHttpMethodAndPath(http.method(), http.path(), http.hasBody()); } else if (annotation instanceof Multipart) { if (isFormEncoded) { throw methodError(method, "Only one encoding annotation is allowed."); } isMultipart = true; } else if (annotation instanceof FormUrlEncoded) { if (isMultipart) { throw methodError(method, "Only one encoding annotation is allowed."); } isFormEncoded = true; } else if (annotation instanceof Streaming) { Log.v(TAG, "streaming interface"); } else if (annotation instanceof retrofit2.http.Headers) { String[] headersToParse = ((retrofit2.http.Headers) annotation).value(); if (headersToParse.length == 0) { throw methodError(method, "@Headers annotation is empty."); } headers = parseHeaders(headersToParse); } else if(annotation instanceof FormUrlEncoded) { //formUrlEncoded = true; Log.v(TAG, "FormUrlEncoded request"); } else if(annotation instanceof NextcloudAPI.FollowRedirects) { followRedirects = true; } else { throw new UnsupportedOperationException(String.valueOf(annotation)); } } private void parseHttpMethodAndPath(String httpMethod, String value, boolean hasBody) { if (this.httpMethod != null) { throw methodError(method, "Only one HTTP method is allowed. Found: %s and %s.", this.httpMethod, httpMethod); } this.httpMethod = httpMethod; if (value.isEmpty()) { return; } this.relativeUrl = value; } private Headers parseHeaders(String[] headers) { Headers.Builder builder = new Headers.Builder(); for (String header : headers) { int colon = header.indexOf(':'); if (colon == -1 || colon == 0 || colon == header.length() - 1) { throw methodError(method, "@Headers value must be in the form \"Name: Value\". Found: \"%s\"", header); } String headerName = header.substring(0, colon); String headerValue = header.substring(colon + 1).trim(); if ("Content-Type".equalsIgnoreCase(headerName)) { try { MediaType.parse(headerValue); } catch (IllegalArgumentException e) { throw methodError(method, e, "Malformed content type: %s", headerValue); } } else { builder.add(headerName, headerValue); } } return builder.build(); } /** * Gets the set of unique path parameters used in the given URI. If a parameter is used twice * in the URI, it will only show up once in the set. */ private Map<String, String> parsePathParameters() { Map<String, String> queryPairs = new LinkedHashMap<>(); if(this.relativeUrl == null) { return queryPairs; } int idxQuery = this.relativeUrl.indexOf("?"); if (idxQuery != -1 && idxQuery < this.relativeUrl.length() - 1) { // Ensure the query string does not have any named parameters. String query = this.relativeUrl.substring(idxQuery + 1); // Check for named parameters Matcher queryParamMatcher = PARAM_URL_REGEX.matcher(query); if (queryParamMatcher.find()) { throw methodError(method, "URL query string \"%s\" must not have replace block. " + "For dynamic query parameters use @Query.", query); } // If none found.. parse the static query parameters String[] pairs = query.split("&"); for (String pair : pairs) { int idx = pair.indexOf("="); queryPairs.put(pair.substring(0, idx), pair.substring(idx + 1)); } // Remove query params from url this.relativeUrl = this.relativeUrl.substring(0, idxQuery); } return queryPairs; } private static RuntimeException methodError(Method method, String message, Object... args) { return methodError(method, null, message, args); } private static RuntimeException methodError(Method method, @Nullable Throwable cause, String message, Object... args) { String formattedMessage = String.format(message, args); return new IllegalArgumentException(formattedMessage + "\n for method " + method.getDeclaringClass().getSimpleName() + "." + method.getName(), cause); } }
agpl-3.0
jzinedine/CMDBuild
core/src/main/java/org/cmdbuild/auth/AuthenticationStore.java
218
package org.cmdbuild.auth; import org.cmdbuild.services.auth.UserType; public interface AuthenticationStore { UserType getType(); void setType(UserType type); Login getLogin(); void setLogin(Login login); }
agpl-3.0
dmitr25/demobbed-viewer
js/nuEventsData/charm/loadEvent231062848.js
16236
demobbed.resetEvent(); demobbed.event().id(231062848); demobbed.event().date(1222594299000); demobbed.event().hitsTT()[0] = [ new HitTT(10000, -189.12, -477.78, 134.47), new HitTT(10001, -186.48, -477.78, 33.95), new HitTT(10002, -191.76, -477.78, 143.69), new HitTT(10003, -191.43, -464.38, 9.95), new HitTT(10004, -194.07, -464.38, 18.67), new HitTT(10005, -196.71, -464.38, 2.73), new HitTT(10006, -186.15, -464.38, 41.87), new HitTT(10007, -183.51, -464.38, 4.28), new HitTT(10008, -180.87, -464.38, 4.19), new HitTT(10009, -188.79, -464.38, 89.84), new HitTT(10010, -194.25, -450.98, 6.48), new HitTT(10011, -175.77, -450.98, 5.06), new HitTT(10012, -188.97, -450.98, 41.56), new HitTT(10013, -186.33, -450.98, 6.6), new HitTT(10014, -183.69, -450.98, 11.46), new HitTT(10015, -191.61, -450.98, 9.75), new HitTT(10016, -189.1, -437.58, 111.94), new HitTT(10017, -186.46, -437.58, 59.82), new HitTT(10018, -207.58, -437.58, 32.73), new HitTT(10019, -204.94, -437.58, 7.41), new HitTT(10020, -181.18, -437.58, 41.13), new HitTT(10021, -165, -437.58, 9.26), new HitTT(10022, -167.64, -437.58, 15.86), new HitTT(10023, -188.69, -424.18, 56.78), new HitTT(10024, -178.13, -424.18, 1.99), new HitTT(10025, -193.97, -424.18, 4.87), new HitTT(10026, -191.33, -424.18, 12.44), new HitTT(10027, -162.02, -424.18, 8.18), new HitTT(10028, -189.16, -410.78, 29.25), new HitTT(10029, -186.52, -410.78, 54.13), new HitTT(10030, -199.72, -410.78, 26.64), new HitTT(10031, -202.36, -410.78, 40.23), new HitTT(10032, -191.8, -410.78, 13.41), new HitTT(10033, -196.4, -397.38, 54.66), new HitTT(10034, -199.04, -397.38, 5.25), new HitTT(10035, -191.12, -397.38, 80.27), new HitTT(10036, -185.84, -397.38, 20.14), new HitTT(10037, -188.48, -397.38, 60.06), new HitTT(10038, -170, -397.38, 3.54), new HitTT(10039, -188.59, -383.98, 37.64), new HitTT(10040, -175.39, -383.98, 21.47), new HitTT(10041, -193.87, -383.98, 33.88), new HitTT(10042, -188.94, -370.58, 32.41), new HitTT(10043, -194.22, -370.58, 51.49), new HitTT(10044, -183.66, -370.58, 11.16), new HitTT(10045, -188.47, 161.59, 27.79), new HitTT(10046, -191.27, 174.99, 43.1), new HitTT(10047, -185.87, 188.39, 19.35), new HitTT(10048, -188.51, 188.39, 26.92), new HitTT(10049, -186.45, 201.79, 4.9), new HitTT(10050, -189.07, 215.19, 5.95), new HitTT(10051, -189.07, 228.59, 16.42), new HitTT(10052, -186.26, 241.99, 3.03), new HitTT(10053, -188.86, 255.39, 8.87), new HitTT(10054, -188.87, 268.79, 14.5), new HitTT(10055, -189.16, 282.19, 2.57), new HitTT(10056, -188.98, 295.59, 17.18), new HitTT(10057, -189.12, 308.99, 32.49), new HitTT(10058, -188.85, 322.39, 14.96), new HitTT(10059, -186.48, 335.79, 23.21), new HitTT(10060, -189.12, 335.79, 19.83), new HitTT(10061, -186.32, 349.19, 8.64), new HitTT(10062, -186.37, 362.59, 12.67), new HitTT(10063, -186.75, 375.99, 9.81), new HitTT(10064, -186.42, 389.39, 8.11), new HitTT(10065, -186.48, 402.79, 13.03), new HitTT(10066, -186.4, 416.19, 17.3), new HitTT(10067, -186.45, 429.59, 19.39), new HitTT(10068, -186.05, 442.99, 20.33), new HitTT(10069, -186.16, 456.39, 21.48), new HitTT(10070, -183.66, 483.19, 15.02), new HitTT(10071, -183.64, 496.59, 3.42), new HitTT(10072, -183.91, 509.99, 19.21), new HitTT(10073, -183.74, 523.39, 9.23), new HitTT(10074, -181.04, 536.79, 11.71), new HitTT(10075, -181.21, 550.19, 13.15), new HitTT(10076, -181.11, 563.59, 20.12) ]; demobbed.event().hitsTT()[1] = [ new HitTT(11000, -84.67, -479.24, 27.56), new HitTT(11001, -82.03, -479.24, 154.07), new HitTT(11002, -79.39, -479.24, 2.05), new HitTT(11003, -87.31, -479.24, 105.94), new HitTT(11004, -89.95, -479.24, 42.59), new HitTT(11005, -92.59, -479.24, 5.5), new HitTT(11006, -87.42, -465.84, 107.26), new HitTT(11007, -90.06, -465.84, 103.37), new HitTT(11008, -92.7, -465.84, 13.72), new HitTT(11009, -82.14, -465.84, 19.09), new HitTT(11010, -79.5, -465.84, 4.79), new HitTT(11011, -76.86, -465.84, 3.46), new HitTT(11012, -82.47, -452.44, 22.01), new HitTT(11013, -79.83, -452.44, 31.57), new HitTT(11014, -87.75, -452.44, 25.82), new HitTT(11015, -93.03, -452.44, 86.27), new HitTT(11016, -61, -439.04, 12.94), new HitTT(11017, -82.12, -439.04, 12.97), new HitTT(11018, -76.84, -439.04, 21.09), new HitTT(11019, -87.4, -439.04, 117.23), new HitTT(11020, -90.04, -439.04, 26.6), new HitTT(11021, -74.2, -439.04, 23.13), new HitTT(11022, -50.44, -439.04, 39.49), new HitTT(11023, -58.36, -439.04, 4.32), new HitTT(11024, -84.76, -439.04, 5.55), new HitTT(11025, -79.48, -439.04, 38.48), new HitTT(11026, -85.04, -425.64, 15.49), new HitTT(11027, -79.76, -425.64, 5.56), new HitTT(11028, -71.84, -425.64, 27.25), new HitTT(11029, -114.08, -425.64, 24.48), new HitTT(11030, -87.68, -425.64, 26.98), new HitTT(11031, -90.32, -425.64, 20.51), new HitTT(11032, -92.96, -425.64, 14.28), new HitTT(11033, -82.4, -425.64, 7.01), new HitTT(11034, -98.29, -412.24, 10.98), new HitTT(11035, -108.85, -412.24, 6.31), new HitTT(11036, -111.49, -412.24, 5.74), new HitTT(11037, -93.01, -412.24, 35.01), new HitTT(11038, -95.65, -412.24, 10.06), new HitTT(11039, -69.25, -412.24, 33.71), new HitTT(11040, -87.73, -412.24, 105.9), new HitTT(11041, -118.85, -398.84, 68.45), new HitTT(11042, -108.29, -398.84, 3.06), new HitTT(11043, -87.17, -398.84, 96.21), new HitTT(11044, -95.09, -398.84, 11.32), new HitTT(11045, -66.05, -398.84, 5.41), new HitTT(11046, -63.17, -385.44, 16.27), new HitTT(11047, -97.49, -385.44, 9.16), new HitTT(11048, -123.89, -385.44, 176.45), new HitTT(11049, -115.97, -385.44, 6.01), new HitTT(11050, -86.93, -385.44, 34.68), new HitTT(11051, -89.57, -385.44, 10.1), new HitTT(11052, -94.85, -385.44, 115.73), new HitTT(11053, -58.98, -372.04, 15.99), new HitTT(11054, -101.22, -372.04, 20.84), new HitTT(11055, -127.62, -372.04, 89.79), new HitTT(11056, -88.02, -372.04, 38.13), new HitTT(11057, -109.14, -372.04, 4.4), new HitTT(11058, -130.26, -372.04, 11.58), new HitTT(11059, 65.67, 160.13, 19.7), new HitTT(11060, 68.52, 173.53, 5.76), new HitTT(11061, 73.8, 173.53, 9.37), new HitTT(11062, 71.29, 186.93, 63.15), new HitTT(11063, 75.81, 200.33, 35.92), new HitTT(11064, 79.19, 213.73, 23.46), new HitTT(11065, 81.68, 227.13, 4.55), new HitTT(11066, 84.55, 240.53, 16.44), new HitTT(11067, 87.15, 253.93, 5.27), new HitTT(11068, 97.78, 267.33, 8.07), new HitTT(11069, 89.86, 267.33, 14.97), new HitTT(11070, 87.22, 267.33, 14.21), new HitTT(11071, 92.55, 280.73, 16.56), new HitTT(11072, 95.26, 294.13, 36.48), new HitTT(11073, 100.37, 307.53, 22.5), new HitTT(11074, 102.85, 320.93, 17.43), new HitTT(11075, 105.16, 334.33, 48.9), new HitTT(11076, 107.98, 347.73, 3.26), new HitTT(11077, 110.68, 361.13, 7.34), new HitTT(11078, 113.32, 361.13, 11.46), new HitTT(11079, 121.24, 361.13, 1.23), new HitTT(11080, 115.84, 374.53, 25.74), new HitTT(11081, 118.84, 387.93, 20.59), new HitTT(11082, 124.24, 401.33, 20.8), new HitTT(11083, 127, 414.73, 15.24), new HitTT(11084, 129.67, 428.13, 18.82), new HitTT(11085, 135.02, 441.53, 21.52), new HitTT(11086, 137.65, 454.93, 7.52), new HitTT(11087, 140.39, 468.33, 14.07), new HitTT(11088, 145.45, 481.73, 15.37), new HitTT(11089, 148.13, 495.13, 49.73), new HitTT(11090, 153.12, 508.53, 21.07), new HitTT(11091, 155.48, 521.93, 10.87), new HitTT(11092, 160.95, 535.33, 10.43), new HitTT(11093, 164.22, 548.73, 37.63), new HitTT(11094, 166.87, 562.13, 18.8) ]; demobbed.event().hitsRPC()[0] = [ new HitRPC(20000, -191.8, -261.48, 10.4), new HitRPC(20001, -171, -261.48, 15.6), new HitRPC(20002, -91.7, -261.48, 7.8), new HitRPC(20003, -189.2, -254.48, 5.2), new HitRPC(20004, -173.6, -254.48, 15.6), new HitRPC(20005, -189.2, -247.48, 5.2), new HitRPC(20006, -189.2, -240.48, 5.2), new HitRPC(20007, -189.2, -233.48, 5.2), new HitRPC(20008, -189.2, -226.48, 5.2), new HitRPC(20009, -189.2, -219.48, 5.2), new HitRPC(20010, -189.2, -212.48, 5.2), new HitRPC(20011, -187.9, -205.48, 2.6), new HitRPC(20012, -189.2, -198.48, 5.2), new HitRPC(20013, -189.2, -191.48, 5.2), new HitRPC(20014, -185.3, -60.18, 2.6), new HitRPC(20015, -182.7, -53.18, 2.6), new HitRPC(20016, -185.3, -46.18, 2.6), new HitRPC(20017, -184, -39.18, 5.2), new HitRPC(20018, -186.6, -32.18, 10.4), new HitRPC(20019, -184, -25.18, 5.2), new HitRPC(20020, -184, -11.18, 5.2), new HitRPC(20021, -184, -4.18, 5.2), new HitRPC(20022, -184, 2.82, 5.2), new HitRPC(20023, -184, 9.82, 5.2), new HitRPC(20024, -174.7, 672.71, 2.6), new HitRPC(20025, -174.7, 679.71, 7.8), new HitRPC(20026, -174.7, 686.71, 2.6), new HitRPC(20027, -174.7, 693.71, 7.8), new HitRPC(20028, -172.1, 700.71, 2.6), new HitRPC(20029, -172.1, 707.71, 2.6), new HitRPC(20030, -172.1, 714.71, 2.6), new HitRPC(20031, -170.8, 728.71, 5.2), new HitRPC(20032, -169.5, 735.71, 2.6), new HitRPC(20033, -169.5, 742.71, 2.6), new HitRPC(20034, -112.3, 874.01, 2.6), new HitRPC(20035, -153.9, 888.01, 2.6), new HitRPC(20036, -152.6, 895.01, 5.2), new HitRPC(20037, -151.3, 909.01, 2.6), new HitRPC(20038, -151.3, 916.01, 2.6), new HitRPC(20039, -151.3, 923.01, 2.6), new HitRPC(20040, -151.3, 930.01, 2.6), new HitRPC(20041, -151.3, 937.01, 2.6), new HitRPC(20042, -151.3, 944.01, 2.6) ]; demobbed.event().hitsRPC()[1] = [ new HitRPC(21000, -179.7, -261.48, 3.5), new HitRPC(21001, -127.2, -261.48, 3.5), new HitRPC(21002, -87.45, -261.48, 35), new HitRPC(21003, -33.2, -261.48, 3.5), new HitRPC(21004, -99.7, -254.48, 3.5), new HitRPC(21005, -89.2, -254.48, 3.5), new HitRPC(21006, -80.45, -254.48, 7), new HitRPC(21007, -29.7, -254.48, 3.5), new HitRPC(21008, -29.7, -247.48, 3.5), new HitRPC(21009, -26.2, -240.48, 3.5), new HitRPC(21010, -26.2, -233.48, 3.5), new HitRPC(21011, -22.7, -226.48, 3.5), new HitRPC(21012, -22.7, -219.48, 3.5), new HitRPC(21013, -19.2, -212.48, 3.5), new HitRPC(21014, -19.2, -205.48, 3.5), new HitRPC(21015, -15.7, -198.48, 3.5), new HitRPC(21016, -15.7, -191.48, 3.5), new HitRPC(21017, 15.3, -60.18, 3.5), new HitRPC(21018, 18.8, -53.18, 3.5), new HitRPC(21019, 18.8, -46.18, 3.5), new HitRPC(21020, 18.8, -39.18, 3.5), new HitRPC(21021, 20.55, -32.18, 7), new HitRPC(21022, 22.3, -25.18, 3.5), new HitRPC(21023, 25.8, -11.18, 3.5), new HitRPC(21024, 29.3, -4.18, 3.5), new HitRPC(21025, 29.3, 2.82, 3.5), new HitRPC(21026, 32.8, 9.82, 3.5), new HitRPC(21027, 196.3, 672.71, 3.5), new HitRPC(21028, 199.8, 679.71, 3.5), new HitRPC(21029, 199.8, 686.71, 3.5), new HitRPC(21030, 203.3, 693.71, 3.5), new HitRPC(21031, 203.3, 700.71, 3.5), new HitRPC(21032, 206.8, 707.71, 3.5), new HitRPC(21033, 210.3, 714.71, 3.5), new HitRPC(21034, 213.8, 728.71, 3.5), new HitRPC(21035, 213.8, 735.71, 3.5), new HitRPC(21036, 217.3, 742.71, 3.5), new HitRPC(21037, 307.8, 874.01, 3.5), new HitRPC(21038, 255.3, 888.01, 3.5), new HitRPC(21039, 257.05, 895.01, 7), new HitRPC(21040, 258.8, 902.01, 3.5), new HitRPC(21041, 262.3, 909.01, 3.5), new HitRPC(21042, 262.3, 916.01, 3.5), new HitRPC(21043, 262.3, 923.01, 3.5), new HitRPC(21044, 265.8, 930.01, 3.5), new HitRPC(21045, 265.8, 937.01, 3.5), new HitRPC(21046, 269.3, 944.01, 3.5) ]; demobbed.event().hitsDT()[0] = [ new HitDT(30000, 217.32, -359.62, 0.84), new HitDT(30001, -181.68, -359.62, 1.35), new HitDT(30002, -190.08, -359.62, 1.42), new HitDT(30003, -194.28, -359.62, 0.55), new HitDT(30004, -152.28, -359.62, 0.53), new HitDT(30005, -183.78, -355.98, 1.24), new HitDT(30006, -187.98, -355.98, 0.56), new HitDT(30007, -200.58, -355.98, 0.7), new HitDT(30008, -196.38, -355.98, 0.97), new HitDT(30009, -150.18, -355.98, 0.89), new HitDT(30010, -25.28, -351.92, 1.1), new HitDT(30011, -239.48, -351.92, 1.38), new HitDT(30012, -180.68, -351.92, 1.69), new HitDT(30013, -189.08, -351.92, 0.59), new HitDT(30014, -197.48, -351.92, 1.69), new HitDT(30015, -147.08, -351.92, 0.54), new HitDT(30016, 128.02, -348.28, 1.36), new HitDT(30017, -195.38, -348.28, 0.8), new HitDT(30018, -182.78, -348.28, 0.95), new HitDT(30019, -186.98, -348.28, 1.07), new HitDT(30020, -140.78, -348.28, 1.52), new HitDT(30021, -199.23, -289.45, 1.41), new HitDT(30022, -186.63, -289.45, 0.6), new HitDT(30023, -178.23, -289.45, 1.3), new HitDT(30024, -94.23, -289.45, 1.31), new HitDT(30025, -184.53, -285.81, 1.82), new HitDT(30026, -176.13, -285.81, 0.8), new HitDT(30027, -188.73, -285.81, 0.97), new HitDT(30028, -201.33, -285.81, 0.72), new HitDT(30029, -87.93, -285.81, 1.3), new HitDT(30030, -202.43, -281.75, 1.35), new HitDT(30031, -189.83, -281.75, 0.6), new HitDT(30032, -185.63, -281.75, 0.79), new HitDT(30033, -177.23, -281.75, 0.98), new HitDT(30034, -84.83, -281.75, 1), new HitDT(30035, -175.13, -278.11, 1.07), new HitDT(30036, -187.73, -278.11, 1.65), new HitDT(30037, -200.33, -278.11, 1.14), new HitDT(30038, -82.73, -278.11, 0.51), new HitDT(30039, -189.05, -174.98, 0.63), new HitDT(30040, 428.35, -174.79, 1.25), new HitDT(30041, -190.15, -170.92, 1.11), new HitDT(30042, 427.25, -170.73, 1.82), new HitDT(30043, -188.05, -167.28, 0.69), new HitDT(30044, -185.79, -84.67, 0.7), new HitDT(30045, -187.89, -81.03, 1.77), new HitDT(30046, -184.79, -76.97, 1.37), new HitDT(30047, -186.89, -73.33, 1.04), new HitDT(30048, -187.03, 22.97, 1.71), new HitDT(30049, -184.93, 26.61, 0.72), new HitDT(30050, -186.03, 30.67, 0.77), new HitDT(30051, -183.92, 34.31, 1.68), new HitDT(30052, -188.39, 124.04, 1.53), new HitDT(30053, -186.29, 127.68, 0.86), new HitDT(30054, -187.39, 131.74, 0.64), new HitDT(30055, -185.29, 135.38, 0.99), new HitDT(30056, -181.25, 574.18, 1.15), new HitDT(30057, -179.15, 577.82, 1.05), new HitDT(30058, -180.25, 581.88, 0.69), new HitDT(30059, -178.15, 585.52, 0.88), new HitDT(30060, -102.55, 585.48, 1.3), new HitDT(30061, -123.53, 644.19, 1.74), new HitDT(30062, -178.13, 644.22, 1.36), new HitDT(30063, -176.03, 647.86, 0.83), new HitDT(30064, -177.13, 651.92, 0.84), new HitDT(30065, -175.03, 655.56, 1.36), new HitDT(30066, -170.04, 755.51, 1.65), new HitDT(30067, 329.6, 755.26, 1.82), new HitDT(30068, 380, 755.23, 1.77), new HitDT(30069, -167.94, 759.15, 0.56), new HitDT(30070, 382.1, 758.87, 1.76), new HitDT(30071, 428.3, 758.85, 1.81), new HitDT(30072, -169.03, 763.21, 1.49), new HitDT(30073, 427.2, 762.91, 1.81), new HitDT(30074, 381, 762.93, 1.78), new HitDT(30075, -166.93, 766.85, 0.63), new HitDT(30076, 399.91, 766.56, 1.82), new HitDT(30077, 395.71, 766.57, 1.82), new HitDT(30078, 378.91, 766.57, 1.78), new HitDT(30079, 377.51, 849.13, 1.82), new HitDT(30080, 427.91, 849.09, 1.82), new HitDT(30081, -158.13, 853.15, 0.73), new HitDT(30082, 374.32, 856.84, 1.82), new HitDT(30083, -157.13, 860.85, 0.64), new HitDT(30084, 426.82, 860.43, 0.01), new HitDT(30085, -152.91, 956.84, 1.25), new HitDT(30086, -150.81, 960.48, 1.19), new HitDT(30087, -151.91, 964.54, 0.56), new HitDT(30088, -275.81, 968.27, 1.82), new HitDT(30089, -155.36, 1058.17, 0.68), new HitDT(30090, -154.36, 1065.87, 0.99), new HitDT(30091, -156.46, 1069.51, 1.21) ]; demobbed.event().verticesECC([ new Vertex([ 45057.0, 4931.5, 65628.8], [ -188.001, -86.292, -483.13]), new Vertex([ 44812.0, 4909.0, 68321.0], [ -188.026, -86.294, -482.86]) ]); demobbed.event().tracksECC([ new TrackECC(0, 8, [ 45057.0, 4931.5, 65628.8], [1000000., 1000000.], [ 44812.0, 4909.0, 68321.0]), new TrackECC(1, 11, [ 45057.0, 4931.5, 65628.8], [1000000., 1000000.], [ 44998.5, 6660.5, 72128.8]), new TrackECC(2, 14, [ 44812.0, 4909.0, 68321.0], [1000000., 1000000.], [ 44418.1, 4979.2, 72221.0]) ]); demobbed.event().tracksECCforED([ new TrackECC(0, 1, [ -188.001, -86.292, -483.130], [1000000., 1000000.], [ -189.207, -50.648, -349.130]) ]); demobbed.mgrDrawED().onEventChange(); demobbed.mgrDrawECC().onEventChange();
agpl-3.0
horus68/SuiteCRM-Horus68
tests/unit/modules/CampaignLog/CampaignLogTest.php
2231
<?php class CampaignLogTest extends SuiteCRM\StateCheckerPHPUnitTestCaseAbstract { public function setUp() { parent::setUp(); global $current_user; get_sugar_config_defaults(); $current_user = new User(); } public function testCampaignLog() { //execute the contructor and check for the Object type and attributes $campaignLog = new CampaignLog(); $this->assertInstanceOf('CampaignLog', $campaignLog); $this->assertInstanceOf('SugarBean', $campaignLog); $this->assertAttributeEquals('CampaignLog', 'module_dir', $campaignLog); $this->assertAttributeEquals('CampaignLog', 'object_name', $campaignLog); $this->assertAttributeEquals('campaign_log', 'table_name', $campaignLog); $this->assertAttributeEquals(true, 'new_schema', $campaignLog); } public function testget_list_view_data() { $state = new SuiteCRM\StateSaver(); $campaignLog = new CampaignLog(); //execute the method and verify it returns an array $actual = $campaignLog->get_list_view_data(); $this->assertTrue(is_array($actual)); $this->assertSame(array(), $actual); // clean up } public function testretrieve_email_address() { $campaignLog = new CampaignLog(); $actual = $campaignLog->retrieve_email_address(); $this->assertGreaterThanOrEqual('', $actual); } public function testget_related_name() { $campaignLog = new CampaignLog(); //execute the method and verify that it retunrs expected results for all type parameters $this->assertEquals('1Emails', $campaignLog->get_related_name(1, 'Emails')); $this->assertEquals('1Contacts', $campaignLog->get_related_name(1, 'Contacts')); $this->assertEquals('1Leads', $campaignLog->get_related_name(1, 'Leads')); $this->assertEquals('1Prospects', $campaignLog->get_related_name(1, 'Prospects')); $this->assertEquals('1CampaignTrackers', $campaignLog->get_related_name(1, 'CampaignTrackers')); $this->assertEquals('1Accounts', $campaignLog->get_related_name(1, 'Accounts')); } }
agpl-3.0
akvo/akvo-sites-zz-template
code/wp-content/plugins/google-website-translator/classes/admin.class.php
12679
<?php class PrisnaGWTAdmin { public static function initialize() { if (!is_admin()) return; add_action('admin_init', array('PrisnaGWTAdmin', '_initialize')); add_action('admin_head', array('PrisnaGWTAdmin', '_remove_messages')); add_action('plugins_loaded', array('PrisnaGWTAdmin', 'initializeMenus')); } public static function _initialize() { self::_watch_events(); self::_select_language(); self::_load_styles(); self::_load_scripts(); } protected static function _watch_events() { @header('X-XSS-Protection: 0'); if (PrisnaGWTAdminEvents::isSavingSettings() || PrisnaGWTAdminEvents::isResetingSettings()) if (!check_admin_referer(PrisnaGWTConfig::getAdminHandle(), '_prisna_gwt_nonce')) PrisnaGWTCommon::redirect(PrisnaGWTCommon::getAdminPluginUrl()); if (PrisnaGWTAdminEvents::isSavingSettings()) self::_save_settings(); if (PrisnaGWTAdminEvents::isResetingSettings()) self::_reset_settings(); } protected static function _save_settings() { PrisnaGWTAdminForm::save(); } protected static function _reset_settings() { PrisnaGWTAdminForm::reset(); } protected static function _load_scripts() { if (PrisnaGWTAdminEvents::isLoadingAdminPage()) { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-widget'); wp_enqueue_script('jquery-ui-mouse'); wp_enqueue_script('prisna-gwt-admin-common', PRISNA_GWT__JS .'/common.class.js', 'jquery-ui-core', PrisnaGWTConfig::getVersion(), true); wp_enqueue_script('prisna-gwt-admin', PRISNA_GWT__JS .'/admin.class.js', array(), PrisnaGWTConfig::getVersion()); } } protected static function _load_styles() { if (PrisnaGWTAdminEvents::isLoadingAdminPage() || strpos(PrisnaGWTCommon::getAdminWidgetsUrl(), $_SERVER['REQUEST_URI']) !== false) wp_enqueue_style('prisna-gwt-admin', PRISNA_GWT__CSS .'/admin.css', false, PrisnaGWTConfig::getVersion(), 'screen'); } public static function _remove_messages() { if (PrisnaGWTAdminEvents::isLoadingAdminPage() || strpos(PrisnaGWTCommon::getAdminWidgetsUrl(), $_SERVER['REQUEST_URI']) !== false) PrisnaGWTCommon::renderCSS('.update-nag,div.updated,div.error{display:none}'); } public static function initializeMenus() { add_action('admin_menu', array('PrisnaGWTAdmin', '_add_options_page')); } public static function _add_options_page() { add_submenu_page('plugins.php', PrisnaGWTConfig::getName(false, true), PrisnaGWTConfig::getName(false, true), 'manage_options', PrisnaGWTConfig::getAdminHandle(), array('PrisnaGWTAdmin', '_render_main_form')); } protected static function _gen_meta_tag_rules_for_tabs() { $tabs = array( array('general', 'advanced', 'premium'), array('advanced_general', 'advanced_import_export') ); $current_tabs = array( PrisnaGWTCommon::getVariable('prisna_tab', 'POST'), PrisnaGWTCommon::getVariable('prisna_tab_2', 'POST') ); $result = self::_gen_meta_tag_rules_for_tabs_aux($tabs, $current_tabs); return $result; } protected static function _gen_meta_tag_rules_for_tabs_aux($_tabs, $_currents, $_level=0) { $result = array(); if (!is_array($_tabs[0])) { $current = $_currents[$_level]; if (PrisnaGWTValidator::isEmpty($current)) $current = $_tabs[0]; for ($i=0; $i<count($_tabs); $i++) $result[] = array( 'expression' => $_tabs[$i] == $current, 'tag' => $_tabs[$i] . '.show' ); } else for ($j=0; $j<count($_tabs); $j++) $result = array_merge($result, self::_gen_meta_tag_rules_for_tabs_aux($_tabs[$j], $_currents, $j)); return $result; } public static function _render_main_form() { $form = new PrisnaGWTAdminForm(); echo $form->render(array( 'type' => 'file', 'content' => '/admin/main_form.tpl', 'meta_tag_rules' => self::_gen_meta_tag_rules_for_tabs() )); } protected static function _select_language() { load_plugin_textdomain('prisna-gwt', false, dirname(plugin_basename(__FILE__)) . '/../languages'); } } class PrisnaGWTAdminBaseForm extends PrisnaGWTItem { public $title_message; public $saved_message; public $save_button_message; public $reset_message; public $reset_button_message; public $reseted_message; protected $_fields; public function __construct() { $this->title_message = __('Google Website Translator', 'prisna-gwt'); $this->saved_message = __('Settings saved.', 'prisna-gwt'); $this->reseted_message = __('Settings reseted.', 'prisna-gwt'); $this->reset_message = __('All the settings will be reseted and restored to their default values. Do you want to continue?', 'prisna-gwt'); $this->save_button_message = __('Save changes', 'prisna-gwt'); $this->reset_button_message = __('Reset settings', 'prisna-gwt'); } public static function commit($_name, $_result) { self::_commit($_name, $_result); } protected static function _commit($_name, $_result) { if (!get_option($_name)) add_option($_name, $_result); else update_option($_name, $_result); if (!get_option($_name)) { delete_option($_name); add_option($_name, $_result); } } public function render($_options, $_html_encode=false) { return parent::render($_options, $_html_encode); } protected function _prepare_settings() {} protected function _set_fields() {} } class PrisnaGWTAdminForm extends PrisnaGWTAdminBaseForm { public $group_0; public $group_1; public $group_2; public $group_3; public $group_4; public $nonce; public $tab; public $tab_2; public $general_message; public $advanced_message; public $advanced_general_message; public $advanced_import_export_message; public $premium_message; public $advanced_import_success_message; public $advanced_import_fail_message; public $wp_version_check_fail_message; protected static $_imported_status; public function __construct() { parent::__construct(); $this->general_message = __('General', 'prisna-gwt'); $this->advanced_message = __('Advanced', 'prisna-gwt'); $this->advanced_general_message = __('General', 'prisna-gwt'); $this->premium_message = __('Premium', 'prisna-gwt'); $this->advanced_import_export_message = __('Import / Export', 'prisna-gwt'); $this->advanced_import_success_message = __('Settings succesfully imported.', 'prisna-gwt'); $this->advanced_import_fail_message = __('There was a problem while importing the settings. Please make sure the exported string is complete. Changes weren\'t saved.', 'prisna-gwt'); $this->wp_version_check_fail_message = sprintf(__('Google Website Translator requires WordPress version %s or later.', 'prisna-gwt'), PRISNA_GWT__MINIMUM_WP_VERSION); $this->nonce = wp_nonce_field(PrisnaGWTConfig::getAdminHandle(), '_prisna_gwt_nonce'); $this->_set_fields(); } public static function getImportedStatus() { return self::$_imported_status; } protected static function _set_imported_status($_status) { self::$_imported_status = $_status; } protected static function _import() { $settings = PrisnaGWTConfig::getDefaults(true); $key = $settings['import']['id']; $value = PrisnaGWTCommon::getVariable($key, 'POST'); if ($value === false || PrisnaGWTValidator::isEmpty($value)) return null; $decode = base64_decode($value); if ($decode === false) { self::_set_imported_status(false); return false; } $unserialize = @unserialize($decode); if (!is_array($unserialize)) { self::_set_imported_status(false); return false; } $result = array(); foreach ($settings as $key => $setting) { if (in_array($key, array('import', 'export'))) continue; if (array_key_exists($key, $unserialize)) $result[$key] = $unserialize[$key]; } if (count($result) == 0) { self::_set_imported_status(false); return false; } self::_commit(PrisnaGWTConfig::getDbSettingsName(), $result); self::_set_imported_status(true); return true; } public static function save() { if (!is_null(self::_import())) return; $settings = PrisnaGWTConfig::getDefaults(); $result = array(); foreach ($settings as $key => $setting) { $value = PrisnaGWTCommon::getVariable($setting['id'], 'POST'); switch ($key) { case 'languages': { $value = PrisnaGWTCommon::getVariable(str_replace('languages', 'languages_order', $setting['id']), 'POST'); if ($value !== false) { $value = explode(',', $value); if ($value !== $setting['value']) $result[$key] = array('value' => $value); else unset($result[$key]); } else unset($result[$key]); break; } case 'import': case 'export': { break; } default: { if ($key == 'id' || (PrisnaGWTCommon::endsWith($key, '_class') && $key != 'language_selector_class' && $key != 'translated_to_class')) $value = trim(PrisnaGWTCommon::cleanId($value)); else if ($key == 'translated_to_class') $value = trim(PrisnaGWTCommon::cleanId($value, '-', false)); $unset_template = PrisnaGWTCommon::endsWith($key, '_template') && PrisnaGWTCommon::stripBreakLinesAndTabs($value) == PrisnaGWTCommon::stripBreakLinesAndTabs($setting['value']); if (!$unset_template && $value !== false && $value != $setting['value']) $result[$key] = array('value' => $value); else unset($result[$key]); break; } } } if (array_key_exists('display_mode', $result) && $result['display_mode']['value'] == 'tabbed' && !array_key_exists('banner', $result)) $result['banner'] = array( 'value' => 'false' ); self::_commit(PrisnaGWTConfig::getDbSettingsName(), $result); } public static function reset() { if (get_option(PrisnaGWTConfig::getDbSettingsName())) delete_option(PrisnaGWTConfig::getDbSettingsName()); } public function render($_options, $_html_encode=false) { $this->_prepare_settings(); $is_importing = PrisnaGWTAdminEvents::isSavingSettings() && PrisnaGWTValidator::isBool(self::getImportedStatus()); if (!array_key_exists('meta_tag_rules', $_options)) $_options['meta_tag_rules'] = array(); $_options['meta_tag_rules'][] = array( 'expression' => PrisnaGWTAdminEvents::isSavingSettings() && !$is_importing, 'tag' => 'just_saved' ); $_options['meta_tag_rules'][] = array( 'expression' => $is_importing && self::getImportedStatus(), 'tag' => 'just_imported_success' ); $_options['meta_tag_rules'][] = array( 'expression' => $is_importing && !self::getImportedStatus(), 'tag' => 'just_imported_fail' ); $_options['meta_tag_rules'][] = array( 'expression' => !version_compare($GLOBALS['wp_version'], PRISNA_GWT__MINIMUM_WP_VERSION, '<'), 'tag' => 'wp_version_check' ); $_options['meta_tag_rules'][] = array( 'expression' => PrisnaGWTAdminEvents::isResetingSettings(), 'tag' => 'just_reseted' ); return parent::render($_options, $_html_encode); } protected function _set_fields() { if (is_array($this->_fields)) return; $this->_fields = array(); $settings = PrisnaGWTConfig::getSettings(true); foreach ($settings as $key => $setting) { if (!array_key_exists('type', $setting)) continue; $field_class = 'PrisnaGWT' . ucfirst($setting['type']) . 'Field'; if ($field_class == 'PrisnaGWTField') continue; $this->_fields[$key] = new $field_class($setting); } } protected function _prepare_settings() { $settings = PrisnaGWTConfig::getSettings(); $groups = 4; for ($i=1; $i<$groups+1; $i++) { $partial = array(); foreach ($this->_fields as $key => $field) { if ($field->group == $i) { $field->satisfyDependence($this->_fields); $partial[] = $field->output(); } } $group = 'group_' . $i; $this->{$group} = implode("\n", $partial); } $tab = PrisnaGWTCommon::getVariable('prisna_tab', 'POST'); $this->tab = $tab !== false ? $tab : ''; $tab_2 = PrisnaGWTCommon::getVariable('prisna_tab_2', 'POST'); $this->tab_2 = $tab_2 !== false ? $tab_2 : ''; } } class PrisnaGWTAdminEvents { public static function isLoadingAdminPage() { return in_array(PrisnaGWTCommon::getVariable('page', 'GET'), array(PrisnaGWTConfig::getAdminHandle())); } public static function isSavingSettings() { return PrisnaGWTCommon::getVariable('prisna_gwt_admin_action', 'POST') === 'prisna_gwt_save_settings'; } public static function isResetingSettings() { return PrisnaGWTCommon::getVariable('prisna_gwt_admin_action', 'POST') === 'prisna_gwt_reset_settings'; } } PrisnaGWTAdmin::initialize(); ?>
agpl-3.0
jgalle/DRC
app/controllers/glass_bottle_shapes_controller.rb
2468
class GlassBottleShapesController < ApplicationController # GET /glass_bottle_shapes # GET /glass_bottle_shapes.json def index @glass_bottle_shapes = GlassBottleShape.all respond_to do |format| format.html # index.html.erb format.json { render json: @glass_bottle_shapes } end end # GET /glass_bottle_shapes/1 # GET /glass_bottle_shapes/1.json def show @glass_bottle_shape = GlassBottleShape.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @glass_bottle_shape } end end # GET /glass_bottle_shapes/new # GET /glass_bottle_shapes/new.json def new @glass_bottle_shape = GlassBottleShape.new respond_to do |format| format.html # new.html.erb format.json { render json: @glass_bottle_shape } end end # GET /glass_bottle_shapes/1/edit def edit @glass_bottle_shape = GlassBottleShape.find(params[:id]) end # POST /glass_bottle_shapes # POST /glass_bottle_shapes.json def create @glass_bottle_shape = GlassBottleShape.new(params[:glass_bottle_shape]) respond_to do |format| if @glass_bottle_shape.save format.html { redirect_to @glass_bottle_shape, notice: 'Glass bottle shape was successfully created.' } format.json { render json: @glass_bottle_shape, status: :created, location: @glass_bottle_shape } else format.html { render action: "new" } format.json { render json: @glass_bottle_shape.errors, status: :unprocessable_entity } end end end # PUT /glass_bottle_shapes/1 # PUT /glass_bottle_shapes/1.json def update @glass_bottle_shape = GlassBottleShape.find(params[:id]) respond_to do |format| if @glass_bottle_shape.update_attributes(params[:glass_bottle_shape]) format.html { redirect_to @glass_bottle_shape, notice: 'Glass bottle shape was successfully updated.' } format.json { head :no_content } else format.html { render action: "edit" } format.json { render json: @glass_bottle_shape.errors, status: :unprocessable_entity } end end end # DELETE /glass_bottle_shapes/1 # DELETE /glass_bottle_shapes/1.json def destroy @glass_bottle_shape = GlassBottleShape.find(params[:id]) @glass_bottle_shape.destroy respond_to do |format| format.html { redirect_to glass_bottle_shapes_url } format.json { head :no_content } end end end
agpl-3.0
baca0/churming-server
routes/nation.js
1152
module.exports = function (app, Nation) { app.get('/nations', function (req, res) { Nation.find(function (err, countries) { if (err) { return res.status(500).send({error: 'database failure'}); } res.send(countries); }) }); app.get('/nations/:nationId', function (req, res) { console.log('nationId is ' + req.params.nationId); Nation.find({_id: req.params.nationId}, function (err, nation) { if (err) { return res.status(500).json({error: err}); } if (!nation) { return res.status(404).json({error: 'nation not found'}); } res.send(nation); }); }); // app.post('/nations', function (req, res) { // var nation = new Nation(); // nation.name = req.body.name; // // nation.save(function (err) { // if (err) { // console.error(err); // res.send({result: 0}); // return; // } // // res.send({result: 1}); // }); // }); };
agpl-3.0
RainLoop/rainloop-webmail
dev/Stores/User/Folder.js
6187
import ko from 'ko'; import _ from '_'; import { settingsGet } from 'Storage/Settings'; import { FolderType } from 'Common/Enums'; import { UNUSED_OPTION_VALUE } from 'Common/Consts'; import { isArray, folderListOptionsBuilder } from 'Common/Utils'; import { getFolderInboxName, getFolderFromCacheList } from 'Common/Cache'; import { momentNowUnix } from 'Common/Momentor'; class FolderUserStore { constructor() { this.displaySpecSetting = ko.observable(true); this.sentFolder = ko.observable(''); this.draftFolder = ko.observable(''); this.spamFolder = ko.observable(''); this.trashFolder = ko.observable(''); this.archiveFolder = ko.observable(''); this.namespace = ''; this.folderList = ko.observableArray([]); this.folderList.optimized = ko.observable(false); this.folderList.error = ko.observable(''); this.foldersLoading = ko.observable(false); this.foldersCreating = ko.observable(false); this.foldersDeleting = ko.observable(false); this.foldersRenaming = ko.observable(false); this.foldersInboxUnreadCount = ko.observable(0); this.currentFolder = ko.observable(null).extend({ toggleSubscribeProperty: [this, 'selected'] }); this.sieveAllowFileintoInbox = !!settingsGet('SieveAllowFileintoInbox'); this.computers(); this.subscribers(); } computers() { this.draftFolderNotEnabled = ko.computed( () => '' === this.draftFolder() || UNUSED_OPTION_VALUE === this.draftFolder() ); this.foldersListWithSingleInboxRootFolder = ko.computed( () => !_.find(this.folderList(), (folder) => folder && !folder.isSystemFolder() && folder.visible()) ); this.currentFolderFullNameRaw = ko.computed(() => (this.currentFolder() ? this.currentFolder().fullNameRaw : '')); this.currentFolderFullName = ko.computed(() => (this.currentFolder() ? this.currentFolder().fullName : '')); this.currentFolderFullNameHash = ko.computed(() => (this.currentFolder() ? this.currentFolder().fullNameHash : '')); this.foldersChanging = ko.computed(() => { const loading = this.foldersLoading(), creating = this.foldersCreating(), deleting = this.foldersDeleting(), renaming = this.foldersRenaming(); return loading || creating || deleting || renaming; }); this.folderListSystemNames = ko.computed(() => { const list = [getFolderInboxName()], folders = this.folderList(), sentFolder = this.sentFolder(), draftFolder = this.draftFolder(), spamFolder = this.spamFolder(), trashFolder = this.trashFolder(), archiveFolder = this.archiveFolder(); if (isArray(folders) && 0 < folders.length) { if ('' !== sentFolder && UNUSED_OPTION_VALUE !== sentFolder) { list.push(sentFolder); } if ('' !== draftFolder && UNUSED_OPTION_VALUE !== draftFolder) { list.push(draftFolder); } if ('' !== spamFolder && UNUSED_OPTION_VALUE !== spamFolder) { list.push(spamFolder); } if ('' !== trashFolder && UNUSED_OPTION_VALUE !== trashFolder) { list.push(trashFolder); } if ('' !== archiveFolder && UNUSED_OPTION_VALUE !== archiveFolder) { list.push(archiveFolder); } } return list; }); this.folderListSystem = ko.computed(() => _.compact(_.map(this.folderListSystemNames(), (name) => getFolderFromCacheList(name))) ); this.folderMenuForMove = ko.computed(() => folderListOptionsBuilder( this.folderListSystem(), this.folderList(), [this.currentFolderFullNameRaw()], null, null, null, null, (item) => (item ? item.localName() : '') ) ); this.folderMenuForFilters = ko.computed(() => folderListOptionsBuilder( this.folderListSystem(), this.folderList(), [this.sieveAllowFileintoInbox ? '' : 'INBOX'], [['', '']], null, null, null, (item) => (item ? item.localName() : '') ) ); } subscribers() { const fRemoveSystemFolderType = (observable) => () => { const folder = getFolderFromCacheList(observable()); if (folder) { folder.type(FolderType.User); } }; const fSetSystemFolderType = (type) => (value) => { const folder = getFolderFromCacheList(value); if (folder) { folder.type(type); } }; this.sentFolder.subscribe(fRemoveSystemFolderType(this.sentFolder), this, 'beforeChange'); this.draftFolder.subscribe(fRemoveSystemFolderType(this.draftFolder), this, 'beforeChange'); this.spamFolder.subscribe(fRemoveSystemFolderType(this.spamFolder), this, 'beforeChange'); this.trashFolder.subscribe(fRemoveSystemFolderType(this.trashFolder), this, 'beforeChange'); this.archiveFolder.subscribe(fRemoveSystemFolderType(this.archiveFolder), this, 'beforeChange'); this.sentFolder.subscribe(fSetSystemFolderType(FolderType.SentItems), this); this.draftFolder.subscribe(fSetSystemFolderType(FolderType.Draft), this); this.spamFolder.subscribe(fSetSystemFolderType(FolderType.Spam), this); this.trashFolder.subscribe(fSetSystemFolderType(FolderType.Trash), this); this.archiveFolder.subscribe(fSetSystemFolderType(FolderType.Archive), this); } /** * @returns {Array} */ getNextFolderNames() { const result = [], limit = 5, utc = momentNowUnix(), timeout = utc - 60 * 5, timeouts = [], inboxFolderName = getFolderInboxName(), fSearchFunction = (list) => { _.each(list, (folder) => { if ( folder && inboxFolderName !== folder.fullNameRaw && folder.selectable && folder.existen && timeout > folder.interval && (folder.isSystemFolder() || (folder.subScribed() && folder.checkable())) ) { timeouts.push([folder.interval, folder.fullNameRaw]); } if (folder && 0 < folder.subFolders().length) { fSearchFunction(folder.subFolders()); } }); }; fSearchFunction(this.folderList()); timeouts.sort((a, b) => { if (a[0] < b[0]) { return -1; } else if (a[0] > b[0]) { return 1; } return 0; }); _.find(timeouts, (aItem) => { const folder = getFolderFromCacheList(aItem[1]); if (folder) { folder.interval = utc; result.push(aItem[1]); } return limit <= result.length; }); return _.uniq(result); } } export default new FolderUserStore();
agpl-3.0
marek-stoj/justRead.it
Src/DotNet/JustReadIt.Core/Common/StringUtil.cs
18095
// Copyright (c) 2008 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace JustReadIt.Core.Common { /// <summary> /// Some common string manipulation utilities. /// </summary> internal static class StringUtil { // \u3000 is the double-byte space character in UTF-8 // \u00A0 is the non-breaking space character (&nbsp;) // \u2007 is the figure space character (&#8199;) // \u202F is the narrow non-breaking space character (&#8239;) private const string _WhiteSpaces = " \r\n\t\u3000\u00A0\u2007\u202F"; private static readonly Dictionary<string, char> _escapeStrings; #region Constructor(s) static StringUtil() { // HTML character entity references as defined in HTML 4, see http://www.w3.org/TR/REC-html40/sgml/entities.html _escapeStrings = new Dictionary<string, char>(252) { #region Entity references { "&nbsp;", '\u00A0' }, { "&iexcl;", '\u00A1' }, { "&cent;", '\u00A2' }, { "&pound;", '\u00A3' }, { "&curren;", '\u00A4' }, { "&yen;", '\u00A5' }, { "&brvbar;", '\u00A6' }, { "&sect;", '\u00A7' }, { "&uml;", '\u00A8' }, { "&copy;", '\u00A9' }, { "&ordf;", '\u00AA' }, { "&laquo;", '\u00AB' }, { "&not;", '\u00AC' }, { "&shy;", '\u00AD' }, { "&reg;", '\u00AE' }, { "&macr;", '\u00AF' }, { "&deg;", '\u00B0' }, { "&plusmn;", '\u00B1' }, { "&sup2;", '\u00B2' }, { "&sup3;", '\u00B3' }, { "&acute;", '\u00B4' }, { "&micro;", '\u00B5' }, { "&para;", '\u00B6' }, { "&middot;", '\u00B7' }, { "&cedil;", '\u00B8' }, { "&sup1;", '\u00B9' }, { "&ordm;", '\u00BA' }, { "&raquo;", '\u00BB' }, { "&frac14;", '\u00BC' }, { "&frac12;", '\u00BD' }, { "&frac34;", '\u00BE' }, { "&iquest;", '\u00BF' }, { "&Agrave;", '\u00C0' }, { "&Aacute;", '\u00C1' }, { "&Acirc;", '\u00C2' }, { "&Atilde;", '\u00C3' }, { "&Auml;", '\u00C4' }, { "&Aring;", '\u00C5' }, { "&AElig;", '\u00C6' }, { "&Ccedil;", '\u00C7' }, { "&Egrave;", '\u00C8' }, { "&Eacute;", '\u00C9' }, { "&Ecirc;", '\u00CA' }, { "&Euml;", '\u00CB' }, { "&Igrave;", '\u00CC' }, { "&Iacute;", '\u00CD' }, { "&Icirc;", '\u00CE' }, { "&Iuml;", '\u00CF' }, { "&ETH;", '\u00D0' }, { "&Ntilde;", '\u00D1' }, { "&Ograve;", '\u00D2' }, { "&Oacute;", '\u00D3' }, { "&Ocirc;", '\u00D4' }, { "&Otilde;", '\u00D5' }, { "&Ouml;", '\u00D6' }, { "&times;", '\u00D7' }, { "&Oslash;", '\u00D8' }, { "&Ugrave;", '\u00D9' }, { "&Uacute;", '\u00DA' }, { "&Ucirc;", '\u00DB' }, { "&Uuml;", '\u00DC' }, { "&Yacute;", '\u00DD' }, { "&THORN;", '\u00DE' }, { "&szlig;", '\u00DF' }, { "&agrave;", '\u00E0' }, { "&aacute;", '\u00E1' }, { "&acirc;", '\u00E2' }, { "&atilde;", '\u00E3' }, { "&auml;", '\u00E4' }, { "&aring;", '\u00E5' }, { "&aelig;", '\u00E6' }, { "&ccedil;", '\u00E7' }, { "&egrave;", '\u00E8' }, { "&eacute;", '\u00E9' }, { "&ecirc;", '\u00EA' }, { "&euml;", '\u00EB' }, { "&igrave;", '\u00EC' }, { "&iacute;", '\u00ED' }, { "&icirc;", '\u00EE' }, { "&iuml;", '\u00EF' }, { "&eth;", '\u00F0' }, { "&ntilde;", '\u00F1' }, { "&ograve;", '\u00F2' }, { "&oacute;", '\u00F3' }, { "&ocirc;", '\u00F4' }, { "&otilde;", '\u00F5' }, { "&ouml;", '\u00F6' }, { "&divide;", '\u00F7' }, { "&oslash;", '\u00F8' }, { "&ugrave;", '\u00F9' }, { "&uacute;", '\u00FA' }, { "&ucirc;", '\u00FB' }, { "&uuml;", '\u00FC' }, { "&yacute;", '\u00FD' }, { "&thorn;", '\u00FE' }, { "&yuml;", '\u00FF' }, { "&fnof;", '\u0192' }, { "&Alpha;", '\u0391' }, { "&Beta;", '\u0392' }, { "&Gamma;", '\u0393' }, { "&Delta;", '\u0394' }, { "&Epsilon;", '\u0395' }, { "&Zeta;", '\u0396' }, { "&Eta;", '\u0397' }, { "&Theta;", '\u0398' }, { "&Iota;", '\u0399' }, { "&Kappa;", '\u039A' }, { "&Lambda;", '\u039B' }, { "&Mu;", '\u039C' }, { "&Nu;", '\u039D' }, { "&Xi;", '\u039E' }, { "&Omicron;", '\u039F' }, { "&Pi;", '\u03A0' }, { "&Rho;", '\u03A1' }, { "&Sigma;", '\u03A3' }, { "&Tau;", '\u03A4' }, { "&Upsilon;", '\u03A5' }, { "&Phi;", '\u03A6' }, { "&Chi;", '\u03A7' }, { "&Psi;", '\u03A8' }, { "&Omega;", '\u03A9' }, { "&alpha;", '\u03B1' }, { "&beta;", '\u03B2' }, { "&gamma;", '\u03B3' }, { "&delta;", '\u03B4' }, { "&epsilon;", '\u03B5' }, { "&zeta;", '\u03B6' }, { "&eta;", '\u03B7' }, { "&theta;", '\u03B8' }, { "&iota;", '\u03B9' }, { "&kappa;", '\u03BA' }, { "&lambda;", '\u03BB' }, { "&mu;", '\u03BC' }, { "&nu;", '\u03BD' }, { "&xi;", '\u03BE' }, { "&omicron;", '\u03BF' }, { "&pi;", '\u03C0' }, { "&rho;", '\u03C1' }, { "&sigmaf;", '\u03C2' }, { "&sigma;", '\u03C3' }, { "&tau;", '\u03C4' }, { "&upsilon;", '\u03C5' }, { "&phi;", '\u03C6' }, { "&chi;", '\u03C7' }, { "&psi;", '\u03C8' }, { "&omega;", '\u03C9' }, { "&thetasym;", '\u03D1' }, { "&upsih;", '\u03D2' }, { "&piv;", '\u03D6' }, { "&bull;", '\u2022' }, { "&hellip;", '\u2026' }, { "&prime;", '\u2032' }, { "&Prime;", '\u2033' }, { "&oline;", '\u203E' }, { "&frasl;", '\u2044' }, { "&weierp;", '\u2118' }, { "&image;", '\u2111' }, { "&real;", '\u211C' }, { "&trade;", '\u2122' }, { "&alefsym;", '\u2135' }, { "&larr;", '\u2190' }, { "&uarr;", '\u2191' }, { "&rarr;", '\u2192' }, { "&darr;", '\u2193' }, { "&harr;", '\u2194' }, { "&crarr;", '\u21B5' }, { "&lArr;", '\u21D0' }, { "&uArr;", '\u21D1' }, { "&rArr;", '\u21D2' }, { "&dArr;", '\u21D3' }, { "&hArr;", '\u21D4' }, { "&forall;", '\u2200' }, { "&part;", '\u2202' }, { "&exist;", '\u2203' }, { "&empty;", '\u2205' }, { "&nabla;", '\u2207' }, { "&isin;", '\u2208' }, { "&notin;", '\u2209' }, { "&ni;", '\u220B' }, { "&prod;", '\u220F' }, { "&sum;", '\u2211' }, { "&minus;", '\u2212' }, { "&lowast;", '\u2217' }, { "&radic;", '\u221A' }, { "&prop;", '\u221D' }, { "&infin;", '\u221E' }, { "&ang;", '\u2220' }, { "&and;", '\u2227' }, { "&or;", '\u2228' }, { "&cap;", '\u2229' }, { "&cup;", '\u222A' }, { "&int;", '\u222B' }, { "&there4;", '\u2234' }, { "&sim;", '\u223C' }, { "&cong;", '\u2245' }, { "&asymp;", '\u2248' }, { "&ne;", '\u2260' }, { "&equiv;", '\u2261' }, { "&le;", '\u2264' }, { "&ge;", '\u2265' }, { "&sub;", '\u2282' }, { "&sup;", '\u2283' }, { "&nsub;", '\u2284' }, { "&sube;", '\u2286' }, { "&supe;", '\u2287' }, { "&oplus;", '\u2295' }, { "&otimes;", '\u2297' }, { "&perp;", '\u22A5' }, { "&sdot;", '\u22C5' }, { "&lceil;", '\u2308' }, { "&rceil;", '\u2309' }, { "&lfloor;", '\u230A' }, { "&rfloor;", '\u230B' }, { "&lang;", '\u2329' }, { "&rang;", '\u232A' }, { "&loz;", '\u25CA' }, { "&spades;", '\u2660' }, { "&clubs;", '\u2663' }, { "&hearts;", '\u2665' }, { "&diams;", '\u2666' }, { "&quot;", '\u0022' }, { "&amp;", '\u0026' }, { "&lt;", '\u003C' }, { "&gt;", '\u003E' }, { "&OElig;", '\u0152' }, { "&oelig;", '\u0153' }, { "&Scaron;", '\u0160' }, { "&scaron;", '\u0161' }, { "&Yuml;", '\u0178' }, { "&circ;", '\u02C6' }, { "&tilde;", '\u02DC' }, { "&ensp;", '\u2002' }, { "&emsp;", '\u2003' }, { "&thinsp;", '\u2009' }, { "&zwnj;", '\u200C' }, { "&zwj;", '\u200D' }, { "&lrm;", '\u200E' }, { "&rlm;", '\u200F' }, { "&ndash;", '\u2013' }, { "&mdash;", '\u2014' }, { "&lsquo;", '\u2018' }, { "&rsquo;", '\u2019' }, { "&sbquo;", '\u201A' }, { "&ldquo;", '\u201C' }, { "&rdquo;", '\u201D' }, { "&bdquo;", '\u201E' }, { "&dagger;", '\u2020' }, { "&Dagger;", '\u2021' }, { "&permil;", '\u2030' }, { "&lsaquo;", '\u2039' }, { "&rsaquo;", '\u203A' }, { "&euro;", '\u20AC' }, #endregion }; } #endregion #region Public methods /// <summary> /// Replace all the occurences of HTML escape strings with the respective characters. /// </summary> public static string UnescapeHTML(string str) { char[] chars = str.ToCharArray(); char[] escaped = new char[chars.Length]; // Note: escaped[pos] = end of the escaped char array. int pos = 0; for (int i = 0; i < chars.Length; ) { if (chars[i] != '&') { escaped[pos++] = chars[i++]; continue; } // Allow e.g. &#123; int j = i + 1; if (j < chars.Length && chars[j] == '#') { j++; } // Scan until we find a char that is not letter or digit. for (; j < chars.Length; j++) { if (!char.IsLetterOrDigit(chars[j])) { break; } } bool replaced = false; if (j < chars.Length && chars[j] == ';') { if (str[i + 1] == '#') // Check for &#D; and &#xD; pattern { try { long charCode = 0; char ch = str[i + 2]; if (ch == 'x' || ch == 'X') { charCode = long.Parse(new string(chars, i + 3, j - i - 3), NumberStyles.HexNumber); } else if (char.IsDigit(ch)) { charCode = long.Parse(new string(chars, i + 2, j - i - 2)); } if (charCode > 0 && charCode < 65536) { escaped[pos++] = (char)charCode; replaced = true; } } catch (FormatException) { // Failed, not replaced. } } else { string key = new string(chars, i, j - i + 1); char repl; if (_escapeStrings.TryGetValue(key, out repl)) { escaped[pos++] = repl; replaced = true; } } j++; // Skip over ';' } if (!replaced) { // Not a recognized escape sequence, leave as-is Array.Copy(chars, i, escaped, pos, j - i); pos += j - i; } i = j; } return new string(escaped, 0, pos); } /// <summary> /// Strip white spaces from both end, and collapse white spaces in the middle. /// </summary> public static string StripAndCollapse(string str) { return CollapseWhitespace(Strip(str)); } /// <summary> /// Reformats the given array of lines to a fixed width by inserting carriage returns and trimming unnecessary whitespace. /// </summary> public static string FixedWidth(string[] lines, int width) { var formatStr = new StringBuilder(); for (int i = 0; i < lines.Length; i++) { int curWidth = 0; if (i != 0) { formatStr.Append("\n"); } // a small optimization if (lines[i].Length <= width) { formatStr.Append(lines[i]); continue; } IEnumerable<string> words = SplitAndTrim(lines[i], _WhiteSpaces); foreach (string word in words) { if (curWidth == 0 || (curWidth + word.Length) < width) { // add a space if we're not at the beginning of a line if (curWidth != 0) { formatStr.Append(" "); curWidth += 1; } curWidth += word.Length; formatStr.Append(word); } else { formatStr.Append("\n"); curWidth = word.Length; formatStr.Append(word); } } } return formatStr.ToString(); } #endregion #region Private helper methods /// <summary> /// Replaces any string of adjacent whitespace characters with the whitespace character " ". /// </summary> private static string CollapseWhitespace(string str) { return Collapse(str, _WhiteSpaces, " "); } /// <summary> /// Replaces any string of matched characters with the supplied string. /// This is a more general version of CollapseWhitespace. /// E.g. Collapse("hello world", " ", "::") will return the following string: "hello::world" /// </summary> private static string Collapse(string str, string chars, string replacement) { if (str == null) { return null; } StringBuilder newStr = new StringBuilder(); bool prevCharMatched = false; foreach (char ch in str) { if (chars.IndexOf(ch) != -1) { // this character is matched if (prevCharMatched) { // apparently a string of matched chars, so don't Append anything // to the string continue; } prevCharMatched = true; newStr.Append(replacement); } else { prevCharMatched = false; newStr.Append(ch); } } return newStr.ToString(); } /// <summary> /// Strip - strips both ways /// </summary> private static string Strip(string str) { return MegaStrip(str, true, true, _WhiteSpaces); } /// <summary> /// This is a both way strip. /// </summary> private static string MegaStrip(string str, bool left, bool right, string what) { if (str == null) { return null; } int limitLeft = 0; int limitRight = str.Length - 1; while (left && limitLeft <= limitRight && what.IndexOf(str[limitLeft]) >= 0) { limitLeft++; } while (right && limitRight >= limitLeft && what.IndexOf(str[limitRight]) >= 0) { limitRight--; } return str.SubSequence(limitLeft, limitRight + 1); } /// <summary> /// Split "str" into tokens by delimiters and optionally remove white spaces from the splitted tokens. /// </summary> private static IEnumerable<string> Split(string str, string delims, bool trimTokens) { string[] tokens = str.Split(delims.ToCharArray()); if (!trimTokens) { return tokens; } return tokens .Select(t => t.Trim()) .ToArray(); } /// <summary> /// Shorthand for <code>Split(str, delims, true)</code>. /// </summary> private static IEnumerable<string> SplitAndTrim(string str, string delims) { return Split(str, delims, true); } #endregion } }
agpl-3.0
malexmave/pdok-mirror
controller/uploader.py
9092
# -*- encoding: utf-8 -*- """Upload files to InternetArchive. Copyright (C) 2017 Max Maass This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ from internetarchive import upload from models.database import Wahlperiode, Drucksache, Plenarprotokoll from multiprocessing.pool import ThreadPool def upload_legislaturperiode(period_no_numeric): """Upload all files from a legislaturperiode. Files that have already been uploaded are ignored. """ # Format period number properly period_no = '%02d' % period_no_numeric # Get from database or create period = Wahlperiode.get(period_no=period_no) # If the period has already been scraped, return instantly if period.period_uploaded: print "INFO: Period", period_no, "has already been uploaded - skipping" return # Upload all plenary protocols upload_plenarprotokoll(period) # Upload all Drucksachen upload_drucksachen(period) def upload_plenarprotokoll(period): """Upload all plenary protocols belonging to the given period.""" to_upload = [] for plenary in Plenarprotokoll.select().where(Plenarprotokoll.period == period): if plenary.archive_ident is not None: continue metadata = dict(collection='deutscherbundestag', title=plenary.docno + " - " + plenary.title, mediatype='texts', source=u'<a href="http://pdok.bundestag.de/" target="blank">Parlamentarisches Dokumentationssystem</a>', contributor=u'<a href="https://twitter.com/malexmave">@malexmave</a>', rights=u'Free to republish without modification as long as the source is credited, as per § 5 Abs. 2 UrhG', publisher=u"Deutscher Bundestag", creator=u'Deutscher Bundestag', credits=u"Steganografischer Dienst des Bundestages", # TODO Add authors / steganografischer Dienst here description=u'<p>Plenarprotokoll des deutschen Bundestages vom ' + str(plenary.date) + u'.</p><br><p>Automatically mirrored from the german <a href="http://pdok.bundestag.de/" target="blank">parliamentary documentation system</a>. Reproduction without modification allowed as long as the source is credited (according to § 5 Abs. 2 of the german Urheberrecht).</p><p>This is not the authoritative version, but an unofficial mirror. Please check the primary sources when in doubt.</p><p>This post was automatically created using <a href="https://github.com/malexmave/pdok-mirror" target="blank">pdok-mirror</a> and the python <a href="https://internetarchive.readthedocs.io/en/latest/" target="blank">internetarchive</a> library.</p>', # TODO Update language=u"ger", subject=["Deutscher Bundestag", "Plenarprotokoll", "Legislaturperiode " + str(period.period_no)] ) identifier = 'ger-bt-plenary-' + plenary.docno.replace('/', '-') to_upload += [(identifier, {plenary.path.split('/')[-1]: plenary.path}, metadata, plenary)] pool = ThreadPool(processes=10) results = pool.map(upload_parallel, to_upload) pool.close() for result in results: if result is None: continue plenary, identifier = result plenary.archive_ident = identifier print "DEBUG: Successfully uploaded", identifier plenary.save() def upload_drucksachen(period): """Upload all drucksachen belonging to the given period.""" to_upload = [] for drucksache in Drucksache.select().where(Drucksache.period == period): if drucksache.archive_ident is not None: continue metadata = dict(collection='deutscherbundestag', title=drucksache.docno + " - " + drucksache.title, mediatype='texts', source=u'<a href="http://pdok.bundestag.de/" target="blank">Parlamentarisches Dokumentationssystem</a>', contributor=u'<a href="https://twitter.com/malexmave">@malexmave</a>', rights=u'Free to republish without modification as long as the source is credited, as per § 5 Abs. 2 UrhG', publisher=u"Deutscher Bundestag", description=u'<p>Drucksache des deutschen Bundestages vom ' + str(drucksache.date) + u'.</p><br><p>Automatically mirrored from the german <a href="http://pdok.bundestag.de/" target="blank">parliamentary documentation system</a>. Reproduction without modification allowed as long as the source is credited (according to § 5 Abs. 2 of the german Urheberrecht).</p><p>This is not the authoritative version, but an unofficial mirror. Please check the primary sources when in doubt.</p><p>This post was automatically created using <a href="https://github.com/malexmave/pdok-mirror" target="blank">pdok-mirror</a> and the python <a href="https://internetarchive.readthedocs.io/en/latest/" target="blank">internetarchive</a> library.</p>', # TODO Update language=u"ger", subject=["Deutscher Bundestag", drucksache.doctype, "Legislaturperiode " + str(period.period_no)] ) if drucksache.autor is not None: metadata['credits'] = drucksache.autor else: metadata['credits'] = u"Unbekannt" if drucksache.urheber is not None: metadata['creator'] = drucksache.urheber else: metadata['creator'] = u"Unbekannt" identifier = 'ger-bt-drucksache-' + drucksache.docno.replace('/', '-') to_upload += [(identifier, {drucksache.path.split('/')[-1]: drucksache.path}, metadata, drucksache)] pool = ThreadPool(processes=10) results = pool.map(upload_parallel, to_upload) pool.close() for result in results: if result is None: continue drucksache, identifier = result drucksache.archive_ident = identifier print "DEBUG: Successfully uploaded", identifier drucksache.save() def upload_parallel(params): """Helper function to upload stuff in parallel.""" if params is None or len(params) != 4: print "ERROR: Bad parameters" return identifier, files, metadata, dbobj = params try: r = upload(identifier, files=files, metadata=metadata, verify=True, retries=5) except Exception as e: print "ERROR: Received exception, stopping upload attempt" print e return None if r[0].status_code != 200: print "ERROR: Upload of", identifier, "failed:", r[0].status_code return None else: print "DEBUG: Uploaded", identifier return (dbobj, identifier) # metadata = dict(collection='test_collection', # TODO Update # title='Test upload 13/37 - Hurr durr herp derp doodle', # TODO Update # mediatype='texts', # source='<a href="http://pdok.bundestag.de/" target="blank">Parlamentarisches Dokumentationssystem</a>', # contributor='<a href="https://twitter.com/malexmave">@malexmave</a>', # rights='Free to republish without modification as long as the source is credited, as per § 5 Abs. 2 UrhG', # publisher="Deutscher Bundestag", # creator='Deutscher Bundestag', # credits="", # TODO Add authors / steganografischer Dienst here # description='<p>Automatically mirrored from the german <a href="http://pdok.bundestag.de/" target="blank">parliamentary documentation system</a>. Reproduction without modification allowed as long as the source is credited (according to § 5 Abs. 2 of the german Urheberrecht).</p><p>This is not the authoritative version, but an unofficial mirror. Please check the primary sources when in doubt.</p><p>This post was created using <a href="https://github.com/malexmave/pdok-mirror" target="blank">pdok-mirror</a> and the python <a href="https://internetarchive.readthedocs.io/en/latest/" target="blank">internetarchive</a> library.</p>', # TODO Update # language="ger", # subject=["Deutscher Bundestag", "Drucksache"] # TODO Add Parlamentsprotokoll, Kleine Anfrage, ... # ) # r = upload('malexmave-test-upload-ignore3', files={'testfile.txt': 'testfile.txt'}, metadata=metadata, retries=5) # TODO Update # print r[0].status_code
agpl-3.0
openfisca/openfisca-matplotlib
openfisca_matplotlib/tests/test_dataframes.py
2507
# -*- coding: utf-8 -*- from __future__ import division import os from openfisca_core.decompositions import get_decomposition_json from openfisca_france import FranceTaxBenefitSystem from openfisca_matplotlib.tests.test_graphs import create_simulation from openfisca_matplotlib.dataframes import data_frame_from_decomposition_json tax_benefit_system = FranceTaxBenefitSystem() def test(): reform_simulation, reference_simulation = create_simulation() data_frame = data_frame_from_decomposition_json( reform_simulation, decomposition_json = None, reference_simulation = reference_simulation, ) return data_frame def test_bareme(): reform_simulation, reference_simulation = create_simulation(bareme = True) data_frame = data_frame_from_decomposition_json( reform_simulation, decomposition_json = None, reference_simulation = reference_simulation, ) return data_frame def test_remove_null(): reform_simulation, reference_simulation = create_simulation() data_frame = data_frame_from_decomposition_json( reform_simulation, decomposition_json = None, reference_simulation = reference_simulation, remove_null = True) return data_frame def test_fiche_de_paie(): reform_simulation, reference_simulation = create_simulation() xml_file_path = os.path.join( os.path.dirname(tax_benefit_system.decomposition_file_path), "fiche_de_paie_decomposition.xml" ) decomposition_json = get_decomposition_json(tax_benefit_system, xml_file_path) data_frame = data_frame_from_decomposition_json( reform_simulation, decomposition_json = decomposition_json, reference_simulation = reference_simulation, remove_null = True) return data_frame def test_fiche_de_paie_bareme(bareme=True): reform_simulation, reference_simulation = create_simulation(bareme=bareme) xml_file_path = os.path.join( os.path.dirname(tax_benefit_system.decomposition_file_path), "fiche_de_paie_decomposition.xml" ) decomposition_json = get_decomposition_json(tax_benefit_system, xml_file_path) data_frame = data_frame_from_decomposition_json( reference_simulation, decomposition_json = decomposition_json, remove_null = True) return data_frame if __name__ == '__main__': # test() # df = test_remove_null() df = test_fiche_de_paie_bareme() print(df)
agpl-3.0
fengoffice/fengoffice
application/models/project_files/base/BaseProjectFiles.class.php
7396
<?php /** * ProjectFiles class * * @author Ilija Studen <ilija.studen@gmail.com> */ abstract class BaseProjectFiles extends ContentDataObjects { /** * Column name => Column type map * * @var array * @static */ static private $columns = array( 'object_id' => DATA_TYPE_INTEGER, 'description' => DATA_TYPE_STRING, 'is_locked' => DATA_TYPE_BOOLEAN, 'is_visible' => DATA_TYPE_BOOLEAN, 'expiration_time' => DATA_TYPE_DATETIME, 'checked_out_on' => DATA_TYPE_DATETIME, 'checked_out_by_id' => DATA_TYPE_INTEGER, 'was_auto_checked_out' => DATA_TYPE_BOOLEAN, 'type' => DATA_TYPE_INTEGER, 'url' => DATA_TYPE_STRING, 'mail_id' => DATA_TYPE_INTEGER, 'attach_to_notification' => DATA_TYPE_BOOLEAN, 'default_subject' => DATA_TYPE_STRING, ); /** * Construct * * @return BaseProjectFiles */ function __construct() { Hook::fire('object_definition', 'ProjectFile', self::$columns); parent::__construct('ProjectFile', 'project_files', true); } // __construct // ------------------------------------------------------- // Description methods // ------------------------------------------------------- /** * Return array of object columns * * @access public * @param void * @return array */ function getColumns() { return array_keys(self::$columns); } // getColumns /** * Return column type * * @access public * @param string $column_name * @return string */ function getColumnType($column_name) { return parent::getCOColumnType($column_name, self::$columns); } /** * Return array of PK columns. If only one column is PK returns its name as string * * @access public * @param void * @return array or string */ function getPkColumns() { return 'object_id'; } // getPkColumns /** * Return name of first auto_incremenent column if it exists * * @access public * @param void * @return string */ function getAutoIncrementColumn() { return null; } // getAutoIncrementColumn /** * Return system columns * * @access public * @param void * @return array */ function getSystemColumns() { return array_merge(parent::getSystemColumns(), array( 'checked_out_by_id', 'was_auto_checked_out', 'mail_id', 'type', 'attach_to_notification', 'default_subject', 'expiration_time') ); } // getSystemColumns*/ /** * Return external columns * * @access public * @param void * @return array */ function getExternalColumns() { return array_merge(parent::getExternalColumns(), array()); } // getExternalColumns /** * Return report object title columns * * @access public * @param void * @return array */ function getReportObjectTitleColumns() { return array('filename'); } // getReportObjectTitleColumns /** * Return report object title * * @access public * @param void * @return string */ /*function getReportObjectTitle($values) { $filename = isset($values['filename']) ? $values['filename'] : ''; return $filename; } // getReportObjectTitle*/ // ------------------------------------------------------- // Finders // ------------------------------------------------------- /** * Do a SELECT query over database with specified arguments * * @access public * @param array $arguments Array of query arguments. Fields: * * - one - select first row * - conditions - additional conditions * - order - order by string * - offset - limit offset, valid only if limit is present * - limit * * @return one or ProjectFiles objects * @throws DBQueryError */ function find($arguments = null) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::find($arguments); } else { return ProjectFiles::instance()->find($arguments); } // if } // find /** * Find all records * * @access public * @param array $arguments * @return one or ProjectFiles objects */ function findAll($arguments = null) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::findAll($arguments); } else { return ProjectFiles::instance()->findAll($arguments); } // if } // findAll /** * Find one specific record * * @access public * @param array $arguments * @return ProjectFile */ function findOne($arguments = null) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::findOne($arguments); } else { return ProjectFiles::instance()->findOne($arguments); } // if } // findOne /** * Return object by its PK value * * @access public * @param mixed $id * @param boolean $force_reload If true cache will be skipped and data will be loaded from database * @return ProjectFile */ function findById($id, $force_reload = false) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::findById($id, $force_reload); } else { return ProjectFiles::instance()->findById($id, $force_reload); } // if } // findById /** * Return number of rows in this table * * @access public * @param string $conditions Query conditions * @return integer */ function count($condition = null) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::count($condition); } else { return ProjectFiles::instance()->count($condition); } // if } // count /** * Delete rows that match specific conditions. If $conditions is NULL all rows from table will be deleted * * @access public * @param string $conditions Query conditions * @return boolean */ function delete($condition = null) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::delete($condition); } else { return ProjectFiles::instance()->delete($condition); } // if } // delete /** * This function will return paginated result. Result is an array where first element is * array of returned object and second populated pagination object that can be used for * obtaining and rendering pagination data using various helpers. * * Items and pagination array vars are indexed with 0 for items and 1 for pagination * because you can't use associative indexing with list() construct * * @access public * @param array $arguments Query argumens (@see find()) Limit and offset are ignored! * @param integer $items_per_page Number of items per page * @param integer $current_page Current page number * @return array */ function paginate($arguments = null, $items_per_page = 10, $current_page = 1, $count = null) { if(isset($this) && instance_of($this, 'ProjectFiles')) { return parent::paginate($arguments, $items_per_page, $current_page); } else { return ProjectFiles::instance()->paginate($arguments, $items_per_page, $current_page); } // if } // paginate /** * Return manager instance * * @return ProjectFiles */ function instance() { static $instance; if(!instance_of($instance, 'ProjectFiles')) { $instance = new ProjectFiles(); } // if return $instance; } // instance } // ProjectFiles
agpl-3.0
torakiki/pdfsam
pdfsam-gui/src/test/java/org/pdfsam/ui/log/LogLevelTest.java
1463
/* * This file is part of the PDF Split And Merge source code * Created on 22/ago/2014 * Copyright 2017 by Sober Lemur S.a.s. di Vacondio Andrea (info@pdfsam.org). * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.pdfsam.ui.log; import static org.junit.Assert.assertEquals; import org.junit.Test; import ch.qos.logback.classic.Level; /** * @author Andrea Vacondio * */ public class LogLevelTest { @Test public void toLogLevel() { assertEquals(LogLevel.ERROR, LogLevel.toLogLevel(Level.ERROR_INT)); assertEquals(LogLevel.WARN, LogLevel.toLogLevel(Level.WARN_INT)); assertEquals(LogLevel.INFO, LogLevel.toLogLevel(Level.INFO_INT)); assertEquals(LogLevel.INFO, LogLevel.toLogLevel(Level.DEBUG_INT)); assertEquals(LogLevel.INFO, LogLevel.toLogLevel(Level.TRACE_INT)); } }
agpl-3.0
JBetser/MiDax
IGApi/IGPublicPcl/dto/endpoint/marketdetails/v2/DepositBand.cs
1221
using System.Collections.Generic; using dto.endpoint.auth.session; namespace dto.endpoint.marketdetails.v2 { /// <Summary> /// /// IG API - Sample Client /// /// Copyright 2014 IG Index /// /// 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. /// /// </Summary> public class DepositBand{ ///<Summary> ///Band minimum ///</Summary> public int min { get; set; } ///<Summary> ///Band maximum ///</Summary> public int max { get; set; } ///<Summary> ///Margin Percentage ///</Summary> public decimal? margin { get; set; } ///<Summary> ///the currency for this currency band factor calculation ///</Summary> public string currency { get; set; } } }
agpl-3.0
refugee-it/note_system
web/custom/lang/de/nationality.lang.php
1414
<?php /* Copyright (C) 2016-2017 Stephan Kreutzer * * This file is part of note system for refugee-it.de. * * note system for refugee-it.de is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License version 3 or any later version, * as published by the Free Software Foundation. * * note system for refugee-it.de is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License 3 for more details. * * You should have received a copy of the GNU Affero General Public License 3 * along with note system for refugee-it.de. If not, see <http://www.gnu.org/licenses/>. */ /** * @file $/web/custom/lang/de/nationality.lang.php * @author Stephan Kreutzer * @since 2016-11-27 */ define("LANG_CUSTOM_NATIONALITY_UNKNOWN", "unbekannt"); define("LANG_CUSTOM_NATIONALITY_SYRIAN", "Syrisch"); define("LANG_CUSTOM_NATIONALITY_IRAQI", "Irakisch"); define("LANG_CUSTOM_NATIONALITY_AFGHAN", "Afghanisch"); define("LANG_CUSTOM_NATIONALITY_PAKISTANI", "Pakistanisch"); define("LANG_CUSTOM_NATIONALITY_GAMBIAN", "Gambisch"); define("LANG_CUSTOM_NATIONALITY_KOSOVAR", "Kosovarisch"); define("LANG_CUSTOM_NATIONALITY_ALGERIAN", "Algerisch"); define("LANG_CUSTOM_NATIONALITY_SOMALI", "Somalisch"); ?>
agpl-3.0
Paperight/website
common/src/main/java/com/paperight/content/Article.java
4933
package com.paperight.content; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.PersistenceContext; import javax.persistence.PrePersist; import org.hibernate.annotations.Type; import org.joda.time.DateTime; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.transaction.annotation.Transactional; @Configurable @Entity public class Article implements Serializable { @PersistenceContext transient EntityManager entityManager; private static final long serialVersionUID = -1216751128340901649L; private Long id; private DateTime createdDate; private String name; private String title; private String content; private int revision = 0; private String language = "en"; private boolean published = false; public static final EntityManager entityManager() { EntityManager em = new Article().entityManager; if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)"); return em; } @SuppressWarnings("unused") @PrePersist private void onCreate() { this.setCreatedDate(new DateTime()); } public static long count() { return entityManager().createQuery("SELECT COUNT(o) FROM Article o", Long.class).getSingleResult(); } public static List<Article> findAll() { return entityManager().createQuery("SELECT o FROM Article o", Article.class).getResultList(); } public static List<Article> findLatestAll() { return entityManager().createQuery("SELECT o FROM Article o WHERE o.id in (SELECT MAX(a.id) FROM Article a GROUP By a.name)", Article.class).getResultList(); } public static Article find(Long id) { if (id == null) return null; return entityManager().find(Article.class, id); } public static Article findLatestByName(String name) { List<Article> articles = entityManager().createQuery("SELECT o FROM Article o WHERE o.id IN (SELECT MAX(a.id) FROM Article a WHERE a.name = :name)", Article.class).setParameter("name", name).getResultList(); return articles.isEmpty() ? null : articles.get(0); } @Transactional public void publishArticlesByName(String name, boolean isPublished) { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.createQuery("UPDATE Article SET published = :published WHERE name = :name)").setParameter("published", isPublished).setParameter("name", name).executeUpdate(); } @Transactional public void persist() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.persist(this); } @Transactional public void remove() { if (this.entityManager == null) this.entityManager = entityManager(); if (this.entityManager.contains(this)) { this.entityManager.remove(this); } else { Article attached = find(this.getId()); this.entityManager.remove(attached); } } @Transactional public void flush() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.flush(); } @Transactional public void clear() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.clear(); } @Transactional public Article merge() { if (this.entityManager == null) this.entityManager = entityManager(); Article merged = this.entityManager.merge(this); this.entityManager.flush(); return merged; } @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(nullable = false) @Type(type = "org.jadira.usertype.dateandtime.joda.PersistentDateTime") public DateTime getCreatedDate() { return createdDate; } public void setCreatedDate(DateTime createdDate) { this.createdDate = createdDate; } @Column(nullable = false) public String getName() { return name; } public void setName(String name) { this.name = name; } @Lob @Column(nullable = false) public String getContent() { return content; } public void setContent(String content) { this.content = content; } @Column(nullable = false) public int getRevision() { return revision; } public void setRevision(int revision) { this.revision = revision; } @Column(length = 3, nullable = false) public String getLanguage() { return language; } public void setLanguage(String language) { this.language = language; } @Column(nullable = false) public boolean isPublished() { return published; } public void setPublished(boolean published) { this.published = published; } //@Column(nullable = false) public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
agpl-3.0
ddmck/Empirical-Core
app/models/csv_exporter/standards/topic_student.rb
834
module CsvExporter::Standards class TopicStudent def header_row [ 'Page Title', 'Student Name', 'Activities', 'Average', 'Mastery Status' ] end def data_row(record, filters) json_hash = ProgressReports::Standards::StudentSerializer.new(record).as_json(root: false) [ page_title(filters), json_hash[:name], json_hash[:total_activity_count], json_hash[:average_score], json_hash[:mastery_status] ] end def model_data(teacher, filters) ::ProgressReports::Standards::Student.new(teacher) .results(HashWithIndifferentAccess.new(filters) || {}) end private def page_title(filters) topic = ::Topic.find(filters[:topic_id]) "Standards: #{topic.name}" end end end
agpl-3.0
alexhuang888/xibo-cms
tests/integration/ResolutionTest.php
8110
<?php /* * Spring Signage Ltd - http://www.springsignage.com * Copyright (C) 2015 Spring Signage Ltd * (ResolutionTest.php) */ namespace Xibo\Tests\Integration; use Xibo\Helper\Random; use Xibo\OAuth2\Client\Entity\XiboResolution; use Xibo\Tests\LocalWebTestCase; /** * Class ResolutionTest * @package Xibo\Tests\Integration */ class ResolutionTest extends LocalWebTestCase { protected $startResolutions; /** * setUp - called before every test automatically */ public function setup() { parent::setup(); $this->startResolutions = (new XiboResolution($this->getEntityProvider()))->get(['start' => 0, 'length' => 10000]); } /** * tearDown - called after every test automatically */ public function tearDown() { // tearDown all resolutions that weren't there initially $finalResolutions = (new XiboResolution($this->getEntityProvider()))->get(['start' => 0, 'length' => 10000]); # Loop over any remaining resolutions and nuke them foreach ($finalResolutions as $resolution) { /** @var XiboResolution $resolution */ $flag = true; foreach ($this->startResolutions as $startRes) { if ($startRes->resolutionId == $resolution->resolutionId) { $flag = false; } } if ($flag) { try { $resolution->delete(); } catch (\Exception $e) { fwrite(STDERR, 'Unable to delete ' . $resolution->resolutionId . '. E:' . $e->getMessage()); } } } parent::tearDown(); } public function testListAll() { $this->client->get('/resolution'); $this->assertSame(200, $this->client->response->status()); $this->assertNotEmpty($this->client->response->body()); $object = json_decode($this->client->response->body()); $this->assertObjectHasAttribute('data', $object, $this->client->response->body()); } /** * testAddSuccess - test adding various Resolutions that should be valid * @dataProvider provideSuccessCases * @group minimal */ public function testAddSuccess($resolutionName, $resolutionWidth, $resolutionHeight) { // Loop through any pre-existing resolutions to make sure we're not // going to get a clash foreach ($this->startResolutions as $tmpRes) { if ($tmpRes->resolution == $resolutionName) { $this->skipTest("There is a pre-existing resolution with this name"); return; } } $response = $this->client->post('/resolution', [ 'resolution' => $resolutionName, 'width' => $resolutionWidth, 'height' => $resolutionHeight ]); $this->assertSame(200, $this->client->response->status(), "Not successful: " . $response); $object = json_decode($this->client->response->body()); $this->assertObjectHasAttribute('data', $object); $this->assertObjectHasAttribute('id', $object); $this->assertSame($resolutionName, $object->data->resolution); $this->assertSame($resolutionWidth, $object->data->width); $this->assertSame($resolutionHeight, $object->data->height); # Check that the resolution was added correctly $resolution = (new XiboResolution($this->getEntityProvider()))->getById($object->id); $this->assertSame($resolutionName, $resolution->resolution); $this->assertSame($resolutionWidth, $resolution->width); $this->assertSame($resolutionHeight, $resolution->height); # Clean up the Resolutions as we no longer need it $this->assertTrue($resolution->delete(), 'Unable to delete ' . $resolution->resolutionId); } /** * Each array is a test run * Format (resolution name, width, height) * @return array */ public function provideSuccessCases() { return [ 'resolution 1' => ['test resolution', 800, 200], 'resolution 2' => ['different test resolution', 1069, 1699] ]; } /** * testAddFailure - test adding various resolutions that should be invalid * @dataProvider provideFailureCases */ public function testAddFailure($resolutionName, $resolutionWidth, $resolutionHeight) { $response = $this->client->post('/resolution', [ 'resolution' => $resolutionName, 'width' => $resolutionWidth, 'height' => $resolutionHeight ]); $this->assertSame(500, $this->client->response->status(), 'Expecting failure, received ' . $this->client->response->status()); } /** * Each array is a test run * Format (resolution name, width, height) * @return array */ public function provideFailureCases() { return [ 'incorrect width and height' => ['wrong parameters', 'abc', NULL], 'incorrect width' => [12, 'width', 1699] ]; } /** * Edit an existing resolution * @depends testAddSuccess * @group minimal */ public function testEdit() { # Load in a known resolution /** @var XiboResolution $resolution */ $resolution = (new XiboResolution($this->getEntityProvider()))->create('phpunit resolution', 1200, 860); $newWidth = 2400; # Change the resolution name, width and enable flag $name = Random::generateString(8, 'phpunit'); $this->client->put('/resolution/' . $resolution->resolutionId, [ 'resolution' => $name, 'width' => $newWidth, 'height' => $resolution->height, 'enabled' => 0 ], ['CONTENT_TYPE' => 'application/x-www-form-urlencoded']); $this->assertSame(200, $this->client->response->status(), 'Not successful: ' . $this->client->response->body()); $object = json_decode($this->client->response->body()); # Examine the returned object and check that it's what we expect $this->assertObjectHasAttribute('data', $object); $this->assertObjectHasAttribute('id', $object); $this->assertSame($name, $object->data->resolution); $this->assertSame($newWidth, $object->data->width); $this->assertSame(0, $object->data->enabled); # Check that the resolution was actually renamed $resolution = (new XiboResolution($this->getEntityProvider()))->getById($object->id); $this->assertSame($name, $resolution->resolution); $this->assertSame($newWidth, $resolution->width); # Clean up the resolution as we no longer need it $resolution->delete(); } /** * Test delete * @depends testAddSuccess * @group minimal */ public function testDelete() { $name1 = Random::generateString(8, 'phpunit'); $name2 = Random::generateString(8, 'phpunit'); # Load in a couple of known resolutions $res1 = (new XiboResolution($this->getEntityProvider()))->create($name1, 1000, 500); $res2 = (new XiboResolution($this->getEntityProvider()))->create($name2, 2000, 760); # Delete the one we created last $this->client->delete('/resolution/' . $res2->resolutionId); # This should return 204 for success $response = json_decode($this->client->response->body()); $this->assertSame(200, $response->status, $this->client->response->body()); # Check only one remains $resolutions = (new XiboResolution($this->getEntityProvider()))->get(); $this->assertEquals(count($this->startResolutions) + 1, count($resolutions)); $flag = false; foreach ($resolutions as $res) { if ($res->resolutionId == $res1->resolutionId) { $flag = true; } } $this->assertTrue($flag, 'Resolution ID ' . $res1->resolutionId . ' was not found after deleting a different Resolution'); $res1->delete(); } }
agpl-3.0
RBSChange/modules.videos
actions/DisplayYoutubeVideoBoAction.class.php
381
<?php /** * videos_DisplayYoutubeVideoBoAction * @package modules.videos.actions */ class videos_DisplayYoutubeVideoBoAction extends f_action_BaseAction { /** * @param Context $context * @param Request $request */ public function _execute($context, $request) { $request->setParameter("video", $this->getDocumentInstanceFromRequest($request)); return 'Success'; } }
agpl-3.0
ging/isabel
components/audio/app4/common/vumeter.cpp
3353
///////////////////////////////////////////////////////////////////////// // // ISABEL: A group collaboration tool for the Internet // Copyright (C) 2009 Agora System S.A. // // This file is part of Isabel. // // Isabel is free software: you can redistribute it and/or modify // it under the terms of the Affero GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Isabel is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // Affero GNU General Public License for more details. // // You should have received a copy of the Affero GNU General Public License // along with Isabel. If not, see <http://www.gnu.org/licenses/>. // ///////////////////////////////////////////////////////////////////////// #include "vumeter.h" #include <icf2/notify.hh> #include <icf2/sockIO.hh> #include <math.h> // ----------------------------------------------------------------------------- // Vumeter::Vumeter // // ----------------------------------------------------------------------------- // Vumeter::Vumeter(u32 achId, int abeats, dgramSocket_t *sock, const char *aport, const char *anotherport ) : chId(achId), beats(abeats), counter(0), socket(sock), addr2(NULL) { header.SetSSRC(chId); header.SetPayloadType(VUMETER_PT); addr = new inetAddr_t("127.0.0.1", aport, serviceAddr_t::DGRAM); if (anotherport) addr2 = new inetAddr_t("127.0.0.1", anotherport, serviceAddr_t::DGRAM); } // ----------------------------------------------------------------------------- // Vumeter::~Vumeter // // ----------------------------------------------------------------------------- // Vumeter::~Vumeter(void) { if (addr) delete addr; if (addr2) delete addr2; } // ----------------------------------------------------------------------------- // Vumeter::nextData // // ----------------------------------------------------------------------------- // void Vumeter::nextData(double power) { static unsigned char packet[PACKET_SIZE]; // Almaceno el dato data[counter++] = power; // Si hay suficientes datos se envia un paquete if (counter >= beats) { double media = 0; for (int i = 0; i < counter; i++) { media += pow(10.0, data[i]/10); } media = media/counter; media = 10*log10(media); media = media*2+100; // Para que el valor quede entre 0 y 100; if (media > 100) media = 100; if (media < 0) media = 0; if (media > 2 && media < 35) media = 35; char result = (char)media; header.SetSeqNumber(header.GetSeqNumber() + 1); header.SetTimestamp(header.GetTimestamp() + 1); memcpy(packet, &header, RTPHeader::SIZE); memcpy(packet+RTPHeader::SIZE, ((char*)&header) + 8, 4); memcpy(packet+RTPHeader::SIZE+4, &result, 1); socket->writeTo(*addr, packet, PACKET_SIZE); if (addr2) { socket->writeTo(*addr2, packet, PACKET_SIZE); } counter = 0; } }
agpl-3.0
mtlchun/edx
lms/djangoapps/student_account/test/test_views.py
19573
# -*- coding: utf-8 -*- """ Tests for student account views. """ import re from unittest import skipUnless from urllib import urlencode import json import mock import ddt import markupsafe from django.test import TestCase from django.conf import settings from django.core.urlresolvers import reverse from django.core import mail from django.test.utils import override_settings from util.testing import UrlResetMixin from third_party_auth.tests.testutil import simulate_running_pipeline from embargo.test_utils import restrict_course from openedx.core.djangoapps.user_api.api import account as account_api from openedx.core.djangoapps.user_api.api import profile as profile_api from xmodule.modulestore.tests.django_utils import ( ModuleStoreTestCase, mixed_store_config ) from xmodule.modulestore.tests.factories import CourseFactory from student.tests.factories import CourseModeFactory @ddt.ddt class StudentAccountUpdateTest(UrlResetMixin, TestCase): """ Tests for the student account views that update the user's account information. """ USERNAME = u"heisenberg" ALTERNATE_USERNAME = u"walt" OLD_PASSWORD = u"ḅḷüëṡḳÿ" NEW_PASSWORD = u"🄱🄸🄶🄱🄻🅄🄴" OLD_EMAIL = u"walter@graymattertech.com" NEW_EMAIL = u"walt@savewalterwhite.com" INVALID_ATTEMPTS = 100 INVALID_EMAILS = [ None, u"", u"a", "no_domain", "no+domain", "@", "@domain.com", "test@no_extension", # Long email -- subtract the length of the @domain # except for one character (so we exceed the max length limit) u"{user}@example.com".format( user=(u'e' * (account_api.EMAIL_MAX_LENGTH - 11)) ) ] INVALID_KEY = u"123abc" def setUp(self): super(StudentAccountUpdateTest, self).setUp("student_account.urls") # Create/activate a new account activation_key = account_api.create_account(self.USERNAME, self.OLD_PASSWORD, self.OLD_EMAIL) account_api.activate_account(activation_key) # Login result = self.client.login(username=self.USERNAME, password=self.OLD_PASSWORD) self.assertTrue(result) @skipUnless(settings.ROOT_URLCONF == 'lms.urls', 'Test only valid in LMS') def test_password_change(self): # Request a password change while logged in, simulating # use of the password reset link from the account page response = self._change_password() self.assertEqual(response.status_code, 200) # Check that an email was sent self.assertEqual(len(mail.outbox), 1) # Retrieve the activation link from the email body email_body = mail.outbox[0].body result = re.search('(?P<url>https?://[^\s]+)', email_body) self.assertIsNot(result, None) activation_link = result.group('url') # Visit the activation link response = self.client.get(activation_link) self.assertEqual(response.status_code, 200) # Submit a new password and follow the redirect to the success page response = self.client.post( activation_link, # These keys are from the form on the current password reset confirmation page. {'new_password1': self.NEW_PASSWORD, 'new_password2': self.NEW_PASSWORD}, follow=True ) self.assertEqual(response.status_code, 200) self.assertContains(response, "Your password has been set.") # Log the user out to clear session data self.client.logout() # Verify that the new password can be used to log in result = self.client.login(username=self.USERNAME, password=self.NEW_PASSWORD) self.assertTrue(result) # Try reusing the activation link to change the password again response = self.client.post( activation_link, {'new_password1': self.OLD_PASSWORD, 'new_password2': self.OLD_PASSWORD}, follow=True ) self.assertEqual(response.status_code, 200) self.assertContains(response, "The password reset link was invalid, possibly because the link has already been used.") self.client.logout() # Verify that the old password cannot be used to log in result = self.client.login(username=self.USERNAME, password=self.OLD_PASSWORD) self.assertFalse(result) # Verify that the new password continues to be valid result = self.client.login(username=self.USERNAME, password=self.NEW_PASSWORD) self.assertTrue(result) @ddt.data(True, False) def test_password_change_logged_out(self, send_email): # Log the user out self.client.logout() # Request a password change while logged out, simulating # use of the password reset link from the login page if send_email: response = self._change_password(email=self.OLD_EMAIL) self.assertEqual(response.status_code, 200) else: # Don't send an email in the POST data, simulating # its (potentially accidental) omission in the POST # data sent from the login page response = self._change_password() self.assertEqual(response.status_code, 400) def test_password_change_inactive_user(self): # Log out the user created during test setup self.client.logout() # Create a second user, but do not activate it account_api.create_account(self.ALTERNATE_USERNAME, self.OLD_PASSWORD, self.NEW_EMAIL) # Send the view the email address tied to the inactive user response = self._change_password(email=self.NEW_EMAIL) # Expect that the activation email is still sent, # since the user may have lost the original activation email. self.assertEqual(response.status_code, 200) self.assertEqual(len(mail.outbox), 1) def test_password_change_no_user(self): # Log out the user created during test setup self.client.logout() # Send the view an email address not tied to any user response = self._change_password(email=self.NEW_EMAIL) self.assertEqual(response.status_code, 400) def test_password_change_rate_limited(self): # Log out the user created during test setup, to prevent the view from # selecting the logged-in user's email address over the email provided # in the POST data self.client.logout() # Make many consecutive bad requests in an attempt to trigger the rate limiter for attempt in xrange(self.INVALID_ATTEMPTS): self._change_password(email=self.NEW_EMAIL) response = self._change_password(email=self.NEW_EMAIL) self.assertEqual(response.status_code, 403) @ddt.data( ('post', 'password_change_request', []), ) @ddt.unpack def test_require_http_method(self, correct_method, url_name, args): wrong_methods = {'get', 'put', 'post', 'head', 'options', 'delete'} - {correct_method} url = reverse(url_name, args=args) for method in wrong_methods: response = getattr(self.client, method)(url) self.assertEqual(response.status_code, 405) def _change_password(self, email=None): """Request to change the user's password. """ data = {} if email: data['email'] = email return self.client.post(path=reverse('password_change_request'), data=data) @ddt.ddt class StudentAccountLoginAndRegistrationTest(UrlResetMixin, ModuleStoreTestCase): """ Tests for the student account views that update the user's account information. """ USERNAME = "bob" EMAIL = "bob@example.com" PASSWORD = "password" @mock.patch.dict(settings.FEATURES, {'ENABLE_COUNTRY_ACCESS': True}) def setUp(self): super(StudentAccountLoginAndRegistrationTest, self).setUp('embargo') @ddt.data( ("account_login", "login"), ("account_register", "register"), ) @ddt.unpack def test_login_and_registration_form(self, url_name, initial_mode): response = self.client.get(reverse(url_name)) expected_data = u"data-initial-mode=\"{mode}\"".format(mode=initial_mode) self.assertContains(response, expected_data) @ddt.data("account_login", "account_register") def test_login_and_registration_form_already_authenticated(self, url_name): # Create/activate a new account and log in activation_key = account_api.create_account(self.USERNAME, self.PASSWORD, self.EMAIL) account_api.activate_account(activation_key) result = self.client.login(username=self.USERNAME, password=self.PASSWORD) self.assertTrue(result) # Verify that we're redirected to the dashboard response = self.client.get(reverse(url_name)) self.assertRedirects(response, reverse("dashboard")) @ddt.data( (False, "account_login"), (False, "account_login"), (True, "account_login"), (True, "account_register"), ) @ddt.unpack def test_login_and_registration_form_signin_preserves_params(self, is_edx_domain, url_name): params = { 'enrollment_action': 'enroll', 'course_id': 'edX/DemoX/Demo_Course' } with mock.patch.dict(settings.FEATURES, {'IS_EDX_DOMAIN': is_edx_domain}): response = self.client.get(reverse(url_name), params) # The response should have a "Sign In" button with the URL # that preserves the querystring params self.assertContains(response, "login?course_id=edX%2FDemoX%2FDemo_Course&enrollment_action=enroll") @mock.patch.dict(settings.FEATURES, {"ENABLE_THIRD_PARTY_AUTH": False}) @ddt.data("account_login", "account_register") def test_third_party_auth_disabled(self, url_name): response = self.client.get(reverse(url_name)) self._assert_third_party_auth_data(response, None, []) @ddt.data( ("account_login", None, None), ("account_register", None, None), ("account_login", "google-oauth2", "Google"), ("account_register", "google-oauth2", "Google"), ("account_login", "facebook", "Facebook"), ("account_register", "facebook", "Facebook"), ) @ddt.unpack def test_third_party_auth(self, url_name, current_backend, current_provider): # Simulate a running pipeline if current_backend is not None: pipeline_target = "student_account.views.third_party_auth.pipeline" with simulate_running_pipeline(pipeline_target, current_backend): response = self.client.get(reverse(url_name)) # Do NOT simulate a running pipeline else: response = self.client.get(reverse(url_name)) # This relies on the THIRD_PARTY_AUTH configuration in the test settings expected_providers = [ { "name": "Facebook", "iconClass": "fa-facebook", "loginUrl": self._third_party_login_url("facebook", "login"), "registerUrl": self._third_party_login_url("facebook", "register") }, { "name": "Google", "iconClass": "fa-google-plus", "loginUrl": self._third_party_login_url("google-oauth2", "login"), "registerUrl": self._third_party_login_url("google-oauth2", "register") } ] self._assert_third_party_auth_data(response, current_provider, expected_providers) @ddt.data([], ["honor"], ["honor", "verified", "audit"], ["professional"]) def test_third_party_auth_course_id_verified(self, modes): # Create a course with the specified course modes course = CourseFactory.create() for slug in modes: CourseModeFactory.create( course_id=course.id, mode_slug=slug, mode_display_name=slug ) # Verify that the entry URL for third party auth # contains the course ID and redirects to the track selection page. course_modes_choose_url = reverse( "course_modes_choose", kwargs={"course_id": unicode(course.id)} ) expected_providers = [ { "name": "Facebook", "iconClass": "fa-facebook", "loginUrl": self._third_party_login_url( "facebook", "login", course_id=unicode(course.id), redirect_url=course_modes_choose_url ), "registerUrl": self._third_party_login_url( "facebook", "register", course_id=unicode(course.id), redirect_url=course_modes_choose_url ) }, { "name": "Google", "iconClass": "fa-google-plus", "loginUrl": self._third_party_login_url( "google-oauth2", "login", course_id=unicode(course.id), redirect_url=course_modes_choose_url ), "registerUrl": self._third_party_login_url( "google-oauth2", "register", course_id=unicode(course.id), redirect_url=course_modes_choose_url ) } ] # Verify that the login page contains the correct provider URLs response = self.client.get(reverse("account_login"), {"course_id": unicode(course.id)}) self._assert_third_party_auth_data(response, None, expected_providers) def test_third_party_auth_course_id_shopping_cart(self): # Create a course with a white-label course mode course = CourseFactory.create() CourseModeFactory.create( course_id=course.id, mode_slug="honor", mode_display_name="Honor", min_price=100 ) # Verify that the entry URL for third party auth # contains the course ID and redirects to the shopping cart shoppingcart_url = reverse("shoppingcart.views.show_cart") expected_providers = [ { "name": "Facebook", "iconClass": "fa-facebook", "loginUrl": self._third_party_login_url( "facebook", "login", course_id=unicode(course.id), redirect_url=shoppingcart_url ), "registerUrl": self._third_party_login_url( "facebook", "register", course_id=unicode(course.id), redirect_url=shoppingcart_url ) }, { "name": "Google", "iconClass": "fa-google-plus", "loginUrl": self._third_party_login_url( "google-oauth2", "login", course_id=unicode(course.id), redirect_url=shoppingcart_url ), "registerUrl": self._third_party_login_url( "google-oauth2", "register", course_id=unicode(course.id), redirect_url=shoppingcart_url ) } ] # Verify that the login page contains the correct provider URLs response = self.client.get(reverse("account_login"), {"course_id": unicode(course.id)}) self._assert_third_party_auth_data(response, None, expected_providers) @mock.patch.dict(settings.FEATURES, {'ENABLE_COUNTRY_ACCESS': True}) def test_third_party_auth_enrollment_embargo(self): course = CourseFactory.create() # Start the pipeline attempting to enroll in a restricted course with restrict_course(course.id) as redirect_url: response = self.client.get(reverse("account_login"), {"course_id": unicode(course.id)}) # Expect that the course ID has been removed from the # login URLs (so the user won't be enrolled) and # the ?next param sends users to the blocked message. expected_providers = [ { "name": "Facebook", "iconClass": "fa-facebook", "loginUrl": self._third_party_login_url( "facebook", "login", course_id=unicode(course.id), redirect_url=redirect_url ), "registerUrl": self._third_party_login_url( "facebook", "register", course_id=unicode(course.id), redirect_url=redirect_url ) }, { "name": "Google", "iconClass": "fa-google-plus", "loginUrl": self._third_party_login_url( "google-oauth2", "login", course_id=unicode(course.id), redirect_url=redirect_url ), "registerUrl": self._third_party_login_url( "google-oauth2", "register", course_id=unicode(course.id), redirect_url=redirect_url ) } ] self._assert_third_party_auth_data(response, None, expected_providers) @override_settings(SITE_NAME=settings.MICROSITE_TEST_HOSTNAME) def test_microsite_uses_old_login_page(self): # Retrieve the login page from a microsite domain # and verify that we're served the old page. resp = self.client.get( reverse("account_login"), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME ) self.assertContains(resp, "Log into your Test Microsite Account") self.assertContains(resp, "login-form") def test_microsite_uses_old_register_page(self): # Retrieve the register page from a microsite domain # and verify that we're served the old page. resp = self.client.get( reverse("account_register"), HTTP_HOST=settings.MICROSITE_TEST_HOSTNAME ) self.assertContains(resp, "Register for Test Microsite") self.assertContains(resp, "register-form") def _assert_third_party_auth_data(self, response, current_provider, providers): """Verify that third party auth info is rendered correctly in a DOM data attribute. """ auth_info = markupsafe.escape( json.dumps({ "currentProvider": current_provider, "providers": providers }) ) expected_data = u"data-third-party-auth='{auth_info}'".format( auth_info=auth_info ) self.assertContains(response, expected_data) def _third_party_login_url(self, backend_name, auth_entry, course_id=None, redirect_url=None): """Construct the login URL to start third party authentication. """ params = [("auth_entry", auth_entry)] if redirect_url: params.append(("next", redirect_url)) if course_id: params.append(("enroll_course_id", course_id)) return u"{url}?{params}".format( url=reverse("social:begin", kwargs={"backend": backend_name}), params=urlencode(params) )
agpl-3.0
chk1/openmensa
config/initializers/geocoder.rb
398
# config/initializers/geocoder.rb Geocoder.configure( # geocoding service lookup: :nominatim, http_headers: {'User-Agent' => 'RubyGeocoder openmensa.org / info@openmensa.org'}, # geocoding service request timeout, in seconds (default 3): timeout: 3, # set default units to kilometers: units: :km, # caching (see below for details): #:cache => Redis.new, #:cache_prefix => "..." )
agpl-3.0
nekodex/osu-web
resources/views/layout/_nav2.blade.php
7407
{{-- Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the GNU Affero General Public License v3.0. See the LICENCE file in the repository root for full licence text. --}} <div class="nav2 js-nav-button"> <div class="nav2__colgroup nav2__colgroup--menu js-nav-button--container"> <div class="nav2__col nav2__col--logo"> <a href="{{ route('home') }}" class="nav2__logo-link"> <div class="nav2__logo nav2__logo--bg"></div> <div class="nav2__logo"></div> </a> </div> @foreach (nav_links() as $section => $links) <div class="nav2__col nav2__col--menu"> <a class="nav2__menu-link-main js-menu" href="{{ $links['_'] ?? array_first($links) }}" data-menu-target="nav2-menu-popup-{{ $section }}" data-menu-show-delay="0" > <span class="u-relative"> {{ trans("layout.menu.{$section}._") }} @if ($section === $currentSection && !($isSearchPage ?? false)) <span class="nav2__menu-link-bar u-section--bg-normal"></span> @endif </span> </a> <div class="nav2__menu-popup"> <div class=" simple-menu simple-menu--nav2 simple-menu--nav2-left-aligned simple-menu--nav2-transparent js-menu " data-menu-id="nav2-menu-popup-{{ $section }}" data-visibility="hidden" > @foreach ($links as $action => $link) @if ($action === '_') @continue @endif <a class="simple-menu__item u-section-{{ $section }}--before-bg-normal" href="{{ $link }}"> {{ trans("layout.menu.{$section}.{$action}") }} </a> @endforeach </div> </div> </div> @endforeach <div class="nav2__col nav2__col--menu js-react--quick-search-button"> <a href="{{ route('search') }}" class=" nav2__menu-link-main nav2__menu-link-main--search {{ isset($isSearchPage) ? 'u-section--bg-normal' : '' }} " > <span class="fas fa-search"></span> </a> </div> </div> <div class="nav2__colgroup js-nav-button--container"> <div class="nav2__col js-nav-button--item"> <a href="{{ osu_url('social.twitter') }}" class="nav-button nav-button--social" title="Twitter" > <span class="fab fa-twitter"></span> </a> </div> <div class="nav2__col"> <a href="{{ route('support-the-game') }}" class="nav-button nav-button--support" title="{{ trans('page_title.main.home_controller.support_the_game') }}" > <span class="fas fa-heart"></span> </a> </div> <div class="nav2__col"> <button class="nav-button nav-button--stadium js-click-menu" data-click-menu-target="nav2-locale-popup" > <img class="nav-button__locale-current-flag" alt="{{ App::getLocale() }}" src="{{ flag_path(locale_flag(App::getLocale())) }}" > </button> <div class="nav-click-popup"> <div class="simple-menu simple-menu--nav2 simple-menu--nav2-locales js-click-menu js-nav2--centered-popup" data-click-menu-id="nav2-locale-popup" data-visibility="hidden" > <div class="simple-menu__content"> @foreach (config('app.available_locales') as $locale) <button type="button" class=" simple-menu__item {{ $locale === App::getLocale() ? 'simple-menu__item--active' : '' }} " @if ($locale !== App::getLocale()) data-url="{{ route('set-locale', ['locale' => $locale]) }}" data-remote="1" data-method="POST" @endif > <span class="nav2-locale-item"> <img src="{{ flag_path(locale_flag($locale)) }}" alt="{{ $locale }}" class="nav2-locale-item__flag" > {{ locale_name($locale) }} </span> </button> @endforeach </div> </div> </div> </div> @if (Auth::user() !== null) <div class="nav2__col"> <a class="nav-button nav-button--stadium js-react--chat-icon" href="{{ route('chat.index') }}" > <span class="notification-icon"> <i class="fas fa-comment-alt"></i> <span class="notification-icon__count">...</span> </span> </a> </div> <div class="nav2__col"> <button class="nav-button nav-button--stadium js-click-menu js-react--notification-icon" data-click-menu-target="nav2-notification-widget" > <span class="notification-icon"> <i class="fas fa-inbox"></i> <span class="notification-icon__count">...</span> </span> </button> <div class="nav-click-popup js-click-menu js-react--notification-widget" data-click-menu-id="nav2-notification-widget" data-visibility="hidden" data-notification-widget="{{ json_encode(['extraClasses' => 'js-nav2--centered-popup']) }}" ></div> </div> @endif <div class="nav2__col nav2__col--avatar"> @include('layout._header_user') <div class="nav-click-popup nav-click-popup--user js-user-header-popup"> @if (Auth::user() !== null) @include('layout._popup_user') @endif </div> </div> </div> </div>
agpl-3.0
myplaceonline/myplaceonline_rails
db/migrate/20160417200614_add_columns2_to_emails.rb
116
class AddColumns2ToEmails < ActiveRecord::Migration def change add_column :emails, :draft, :boolean end end
agpl-3.0
django-rea/nrp
django_rea/valueaccounting/templatetags/footer_tag.py
332
from django import template from django_rea.valueaccounting.models import HomePageLayout register = template.Library() def footer(): try: layout = HomePageLayout.objects.get(id=1) footer = layout.footer except HomePageLayout.DoesNotExist: footer = "" return footer register.simple_tag(footer)
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/IfcOutletTypeEnum.java
9774
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc4; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Ifc Outlet Type Enum</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcOutletTypeEnum() * @model * @generated */ public enum IfcOutletTypeEnum implements Enumerator { /** * The '<em><b>NULL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NULL_VALUE * @generated * @ordered */ NULL(0, "NULL", "NULL"), /** * The '<em><b>NOTDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NOTDEFINED_VALUE * @generated * @ordered */ NOTDEFINED(1, "NOTDEFINED", "NOTDEFINED"), /** * The '<em><b>POWEROUTLET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #POWEROUTLET_VALUE * @generated * @ordered */ POWEROUTLET(2, "POWEROUTLET", "POWEROUTLET"), /** * The '<em><b>TELEPHONEOUTLET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #TELEPHONEOUTLET_VALUE * @generated * @ordered */ TELEPHONEOUTLET(3, "TELEPHONEOUTLET", "TELEPHONEOUTLET"), /** * The '<em><b>DATAOUTLET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #DATAOUTLET_VALUE * @generated * @ordered */ DATAOUTLET(4, "DATAOUTLET", "DATAOUTLET"), /** * The '<em><b>USERDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #USERDEFINED_VALUE * @generated * @ordered */ USERDEFINED(5, "USERDEFINED", "USERDEFINED"), /** * The '<em><b>COMMUNICATIONSOUTLET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #COMMUNICATIONSOUTLET_VALUE * @generated * @ordered */ COMMUNICATIONSOUTLET(6, "COMMUNICATIONSOUTLET", "COMMUNICATIONSOUTLET"), /** * The '<em><b>AUDIOVISUALOUTLET</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #AUDIOVISUALOUTLET_VALUE * @generated * @ordered */ AUDIOVISUALOUTLET(7, "AUDIOVISUALOUTLET", "AUDIOVISUALOUTLET"); /** * The '<em><b>NULL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NULL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NULL * @model * @generated * @ordered */ public static final int NULL_VALUE = 0; /** * The '<em><b>NOTDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NOTDEFINED * @model * @generated * @ordered */ public static final int NOTDEFINED_VALUE = 1; /** * The '<em><b>POWEROUTLET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>POWEROUTLET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #POWEROUTLET * @model * @generated * @ordered */ public static final int POWEROUTLET_VALUE = 2; /** * The '<em><b>TELEPHONEOUTLET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>TELEPHONEOUTLET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #TELEPHONEOUTLET * @model * @generated * @ordered */ public static final int TELEPHONEOUTLET_VALUE = 3; /** * The '<em><b>DATAOUTLET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>DATAOUTLET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #DATAOUTLET * @model * @generated * @ordered */ public static final int DATAOUTLET_VALUE = 4; /** * The '<em><b>USERDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #USERDEFINED * @model * @generated * @ordered */ public static final int USERDEFINED_VALUE = 5; /** * The '<em><b>COMMUNICATIONSOUTLET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>COMMUNICATIONSOUTLET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #COMMUNICATIONSOUTLET * @model * @generated * @ordered */ public static final int COMMUNICATIONSOUTLET_VALUE = 6; /** * The '<em><b>AUDIOVISUALOUTLET</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>AUDIOVISUALOUTLET</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #AUDIOVISUALOUTLET * @model * @generated * @ordered */ public static final int AUDIOVISUALOUTLET_VALUE = 7; /** * An array of all the '<em><b>Ifc Outlet Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final IfcOutletTypeEnum[] VALUES_ARRAY = new IfcOutletTypeEnum[] { NULL, NOTDEFINED, POWEROUTLET, TELEPHONEOUTLET, DATAOUTLET, USERDEFINED, COMMUNICATIONSOUTLET, AUDIOVISUALOUTLET, }; /** * A public read-only list of all the '<em><b>Ifc Outlet Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<IfcOutletTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Ifc Outlet Type Enum</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcOutletTypeEnum get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcOutletTypeEnum result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Outlet Type Enum</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcOutletTypeEnum getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcOutletTypeEnum result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Outlet Type Enum</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcOutletTypeEnum get(int value) { switch (value) { case NULL_VALUE: return NULL; case NOTDEFINED_VALUE: return NOTDEFINED; case POWEROUTLET_VALUE: return POWEROUTLET; case TELEPHONEOUTLET_VALUE: return TELEPHONEOUTLET; case DATAOUTLET_VALUE: return DATAOUTLET; case USERDEFINED_VALUE: return USERDEFINED; case COMMUNICATIONSOUTLET_VALUE: return COMMUNICATIONSOUTLET; case AUDIOVISUALOUTLET_VALUE: return AUDIOVISUALOUTLET; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private IfcOutletTypeEnum(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //IfcOutletTypeEnum
agpl-3.0
grafana/grafana
public/app/features/runtime/init.ts
1376
import { PanelData } from '@grafana/data'; import { getDashboardSrv } from 'app/features/dashboard/services/DashboardSrv'; import { getTimeSrv } from 'app/features/dashboard/services/TimeSrv'; /** * This will setup features that are accessible through the root window location * * This is useful for manipulating the application from external drivers like puppetter/cypress * * @internal and subject to change */ export function initWindowRuntime() { (window as any).grafanaRuntime = { /** Get info for the current dashboard. This will include the migrated dashboard JSON */ getDashboardSaveModel: () => { const d = getDashboardSrv().getCurrent(); if (!d) { return undefined; } return d.getSaveModelClone(); }, /** The selected time range */ getDashboardTimeRange: () => { const tr = getTimeSrv().timeRange(); return { from: tr.from.valueOf(), to: tr.to.valueOf(), raw: tr.raw, }; }, /** Get the query results for the last loaded data */ getPanelData: () => { const d = getDashboardSrv().getCurrent(); if (!d) { return undefined; } return d.panels.reduce((acc, panel) => { acc[panel.id] = panel.getQueryRunner().getLastResult(); return acc; }, {} as Record<number, PanelData | undefined>); }, }; }
agpl-3.0
kaltura/KalturaGeneratedAPIClientsCsharp
KalturaClient/Types/MetroPcsDistributionProfileBaseFilter.cs
2340
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2021 Kaltura Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // @ignore // =================================================================================================== using System; using System.Xml; using System.Collections.Generic; using Kaltura.Enums; using Kaltura.Request; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Kaltura.Types { public class MetroPcsDistributionProfileBaseFilter : ConfigurableDistributionProfileFilter { #region Constants #endregion #region Private Fields #endregion #region Properties #endregion #region CTor public MetroPcsDistributionProfileBaseFilter() { } public MetroPcsDistributionProfileBaseFilter(JToken node) : base(node) { } #endregion #region Methods public override Params ToParams(bool includeObjectType = true) { Params kparams = base.ToParams(includeObjectType); if (includeObjectType) kparams.AddReplace("objectType", "KalturaMetroPcsDistributionProfileBaseFilter"); return kparams; } protected override string getPropertyName(string apiName) { switch(apiName) { default: return base.getPropertyName(apiName); } } #endregion } }
agpl-3.0
cherrygirl/micronaet7
Script/Analisi fatture IMAP/header_analisi_imap.py
3358
#!/usr/bin/python # -*- encoding: utf-8 -*- # Before export data with sprix 549 # Elaboration # Auto open CSV files import os import sys import imaplib import email import subprocess # Access IMAP folder: mail = imaplib.IMAP4_SSL('imap.gmail.com') mail.login('zipperr.fatture@gmail.com', 'password') mail.list() mail.select("inbox") # Connect to inbox. # Read file for get list of invoice and create a CSV output: f_in = open("ftmail.ZPR","r") f_out = open("ftmail.csv","w") formato_csv = "%s,%06d,%s,%s,%s,%s\n" # Num. fattura, Esito, Descrizione, Note # intestazione: f_out.write("%s,%s,%s,%s,%s,%s\n" % ( "Documento", "Numero", "Stato", "Cliente", "Descrizione", "Note", )) for line in f_in: invoice = int(line[:6].strip()) customer = line[16:46].strip().replace(",", ".") to_mexal = line[47:107].strip() documento = line[108:110].strip().upper() # Case: Mexal address not exist: if not to_mexal: f_out.write(formato_csv % ( documento, invoice, "Warning", customer, "Invio manuale", "Manca indirizzo email nel gestionale")) continue if documento == "FT": subject = "Fattura n. %06d" % invoice else: subject = "Nota accredito n. %06d" % invoice try: error = "Errore cercando di leggere l'oggetto del messaggio" result, data = mail.uid( 'search', None, '(HEADER Subject "%s")' % subject) # Case: Subject not found in mail if result != "OK": f_out.write(formato_csv % ( documento, invoice, "Error", customer, "Non si riesce a leggere mail con oggetto: %s" % subject, "")) continue error = "Errore cercando di leggere il messaggio" try: latest_email_uid = data[0].split()[-1] result, data = mail.uid('FETCH', latest_email_uid, '(BODY.PEEK[HEADER.FIELDS (To)] RFC822.SIZE)') except: f_out.write(formato_csv % ( documento, invoice, "Error", customer, "Mexal: %s" % to_mexal, error)) continue # Case: mail not reached from server if result != "OK": f_out.write(formato_csv % ( documento, invoice, "Error", customer, "Messaggio inesistente, oggetto: %s" % subject, "")) continue error = "Errore cercando di leggere l'oggetto del messaggio" to_send = data[0][1].split()[1][1:-1] error = "Errore scrivendo il record su Excel" # Case: Info if to_mexal == to_send: record = ( documento, invoice, "", customer, "Invio: %s" % to_mexal, "") else: # Case: Warning (address non correct) record = ( documento, invoice, "Warning", customer, "Invio mail non corretta [Mexal: %s] [Email: %s]" % ( to_mexal, to_send), "Non corrispondono gli indirizzi!") f_out.write(formato_csv % record) except: # Case: of generic error: f_out.write(formato_csv % ( documento, invoice, "Error", customer, "", error)) continue f_in.close() f_out.close() #os.system('./ftmail.csv')
agpl-3.0
HelloLily/hellolily
lily/cases/admin.py
3229
from django.contrib import admin from lily.tenant.admin import TenantFilter, TenantFilteredChoicesMixin, EstimateCountPaginator from .models import Case, CaseType, CaseStatus @admin.register(Case) class CaseAdmin(TenantFilteredChoicesMixin, admin.ModelAdmin): # List view settings. list_max_show_all = 100 list_per_page = 50 ordering = ['-id', ] show_full_result_count = False paginator = EstimateCountPaginator list_select_related = ('tenant', ) list_display = ('id', 'subject', 'priority', 'is_deleted', 'is_archived', 'tenant', ) list_display_links = ('id', 'subject',) search_fields = ('subject',) list_filter = ('priority', 'is_deleted', 'is_archived', TenantFilter, ) # Form view settings. tenant_filtered_fields = ( 'status', 'type', 'assigned_to', 'assigned_to_teams', 'created_by', 'account', 'contact', 'parcel', ) filter_horizontal = ('assigned_to_teams', ) readonly_fields = ('tenant',) fieldsets = ( (None, { 'fields': ( 'tenant', 'subject', 'description', 'priority', 'status', 'type', 'assigned_to', 'created_by', 'account', 'contact', 'expires', 'parcel', 'billing_checked', 'newly_assigned', 'deleted', 'is_deleted', 'is_archived', ), }), ('Advanced options', { 'classes': ('collapse',), 'fields': ( 'assigned_to_teams', ), }), ) @admin.register(CaseType) class CaseTypeAdmin(TenantFilteredChoicesMixin, admin.ModelAdmin): # List view settings. list_max_show_all = 100 list_per_page = 50 ordering = ['-id', ] show_full_result_count = False paginator = EstimateCountPaginator list_select_related = ('tenant', ) list_display = ('id', 'name', 'use_as_filter', 'is_archived', 'tenant', ) list_display_links = ('id', 'name', ) search_fields = ('name', ) list_filter = ('use_as_filter', 'is_archived', TenantFilter, ) # Form view settings. readonly_fields = ('tenant',) fieldsets = ( (None, { 'fields': ( 'tenant', 'is_archived', 'name', 'use_as_filter', ), }), ) @admin.register(CaseStatus) class CaseStatusAdmin(TenantFilteredChoicesMixin, admin.ModelAdmin): # List view settings. list_max_show_all = 100 list_per_page = 50 ordering = ['-id', ] show_full_result_count = False paginator = EstimateCountPaginator list_select_related = ('tenant', ) list_display = ('id', 'name', 'position', 'tenant', ) list_display_links = ('id', 'name', ) search_fields = ('name', ) list_filter = (TenantFilter, 'position', ) # Form view settings. readonly_fields = ('tenant',) fieldsets = ( (None, { 'fields': ( 'tenant', 'position', 'name', ), }), )
agpl-3.0
glidernet/python-ogn-client
tests/parser/test_utils.py
3090
import unittest from datetime import datetime, timezone from ogn.parser.utils import parseAngle, createTimestamp, CheapRuler, normalized_quality class TestStringMethods(unittest.TestCase): def test_parseAngle(self): self.assertAlmostEqual(parseAngle('05048.30'), 50.805, 5) def proceed_test_data(self, test_data={}): for test in test_data: timestamp = createTimestamp(test[0], reference_timestamp=test[1]) self.assertEqual(timestamp, test[2]) def test_createTimestamp_hhmmss(self): test_data = [ ('000001h', datetime(2015, 1, 10, 0, 0, 1), datetime(2015, 1, 10, 0, 0, 1)), # packet from current day (on the tick) ('235959h', datetime(2015, 1, 10, 0, 0, 1), datetime(2015, 1, 9, 23, 59, 59)), # packet from previous day (2 seconds old) ('110000h', datetime(2015, 1, 10, 0, 0, 1), datetime(2015, 1, 10, 11, 0, 0)), # packet 11 hours from future or 13 hours old ('123500h', datetime(2015, 1, 10, 23, 50, 0), datetime(2015, 1, 10, 12, 35, 0)), # packet from current day (11 hours old) ('000001h', datetime(2015, 1, 10, 23, 50, 0), datetime(2015, 1, 11, 0, 0, 1)), # packet from next day (11 minutes from future) ] self.proceed_test_data(test_data) def test_createTimestamp_ddhhmm(self): test_data = [ ('011212z', datetime(2017, 9, 28, 0, 0, 1), datetime(2017, 10, 1, 12, 12, 0)), # packet from 1st of month, received on september 28th, ('281313z', datetime(2017, 10, 1, 0, 0, 1), datetime(2017, 9, 28, 13, 13, 0)), # packet from 28th of month, received on october 1st, ('281414z', datetime(2017, 1, 1, 0, 0, 1), datetime(2016, 12, 28, 14, 14, 0)), # packet from 28th of month, received on january 1st, ] self.proceed_test_data(test_data) def test_createTimestamp_tzinfo(self): test_data = [ ('000001h', datetime(2020, 9, 10, 0, 0, 1, tzinfo=timezone.utc), (datetime(2020, 9, 10, 0, 0, 1, tzinfo=timezone.utc))) ] self.proceed_test_data(test_data) def test_cheap_ruler_distance(self): koenigsdf = (11.465353, 47.829825) hochkoenig = (13.062405, 47.420516) cheap_ruler = CheapRuler((koenigsdf[1] + hochkoenig[1]) / 2) distance = cheap_ruler.distance(koenigsdf, hochkoenig) self.assertAlmostEqual(distance, 128381.47612138899) def test_cheap_ruler_bearing(self): koenigsdf = (11.465353, 47.829825) hochkoenig = (13.062405, 47.420516) cheap_ruler = CheapRuler((koenigsdf[1] + hochkoenig[1]) / 2) bearing = cheap_ruler.bearing(koenigsdf, hochkoenig) self.assertAlmostEqual(bearing, 110.761300063515) def test_normalized_quality(self): self.assertAlmostEqual(normalized_quality(10000, 1), 1) self.assertAlmostEqual(normalized_quality(20000, 10), 16.020599913279625) self.assertAlmostEqual(normalized_quality(5000, 5), -1.0205999132796242) if __name__ == '__main__': unittest.main()
agpl-3.0
Quickpaster/quickpaster
client/main.js
1908
import Tasks from './../tasks'; import { uuidToWriteable, uuidToUrlable } from './../lib/uuidGen'; import { initClientId, getClientId, clientIdNotifyConnected } from './lib/userId'; import start from './lib/engine'; import App from './app'; Meteor.startup(() => { window.addEventListener('beforeunload', e => console.log(`Before Unload: ${e}`)); window.addEventListener('unload', e => console.log(`Unload: ${e}`)); // Init client identification params on each start and even hot code reload. const clientId = initClientId(); Tracker.autorun(function () { if (Meteor.status().connected) { if (clientIdNotifyConnected()) { console.log(`${new Date()} Connected.\nClient ID params:`, getClientId()); } else { console.log('Reconnected.\nClient ID params:', getClientId()); } } else { console.log('Warning: Connection Lost.'); } }); const handle = Meteor.subscribe('tasks', () => { bypass = false; console.log('State is loaded.'); Meteor.call('notifyLoaded', `State ${Session.get('sessionId')} is loaded from`);// IP ${clientmultihomeIp}`); }); let bypass = true; Tasks .find({}, {sort: {createdAt: -1}}) .observe({ changed: res => { if (!bypass) console.log('CHANGED:', res); }, added: res => { if (!bypass) console.log('ADDED:', res); } }); /* const root = document.createElement('div'); root.setAttribute('id', 'root'); document.body.appendChild(root); const title = document.createElement('title'); title.text = 'Quickpaster MVP'; document.head.appendChild(title); */ // See https://github.com/leeoniya/domvm/blob/master/src/view.js#L309 // To modify Snabbdom for absorbing existing DOM ('hydrating'). let root = document.getElementById('root'); while (root.hasChildNodes()) { root.removeChild(root.firstChild); } start(App, root, window.location.pathname); });
agpl-3.0
cointhink/rails
db/seeds.rb
4746
# Access Control AclFlag.create({name:"blog"}) # Exchanges [ [{name:'cointhink', display_name:'CoinThink',country_code: 'us', active: false}, 0.5], [{name:'mtgox', display_name:'Mt. Gox',country_code: 'jp', active: false}, 0.6], [{name:'bitstamp', display_name:'Bitstamp', country_code: 'si', active: true}, 0.5], [{name:'intersango', display_name:'InterSango', country_code: 'gb', active: false}, 0.65], [{name:'btce', display_name:'BTC-E', country_code: 'bg', active: true}, 0.2], [{name:'cryptoxchange', display_name:'CryptoXchange', country_code: 'au', active: false}, 0.4], [{name:'bitfloor', display_name:'BitFloor', country_code: 'us', active: false}, 0.4], [{name:'bitcoin24', display_name:'Bitcoin-24', country_code: 'de', active: false}, 0.0], [{name:'campbx', display_name:'CampBX', country_code: 'us', active: false}, 0.55], [{name:'bitfinex', display_name:'Bitfinex', country_code: 'vg', active: true}, 0.2], [{name:'coinbase', display_name:'Coinbase', country_code: 'us', active: true}, 0.0], [{name:'cryptsy', display_name:'Cryptsy', country_code: 'us', active: true}, 0.3], [{name:'gemini', display_name:'Gemini', country_code: 'us', active: true}, 0.3], ].each do |info| e = Exchange.create(info.first) e.markets.create(from_exchange: e, from_currency:'btc', to_exchange: e, to_currency:'usd', fee_percentage: info.last, delay_ms: 500) e.markets.create(from_exchange: e, from_currency:'usd', to_exchange: e, to_currency:'btc', fee_percentage: info.last, delay_ms: 500) e.balances.create({currency:"usd", amount: 0}) e.balances.create({currency:"btc", amount: 0}) end [ [{name:'coinse', display_name:'Coins-e', country_code: 'ca', active: true}, 0.15], [{name:'bleutrade', display_name:'Bluetrade', country_code: 'br', active: true}, 0.25] ].each do |info| e = Exchange.create(info.first) e.markets.create(from_exchange: e, from_currency:'doge', to_exchange: e, to_currency:'btc', fee_percentage: info.last, delay_ms: 500, active: true) e.markets.create(from_exchange: e, from_currency:'btc', to_exchange: e, to_currency:'doge', fee_percentage: info.last, delay_ms: 500, active: true) e.balances.create({currency:"btc", amount: 0}) e.balances.create({currency:"doge", amount: 0}) end [ [{name:'kraken', display_name:'Kraken', country_code: 'us', active: true}, 0.2], [{name:'poloniex', display_name:'Poloniex', country_code: 'us', active: true}, 0.2] [{name:'bittrex', display_name:'Bittrex', country_code: 'us', active: true}, 0.2] ].each do |info| e = Exchange.create(info.first) e.markets.create(from_exchange: e, from_currency:'eth', to_exchange: e, to_currency:'btc', fee_percentage: info.last, delay_ms: 500, active: true) e.markets.create(from_exchange: e, from_currency:'btc', to_exchange: e, to_currency:'eth', fee_percentage: info.last, delay_ms: 500, active: true) e.balances.create({currency:"btc", amount: 0}) e.balances.create({currency:"eth", amount: 0}) end # bitcoin client e = Exchange.create(name:'bitcoin') e.balances.create({currency:"btc", amount: 0}) # web-banks e = Exchange.create(name:'dwolla') e.balances.create({currency:"usd", amount: 0}) # Money Changers e = Exchange.create(name:'bitinstant') m1=e.markets.create(from_exchange: Exchange.find_by_name('dwolla'), from_currency:'usd', to_exchange: Exchange.find_by_name('btce'), to_currency:'usd', fee_percentage: 2.0, delay_ms: 1000 * 60 * 60 * 12) m2=e.markets.create(from_exchange: Exchange.find_by_name('mtgox'), from_currency:'usd', to_exchange: Exchange.find_by_name('btce'), to_currency:'usd', fee_percentage: 1.49, delay_ms: 1000 * 20) m3=e.markets.create(from_exchange: Exchange.find_by_name('mtgox'), from_currency:'usd', to_exchange: Exchange.find_by_name('bitstamp'), to_currency:'usd', fee_percentage: 1.29, delay_ms: 1000 * 20) [m1,m2,m3].each do |m| d=m.depth_runs.create d.offers.create(bidask: 'ask', price: 1, market: m, quantity: 1000000, currency: 'usd') end # Exchange's in-house transfer services e=Exchange.find_by_name('mtgox') m=e.markets.create(from_exchange: e, from_currency: 'usd', to_exchange: Exchange.find_by_name('dwolla'), to_currency: 'usd', fee_percentage: 0, delay_ms: 1000 * 60 * 60 * 24 * 8) d=m.depth_runs.create d.offers.create(bidask: 'ask', price: 1, market: m, quantity: 1000000, currency: 'usd')
agpl-3.0
open-dash/open-dash-diy
app/api/cameras.js
1183
const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const app = express(); var SelfReloadJSON = require('self-reload-json'); const appRoot = require('app-root-path'); var settings = new SelfReloadJSON(appRoot + '/data/settings.json'); var cameras = new SelfReloadJSON(appRoot + '/data/cameras.json'); module.exports.set = function(app) { app.get('/api/camera/:id', (request, response) => { getImage(request.params.id, function(err, result) { //response.send('<img src="' + result + '" >'); response.setHeader('Content-Type', 'image/jpeg'); response.end(result, 'binary'); }); }); }; var getImage = function(id, callback) { var request2 = require('request').defaults({ encoding: null }); var camera = {}; cameras.cameras.forEach((cam) => { camera = cam; }); request2.get(camera.url, function(error, response, body) { if (!error && response.statusCode == 200) { data = "data:image/jpeg;base64," + new Buffer(body).toString('base64'); //console.log(data); callback(null, body); } }); };
agpl-3.0
osuripple/pep.py
events/partLobbyEvent.py
428
from common.log import logUtils as log from helpers import chatHelper as chat def handle(userToken, _): # Get usertoken data username = userToken.username # Remove user from users in lobby userToken.leaveStream("lobby") # Part lobby channel # Done automatically by the client chat.partChannel(channel="#lobby", token=userToken, kick=True) # Console output log.info("{} has left multiplayer lobby".format(username))
agpl-3.0
Lidefeath/ACE
Source/ACE.Server/WorldObjects/Clothing.cs
1700
using ACE.Database.Models.Shard; using ACE.Database.Models.World; using ACE.DatLoader; using ACE.DatLoader.FileTypes; using ACE.Entity; using ACE.Entity.Enum; using ACE.Entity.Enum.Properties; using System.IO; namespace ACE.Server.WorldObjects { public class Clothing : WorldObject { /// <summary> /// A new biota be created taking all of its values from weenie. /// </summary> public Clothing(Weenie weenie, ObjectGuid guid) : base(weenie, guid) { SetEphemeralValues(); } /// <summary> /// Restore a WorldObject from the database. /// </summary> public Clothing(Biota biota) : base(biota) { SetEphemeralValues(); } private void SetEphemeralValues() { } /// <summary> /// This will also set the icon based on the palette /// </summary> public void SetProperties(int palette, double shade) { var icon = DatManager.PortalDat.ReadFromDat<ClothingTable>(GetProperty(PropertyDataId.ClothingBase) ?? 0).GetIcon((uint)palette); SetProperty(PropertyDataId.Icon, icon); SetProperty(PropertyInt.PaletteTemplate, palette); SetProperty(PropertyFloat.Shade, shade); } public override void SerializeIdentifyObjectResponse(BinaryWriter writer, bool success, IdentifyResponseFlags flags = IdentifyResponseFlags.None) { flags |= IdentifyResponseFlags.ArmorProfile; base.SerializeIdentifyObjectResponse(writer, success, flags); WriteIdentifyObjectArmorProfile(writer, this, success); } } }
agpl-3.0
python27/AlgorithmSolution
hdoj/BigNum/N!.cpp
1820
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #if 0 #define N 50050 int ret[N]; int tmp[N]; char strn[N]; int intn[N]; int pos = 0; void product(int* A, int nA, int* B, int nB, int *C); void nfrac(int n) { for (int i = 0; i < N; ++i) ret[i] = 0; ret[0] = 1; for (int i = n; i >= 1; --i) { // covert n to str sprintf(strn, "%d", i); int nlen = strlen(strn); // ready B for (int j = 0; j < N; ++j) intn[j] = 0; pos = 0; for (int j = nlen - 1; j >= 0; --j) intn[pos++] = strn[j] - '0'; // ready C for (int j = 0; j < N; ++j) tmp[j] = 0; // C = A * B pos = N - 1; while (pos >= 0 && ret[pos] == 0) pos--; product(ret, pos + 1, intn, nlen, tmp); // update ret to C for (int k = 0; k < N; ++k) ret[k] = tmp[k]; } } // C = A * B void product(int* A, int nA, int* B, int nB, int *C) { // init for (int i = 0; i < N; ++i) C[i] = 0; for (int i = 0; i < nB; ++i) { int x = B[i]; int xpos = i; // product int pos = xpos; for (int j = 0; j < nA; ++j) { C[pos++] += x * A[j]; } // carry for (int j = 0; j < N - 1; ++j) { if (C[j] >= 10) { C[j + 1] += C[j] / 10; C[j] %= 10; } } } } int main() { int n = 0; while (scanf("%d", &n) == 1) { if (n == 0) { printf("1\n"); continue; } clock_t start = clock(); nfrac(n); char strC[N]; memset(strC, '\0', N); pos = N - 1; while (pos >= 0 && ret[pos] == 0) pos--; int i = 0; while (pos >= 0) { strC[i++] = ret[pos--] + '0'; } strC[i] = '\0'; printf("%s\n", strC); clock_t end = clock(); //printf("cost time: %f\n", double(end - start) / CLOCKS_PER_SEC); } return 0; } #endif //0 // ×ܽ᣺ // 1. ¼ÆËãÁ½¸ö´óÕûÊýµÄ³Ë»ý£¬ ¸´ÔÓ¶È N * nB // 2. ¶ÔÓÚ 1...n µÄÿ¸öÊý¼ÆËãÒ»´Î£¬×ܸ´ÔÓ¶ÈΪ n * N * nB = n^2 * N // 3. TLE
agpl-3.0
Micronaet/micronaet-bom
bom_half_worked/__init__.py
1038
# -*- coding: utf-8 -*- ############################################################################### # # Copyright (C) 2001-2014 Micronaet SRL (<http://www.micronaet.it>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as published # by the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### from . import halfwork # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
agpl-3.0
RBSChange/modules.twitterconnect
actions/ResendTweetAction.class.php
1129
<?php /** * twitterconnect_ResendTweetAction * @package modules.twitterconnect.actions */ class twitterconnect_ResendTweetAction extends f_action_BaseJSONAction { /** * @param Context $context * @param Request $request */ public function _execute($context, $request) { $result = array(); $module = $request->getParameter('currentModule'); $tweet = $this->getDocumentInstanceFromRequest($request); $tweet->getDocumentService()->sendTweet($tweet); if ($tweet->getSendingStatus() == twitterconnect_TweetService::STATUS_ERROR) { $account = $tweet->getAccount()->getLabel(); return $this->sendJSONError(f_Locale::translate('&modules.twitterconnect.bo.general.error.Error-sending-tweet;', array('account' => $account, 'error' => $tweet->getErrorMessage()))); } $startIndex = $request->hasParameter('startIndex') ? $request->getParameter('startIndex') : 0; $pageSize = $request->getParameter('pageSize'); $result = twitterconnect_ModuleService::getInstance()->getInfosByDocumentId($request->getParameter('relatedId'), $module, $startIndex, $pageSize); return $this->sendJSON($result); } }
agpl-3.0
mumuki/mumuki-laboratory
app/controllers/api/roles_controller.rb
1025
module Api class RolesController < BaseController include WithUserParams before_action :set_slug! before_action :set_course! before_action :set_user!, except: :create before_action :authorize_janitor! def create @user = User.create_if_necessary(user_params) @user.attach! role, @course render json: @user end def attach @user.attach! role, @course head :ok end def detach @user.detach! role, @course head :ok end private def role raise 'Not Implemented' end def user_params params.require(role).permit(*permissible_params) end def permissible_params super + [:image_url, :email, :uid] end def set_course! @course = Course.find_by!(slug: @slug) end def set_user! @user = User.find_by!(uid: params[:uid]) end def set_slug! @slug = Mumukit::Auth::Slug.join_s params.to_unsafe_h end def authorization_slug @slug end end end
agpl-3.0
diogo-andrade/DataHubSystem
petascope/src/main/java/petascope/swe/datamodel/AbstractSimpleComponent.java
3136
/* * This file is part of rasdaman community. * * Rasdaman community 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. * * Rasdaman community 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 rasdaman community. If not, see <http://www.gnu.org/licenses/>. * * Copyright 2003 - 2014 Peter Baumann / rasdaman GmbH. * * For more information please see <http://www.rasdaman.org> * or contact Peter Baumann via <baumann@rasdaman.com>. */ package petascope.swe.datamodel; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import nu.xom.Element; /** * SWE abstract simple component. * From this classe derive the concrete subclasses `Quantity', `Category', `Count' and `Time'. * * @author <a href="mailto:p.campalani@jacobs-university.de">Piero Campalani</a> */ public abstract class AbstractSimpleComponent extends AbstractDataComponent { // fields // List<QualityProperty> quality; // not supported /** * The optional "nilValues" attribute is used to provide a list (ie one or more) of NIL values. * swe:AbstractSimpleComponent : [0..1] nilValues ((type="swe:NilValuesPropertyType")) */ private final List<NilValue> nilValues; /** * The "referenceFrame" attribute identifies the reference frame (as defined by the "SC_CRS" object) * relative to which the coordinate value is given. * Not supported. */ private final String referenceFrame = null; /** * The "axisID" attribute takes a string that uniquely identifies one of the * reference frame’s axes along which the coordinate value is given. * Not supported. */ private final String axisID = null; // constructors /** * Constructor with empty initialization. */ protected AbstractSimpleComponent() { super(); nilValues = new ArrayList<NilValue>(0); } /** * Full attributes constructor (currently supported elements). * * @param label * @param description * @param definition * @param nils */ protected AbstractSimpleComponent(String label, String description, String definition, List<NilValue> nils) { super(label, description, definition); nilValues = new ArrayList<NilValue>(nils.size()); for (NilValue nil : nils) { nilValues.add(nil); } } // access /** * Getter method for the list of NIL values. * * @return The iterator of the list of NIL values for this SWE component. */ public Iterator<NilValue> getNilValuesIterator() { return nilValues.iterator(); } // methods public abstract String toGML(); }
agpl-3.0
md11235/fengoffice
language/fr_fr/lang.js
39606
locale = 'fr_fr'; addLangs({ 'more info': 'Plus d\'Information', 'less info': 'Moins d\'Information', 'projects': 'Espaces de Travails', 'see more': 'Voir Plus', 'filter members': 'Filtrer les Membres', 'check in': '<b>S\'Enregistrer</b>', 'cannot check in': 'Impossible de s\'Enregistrer', 'add as new revision to': 'Ajouter une nouvelle révision à', 'error loading content': 'Erreur de chargement. Essayer plus tard.\nSi le problème persiste contacter l\'administrateur.', 'administration': 'Administration', 'open link': 'Ouvrir le Lien', 'open in new tab': 'Ouvrir dans un nouvel onglet', 'close tab': 'Fermer l\'onglet', 'close other tabs': 'Isoler', 'loading': 'Chargement en cours...', 'help': 'Aide', 'menu': 'Menu', 'back': 'Retour', 'server could not be reached': 'Le serveur est inaccessible', 'http error': 'Erreur {0}: {1}', 'refesh desc': 'Actualiser', 'last updated by at': '{0}, à {1}', 'last updated by on': '{0}, le {1}', 'last updated by': 'Dernière modification par', 'close this tag': 'Fermer cette étiquette', 'by': 'par', 'name': 'Nom', 'project': 'Contexte', 'user': 'Utilisateur', 'tag': 'Étiquette', 'type': 'Type', 'tags': 'Étiquettes', 'last update': 'dernière Màj', 'created on': 'Créé par', 'download': 'Télécharger', 'properties': 'Propriétés', 'revisions and comments': 'Révisions & Commentaires', 'slideshow': 'Présentation', 'add tag': 'Ajouter une étiquette', 'enter the desired tag': 'Nommez votre étiquette', 'new': 'Nouveau', 'create an object': 'Créer un objet', 'document': 'Document', 'spreadsheet': 'Tableur', 'presentation': 'Présentation', 'upload': 'Chargement', 'upload a file': 'Charger un fichier', 'tag selected objects': 'Étiqueter les objets sélectionnés', 'delete': 'Supprimer', 'delete selected objects': 'Supprimer les objets sélectionnés', 'confirm delete object': 'Êtes-vous sûr de vouloir supprimer le(s) objet(s) sélectionné(s) ?', 'confirm delete contact': 'Êtes-vous sûr de vouloir supprimer ce contact ?', 'confirm delete company': 'Êtes-vous sûr de vouloir supprimer cette société ?', 'confirm delete event': 'Êtes-vous sûr de vouloir de supprimer définitivement cet évènement ? \nAprès suppression de l\'évènement les autres utilisateurs ne le verront plus dans leur calendrier', 'confirm delete file': 'Êtes-vous sûr de vouloir supprimer ce fichier ?', 'confirm delete mail content': 'Êtes-vous certain de vouloir supprimer ce message ?', 'confirm delete mail account': 'Attention : tous les messages de ce compte seront aussi supprimés, êtes-vous sûr de vouloir supprimer ce compte de messagerie ?', 'confirm delete milestone': 'Êtes-vous sûr de vouloir supprimer cette Etape ?', 'confirm delete chart': 'Êtes-vous sûr de vouloir supprimer ce graphique ?', 'confirm delete message': 'Êtes-vous sûr de vouloir supprimer cette note ?', 'confirm delete task list': 'Êtes-vous sûr de vouloir supprimer cette liste de tâche, ainsi que ses sous-tâches ?', 'confirm delete webpage': 'Êtes-vous sûr de vouloir supprimer ce lien web ?', 'confirm delete workspace': 'Êtes-vous sûr de vouloir supprimer cet Espace de Travail \'{0}\' ?', 'confirm delete project': 'Êtes-vous sûr de vouloir supprimer cet Espace de Travail et toutes ses données (Messages, Tâches, Etapes, Fichiers...) ?', 'confirm cancel work timeslot': 'Êtes-vous sûr de vouloir annuler cet intervalle de temps courant ?', 'more': 'Plus', 'more actions': 'Plus d\'actions', 'more actions on first selected object': 'Plus d\'actions pour le premier objet sélectionné', 'displaying files of': 'Affichage des fichiers {0} de {1} sur {2}', 'no files to display': 'Aucun fichier à afficher', 'no tasks to display': 'Aucune tâche à afficher', 'refresh desc': 'Actualiser l\'affichage', 'templates desc': 'Gérer les modèles', 'templates': 'Modèles', 'edit workspace': 'Éditer l\'Espace de Travail sélectionné', 'company': 'Société', 'companies': 'Sociétés', 'email': 'Adresse de messagerie ', 'email tab': 'Messagerie', 'checkin': 'Nouvelle révision', 'checkout': 'Enregistrer', 'checked out by': 'Enregistré par {0}', 'add file checked out by': '{0} enregistré par {1}', 'song': 'Titre', 'artist': 'Artiste', 'album': 'Album', 'year': 'Année', 'playlist': 'Liste d\'écoute', 'playlists': 'Listes d\'écoute', 'unknown': 'Inconnu', 'previous': 'Précèdent', 'play': 'Lecture', 'pause': 'Pause', 'stop': 'Arrêter la lecture', 'next': 'Suivant', 'mute': 'Muet', 'unmute': 'Sonore', 'load from current workspace': 'Charger les morceaux depuis l\'Espace de Travail actuel', 'load playlist from file': 'Charger la liste d\'écoute depuis le fichier', 'save playlist to file': 'Enregistrer la liste d\'écoute dans le fichier', 'clear playlist': 'Effacer la liste d\'écoute', 'remove selected from playlist': 'Supprimer la sélection de la liste d\'écoute', 'shuffle playlist': 'Lire en mode aléatoire', 'toggle loop playlist': 'Lire en boucle', 'play this file': 'Lire ce morceau', 'queue': 'File d\'attente', 'queue this file': 'Mettre ce morceau en attente', 'must choose a file': 'Choisir un fichier', 'file has no valid songs': 'Le fichier choisi n\'est pas un fichier audio supporté', 'error': 'Erreur ', 'success': 'Opération effectuée ', 'unexpected server response': 'Réponse du serveur inattendue', 'new tab': 'Nouvel onglet', 'dashboard': 'Tableau de bord', 'upload file': 'Charger un fichier', 'contact': 'Contact', 'event': 'Évènement', 'task': 'Tâche', 'milestone': 'Etape', 'refresh': 'Actualiser', 'author': 'Auteur', 'overview': 'Tableau de bord', 'messages': 'Notes', 'contacts': 'Contacts', 'calendar': 'Calendrier', 'tasks': 'Tâches', 'web pages': 'Liens Web', 'documents': 'Documents', 'account': 'Compte', 'search': 'Recherche', 'webpage': 'Lien Web', 'message': 'Note', 'workspaces': 'Espace de Travail', 'all': 'Tous', 'create a workspace': 'Créer un nouvel Espace de Travail', 'delete selected workspace': 'Supprimer cet Espace de Travail', 'select an object': 'Sélectionnez un objet...', 'filter': 'Filtrer ', 'all ws': 'Tous les Espaces de Travail', 'all type': 'Tous les types', 'all tag': 'Toutes les étiquettes', 'view': 'Afficher', 'details': 'Détails', 'icons': 'Icônes', 'displaying objects of': 'Affichage des objets {0} à {1} sur {2}', 'no objects to display': 'Aucun objet à afficher', 'ok': 'OK', 'cancel': 'Annuler', 'add new contact': 'Ajouter un nouveau contact', 'displaying contacts of': 'Affichage des contacts {0} à {1} sur {2}', 'no contacts to display': 'Aucun contact à afficher', 'delete selected contacts': 'Supprimer les contacts sélectionnés', 'confirm delete contacts': 'Êtes-vous sûr de vouloir supprimer les contacts sélectionnés ?', 'role': 'Rôle', 'tag selected contacts': 'Étiquettes des Contacts sélectionnés', 'department': 'Département', 'email2': 'Courriel 2', 'email3': 'Courriel 3', 'workWebsite': 'Site Web Professionnel', 'workAddress': 'Adresse Professionnelle', 'workPhone1': 'Téléphone Professionnel 1', 'workPhone2': 'Téléphone Professionnel 2', 'homeWebsite': 'Site Web Personnel', 'homeAddress': 'Adresse Personnelle', 'homePhone1': 'Téléphone Personnel 1', 'homePhone2': 'Téléphone Personnel 2', 'mobilePhone': 'Téléphone portable', 'edit selected contact': 'Éditer le contact sélectionné', 'edit selected object': 'Éditer l\'objet sélectionné', 'assign to project': 'Affecter au contexte', 'assign contact to project': 'Affecter le contact au contexte', 'description': 'Description', 'title': 'Titre', 'add new webpage': 'Ajouter un nouveau lien Web', 'displaying webpages of': 'Affichage des liens web {0} à {1} sur {2}', 'no webpages to display': 'Aucun lien Web à afficher', 'delete selected webpages': 'Supprimer les liens web sélectionnés', 'confirm delete webpages': 'Êtes-vous sûr de vouloir supprimer les liens web sélectionnés ?', 'tag selected webpages': 'Étiqueter les liens web sélectionnés', 'edit': 'Éditer', 'edit selected webpage': 'Éditer', 'text': 'Texte', 'date': 'Date', 'add mail account': 'Ajouter un compte de messagerie', 'classify': 'Classer les messages', 'add new message': 'Ajouter une nouvelle note', 'view by account': 'Vue par compte', 'view emails by account': 'Vue des messages par compte', 'edit account': 'Éditer le compte', 'edit email account': 'Éditer le compte de messagerie', 'email actions': 'Actions', 'more email actions': 'Plus d\'actions de messagerie', 'view unclassified': 'Afficher les non classés', 'view unclassified emails': 'Afficher les messages non classés', 'all accounts': 'Tous les comptes', 'view all accounts': 'Afficher tous les comptes', 'hide messages': 'Cacher les notes', 'show messages': 'Afficher les notes', 'view all': 'Tout afficher', 'all emails': 'Tous les messages', 'unclassified emails': 'Messages non classés', 'view options': 'Afficher les Options', 'check mails': 'Relever les messages', 'emails': 'Messages', 'create an email': 'Créer un nouveau message', 'filter workspaces': 'Filtrer les Espaces de Travail...', 'filter tags': 'Filtrer les étiquettes...', 'alphabetical': 'Alphabétique', 'most active': 'Plus actif', 'alphabetical desc': 'Trier par ordre alphabétique', 'most active desc': 'Trier par activité', 'sort desc': 'Trier la vue', 'no objects message': 'il n\'y a pas de \'{0}\' dans \'{1}\'', 'no objects with tag message': 'il n\'y a pas de {0} marqué comme \'{2}\' dans \'{1}\'', 'objects': 'objets', 'checkout description': 'Verrouiller ce fichier', 'undo checkout description': 'Rendre ce fichier disponible', 'checkin description': 'Créer une révision de ce fichier', 'created by on': 'Créé par {0} le {1}', 'write': 'Écrire', 'write new mail': 'Rédiger un nouveau message', 'weblink': 'Lien Web', 'emailunclassified': 'Message', 'file': 'Fichier', 'debug': 'Debug', 'incomplete': 'Incomplet', 'complete': 'Achevés', 'do complete': 'Achever', 'late': 'En retard', 'status': 'Statut ', 'event status': 'Statut Evènement', 'task status': 'Statut Tâche', 'hide all tasks': 'Hide all tasks', 'sync': 'Synchroniser', 'delete calendar': 'Supprimer le Calendrier?', 'delete calendar events': 'Les Evénements au sein de Intranet liées au calendrier seront supprimés. Cochez la case sur votre droite si vous souhaitez également les supprimer de Google Calendar.', 'open link in new window': 'Ouvrir \'{0}\' dans une nouvelle fenêtre', 'wschooser desc from': 'Espaces de Travail disponibles', 'wschooser desc to': 'Objets des Espaces de Travail', 'updated by': 'MàJ par', 'created by': 'Créé par', 'view as dashboard': 'Voir dans le Tableau de Bord', 'subject': 'Objet ', 'add event': 'Ajouter un évènement', 'next month': 'Mois suivant', 'prev month': 'Mois précèdent', 'today': 'Aujourd\'hui', 'pick a date': 'Choisir une date', 'month': 'Mois', 'month view': 'Vue par mois', 'week': 'Semaine', 'week view': 'Vue par semaine', 'day': 'Jour', 'day view': 'Vue par jour', 'by state': 'Par état', 'view pending response': 'Réponse en attente', 'view will attend': 'Participera', 'view will not attend': 'Ne participera pas', 'view maybe attend': 'Participera peut-être', 'by user': 'Par utilisateur', 'add new event': 'Ajouter un nouvel évènement', 'prev': 'Précèdent', 'my calendar': 'Vous', 'edit event details': 'Éditer les détails de l\'évènement', 'reporting': 'Rapports', 'add new chart': 'Ajouter un nouveau graphique', 'delete selected charts': 'Supprimer le graphique sélectionné', 'confirm delete charts': 'Êtes-vous sûr de vouloir supprimer le graphique sélectionné ?', 'edit selected chart': 'Éditer le graphique sélectionné', 'tag selected charts': 'Marquer les graphiques sélectionnés', 'displaying charts of': 'Affichage des graphiques {0} de {1} sur {2}', 'no charts to display': 'Aucun graphique à afficher', 'charts': 'graphiques', 'unlock': 'Déverrouiller', 'lock': 'Verrouiller', 'edit this document': 'Éditer ce document', 'assigned to': 'Affecté à ', 'assign to': 'Affecter à ', 'add subtask to': 'Ajouter une sous-tâche à \'{0}\'', 'add task to': 'Ajouter une tâche à \'{0}\'', 'add task': 'Ajouter une tâche', 'add milestone': 'Ajouter une Etape', 'add new task': 'Ajouter une nouvelle tâche', 'add new milestone': 'Ajouter une nouvelle Etape', 'confirm delete task': 'Êtes-vous sûr de vouloir supprimer cette tâche et toutes ses sous-tâches ?', 'due date': 'A remettre pour le', 'milestone delete tip': 'Supprimer cette Etape', 'milestone edit tip': 'Éditer cette Etape', 'milestone check tip': 'Achever/ouvrir cette Etape', 'milestone expand tip': 'Afficher/cacher cette Etape de tâche', 'milestone view tip': 'Etape : {0} (Cliquer pour voir plus)', 'task delete tip': 'Supprimer cette tâche', 'task edit tip': 'Éditer cette tâche', 'task check tip': 'Achever/ouvrir cette tâche', 'task expand tip': 'Afficher/cacher cette sous-tâche de la tâche', 'task view tip': 'Tâche : {0} (Clic pour voir plus)', 'task move down tip': 'Descendre cette tâche', 'new milestone': 'Nouvelle Etape', 'new task': 'Nouvelle tâche', 'error adding milestone': 'Erreur lors de l\'ajout de cette Etape', 'error adding task': 'Erreur lors de l\'ajout de la tâche', 'error fetching tasks': 'Erreur lors de la récupération des tâches', 'confirm unload page': 'Des données vont être perdues si vous quittez la page. Enregistrez-les.', 'confirm leave panel': 'Des données vont être perdues si vous quittez la page. \nFaut-il les enregistrer ?', 'unread emails': 'Messages non lus', 'mark read': 'Marquer comme lu', 'mark unread': 'Marquer comme non lu', 'from': 'De', 'draft': 'Brouillons', 'create contact or client company': 'Créer un contact ou un client de société', 'mail sent': 'Message expédié', 'click to remove': 'Clic pour supprimer', 'confirm merge tags': 'Êtes-vous sûr de vouloir fusionner l\'étiquette \'{0}\' avec \'{1}\'?\n(Attention, l\'opération est irréversible)', 'save': 'Enregistrer', 'choose a filename': 'Choisir un nom de fichier ', 'rename tag': 'Renommer l\'étiquette', 'enter a new name for the tag': 'Entrer un nouveau nom pour cette étiquette', 'duplicate company name': '<span style="color:#F00">Une société avec le nom \'{0}\' existe déjà. </span><a href="#" style="text-decoration:underline" onclick="og.selectCompany(\'{1}\',{2})">Choisir cette société</a>, ou un nom différent', 'inbox': 'Recus', 'sent': 'Envoyés', 'unread': 'Non lu', 'more options': 'Plus d\'options', 'login': 'Login', 'username': 'Utilisateur ', 'password': 'Mot de passe ', 'remember me': 'Se souvenir de moi', 'completed': 'Achevé', 'notify': 'Notifier', 'hours worked': 'Heures travaillées', 'completed by': 'Achevé par', 'assigned by': 'Affecté par', 'priority': 'Priorité', 'unclassified': 'Non classé', 'ungrouped': 'Non groupé', 'unassigned': 'Non affecté', 'anyone': 'N\'importe qui', 'pending': 'En attente', 'group by': 'Regroupé par ', 'order by': 'Trié par ', 'workspace': 'Espace de Travail', 'start date': 'Date de début ', 'task name': 'Nom de la tâche', 'show': 'Afficher ', 'time': 'Temps', 'dates': 'Dates', 'select user or group': 'Sélectionner un utilisateur ou un groupe', 'select milestone': 'Sélectionner une Etape', 'select priority': 'Sélectionner une Priorité', 'low': 'Basse', 'normal': 'Normale', 'high': 'Haute', 'me': 'Moi', 'complete selected tasks': 'Achever les tâches sélectionnées', 'earlier than one year': 'Moins d\'un an', 'last year': 'il y a entre 3 mois et un an', 'last three months': 'il y a entre un et 3 mois', 'last month': 'il y a entre 2 semaines et un mois', 'last two weeks': 'il y a une ou deux semaines', 'last week': 'La semaine dernière', 'yesterday': 'Hier', 'tomorrow': 'Demain', 'one week': 'Dans une semaine', 'two weeks': 'Dans deux semaines', 'one month': 'Entre deux semaines et un mois', 'three months': 'De 1 à 3 mois', 'one year': 'Entre 3 mois et un an', 'later than one year': 'Dans plus d\'un an', 'start': 'Début', 'due': 'Dû', 'add subtask': 'Ajouter une sous-tâche', 'completed by name on': 'Achevé par {0} le {1}', 'show more tasks number': 'Afficher plus de ({0})...', 'start_work': 'Travailler sur cette tâche', 'close_work': 'Arrêter le travail sur cette tâche', 'time worked': 'Temps travaillé ', 'hours': 'heures', 'complete this task': 'Achever cette tâche', 'reopen this task': 'Réouvrir cette tâche', 'reopen': 'Réouvrir', 'assign': 'Affecter', 'assigning to': 'Affecté à', 'success add task': 'Tâche ajoutée !', 'invalid action': 'Action invalide', 'hide others': 'Masquer les autres', 'hide other groups': 'Masquer les autres groupes', 'show all': 'Tout afficher', 'show all groups': 'Afficher tous les groupes', 'send notification': 'Notifier par courriel', 'all options': 'Toutes les options', 'click to change workspace': 'Clic pour changer d\'Espace de Travail', 'month 1': 'Janvier', 'month 2': 'Février', 'month 3': 'Mars', 'month 4': 'Avril', 'month 5': 'Mai', 'month 6': 'Juin', 'month 7': 'Juillet', 'month 8': 'Août', 'month 9': 'Septembre', 'month 10': 'Octobre', 'month 11': 'Novembre', 'month 12': 'Décembre', 'monday': 'Lundi', 'tuesday': 'Mardi', 'wednesday': 'Mercredi', 'thursday': 'Jeudi', 'friday': 'Vendredi', 'saturday': 'Samedi', 'sunday': 'Dimanche', 'comment': 'Commentaire ', 'change user': 'Changer d\'utilisateur', 'start work': 'Début', 'add a new task to this group': 'Ajouter une nouvelle tâche à ce groupe', 'login dialog desc': 'Faute d\'activité, la session a expiré.', 'user not found': 'Utilisateur introuvable (id : {0})', 'date format': 'd/m/Y', 'date format alternatives': 'd/m/y|j/n/Y|j/n/y|j/m/y|d/n/y|j/m/Y|d/n/Y', 'warning start date greater than due date': 'Attention : La date de début est postérieure à la date de remise', 'choose an image': 'Choisir une image', 'sort by': 'Trier par ', 'file size': 'Taille du fichier', 'last modified': 'Dernière Màj', 'image name': 'Nom de l\'image', 'size': 'Taille', 'completed on': 'Achevé le', 'view slideshow': 'Lancer la présentation', 'import': 'Importer', 'duration': 'Durée ', 'pause_work': 'Pause-travail sur cette tâche', 'resume_work': 'Reprise du travail sur cette tâche', 'close work': 'Arrêt travail', 'event start time': 'Heure ', 'all day event': 'Toute la journée ', 'save changes': 'Sauvegarder les changements', 'no filter': 'Aucun filtre', 'nothing (groups)': 'Rien', 'none': 'Aucun', 'no images match the specified filter': 'Aucun image ne correspond au filtre indiqué', 'print': 'Imprimer', 'deleted on': 'Supprimé le', 'deleted by': 'Supprimé par', 'trash': 'Corbeille', 'restore': 'Restaurer', 'move to trash': 'Placer dans la corbeille', 'move selected objects to trash': 'Placer les objets sélectionnés dans la corbeille', 'confirm move to trash': 'Êtes-vous certain de vouloir placer les objets sélectionnés dans la corbeille ?', 'object type not supported': 'Ce type d\'objet n\'est pas supporté pour les modèles', 'remove': 'Supprimer', 'no items selected': 'Aucun élément sélectionné', 'no start date': 'Pas de date de départ', 'download selected file': 'Télécharger le fichier sélectionné', 'you must enter a name': 'Vous devez saisir un nom', 'new task time report': 'Nouveau rapport de temps de tâche', 'time estimates': 'Temps Estimé', 'time estimate': 'Temps Estimé', 'no deleted objects message': 'Il n\'y a pas d\'{0} supprimés dans \'{1}\'', 'no deleted objects with tag message': 'Il n\'y a pas d\'{0} supprimés marqué comme \'{2}\' dans \'{1}\'', 'restore selected objects': 'Restaurer les objets sélectionnés', 'delete selected objects permanently': 'Supprimer définitivement les objets sélectionnés', 'confirm restore objects': 'Êtes-vous certain de vouloir restaurer les objets sélectionnés ?', 'file_revision': 'Révision du fichier', 'trash emptied periodically': 'Les objets restés dans la corbeille plus de {0} jours seront supprimés.', 'confirm delete timeslot': 'Êtes-vous certain de vouloir supprimer définitivement cet intervalle de temps ?', 'confirm delete permanently': 'Êtes-vous certain de vouloir supprimer cet objet ?', 'error adding timeslot': 'Une erreur est survenue lors de l\'ajout de l\'intervalle de temps', 'no due date': 'Pas de date d\'achèvement', 'untagged': 'Non marqué', 'edit selected file properties': 'Éditer les propriétés du fichier sélectionné', 'confirm delete objects permanently': 'Êtes-vous certain de vouloir supprimer les objets sélectionnés ? La suppression est définitive, il sera impossible de revenir en arrière. ', 'n/a': '<acronym title="Non Disponible">n/a</acronym>', 'extract': 'Extraire', 'checking email accounts': 'Vérification des comptes de messagerie', 'folder': 'Dossier', 'yes': 'Oui', 'no': 'Non', 'delete account emails': 'Effacer aussi les messages', 'dont assign': 'Ne pas affecter', 'sort tags': 'Trier les étiquettes ', 'sort tags alphabetically': 'Alphabétiquement', 'sort tags by count': 'Par nombre', 'compress': 'Compresser', 'compress selected files': 'Compresser les fichiers sélectionnés', 'add files to zip': 'Ajouter les fichiers au zip', 'new compressed file': 'Nouveau fichier compressé', 'export': 'Exporter', 'import/export': 'Importer / Exporter', 'import - export': 'Importation et exportation des contacts', 'extract files': 'Extraire les fichiers', 'not csv file continue': 'Le fichier sélectionné n\'est pas un fichier CVS.\nÊtes-vous sûr de vouloir continuer ?', 'confirm template with no objects': 'Êtes-vous certain de vouloir créer un modèle sans aucun objet dedans (vous pourrez en rajouter plus tard) ?', 'everyone': 'Tout le monde', 'actions': 'Actions', 'show more': 'Voir plus', 'confirm delete tag': 'Êtes-vous certain de vouloir supprimer cette étiquette ?', 'delete tag': 'Supprimer l\'étiquette', 'reminder_popup': 'Message pop-up', 'reminder_email': 'Email', 'minutes': 'minutes', 'weeks': 'semaines', 'days': 'jours', 'before': 'avant', 'remove object reminder': 'Supprimer le rappel', 'apply to subscribers': 'Appliquer à tous les abonnés', 'must choose company': 'Vous devez choisir une société', 'contact import - export': 'Importation et exportation des contacts', 'calendar import - export': 'Importation et exportation', 'view weblink': 'Afficher le lien Web', 'print all groups': 'Imprimer', 'print this group': 'Imprimer', 'you': 'Vous', 'new version notification title': 'Révision du fichier', 'numeric': 'Numérique', 'boolean': 'Booléen', 'list': 'Liste', 'values comma separated': 'Valeurs (séparées par des virgules)', 'default value': 'Valeur par défaut', 'checked': 'Vérifié ?', 'required': 'Requis ?', 'multiple values': 'Valeurs multiples ?', 'visible by default': 'Visible par défaut ?', 'add custom property': 'Ajouter une propriété personnalisée', 'field': 'Champ', 'condition': 'Condition', 'value': 'Valeur', 'parametrizable': 'Paramètre', 'like': 'Semblable à', 'not like': 'Non-semblable à', 'equals': 'Égale à ', 'not equals': 'Différent de', 'true': 'Vrai', 'false': 'Faux', 'ends with': 'Termine par', 'milestones': 'Etapes', 'no subject': 'Pas d\'objet', 'value is already in the list': 'La valeur est déjà dans la liste', 'checkout notification': 'Notification des révisions', 'document checked out by': 'Ce document est actuellement verrouillé par {0}', 'checkout confirmation': 'Confirmation de verrouillage', 'checkout and download': 'Charger une révision', 'download only': 'Télécharger seulement', 'classify email': 'Classer les messages', 'add': 'Ajouter', 'no results found': 'Aucun résultat trouvé', 'role for this contact': 'Rôle pour ce contact', 'undo': 'Annuler', 'confirm discard changes': 'Abandonner les changements ?', 'value cannot be empty': 'La valeur ne peut être vide', 'value must be numeric': 'La valeur doit être numérique', 'memo': 'Mémo', 'add value': 'Ajouter une valeur', 'save as a new document': 'Enregistrer dans un nouveau document ', 'contact is already assigned': 'Ce contact est déjà affecté', 'confirm remove contact': 'Êtes-vous sûr de vouloir supprimer {0} ?', 'delete custom property confirmation': 'Êtes-vous certain de vouloir supprimer les propriétés personnalisées ?', 'custom property deleted': 'Les propriétés personnalisées et toutes ses valeurs seront supprimées', 'custom property name empty': 'Les noms de propriétés personnalisées sont requis', 'custom property values empty': 'Vous devez saisir des valeurs pour les propriétés personnalisées : {0}', 'delete condition confirmation': 'Êtes-vous certain de vouloir supprimer cette condition ?', 'delete report confirmation': 'Êtes-vous certain de vouloir supprimer ce rapport ?', 'object type not selected': 'Un type d\'objet doit être sélectionné pour ajouter une condition', 'condition deleted': 'Cette condition est en cours de suppression', 'report cols not selected': 'Il n\'y a pas de colonne sélectionnée pour ce rapport', 'no report conditions': 'Il n\'y a aucune condition pour ce rapport', 'condition value empty': 'Vous devez entrer une valeur pour la condition du champ {0}', 'condition value not numeric': 'La valeur du champ {0} doit être numérique', 'custom property wrong default value': 'La valeur par défaut doit être la première des valeurs séparées par des virgules pour la propriété personnalisée : {0}', 'custom property duplicate name': 'Le nom des propriétés personnalisées suivantes doit être unique : {0}', 'checkout recommendation': 'Avez-vous prévu d\'éditer ce document ? Si oui, il est recommandé de vérifier ce document en le téléchargeant.', 'confirm unclassify email': 'Êtes-vous certain de vouloir déclasser ce message ?\nIl sera retiré du contexte avec toutes ses pièces jointes,et n\'apparaitra plus dans l\'onglet Documents.', 'custom property invalid numeric value': 'La valeur par défaut pour la propriété personnalisée suivante doit être un nombre : {0}', 'file revision comments required': 'Les commentaires de la révision sont requis', 'empty trash can': 'Vider la corbeille', 'empty trash can desc': 'Supprimer tous les objets placés dans la corbeille', 'string': 'Chaine de caractères', 'add parameter': 'Ajouter un paramètre', 'select': 'Sélectionner', 'read': 'Lus', 'classified': 'Classés', 'accounts': 'Comptes', 'account options': 'Options des comptes', 'to': 'A', 'view by state': 'Par état', 'view by classification': 'Par classement', 'confirm repeating event edition': 'La modification de cet évènement répété affectera toutes les occurrences passés ou futures évènement.\nVoulez-vous réellement modifier cet évènement ?', 'update file': 'Mettre à jour le fichier', 'months': 'mois', 'click to drag task': 'Cliquez et maintenez pour glisser cette tâche', 'parameter name empty': 'Le nom ne doit pas être vide', 'parameter name exists': 'Le nom que vous avez rentré est déjà celui d\'un paramètre existant', 'object exists in template': 'L\'objet fait déjà partie du modèle', 'edit object property': 'Modifier les propriétés de l\'objet', 'fixed date': 'Date fixe', 'parametric date': 'Paramétrique', 'no parameters in template': 'Aucun paramètres de date n\'est défini pour ce modèle', 'open property editor': 'Ouvrir l\'éditeur de propriétés', 'template parameters': 'Paramétres', 'template property already selected': 'La propriété sélectionnée est déjà utilisée', 'no sender': 'Aucun destinataire', 'linkedobjects': 'Objets liés', 'unlink': 'Détacher', 'link': 'Lier', 'unlink object': 'Détacher l\'objet', 'link object': 'Lier des objets', 'change parent': 'Changer d\'objet', 'confirm unlink objects': 'Êtes vous certain de vouloir détacher le(s) objet(s) sélectionné(s)', 'repetitive task': 'Tâche répétée', 'move to workspace': 'Déplacer dans un Espace de Travail', 'keep old workspaces': 'Conserver l\'ancien Espace de Travail', 'move to workspace or keep old ones': 'Déplacer dans ou conserver les anciens et ajouter', 'do you want to move objects to this ws or keep old ones and add this ws': 'Voulez vous déplacer le(s) objet(s) sélectionné(s) dans ce contexte ou conserver les anciens et l\'ajouter à celui-ci ?', 'this field is required': 'Ce champ est requis', 'tag selected events': 'Étiqueter les évènements sélectionnés', 'edit selected event': 'Editer l\'évènement sélectionné', 'apply milestone to subtasks': 'Appliquer une Etape aux sous-tâches', 'apply workspace to subtasks': 'Appliquer un Espace de Travail aux sous-tâches', 'click here to download the csv file': 'Cliquez ici pour télécharger le fichier CSV.', 'confirm inherit permissions': 'Voulez vous appliquer les permissions héritées du contexte parent ?', 'classify mail attachments': 'Classer les pièces jointes', 'do you want to classify the unclassified emails attachments': 'Voulez-vous ajouter un nouveau document pour chaque pièce jointe de ces messages non classés ?', 'task milestone does not belong to workspace': 'L\'Etape de la tache n\'appartient pas à l\'Espace de Travail de destination, si vous continuez, la tâche sera détachée de L\'Etape. Etes-vous sûr de vouloir continuer?', 'task milestone workspace inconsistency': 'REMARQUE : cette action affectera à la tache au même Espace de travail que celui de L\'Etape sélectionnée. Etes-vous sûr de vouloir continuer?', 'mark as read': 'Marquer comme lu', 'mark as unread': 'Marquer comme non lu', 'mark as read desc': 'Marquer les objets sélectionnés comme lus.', 'no users to display': 'Aucun utilisateur à afficher', 'from csv': 'Depuis un fichier CSV', 'from vcard': 'Depuis un fichier Vcard', 'to csv': 'Vers un fichier CSV', 'to vcard': 'Vers un fichier VCard', 'outbox': 'Boite d\'envoi', 'mail sent msg': 'Le message a été envoyé', 'reply mail': 'Répondre', 'reply to all mail': 'Répondre à tous', 'forward mail': 'Faire suivre', 'archive': 'Archiver', 'unarchive': 'Désarchiver', 'archived objects': 'Objets archivés', 'archived on': 'Archivé le', 'archived by': 'Archivé par', 'junk': 'Indésirables', 'confirm unclassify emails': 'Etes vous certain de vouloir déclasser les objets sélectionnés ?', 'confirm remove tags': 'Etes vous certain de vouloir supprimer toutes les étiquettes des objets sélectionnés ?', 'remove tags': 'Supprimer les étiquettes', 'updated on': 'Mis à jours le', 'delete all tag': 'Supprimer toutes les étiquettes', 'users': 'Utilisateurs', 'groups': 'Groupes', 'switch format warn': 'Basculer en mode texte brut supprimera le formatage HTML. Continuer ?', 'mark as': 'Marquer comme...', 'mark as desc': 'Marquer les objets sélectionnés comme lus/non lus', 'filter users and groups': 'Filtrer les utilisateur et groupes...', 'you must select the contacts from the grid': 'Vous devez sélectionner les contacts à exporter.', 'archive selected object': 'Archive les objets sélectionnés', 'unarchive selected objects': 'Désarchive les objets sélectionnés', 'confirm archive selected objects': 'Etes vous certain de vouloir archiver les objets sélectionnés ?', 'confirm unarchive selected objects': 'Etes vous certain de vouloir désarchiver les objets sélectionnés ?', 'confirm archive object': 'Etes vous certain de vouloir archiver cet objet ?', 'confirm unarchive object': 'Etes vous certain de vouloir désarchiver cet objet ?', 'no more objects message': 'Il n\'y a plus de \'{0}\' à afficher', 'table': 'Tableau', 'columns comma separated': 'Colonnes (séparées par des virgules)', 'click to drag': 'Cliquer et maintenez pour glisser', 'no archived objects message': 'Aucun {0} archivé dans \'{1}\'', 'no archived objects with tag message': 'Aucun(e) {0} étiqueté(e) comme \'{2}\' archivé(e) dans \'{1}\'', 'autoconfig gmail message': 'Auto-configuration Gmail détectée. <br>Pensez à activer le service IMAP pour votre compte Gmail. Plus d\'informations <a href="http://mail.google.com/support/bin/answer.py?answer=77695" class="internallink" target="_blank">ici</a>.', 'autoconfig hotmail message': 'Auto-configuration Hotmail détectée.', 'autoconfig ymail message': 'Auto-configuration Yahoo Mail detectée. <br> Pour profiter des services POP3, vous devez utiliser un compte Yahoo Plus. Plus d\'informations <a href="http://overview.mail.yahoo.com/enhancements/mailplus" class="internallink" target="_blank">ici</a>.', 'autoconfig rocketmail message': 'Auto-configuration Yahoo Mail detectée. <br> Pour profiter des services POP3, vous devez utiliser un compte Yahoo Plus. Plus d\'informations <a href="http://overview.mail.yahoo.com/enhancements/mailplus" class="internallink" target="_blank">ici</a>.', 'autoconfig yahoo message': 'Auto-configuration Yahoo Mail detectée. <br> Pour profiter des services POP3, vous devez utiliser un compte Yahoo Plus. Plus d\'informations <a href="http://overview.mail.yahoo.com/enhancements/mailplus" class="internallink" target="_blank">ici</a>.', 'allready updated object': 'Pendant que vous l\'éditiez, quelqu\'un à mis à jour cet objet.', 'allready updated object desc': 'Souhaitez vous fusionner les modifications ? <br><br> Choisissez <strong>Oui</strong> pour afficher l\'objet dans un nouvel onglet afin de comparer avec vos changements.<br><br> Choisissez <strong>Non</strong> pour fermer cette fenêtre et écraser les modifications.', 'send outbox': 'Envoyer les messages', 'send outbox title': 'Envoyer les messages de la boite d\'envoi', 'sending outbox mails': 'Envoi des messages de la boite d\'envoi', 'fixed user': 'Utilisateur fixe', 'parametric user': 'Utilisateur depuis un paramètre', 'object type': 'Type d\'objet', 'attach contents': 'Contenu attaché', 'is archived': 'Archivé', 'archived': 'Archivé', 'no recipient': 'Pas de destinataire', 'applies to': 'S\'applique à :', 'select co types to apply': 'Sélectionnez les types d\'objet auxquels vous souhaitez appliquer la propriété.', 'write an email to contact': 'Envoyer un courriel à : {0}', 'quick upload desc': 'Lier un nouveau fichier depuis votre ordinateur', 'expand': 'Développer', 'collapse': 'Replier', 'warning': 'Attention', 'new email in conversation text': 'Il n\'y a pas de nouveau message dans la conversation à laquele vous répondez. Voulez vous envoyer quand même le message ou le visualiser dans un nouvel onglet ?', 'send anyway': 'Envoyer quand même', 'view new email': 'Visualiser le message ?', 'confirm delete permanently company': 'Etes vous certains de vouloir supprimer définitivement cette société ?\nTous les utilisateurs affiliés à cette société seront également supprimés.', 'confirm move to trash company': 'Etes vous certains de vouloir supprimer cette société ?\nTous les utilisateurs affiliés à cette société seront également supprimés.', 'urgent': 'Urgent', 'assign contact role on workspace': 'Affecter un rôle à des contacts dans un Espace de Travail', 'assign roles': 'Affecter des rôles', 'apply assignee to subtasks': 'Appliquer les assignations aux sous-tâches', 'work week': '5 jours', 'work week view': 'Semaine de travail', 'mark spam': 'Marquer comme spam', 'mark ham': 'Marquer comme non-spam', 'select all tasks': 'Sélectionner toutes les tâches', 'close': 'Fermer', 'All': 'Tout', 'person': 'Personne', 'information': 'Information', 'filters': 'Filtres', 'persons': 'Personnes', 'all customers': 'Tous les Clients', 'to vcard all': 'Tout vers Vcard', 'subscribed to': 'Abonné à', 'overdue': 'En Retard', 'active': 'Actif', 'my active': 'Mes Actifs', 'my subscribed': 'Mes Inscriptions', 'progress': 'En cours', 'estimated times': 'Temps estimés', 'estimated time': 'Temps estimé', 'empty milestones': 'Étapes vides', 'print calendar': 'Imprimer le Calendrier', 'add object subtype': 'Ajouter le sous-type d\'objet', 'delete object subtype': 'Supprimer le sous-type d\'objet', 'delete object subtype warning': 'Si vous supprimez ce sous-type, il sera retiré de tous les objets qui lui ont fixés. Êtes-vous sûr de vouloir supprimer ce sous-type?', 'object subtype deleted': 'Sous-type supprimés. {0}', 'context': 'Relations', 'none selected': 'Aucun sélectionné', 'select context members': 'Sélectionner les Membres concernés', 'member fields': 'Champs Membres', 'must be numeric': '{0] doit être un chiffre', 'new member': 'Nouveau Membre', 'view more': 'Voir plus', 'estimated': 'Estimé', 'this task has x pending tasks': 'Cette tache a {0] taches ouverte en attente ', 'this task has no pending dependencies and can be completed': 'Cette tâche n\'a pas de dépendances en attente et peut être complétée', 'you must select a member from the following dimensions': 'Pour effectuer cette action, vous devez sélectionner un membre dans ces dimensions: {0}', 'dimensions': 'Dimensions', 'all workspaces': 'Tous les Espaces de Travail', 'all tags': 'Toutes les étiquettes', 'new person': 'Nouvelle personne', 'new company': 'Nouvelle Société', 'in': 'dans', 'fee': 'Honoraire', 'email already taken by': 'Email déjà pris par {0}', 'passwords dont match': 'les Mots de Passe ne correspondent pas', 'password value missing': 'Mot de Passe requis', 'confirm disable user': 'Cet utilisateur va être désactivé. Continuez?', 'confirm delete user': 'Etes-vous sûr que vous voulez supprimer ce compte utilisateur?', 'add sub task': 'Ajouter une sous-tâche', 'do you want to mantain the current associations of this obj with members of': 'Voulez-vous maintenir les associations actuelles de cet objet avec {0}', 'tasks related': 'Taches concernées', 'apply changes to': 'Appliquer les changements à:', 'only this task': 'Seulement cette tâche', 'this task alone and all to come forward': 'Cette tâche seulement et les autres viennent avant', 'all tasks related': 'Toutes les tâches concernées', 'accept': 'Accepter', 'events related': 'Evènements concernés', 'only this event': 'Seulement cet Evènement', 'this event alone and all to come forward': 'Ces Evènements seulement et les autres viennent avant', 'all events related': 'Tous les Evènements concernés', 'add new workspace': 'Ajouter un nouvel espace de travail', 'edit selected workspace': 'Editer l\'espace de travail sélectionné', 'delete selected workspace_': 'Supprimer l\'espace de travail sélectionné', 'delete workspace warning': 'Etes-vous sûr que vous voulez déplacer l\'espace de travail sélectionné à la poubelle?', 'complete task and subtask': 'Cette tâche contient des sous-tâches qui sont encore en attente. <br/> Voulez-vous les compléter aussi?', 'option repetitive title popup': 'Cette tâche est déjà terminée. <br/> Que souhaitez-vous:', 'option repetitive only task': 'Modifier ces données de travail?', 'option repetitive pending task': 'Modifier toutes les séries de tâches? (Modifier la tâche à venir en cours)', 'add first task': 'Ajouter la 1ère Tâche', 'company not found': 'Société introuvable (id: {0})', 'and number more': 'et {0} plus.' });
agpl-3.0
gsnbng/erpnext
erpnext/loan_management/doctype/loan_interest_accrual/loan_interest_accrual.py
7653
# -*- coding: utf-8 -*- # Copyright (c) 2019, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe, erpnext from frappe import _ from frappe.model.document import Document from frappe.utils import (nowdate, getdate, now_datetime, get_datetime, flt, date_diff, get_last_day, cint, get_first_day, get_datetime, add_days) from erpnext.controllers.accounts_controller import AccountsController from erpnext.accounts.general_ledger import make_gl_entries class LoanInterestAccrual(AccountsController): def validate(self): if not self.loan: frappe.throw(_("Loan is mandatory")) if not self.posting_date: self.posting_date = nowdate() if not self.interest_amount: frappe.throw(_("Interest Amount is mandatory")) def on_submit(self): self.make_gl_entries() def on_cancel(self): if self.repayment_schedule_name: self.update_is_accrued() self.make_gl_entries(cancel=1) def update_is_accrued(self): frappe.db.set_value('Repayment Schedule', self.repayment_schedule_name, 'is_accrued', 0) def make_gl_entries(self, cancel=0, adv_adj=0): gle_map = [] gle_map.append( self.get_gl_dict({ "account": self.loan_account, "party_type": self.applicant_type, "party": self.applicant, "against": self.interest_income_account, "debit": self.interest_amount, "debit_in_account_currency": self.interest_amount, "against_voucher_type": "Loan", "against_voucher": self.loan, "remarks": _("Against Loan:") + self.loan, "cost_center": erpnext.get_default_cost_center(self.company), "posting_date": self.posting_date }) ) gle_map.append( self.get_gl_dict({ "account": self.interest_income_account, "party_type": self.applicant_type, "party": self.applicant, "against": self.loan_account, "credit": self.interest_amount, "credit_in_account_currency": self.interest_amount, "against_voucher_type": "Loan", "against_voucher": self.loan, "remarks": _("Against Loan:") + self.loan, "cost_center": erpnext.get_default_cost_center(self.company), "posting_date": self.posting_date }) ) if gle_map: make_gl_entries(gle_map, cancel=cancel, adv_adj=adv_adj) # For Eg: If Loan disbursement date is '01-09-2019' and disbursed amount is 1000000 and # rate of interest is 13.5 then first loan interest accural will be on '01-10-2019' # which means interest will be accrued for 30 days which should be equal to 11095.89 def calculate_accrual_amount_for_demand_loans(loan, posting_date, process_loan_interest): no_of_days = get_no_of_days_for_interest_accural(loan, posting_date) if no_of_days <= 0: return pending_principal_amount = loan.total_payment - loan.total_interest_payable \ - loan.total_amount_paid interest_per_day = (pending_principal_amount * loan.rate_of_interest) / (days_in_year(get_datetime(posting_date).year) * 100) payable_interest = interest_per_day * no_of_days args = frappe._dict({ 'loan': loan.name, 'applicant_type': loan.applicant_type, 'applicant': loan.applicant, 'interest_income_account': loan.interest_income_account, 'loan_account': loan.loan_account, 'pending_principal_amount': pending_principal_amount, 'interest_amount': payable_interest, 'process_loan_interest': process_loan_interest, 'posting_date': posting_date }) make_loan_interest_accrual_entry(args) def make_accrual_interest_entry_for_demand_loans(posting_date, process_loan_interest, open_loans=None, loan_type=None): query_filters = { "status": "Disbursed", "docstatus": 1 } if loan_type: query_filters.update({ "loan_type": loan_type }) if not open_loans: open_loans = frappe.get_all("Loan", fields=["name", "total_payment", "total_amount_paid", "loan_account", "interest_income_account", "is_term_loan", "disbursement_date", "applicant_type", "applicant", "rate_of_interest", "total_interest_payable", "repayment_start_date"], filters=query_filters) for loan in open_loans: calculate_accrual_amount_for_demand_loans(loan, posting_date, process_loan_interest) def make_accrual_interest_entry_for_term_loans(posting_date, process_loan_interest, term_loan=None, loan_type=None): curr_date = posting_date or add_days(nowdate(), 1) term_loans = get_term_loans(curr_date, term_loan, loan_type) accrued_entries = [] for loan in term_loans: accrued_entries.append(loan.payment_entry) args = frappe._dict({ 'loan': loan.name, 'applicant_type': loan.applicant_type, 'applicant': loan.applicant, 'interest_income_account': loan.interest_income_account, 'loan_account': loan.loan_account, 'interest_amount': loan.interest_amount, 'payable_principal': loan.principal_amount, 'process_loan_interest': process_loan_interest, 'repayment_schedule_name': loan.payment_entry, 'posting_date': posting_date }) make_loan_interest_accrual_entry(args) if accrued_entries: frappe.db.sql("""UPDATE `tabRepayment Schedule` SET is_accrued = 1 where name in (%s)""" #nosec % ", ".join(['%s']*len(accrued_entries)), tuple(accrued_entries)) def get_term_loans(date, term_loan=None, loan_type=None): condition = '' if term_loan: condition +=' AND l.name = %s' % frappe.db.escape(term_loan) if loan_type: condition += ' AND l.loan_type = %s' % frappe.db.escape(loan_type) term_loans = frappe.db.sql("""SELECT l.name, l.total_payment, l.total_amount_paid, l.loan_account, l.interest_income_account, l.is_term_loan, l.disbursement_date, l.applicant_type, l.applicant, l.rate_of_interest, l.total_interest_payable, l.repayment_start_date, rs.name as payment_entry, rs.payment_date, rs.principal_amount, rs.interest_amount, rs.is_accrued , rs.balance_loan_amount FROM `tabLoan` l, `tabRepayment Schedule` rs WHERE rs.parent = l.name AND l.docstatus=1 AND l.is_term_loan =1 AND rs.payment_date <= %s AND rs.is_accrued=0 {0} AND l.status = 'Disbursed'""".format(condition), (getdate(date)), as_dict=1) return term_loans def make_loan_interest_accrual_entry(args): loan_interest_accrual = frappe.new_doc("Loan Interest Accrual") loan_interest_accrual.loan = args.loan loan_interest_accrual.applicant_type = args.applicant_type loan_interest_accrual.applicant = args.applicant loan_interest_accrual.interest_income_account = args.interest_income_account loan_interest_accrual.loan_account = args.loan_account loan_interest_accrual.pending_principal_amount = flt(args.pending_principal_amount, 2) loan_interest_accrual.interest_amount = flt(args.interest_amount, 2) loan_interest_accrual.posting_date = args.posting_date or nowdate() loan_interest_accrual.process_loan_interest_accrual = args.process_loan_interest loan_interest_accrual.repayment_schedule_name = args.repayment_schedule_name loan_interest_accrual.payable_principal_amount = args.payable_principal loan_interest_accrual.save() loan_interest_accrual.submit() def get_no_of_days_for_interest_accural(loan, posting_date): last_interest_accrual_date = get_last_accural_date_in_current_month(loan) no_of_days = date_diff(posting_date or nowdate(), last_interest_accrual_date) + 1 return no_of_days def get_last_accural_date_in_current_month(loan): last_posting_date = frappe.db.sql(""" SELECT MAX(posting_date) from `tabLoan Interest Accrual` WHERE loan = %s""", (loan.name)) if last_posting_date[0][0]: return last_posting_date[0][0] else: return loan.disbursement_date def days_in_year(year): days = 365 if (year % 4 == 0) and (year % 100 != 0) or (year % 400 == 0): days = 366 return days
agpl-3.0
yanlingling/xnjs
application/models/project_milestones/base/BaseProjectMilestone.class.php
11137
<?php /** * BaseProjectMilestone class * * @author Ilija Studen <ilija.studen@gmail.com> */ abstract class BaseProjectMilestone extends ProjectDataObject { protected $objectTypeIdentifier = 'mi'; // ------------------------------------------------------- // Access methods // ------------------------------------------------------- /** * Return value of 'id' field * * @access public * @param void * @return integer */ function getId() { return $this->getColumnValue('id'); } // getId() /** * Set value of 'id' field * * @access public * @param integer $value * @return boolean */ function setId($value) { return $this->setColumnValue('id', $value); } // setId() /** * Return value of 'name' field * * @access public * @param void * @return string */ function getName() { return $this->getColumnValue('name'); } // getName() /** * Set value of 'name' field * * @access public * @param string $value * @return boolean */ function setName($value) { return $this->setColumnValue('name', $value); } // setName() /** * Return value of 'description' field * * @access public * @param void * @return string */ function getDescription() { return $this->getColumnValue('description'); } // getDescription() /** * Set value of 'description' field * * @access public * @param string $value * @return boolean */ function setDescription($value) { return $this->setColumnValue('description', $value); } // setDescription() /** * Return value of 'due_date' field * * @access public * @param void * @return DateTimeValue */ function getDueDate() { return $this->getColumnValue('due_date'); } // getDueDate() /** * Set value of 'due_date' field * * @access public * @param DateTimeValue $value * @return boolean */ function setDueDate($value) { return $this->setColumnValue('due_date', $value); } // setDueDate() /** * Return value of 'assigned_to_company_id' field * * @access public * @param void * @return integer */ function getAssignedToCompanyId() { return $this->getColumnValue('assigned_to_company_id'); } // getAssignedToCompanyId() /** * Set value of 'assigned_to_company_id' field * * @access public * @param integer $value * @return boolean */ function setAssignedToCompanyId($value) { return $this->setColumnValue('assigned_to_company_id', $value); } // setAssignedToCompanyId() /** * Return value of 'assigned_to_user_id' field * * @access public * @param void * @return integer */ function getAssignedToUserId() { return $this->getColumnValue('assigned_to_user_id'); } // getAssignedToUserId() /** * Set value of 'assigned_to_user_id' field * * @access public * @param integer $value * @return boolean */ function setAssignedToUserId($value) { return $this->setColumnValue('assigned_to_user_id', $value); } // setAssignedToUserId() /** * Return value of 'is_private' field * * @access public * @param void * @return boolean */ function getIsPrivate() { return $this->getColumnValue('is_private'); } // getIsPrivate() /** * Set value of 'is_private' field * * @access public * @param boolean $value * @return boolean */ function setIsPrivate($value) { return $this->setColumnValue('is_private', $value); } // setIsPrivate() /** Return value of 'is_urgent' field * * @access public * @param void * @return boolean */ function getIsUrgent() { return $this->getColumnValue('is_urgent'); } // getIsUrgent() /** * Set value of 'is_urgent' field * * @access public * @param boolean $value * @return boolean */ function setIsUrgent($value) { return $this->setColumnValue('is_urgent', $value); } // setIsUrgent() /** * Return value of 'completed_on' field * * @access public * @param void * @return DateTimeValue */ function getCompletedOn() { return $this->getColumnValue('completed_on'); } // getCompletedOn() /** * Set value of 'completed_on' field * * @access public * @param DateTimeValue $value * @return boolean */ function setCompletedOn($value) { return $this->setColumnValue('completed_on', $value); } // setCompletedOn() /** * Return value of 'completed_by_id' field * * @access public * @param void * @return integer */ function getCompletedById() { return $this->getColumnValue('completed_by_id'); } // getCompletedById() /** * Set value of 'completed_by_id' field * * @access public * @param integer $value * @return boolean */ function setCompletedById($value) { return $this->setColumnValue('completed_by_id', $value); } // setCompletedById() /** * Return value of 'created_on' field * * @access public * @param void * @return DateTimeValue */ function getCreatedOn() { return $this->getColumnValue('created_on'); } // getCreatedOn() /** * Set value of 'created_on' field * * @access public * @param DateTimeValue $value * @return boolean */ function setCreatedOn($value) { return $this->setColumnValue('created_on', $value); } // setCreatedOn() /** * Return value of 'created_by_id' field * * @access public * @param void * @return integer */ function getCreatedById() { return $this->getColumnValue('created_by_id'); } // getCreatedById() /** * Set value of 'created_by_id' field * * @access public * @param integer $value * @return boolean */ function setCreatedById($value) { return $this->setColumnValue('created_by_id', $value); } // setCreatedById() /** * Return value of 'updated_on' field * * @access public * @param void * @return DateTimeValue */ function getUpdatedOn() { return $this->getColumnValue('updated_on'); } // getUpdatedOn() /** * Set value of 'updated_on' field * * @access public * @param DateTimeValue $value * @return boolean */ function setUpdatedOn($value) { return $this->setColumnValue('updated_on', $value); } // setUpdatedOn() /** * Return value of 'updated_by_id' field * * @access public * @param void * @return integer */ function getUpdatedById() { return $this->getColumnValue('updated_by_id'); } // getUpdatedById() /** * Set value of 'updated_by_id' field * * @access public * @param integer $value * @return boolean */ function setUpdatedById($value) { return $this->setColumnValue('updated_by_id', $value); } // setUpdatedById() /** * Return manager instance * * @access protected * @param void * @return ProjectMilestones */ function manager() { if(!($this->manager instanceof ProjectMilestones)) $this->manager = ProjectMilestones::instance(); return $this->manager; } // manager /** * Return value of 'is_template' field * * @access public * @param void * @return boolean */ function getIsTemplate() { return $this->getColumnValue('is_template'); } // getIsTemplate() /** * Set value of 'is_template' field * * @access public * @param boolean $value * @return boolean */ function setIsTemplate($value) { return $this->setColumnValue('is_template', $value); } // setIsTemplate() /** * Return value of 'from_template_id' field * * @access public * @param void * @return integer */ function getFromTemplateId() { return $this->getColumnValue('from_template_id'); } // getFromTemplateId() /** * Set value of 'from_template_id' field * * @access public * @param integer $value * @return boolean */ function setFromTemplateId($value) { return $this->setColumnValue('from_template_id', $value); } // setFromTemplateId() /** Return value of 'trashed_on' field * * @access public * @param void * @return DateTimeValue */ function getTrashedOn() { return $this->getColumnValue('trashed_on'); } // getTrashedOn() /** * Set value of 'trashed_on' field * * @access public * @param DateTimeValue $value * @return boolean */ function setTrashedOn($value) { return $this->setColumnValue('trashed_on', $value); } // setTrashedOn() /** * Return value of 'trashed_by_id' field * * @access public * @param void * @return integer */ function getTrashedById() { return $this->getColumnValue('trashed_by_id'); } // getTrashedById() /** * Set value of 'trashed_by_id' field * * @access public * @param integer $value * @return boolean */ function setTrashedById($value) { return $this->setColumnValue('trashed_by_id', $value); } // setTrashedById() /** * Return value of 'archived_by_id' field * * @access public * @param void * @return integer */ function getArchivedById() { return $this->getColumnValue('archived_by_id'); } // getArchivedById() /** * Set value of 'archived_by_id' field * * @access public * @param integer $value * @return boolean */ function setArchivedById($value) { return $this->setColumnValue('archived_by_id', $value); } // setArchivedById() /** Return value of 'archived_on' field * * @access public * @param void * @return DateTimeValue */ function getArchivedOn() { return $this->getColumnValue('archived_on'); } // getArchivedOn() /** * Set value of 'archived_on' field * * @access public * @param DateTimeValue $value * @return boolean */ function setArchivedOn($value) { return $this->setColumnValue('archived_on', $value); } // setArchivedOn() } // BaseProjectMilestone ?>
agpl-3.0
protyposis/Aurio
Aurio/Aurio.FFmpeg/VideoOutputConfig.cs
2172
// // Aurio: Audio Processing, Analysis and Retrieval Library // Copyright (C) 2010-2017 Mario Guggenberger <mg@protyposis.net> // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; namespace Aurio.FFmpeg { [StructLayout(LayoutKind.Sequential)] public struct VideoOutputFormat { public int width { get; internal set; } public int height { get; internal set; } public double frame_rate { get; internal set; } public double aspect_ratio { get; internal set; } } public enum AVPictureType : int { AV_PICTURE_TYPE_NONE = 0, AV_PICTURE_TYPE_I, AV_PICTURE_TYPE_P, AV_PICTURE_TYPE_B, AV_PICTURE_TYPE_S, AV_PICTURE_TYPE_SI, AV_PICTURE_TYPE_SP, AV_PICTURE_TYPE_BI } [StructLayout(LayoutKind.Sequential)] public struct VideoFrameProperties { public bool keyframe { get; internal set; } public AVPictureType pict_type { get; internal set; } public bool interlaced { get; internal set; } public bool top_field_first { get; internal set; } } [StructLayout(LayoutKind.Sequential)] public struct VideoOutputConfig { public VideoOutputFormat format { get; internal set; } public long length { get; internal set; } public int frame_size { get; internal set; } public VideoFrameProperties current_frame { get; internal set; } } }
agpl-3.0