code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.x.cms.assemble.control.jaxrs.viewfieldconfig; import java.util.ArrayList; import java.util.List; import java.util.Optional; import javax.servlet.http.HttpServletRequest; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.JpaObject; import com.x.base.core.project.bean.WrapCopier; import com.x.base.core.project.bean.WrapCopierFactory; import com.x.base.core.project.cache.Cache; import com.x.base.core.project.cache.CacheManager; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.cms.assemble.control.Business; import com.x.cms.assemble.control.factory.ViewFieldConfigFactory; import com.x.cms.core.entity.element.ViewFieldConfig; import net.sf.ehcache.Element; public class ActionListByViewId extends BaseAction { @SuppressWarnings("unchecked") protected ActionResult<List<Wo>> execute( HttpServletRequest request, EffectivePerson effectivePerson, String viewId ) throws Exception { ActionResult<List<Wo>> result = new ActionResult<>(); List<Wo> wraps = null; Cache.CacheKey cacheKey = new Cache.CacheKey( this.getClass(), viewId ); Optional<?> optional = CacheManager.get(cacheCategory, cacheKey ); if (optional.isPresent()) { wraps = (List<Wo>) optional.get(); result.setData(wraps); } else { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); //如判断用户是否有查看所有展示列配置信息的权限,如果没权限不允许继续操作 if (!business.viewEditAvailable( effectivePerson )) { throw new Exception("person{name:" + effectivePerson.getDistinguishedName() + "} 用户没有查询全部展示列配置信息的权限!"); } //如果有权限,继续操作 ViewFieldConfigFactory viewFieldConfigFactory = business.getViewFieldConfigFactory(); List<String> ids = viewFieldConfigFactory.listByViewId( viewId );//获取指定应用的所有展示列配置信息列表 List<ViewFieldConfig> viewFieldConfigList = emc.list( ViewFieldConfig.class, ids );//查询ID IN ids 的所有展示列配置信息信息列表 wraps = Wo.copier.copy( viewFieldConfigList );//将所有查询出来的有状态的对象转换为可以输出的过滤过属性的对象 CacheManager.put(cacheCategory, cacheKey, wraps ); result.setData(wraps); } catch (Throwable th) { th.printStackTrace(); result.error(th); } } return result; } public static class Wo extends ViewFieldConfig { private static final long serialVersionUID = -5076990764713538973L; public static List<String> excludes = new ArrayList<String>(); public static final WrapCopier<ViewFieldConfig, Wo> copier = WrapCopierFactory.wo( ViewFieldConfig.class, Wo.class, null, JpaObject.FieldsInvisible); } }
o2oa/o2oa
o2server/x_cms_assemble_control/src/main/java/com/x/cms/assemble/control/jaxrs/viewfieldconfig/ActionListByViewId.java
Java
agpl-3.0
2,946
<section id="principal" class="drm"> <div id="application_drm"> <?php if (!$isTeledeclarationMode): ?> <?php include_partial('drm/header', array('drm' => $drm)); ?> <ul id="recap_infos_header"> <li> <label>Nom de l'opérateur : </label><?php echo $drm->getEtablissement()->nom ?><label style="float: right;">Période : <?php echo $drm->periode ?></label> </li> </ul> <?php endif; ?> <?php include_partial('drm/etapes', array('drm' => $drm, 'isTeledeclarationMode' => $isTeledeclarationMode, 'etape_courante' => DRMClient::ETAPE_VALIDATION)); ?> <h2>Modification des informations de votre chai</h2> <form action="<?php echo url_for('drm_validation_update_etablissement', $drm); ?>" method="POST" class="drm_validation_etablissement_form"> <?php echo $form->renderHiddenFields(); ?> <?php echo $form->renderGlobalErrors(); ?> <div class="ligne_form"> <label>Raison Sociale :</label> <?php echo $drm->declarant->nom; ?> </div> <div class="ligne_form"> <?php echo $form['cvi']->renderError(); ?> <?php echo $form['cvi']->renderLabel(); ?> <?php echo $form['cvi']->render(); ?> </div> <div class="ligne_form"> <?php echo $form['no_accises']->renderError(); ?> <?php echo $form['no_accises']->renderLabel(); ?> <?php echo $form['no_accises']->render(); ?> </div> <div class="ligne_form"> <?php echo $form['adresse']->renderError(); ?> <?php echo $form['adresse']->renderLabel(); ?> <?php echo $form['adresse']->render(array('class' => 'champ_long')); ?> </div> <div class="ligne_form"> <?php echo $form['code_postal']->renderError(); ?> <?php echo $form['code_postal']->renderLabel(); ?> <?php echo $form['code_postal']->render(); ?> </div> <div class="ligne_form"> <?php echo $form['commune']->renderError(); ?> <?php echo $form['commune']->renderLabel(); ?> <?php echo $form['commune']->render(); ?> </div> <?php if ($drm->declarant->exist('adresse_compta')): ?> <div class="ligne_form"> <?php echo $form['adresse_compta']->renderError(); ?> <?php echo $form['adresse_compta']->renderLabel(); ?> <?php echo $form['adresse_compta']->render(array('class' => 'champ_long')); ?> </div> <?php endif; ?> <?php if ($drm->declarant->exist('caution')): ?> <div class="ligne_form alignes update_form_radio_list"> <span> <?php echo $form['caution']->renderError(); ?> <?php echo $form['caution']->renderLabel(); ?> <?php echo $form['caution']->render(); ?> </span> </div> <?php endif; ?> <?php $hasSocialeCautionneur = (($drm->getEtablissement()->exist('caution') && ($drm->getEtablissement()->caution == EtablissementClient::CAUTION_CAUTION)) || (($drm->declarant->exist('caution')) && ($drm->declarant->caution == EtablissementClient::CAUTION_CAUTION))); ?> <?php if ($drm->declarant->exist('raison_sociale_cautionneur')): ?> <div class="ligne_form raison_sociale_cautionneur" style="<?php echo (!$hasSocialeCautionneur) ? 'display:none;' : ''; ?>" > <?php echo $form['raison_sociale_cautionneur']->renderError(); ?> <?php echo $form['raison_sociale_cautionneur']->renderLabel(); ?> <?php echo $form['raison_sociale_cautionneur']->render(array('class' => 'champ_long')); ?> </div> <?php endif; ?> <div id="btn_etape_dr"> <a href="<?php echo url_for('drm_validation', $drm) ?>" class="btn_majeur btn_annuler" style="float: left;" id="drm_validation_etablissement_annuler_btn"><span>annuler</span></a> <button type="submit" class="btn_majeur btn_valider" id="drm_validation_etablissement_valider_btn" style="float: right;"><span>Valider</span></button> </div> </form> </div> </section> <?php include_partial('drm/colonne_droite', array('drm' => $drm, 'isTeledeclarationMode' => $isTeledeclarationMode)); ?>
24eme/acVinDRMPlugin
modules/drm_validation/templates/updateEtablissementSuccess.php
PHP
agpl-3.0
4,662
/** * Copyright (C) 2013-2014 Spark Labs, Inc. All rights reserved. - https://www.spark.io/ * * 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/>. * * You can download the source here: https://github.com/spark/spark-server */ var settings = require('../settings.js'); var CoreController = require('../lib/CoreController.js'); var roles = require('../lib/RolesController.js'); var sequence = require('when/sequence'); var parallel = require('when/parallel'); var pipeline = require('when/pipeline'); var logger = require('../lib/logger.js'); var utilities = require("../lib/utilities.js"); var fs = require('fs'); var when = require('when'); var util = require('util'); var path = require('path'); var ursa = require('ursa'); var moment = require('moment'); var crypto = require('crypto'); // var corepath; // var corepath = settings.getToCores(); /* * TODO: modularize duplicate code * TODO: implement proper session handling / user authentication * TODO: add cors handler without losing :params support * */ var Api = { loadViews: function (app) { //our middleware app.param("coreid", Api.loadCore); //core functions / variables app.post('/v1/devices/:coreid/:func', Api.fn_call); app.get('/v1/devices/:coreid/:var', Api.get_var); app.put('/v1/devices/:coreid', Api.set_core_attributes); app.get('/v1/devices/:coreid', Api.get_core_attributes); //doesn't need per-core permissions, only shows owned cores. app.get('/v1/devices', Api.list_devices); app.post('/v1/provisioning/:coreid', Api.provision_core); //app.delete('/v1/devices/:coreid', Api.release_device); app.post('/v1/devices', Api.claim_device); }, getSocketID: function (userID) { return userID + "_" + global._socket_counter++; }, getUserID: function (req) { if (!req.user) { logger.log("User obj was empty"); return null; } //req.user.id is set in authorise.validateAccessToken in the OAUTH code return req.user.id; }, list_devices: function (req, res) { var userid = Api.getUserID(req); logger.log("ListDevices", { userID: userid }); // corepath = settings.getToCores(userid); global.server.loadCoreData(userid); // console.log(corepath); //give me all the cores var allCoreIDs = global.server.getAllCoreIDs(userid); // console.log(allCoreIDs); devices = [], connected_promises = []; if(allCoreIDs == null){ var devices = ("no device is claimed by this user"); res.json(200, devices); } else{ for (var coreid in allCoreIDs) { if (!coreid) { continue; } var core = global.server.getCoreAttributes(coreid); var device = { id: coreid, name: (core) ? core.name : null, last_app: core ? core.last_flashed_app_name : null, last_heard: null }; if (utilities.check_requires_update(core, settings.cc3000_driver_version)) { device["requires_deep_update"] = true; } devices.push(device); connected_promises.push(Api.isDeviceOnline(userid, device.id)); } logger.log("ListDevices... waiting for connected state to settle ", { userID: userid }); //switched 'done' to 'then' - threw an exception with 'done' here. when.settle(connected_promises).then(function (descriptors) { for (var i = 0; i < descriptors.length; i++) { var desc = descriptors[i]; devices[i].connected = ('rejected' !== desc.state); devices[i].last_heard = (desc.value) ? desc.value.lastPing : null; } res.json(200, devices); }); } }, get_core_attributes: function (req, res) { var userid = Api.getUserID(req); var socketID = Api.getSocketID(userid), coreID = req.coreID, socket = new CoreController(socketID); logger.log("GetAttr", { coreID: coreID, userID: userid.toString() }); var objReady = parallel([ function () { return when.resolve(global.server.getCoreAttributes(coreID)); }, function () { return utilities.alwaysResolve(socket.sendAndListenForDFD(coreID, { cmd: "Describe" }, { cmd: "DescribeReturn" })); } ]); //whatever we get back... when(objReady).done(function (results) { try { if (!results || (results.length != 2)) { logger.error("get_core_attributes results was the wrong length " + JSON.stringify(results)); res.json(404, "Oops, I couldn't find that core"); return; } //we're expecting descResult to be an array: [ sender, {} ] var doc = results[0], descResult = results[1], coreState = null; if (!doc || !doc.coreID) { logger.error("get_core_attributes 404 error: " + JSON.stringify(doc)); res.json(404, "Oops, I couldn't find that core"); return; } if (util.isArray(descResult) && (descResult.length > 1)) { coreState = descResult[1].state || {}; } if (!coreState) { logger.error("get_core_attributes didn't get description: " + JSON.stringify(descResult)); } var device = { id: doc.coreID, name: doc.name || null, last_app: doc.last_flashed, connected: !!coreState, variables: (coreState) ? coreState.v : null, functions: (coreState) ? coreState.f : null, cc3000_patch_version: doc.cc3000_driver_version }; if (utilities.check_requires_update(doc, settings.cc3000_driver_version)) { device["requires_deep_update"] = true; } res.json(device); } catch (ex) { logger.error("get_core_attributes merge error: " + ex); res.json(500, { Error: "get_core_attributes error: " + ex }); } }, null); //get_core_attribs - end }, set_core_attributes: function (req, res) { var coreID = req.coreID; var userid = Api.getUserID(req); var promises = []; logger.log("set_core_attributes", { coreID: coreID, userID: userid.toString() }); var coreName = req.body ? req.body.name : null; if (coreName != null) { logger.log("SetAttr", { coreID: coreID, userID: userid.toString(), name: coreName }); global.server.setCoreAttribute(req.coreID, "name", coreName); promises.push(when.resolve({ ok: true, name: coreName })); } var hasFiles = req.files && req.files.file; if (hasFiles) { //oh hey, you want to flash firmware? promises.push(Api.compile_and__or_flash_dfd(req)); } var signal = req.body && req.body.signal; if (signal) { //get your hands up in the air! Or down. promises.push(Api.core_signal_dfd(req)); } var flashApp = req.body ? req.body.app : null; if (flashApp) { // It makes no sense to flash a known app and also // either signal or flash a file sent with the request if (!hasFiles && !signal) { // MUST sanitize app name here, before sending to Device Service if (utilities.contains(settings.known_apps, flashApp)) { promises.push(Api.flash_known_app_dfd(req)); } else { promises.push(when.reject("Can't flash unknown app " + flashApp)); } } } var app_id = req.body ? req.body.app_id : null; if (app_id && !hasFiles && !signal && !flashApp) { //we have an app id, and no files, and stuff //we must be flashing from the db! promises.push(Api.flash_app_in_db_dfd(req)); } var app_example_id = req.body ? req.body.app_example_id : null; if (app_example_id && !hasFiles && !signal && !flashApp && !app_id) { //we have an app id, and no files, and stuff //we must be flashing from the db! promises.push(Api.flash_example_app_in_db_dfd(req)); } if (promises.length >= 1) { when.all(promises).done( function (results) { var aggregate = {}; for (var i in results) { for (var key in results[i]) { aggregate[key] = results[i][key]; } } res.json(aggregate); }, function (err) { res.json({ ok: false, errors: [err] }); } ); } else { logger.error("set_core_attributes - nothing to do?", { coreID: coreID, userID: userid.toString() }); res.json({error: "Nothing to do?"}); } }, isDeviceOnline: function (userID, coreID) { var tmp = when.defer(); var socketID = Api.getSocketID(userID); var socket = new CoreController(socketID); var failTimer = setTimeout(function () { logger.log("isDeviceOnline: Ping timed out ", { coreID: coreID }); socket.close(); tmp.reject("Device is not connected"); }, settings.isCoreOnlineTimeout); //setup listener for response back from the device service socket.listenFor(coreID, { cmd: "Pong" }, function (sender, msg) { clearTimeout(failTimer); socket.close(); logger.log("isDeviceOnline: Device service thinks it is online... ", { coreID: coreID }); if (msg && msg.online) { tmp.resolve(msg); } else { tmp.reject(["Core isn't online", 404]); } }, true); logger.log("isDeviceOnline: Pinging core... ", { coreID: coreID }); //send it along to the device service if (!socket.send(coreID, { cmd: "Ping" })) { tmp.reject("send failed"); } return tmp.promise; }, claim_device: function (req, res) { res.json({ ok: true }); }, loadCore: function (req, res, next) { req.coreID = req.param('coreid') || req.body.id; //load core info! req.coreInfo = { "last_app": "", "last_heard": new Date(), "connected": false, "deviceID": req.coreID }; //if that user doesn't own that coreID, maybe they sent us a core name var userid = Api.getUserID(req); var gotCore = utilities.deferredAny([ function () { var core = global.server.getCoreAttributes(req.coreID); if (core && core.coreID) { return when.resolve(core); } else { return when.reject(); } }, function () { var core = global.server.getCoreByName(req.coreID); if (core && core.coreID) { return when.resolve(core); } else { return when.reject(); } } ]); when(gotCore).then( function (core) { if (core) { req.coreID = core.coreID || req.coreID; req.coreInfo = { last_handshake_at: core.last_handshake_at }; } next(); }, function (err) { //s`okay. next(); }) }, get_var: function (req, res) { var userid = Api.getUserID(req); var socketID = Api.getSocketID(userid), coreID = req.coreID, varName = req.param('var'), format = req.param('format'); logger.log("GetVar", {coreID: coreID, userID: userid.toString()}); //send it along to the device service //and listen for a response back from the device service var socket = new CoreController(socketID); var coreResult = socket.sendAndListenForDFD(coreID, { cmd: "GetVar", name: varName }, { cmd: "VarReturn", name: varName }, settings.coreRequestTimeout ); //sendAndListenForDFD resolves arr to ==> [sender, msg] when(coreResult) .then(function (arr) { var msg = arr[1]; if (msg.error) { //at this point, either we didn't get a describe return, or that variable //didn't exist, either way, 404 return res.json(404, { ok: false, error: msg.error }); } //TODO: make me look like the spec. msg.coreInfo = req.coreInfo; msg.coreInfo.connected = true; if (format && (format == "raw")) { return res.send("" + msg.result); } else { return res.json(msg); } }, function () { res.json(408, {error: "Timed out."}); } ).ensure(function () { socket.close(); }); }, fn_call: function (req, res) { var user_id = Api.getUserID(req), coreID = req.coreID, funcName = req.params.func, format = req.params.format; logger.log("FunCall", { coreID: coreID, user_id: user_id.toString() }); var socketID = Api.getSocketID(user_id); var socket = new CoreController(socketID); var core = socket.getCore(coreID); var args = req.body; delete args.access_token; logger.log("FunCall - calling core ", { coreID: coreID, user_id: user_id.toString() }); var coreResult = socket.sendAndListenForDFD(coreID, { cmd: "CallFn", name: funcName, args: args }, { cmd: "FnReturn", name: funcName }, settings.coreRequestTimeout ); //sendAndListenForDFD resolves arr to ==> [sender, msg] when(coreResult) .then( function (arr) { var sender = arr[0], msg = arr[1]; try { //logger.log("FunCall - heard back ", { coreID: coreID, user_id: user_id.toString() }); if (msg.error && (msg.error.indexOf("Unknown Function") >= 0)) { res.json(404, { ok: false, error: "Function not found" }); } else if (msg.error != null) { res.json(400, { ok: false, error: msg.error }); } else { if (format && (format == "raw")) { res.send("" + msg.result); } else { res.json({ id: core.coreID, name: core.name || null, last_app: core.last_flashed_app_name || null, connected: true, return_value: msg.result }); } } } catch (ex) { logger.error("FunCall handling resp error " + ex); res.json(500, { ok: false, error: "Error while api was rendering response" }); } }, function () { res.json(408, {error: "Timed out."}); } ).ensure(function () { socket.close(); }); //socket.send(coreID, { cmd: "CallFn", name: funcName, args: args }); // send the function call along to the device service }, /** * Ask the core to start / stop the "RaiseYourHand" signal * @param req */ core_signal_dfd: function (req) { var tmp = when.defer(); var userid = Api.getUserID(req), socketID = Api.getSocketID(userid), coreID = req.coreID, showSignal = parseInt(req.body.signal); logger.log("SignalCore", { coreID: coreID, userID: userid.toString()}); var socket = new CoreController(socketID); var failTimer = setTimeout(function () { socket.close(); tmp.reject({error: "Timed out, didn't hear back"}); }, settings.coreSignalTimeout); //listen for a response back from the device service socket.listenFor(coreID, { cmd: "RaiseHandReturn"}, function () { clearTimeout(failTimer); socket.close(); tmp.resolve({ id: coreID, connected: true, signaling: showSignal === 1 }); }, true); //send it along to the core via the device service socket.send(coreID, { cmd: "RaiseHand", args: { signal: showSignal } }); return tmp.promise; }, compile_and__or_flash_dfd: function (req) { var allDone = when.defer(); var userid = Api.getUserID(req), coreID = req.coreID; // // Did they pass us a source file or a binary file? // var hasSourceFiles = false; var sourceExts = [".cpp", ".c", ".h", ".ino" ]; if (req.files) { for (var name in req.files) { if (!req.files.hasOwnProperty(name)) { continue; } var ext = utilities.getFilenameExt(req.files[name].path); if (utilities.contains(sourceExts, ext)) { hasSourceFiles = true; break; } } } if (hasSourceFiles) { //TODO: federate? allDone.reject("Not yet implemented"); } else { //they sent a binary, just flash it! var flashDone = Api.flash_core_dfd(req); //pipe rejection / resolution of flash to response utilities.pipeDeferred(flashDone, allDone); } return allDone.promise; }, /** * Flashing firmware to the core, binary file! * @param req * @returns {promise|*|Function|Promise|when.promise} */ flash_core_dfd: function (req) { var tmp = when.defer(); var userid = Api.getUserID(req), socketID = Api.getSocketID(userid), coreID = req.coreID; logger.log("FlashCore", {coreID: coreID, userID: userid.toString()}); var args = req.query; delete args.coreid; if (req.files) { args.data = fs.readFileSync(req.files.file.path); } var socket = new CoreController(socketID); var failTimer = setTimeout(function () { socket.close(); tmp.reject({error: "Timed out."}); }, settings.coreFlashTimeout); //listen for the first response back from the device service socket.listenFor(coreID, { cmd: "Event", name: "Update" }, function (sender, msg) { clearTimeout(failTimer); socket.close(); var response = { id: coreID, status: msg.message }; if ("Update started" === msg.message) { tmp.resolve(response); } else { logger.error("flash_core_dfd rejected ", response); tmp.reject(response); } }, true); //send it along to the device service socket.send(coreID, { cmd: "UFlash", args: args }); return tmp.promise; }, provision_core: function (req, res) { //if we're here, the user should be allowed to provision cores. var done = Api.provision_core_dfd(req); when(done).then( function (result) { res.json(result); }, function (err) { //different status code here? res.json(400, err); }); }, provision_core_dfd: function (req) { var result = when.defer(), userid = Api.getUserID(req), deviceID = req.body.deviceID, publicKey = req.body.publicKey; if (!deviceID) { return when.reject({ error: "No deviceID provided" }); } try { var keyObj = ursa.createPublicKey(publicKey); if (!publicKey || (!ursa.isPublicKey(keyObj))) { return when.reject({ error: "No key provided" }); } } catch (ex) { logger.error("error while parsing publicKey " + ex); return when.reject({ error: "Key error " + ex }); } global.server.addCoreKey(userid, deviceID, publicKey); global.server.setCoreAttribute(deviceID, "registrar", userid); global.server.setCoreAttribute(deviceID, "timestamp", new Date()); result.resolve("Success!"); return result.promise; }, _: null }; exports = module.exports = Api; //implement :: save core data
SreejitS/spark-server
views/api_v1.js
JavaScript
agpl-3.0
18,143
# frozen_string_literal: true module Decidim module Meetings # This controller is the abstract class from which all other controllers of # this engine inherit. # # Note that it inherits from `Decidim::Components::BaseController`, which # override its layout and provide all kinds of useful methods. module Directory class ApplicationController < Decidim::ApplicationController helper Decidim::Meetings::Directory::ApplicationHelper end end end end
decidim/decidim
decidim-meetings/app/controllers/decidim/meetings/directory/application_controller.rb
Ruby
agpl-3.0
501
class TutorialProgressesController < ApplicationController before_filter :admin_required # GET /tutorial_progresses # GET /tutorial_progresses.json def index @tutorial_progresses = TutorialProgress.all respond_to do |format| format.html # index.html.erb format.json { render json: @tutorial_progresses } end end # GET /tutorial_progresses/1 # GET /tutorial_progresses/1.json def show @tutorial_progress = TutorialProgress.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render json: @tutorial_progress } end end # GET /tutorial_progresses/new # GET /tutorial_progresses/new.json def new @tutorial_progress = TutorialProgress.new respond_to do |format| format.html # new.html.erb format.json { render json: @tutorial_progress } end end # GET /tutorial_progresses/1/edit def edit @tutorial_progress = TutorialProgress.find(params[:id]) end # POST /tutorial_progresses # POST /tutorial_progresses.json def create @tutorial_progress = TutorialProgress.new(params[:tutorial_progress]) respond_to do |format| if @tutorial_progress.save format.html { redirect_to @tutorial_progress, notice: 'Tutorial progress was successfully created.' } format.json { render json: @tutorial_progress, status: :created, location: @tutorial_progress } else format.html { render action: 'new' } format.json { render json: @tutorial_progress.errors, status: :unprocessable_entity } end end end # PUT /tutorial_progresses/1 # PUT /tutorial_progresses/1.json def update @tutorial_progress = TutorialProgress.find(params[:id]) respond_to do |format| if @tutorial_progress.update_attributes(params[:tutorial_progress]) format.html { redirect_to @tutorial_progress, notice: 'Tutorial progress was successfully updated.' } format.json { head :ok } else format.html { render action: 'edit' } format.json { render json: @tutorial_progress.errors, status: :unprocessable_entity } end end end # DELETE /tutorial_progresses/1 # DELETE /tutorial_progresses/1.json def destroy @tutorial_progress = TutorialProgress.find(params[:id]) @tutorial_progress.destroy respond_to do |format| format.html { redirect_to tutorial_progresses_url } format.json { head :ok } end end end
zmdroid/Airesis
app/controllers/tutorial_progresses_controller.rb
Ruby
agpl-3.0
2,464
/* * SessionRnwWeave.hpp * * Copyright (C) 2009-12 by RStudio, Inc. * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * this program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ #ifndef SESSION_MODULES_RNW_WEAVE_HPP #define SESSION_MODULES_RNW_WEAVE_HPP #include <boost/function.hpp> #include <core/tex/TexLogParser.hpp> #include <core/tex/TexMagicComment.hpp> #include <core/json/Json.hpp> #include "SessionRnwConcordance.hpp" namespace core { class Error; class FilePath; } namespace session { namespace modules { namespace tex { namespace rnw_weave { core::json::Array supportedTypes(); void getTypesInstalledStatus(core::json::Object* pObj); core::json::Value chunkOptions(const std::string& weaveType); struct Result { static Result error(const std::string& errorMessage) { Result result; result.succeeded = false; result.errorMessage = errorMessage; return result; } static Result error(const core::tex::LogEntries& logEntries) { Result result; result.succeeded = false; result.errorLogEntries = logEntries; return result; } static Result success( const tex::rnw_concordance::Concordances& concordances) { Result result; result.succeeded = true; result.concordances = concordances; return result; } bool succeeded; std::string errorMessage; core::tex::LogEntries errorLogEntries; tex::rnw_concordance::Concordances concordances; }; typedef boost::function<void(const Result&)> CompletedFunction; void runTangle(const std::string& filePath, const std::string& rnwWeave); void runWeave(const core::FilePath& filePath, const std::string& encoding, const core::tex::TexMagicComments& magicComments, const boost::function<void(const std::string&)>& onOutput, const CompletedFunction& onCompleted); } // namespace rnw_weave } // namespace tex } // namespace modules } // namesapce session #endif // SESSION_MODULES_RNW_WEAVE_HPP
nvoron23/rstudio
src/cpp/session/modules/tex/SessionRnwWeave.hpp
C++
agpl-3.0
2,449
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation version 3 as published by the Free Software Foundation. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.server.channel.handlers; import client.MapleCharacter; import client.MapleClient; import client.MapleDisease; import client.inventory.Item; import client.inventory.MapleInventoryType; import config.YamlConfig; import constants.inventory.ItemConstants; import net.AbstractMaplePacketHandler; import client.inventory.manipulator.MapleInventoryManipulator; import server.MapleItemInformationProvider; import server.MapleStatEffect; import tools.MaplePacketCreator; import tools.data.input.SeekableLittleEndianAccessor; /** * @author Matze */ public final class UseItemHandler extends AbstractMaplePacketHandler { @Override public final void handlePacket(SeekableLittleEndianAccessor slea, MapleClient c) { MapleCharacter chr = c.getPlayer(); if (!chr.isAlive()) { c.announce(MaplePacketCreator.enableActions()); return; } MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance(); slea.readInt(); short slot = slea.readShort(); int itemId = slea.readInt(); Item toUse = chr.getInventory(MapleInventoryType.USE).getItem(slot); if (toUse != null && toUse.getQuantity() > 0 && toUse.getItemId() == itemId) { if (itemId == 2050004) { chr.dispelDebuffs(); remove(c, slot); return; } else if (itemId == 2050001) { chr.dispelDebuff(MapleDisease.DARKNESS); remove(c, slot); return; } else if (itemId == 2050002) { chr.dispelDebuff(MapleDisease.WEAKEN); chr.dispelDebuff(MapleDisease.SLOW); remove(c, slot); return; } else if (itemId == 2050003) { chr.dispelDebuff(MapleDisease.SEAL); chr.dispelDebuff(MapleDisease.CURSE); remove(c, slot); return; } else if (ItemConstants.isTownScroll(itemId)) { int banMap = chr.getMapId(); int banSp = chr.getMap().findClosestPlayerSpawnpoint(chr.getPosition()).getId(); long banTime = currentServerTime(); if (ii.getItemEffect(toUse.getItemId()).applyTo(chr)) { if(YamlConfig.config.server.USE_BANISHABLE_TOWN_SCROLL) { chr.setBanishPlayerData(banMap, banSp, banTime); } remove(c, slot); } return; } else if (ItemConstants.isAntibanishScroll(itemId)) { if (ii.getItemEffect(toUse.getItemId()).applyTo(chr)) { remove(c, slot); } else { chr.dropMessage(5, "You cannot recover from a banish state at the moment."); } return; } remove(c, slot); if(toUse.getItemId() != 2022153) { ii.getItemEffect(toUse.getItemId()).applyTo(chr); } else { MapleStatEffect mse = ii.getItemEffect(toUse.getItemId()); for(MapleCharacter player : chr.getMap().getCharacters()) { mse.applyTo(player); } } } } private void remove(MapleClient c, short slot) { MapleInventoryManipulator.removeFromSlot(c, MapleInventoryType.USE, slot, (short) 1, false); c.announce(MaplePacketCreator.enableActions()); } }
ronancpl/MapleSolaxiaV2
src/net/server/channel/handlers/UseItemHandler.java
Java
agpl-3.0
4,510
<?php /*-------------------------------------------------------+ | PHP-Fusion Content Management System | Copyright (C) PHP-Fusion Inc | https://www.phpfusion.com/ +--------------------------------------------------------+ | Filename: gallery/photo_submit.php | Author: Core Development Team (coredevs@phpfusion.com) +--------------------------------------------------------+ | This program is released as free software under the | Affero GPL license. You can redistribute it and/or | modify it under the terms of this license which you | can read by viewing the included agpl.txt or online | at www.gnu.org/licenses/agpl.html. Removal of this | copyright header is strictly prohibited without | written permission from the original author(s). +--------------------------------------------------------*/ defined('IN_FUSION') || die('Access Denied'); $locale = fusion_get_locale('', [GALLERY_LOCALE, GALLERY_ADMIN_LOCALE]); $gll_settings = get_settings("gallery"); add_to_title($locale['global_200'].$locale['gallery_0100']); opentable("<i class='fa fa-camera-retro m-r-5 fa-lg'></i> ".$locale['gallery_0100']); if ($gll_settings['gallery_allow_submission']) { $criteriaArray = [ 'album_id' => 0, 'photo_title' => '', 'photo_description' => '', 'photo_filename' => '', 'photo_thumb1' => '', 'photo_thumb2' => '', 'photo_keywords' => '', ]; if (isset($_POST['submit_photo'])) { $criteriaArray = [ 'album_id' => form_sanitizer($_POST['album_id'], 0, 'album_id'), 'photo_title' => form_sanitizer($_POST['photo_title'], '', 'photo_title'), 'photo_keywords' => form_sanitizer($_POST['photo_keywords'], '', 'photo_keywords'), 'photo_description' => form_sanitizer($_POST['photo_description'], '', 'photo_description'), 'photo_filename' => '', 'photo_thumb1' => '', 'photo_thumb2' => '', ]; if (fusion_safe()) { if (!empty($_FILES['photo_image']) && is_uploaded_file($_FILES['photo_image']['tmp_name'])) { $upload = form_sanitizer($_FILES['photo_image'], "", "photo_image"); if (isset($upload['error']) && !$upload['error']) { if (isset($upload['image_name']) && isset($upload['thumb1_name']) && isset($upload['thumb2_name'])) { $criteriaArray['photo_filename'] = $upload['image_name']; $criteriaArray['photo_thumb1'] = $upload['thumb1_name']; $criteriaArray['photo_thumb2'] = $upload['thumb2_name']; } else { \Defender::stop(); \Defender::setInputError("photo_image"); add_notice("danger", $locale['photo_0014']); } } } else { \Defender::stop(); \Defender::setInputError('photo_image'); add_notice('danger', $locale['photo_0014']); } } if (fusion_safe()) { $inputArray = [ "submit_id" => 0, "submit_type" => 'p', "submit_user" => fusion_get_userdata('user_id'), "submit_datestamp" => TIME, "submit_criteria" => addslashes(serialize($criteriaArray)) ]; dbquery_insert(DB_SUBMISSIONS, $inputArray, "save"); add_notice("success", $locale['gallery_0101']); redirect(clean_request("submitted=p", ["stype"], TRUE)); } } if (isset($_GET['submitted']) && $_GET['submitted'] == "p") { echo "<div class='well text-center'><p><strong>".$locale['gallery_0101']."</strong></p>"; echo "<p><a href='submit.php?stype=p'>".$locale['gallery_0102']."</a></p>"; echo "<p><a href='index.php'>".str_replace('[SITENAME]', fusion_get_settings('sitename'), $locale['gallery_0113'])."</a></p>\n"; echo "</div>\n"; } else { $result = dbquery("SELECT album_id, album_title FROM ".DB_PHOTO_ALBUMS." ".(multilang_table("PG") ? "WHERE ".in_group('album_language', LANGUAGE)." AND" : "WHERE")." ".groupaccess("album_access")." ORDER BY album_title"); if (dbrows($result) > 0) { $opts = []; while ($data = dbarray($result)) { $opts[$data['album_id']] = $data['album_title']; } echo openform('submit_form', 'post', BASEDIR."submit.php?stype=p", ["enctype" => TRUE]); echo "<div class='alert alert-info m-b-20 submission-guidelines'>".str_replace('[SITENAME]', fusion_get_settings('sitename'), $locale['gallery_0107'])."</div>\n"; echo form_select('album_id', $locale['photo_0003'], '', ["options" => $opts, "inline" => TRUE]); echo form_text('photo_title', $locale['photo_0001'], '', ['required' => TRUE, "inline" => TRUE]); echo form_select('photo_keywords', $locale['photo_0005'], '', [ 'placeholder' => $locale['album_0006'], 'inline' => TRUE, 'multiple' => TRUE, "tags" => TRUE, 'width' => '100%', 'inner_width' => '100%', ]); echo form_fileinput('photo_image', $locale['photo_0004'], '', [ 'upload_path' => INFUSIONS.'gallery/submissions/', 'required' => TRUE, 'thumbnail_folder' => 'thumbs', 'thumbnail' => TRUE, 'thumbnail_w' => $gll_settings['thumb_w'], 'thumbnail_h' => $gll_settings['thumb_h'], 'thumbnail_suffix' => '_t1', 'thumbnail2' => TRUE, 'thumbnail2_w' => $gll_settings['photo_w'], 'thumbnail2_h' => $gll_settings['photo_h'], 'thumbnail2_suffix' => '_t2', 'max_width' => $gll_settings['photo_max_w'], 'max_height' => $gll_settings['photo_max_h'], 'max_byte' => $gll_settings['photo_max_b'], 'delete_original' => FALSE, 'multiple' => FALSE, 'inline' => TRUE, 'error_text' => $locale['photo_0014'], 'template' => 'thumbnail', 'valid_ext' => $gll_settings['gallery_file_types'], ]); echo "<div class='m-b-10 col-xs-12 col-sm-9 col-sm-offset-3'>".sprintf($locale['album_0010'], parsebytesize($gll_settings['photo_max_b']), $gll_settings['gallery_file_types'], $gll_settings['photo_max_w'], $gll_settings['photo_max_h'])."</div>\n"; $textArea_opts = [ 'required' => $gll_settings['gallery_extended_required'] ? TRUE : FALSE, 'autosize' => TRUE, 'form_name' => 'submit_form', ]; echo form_textarea('photo_description', $locale['photo_0008'], '', $textArea_opts); echo form_button('submit_photo', $locale['gallery_0111'], $locale['gallery_0111'], ['class' => 'btn-success', 'icon' => 'fa fa-hdd-o']); echo closeform(); } else { echo "<div class='well' style='text-align:center'><br />".$locale['gallery_0024']."<br /><br /></div>\n"; } } } else { echo "<div class='well text-center'>".$locale['gallery_0112']."</div>\n"; } closetable();
php-fusion/PHP-Fusion
infusions/gallery/photo_submit.php
PHP
agpl-3.0
7,592
/** * 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://repository.silverpeas.com/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.socialNetwork.myProfil.control; import java.sql.SQLException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import com.silverpeas.socialNetwork.model.SocialInformation; import com.silverpeas.socialNetwork.model.SocialInformationType; import com.silverpeas.socialNetwork.relationShip.RelationShipService; import com.silverpeas.socialNetwork.status.Status; import com.silverpeas.socialNetwork.status.StatusService; import com.silverpeas.util.StringUtil; import com.stratelia.silverpeas.silvertrace.SilverTrace; import com.stratelia.webactiv.util.DateUtil; /** * * @author Bensalem Nabil */ public class SocialNetworkService { private String myId; public SocialNetworkService(String myId) { this.myId = myId; } /** * get the List of social Information of my according the type of social information * and the UserId * @return: Map<Date, List<SocialInformation> * @param:SocialInformationType socialInformationType, String userId,String classification, int limit ,int offset */ public Map<Date, List<SocialInformation>> getSocialInformation(SocialInformationType type, Date begin, Date end) { com.silverpeas.calendar.Date dBegin = new com.silverpeas.calendar.Date(begin); com.silverpeas.calendar.Date dEnd = new com.silverpeas.calendar.Date(end); List<SocialInformation> socialInformationsFull = new ProviderService().getSocialInformationsList(type, myId, null, dEnd, dBegin); if (SocialInformationType.ALL.equals(type)) { Collections.sort(socialInformationsFull); } return processResults(socialInformationsFull); } private Map<Date, List<SocialInformation>> processResults(List<SocialInformation> socialInformationsFull) { String date = null; LinkedHashMap<Date, List<SocialInformation>> hashtable = new LinkedHashMap<Date, List<SocialInformation>>(); List<SocialInformation> lsi = new ArrayList<SocialInformation>(); for (SocialInformation information : socialInformationsFull) { if (DateUtil.formatDate(information.getDate()).equals(date)) { lsi.add(information); } else { date = DateUtil.formatDate(information.getDate()); lsi = new ArrayList<SocialInformation>(); lsi.add(information); hashtable.put(information.getDate(), lsi); } } return hashtable; } /** * get the List of social Information of my contatc according the type of social information * and the UserId * @return: Map<Date, List<SocialInformation> * @param:SocialInformationType socialInformationType, String userId,String classification, int limit ,int offset */ public Map<Date, List<SocialInformation>> getSocialInformationOfMyContacts( SocialInformationType type, Date begin, Date end) { com.silverpeas.calendar.Date dBegin = new com.silverpeas.calendar.Date(begin); com.silverpeas.calendar.Date dEnd = new com.silverpeas.calendar.Date(end); List<String> myContactIds = getMyContactsIds(); myContactIds.add(myId); // add myself List<SocialInformation> socialInformationsFull = new ProviderService().getSocialInformationsListOfMyContact(type, myId, myContactIds, dEnd, dBegin); if (SocialInformationType.ALL.equals(type)) { Collections.sort(socialInformationsFull); } return processResults(socialInformationsFull); } public Map<Date, List<SocialInformation>> getSocialInformationOfMyContact(String myContactId, SocialInformationType type, Date begin, Date end) { com.silverpeas.calendar.Date dBegin = new com.silverpeas.calendar.Date(begin); com.silverpeas.calendar.Date dEnd = new com.silverpeas.calendar.Date(end); List<String> myContactIds = new ArrayList<String>(); myContactIds.add(myContactId); List<SocialInformation> socialInformationsFull = new ProviderService().getSocialInformationsListOfMyContact(type, myId, myContactIds, dEnd, dBegin); if (SocialInformationType.ALL.equals(type)) { Collections.sort(socialInformationsFull); } return processResults(socialInformationsFull); } /** * update my status * @param textStatus * @return String */ public String changeStatusService(String textStatus) { Status status = new Status(Integer.parseInt(myId), new Date(), textStatus); return new StatusService().changeStatusService(status); } /** * get my last status * @return String */ public String getLastStatusService() { Status status = new StatusService().getLastStatusService(Integer.parseInt(myId)); if (StringUtil.isDefined(status.getDescription())) { return status.getDescription(); } return " "; } public List<String> getMyContactsIds() { try { return new RelationShipService().getMyContactsIds(Integer.parseInt(myId)); } catch (SQLException ex) { SilverTrace.error("socialNetworkService", "SocialNetworkService.getMyContactsIds", "", ex); } return new ArrayList<String>(); } }
stephaneperry/Silverpeas-Core
war-core/src/main/java/com/silverpeas/socialNetwork/myProfil/control/SocialNetworkService.java
Java
agpl-3.0
6,341
class MH_Intel { idd=-1; fadein = 0; duration = 1e+1000; fadeout = 0; movingEnable=1; name="IntelDisplay"; enableSimulation=1; onLoad="uiNamespace setVariable [""mh_inteldialog"", _this select 0]"; onUnLoad="uiNamespace setVariable [""mh_inteldialog"", nil]"; class controls { class MH_IntelDisplay { type = CT_STATIC; idc = 50; style = ST_LEFT; colorBackground[] = {0, 0, 0, 0}; colorText[] = {0.6, 1.0, 0.6, 0.75}; font = PuristaMedium; sizeEx = 0.0295; h = 0.02; x = -0.3; y = safeZoneY + 0.01; w = 0.4; text = "Intel: 0"; }; }; };
mtusnio/Manhunt
ManhuntUI.hpp
C++
agpl-3.0
751
import loadPolyfills from '../mastodon/load_polyfills'; import ready from '../mastodon/ready'; window.addEventListener('message', e => { const data = e.data || {}; if (!window.parent || data.type !== 'setHeight') { return; } ready(() => { window.parent.postMessage({ type: 'setHeight', id: data.id, height: document.getElementsByTagName('html')[0].scrollHeight, }, '*'); }); }); function main() { const { length } = require('stringz'); const IntlRelativeFormat = require('intl-relativeformat').default; const { delegate } = require('rails-ujs'); const emojify = require('../mastodon/features/emoji/emoji').default; const { getLocale } = require('../mastodon/locales'); const { localeData } = getLocale(); const VideoContainer = require('../mastodon/containers/video_container').default; const MediaGalleryContainer = require('../mastodon/containers/media_gallery_container').default; const CardContainer = require('../mastodon/containers/card_container').default; const React = require('react'); const ReactDOM = require('react-dom'); localeData.forEach(IntlRelativeFormat.__addLocaleData); ready(() => { const locale = document.documentElement.lang; const dateTimeFormat = new Intl.DateTimeFormat(locale, { year: 'numeric', month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric', }); const relativeFormat = new IntlRelativeFormat(locale); [].forEach.call(document.querySelectorAll('.emojify'), (content) => { content.innerHTML = emojify(content.innerHTML); }); [].forEach.call(document.querySelectorAll('time.formatted'), (content) => { const datetime = new Date(content.getAttribute('datetime')); const formattedDate = dateTimeFormat.format(datetime); content.title = formattedDate; content.textContent = formattedDate; }); [].forEach.call(document.querySelectorAll('time.time-ago'), (content) => { const datetime = new Date(content.getAttribute('datetime')); content.title = dateTimeFormat.format(datetime); content.textContent = relativeFormat.format(datetime); }); [].forEach.call(document.querySelectorAll('.logo-button'), (content) => { content.addEventListener('click', (e) => { e.preventDefault(); window.open(e.target.href, 'mastodon-intent', 'width=400,height=400,resizable=no,menubar=no,status=no,scrollbars=yes'); }); }); [].forEach.call(document.querySelectorAll('[data-component="Video"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<VideoContainer locale={locale} {...props} />, content); }); [].forEach.call(document.querySelectorAll('[data-component="MediaGallery"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<MediaGalleryContainer locale={locale} {...props} />, content); }); [].forEach.call(document.querySelectorAll('[data-component="Card"]'), (content) => { const props = JSON.parse(content.getAttribute('data-props')); ReactDOM.render(<CardContainer locale={locale} {...props} />, content); }); }); delegate(document, '.webapp-btn', 'click', ({ target, button }) => { if (button !== 0) { return true; } window.location.href = target.href; return false; }); delegate(document, '.status__content__spoiler-link', 'click', ({ target }) => { const contentEl = target.parentNode.parentNode.querySelector('.e-content'); if (contentEl.style.display === 'block') { contentEl.style.display = 'none'; target.parentNode.style.marginBottom = 0; } else { contentEl.style.display = 'block'; target.parentNode.style.marginBottom = null; } return false; }); delegate(document, '.account_display_name', 'input', ({ target }) => { const nameCounter = document.querySelector('.name-counter'); if (nameCounter) { nameCounter.textContent = 30 - length(target.value); } }); delegate(document, '.account_note', 'input', ({ target }) => { const noteCounter = document.querySelector('.note-counter'); if (noteCounter) { noteCounter.textContent = 333 - length(target.value); } }); delegate(document, '#account_avatar', 'change', ({ target }) => { const avatar = document.querySelector('.card.compact .avatar img'); const [file] = target.files || []; const url = file ? URL.createObjectURL(file) : avatar.dataset.originalSrc; avatar.src = url; }); delegate(document, '#account_header', 'change', ({ target }) => { const header = document.querySelector('.card.compact'); const [file] = target.files || []; const url = file ? URL.createObjectURL(file) : header.dataset.originalSrc; header.style.backgroundImage = `url(${url})`; }); } loadPolyfills().then(main).catch(error => { console.error(error); });
WitchesTown/mastodon
app/javascript/packs/public.js
JavaScript
agpl-3.0
4,984
<?php use Maslosoft\EmbeDi\EmbeDi; use Maslosoft\Ilmatar\Widgets\Interfaces\ButtonInterface; use Maslosoft\Ilmatar\Widgets\Menu\ActionButton; use Maslosoft\Ilmatar\Widgets\Menu\DropDownButton; use Maslosoft\Ilmatar\Widgets\Menu\Toolbar; ?> <?php /* @var $this Toolbar */ ?> <?php if ($this->floating): ?> <div class="ovr toolbar-floating" id="ovr-<?= $this->getId(); ?>"> <?php endif; ?> <?php if ($this->caption): ?> <div class="caption"><?= $this->caption ?></div> <div class="clearfix"></div> <?php endif; ?> <div id="<?= $this->htmlId(); ?>" class="toolbar <?php if($this->inlined):?>toolbar-inlined<?php endif;?>" data-bind=" widget: Maslosoft.Ilmatar.Widgets.Menu.Toolbar, params: <?= $this->getWidgetParams(); ?> " > <div class="btn-group"> <?php $after = []; $buttons = $this->buttons instanceof Closure ? call_user_func($this->buttons) : $this->buttons; foreach ($buttons as $action => $button) { if (!$button instanceof ButtonInterface) { if (!isset($button->class)) { /** * TODO Below should be moved to Toolbar class */ if (is_array($button->action) || $button->action instanceof Closure) { $button->class = DropDownButton::class; } else { $button->class = ActionButton::class; } } $button = EmbeDi::fly()->apply((array) $button); $button->init($this); } echo $button; } ?> </div> </div> <?php if ($this->floating): ?> </div> <?php endif; ?> <?php // Extra markup, for modals etc foreach ($after as $html) { echo $html; } ?>
Maslosoft/IlmatarWidgets
src/Menu/views/toolbar.php
PHP
agpl-3.0
1,672
'use strict'; define(['bitcoinjs-lib', 'crypto-js', 'sjcl'], function(Bitcoin, CryptoJS, sjcl) { function TLCrypto() { } TLCrypto.wordsToBytes = function(words) { var bytes = [] for (var b = 0; b < words.length * 32; b += 8) { bytes.push((words[b >>> 5] >>> (24 - b % 32)) & 0xFF) } return bytes }; TLCrypto.wordArrayToBytes = function(wordArray) { return TLCrypto.wordsToBytes(wordArray.words) }; TLCrypto.hexStringToData = function(hexString) { return new Bitcoin.Buffer(hexString, 'hex'); }; TLCrypto.getPasswordDigest = function(password) { var SHA256 = CryptoJS.SHA256; var passwordDigest = TLCrypto.wordArrayToBytes(SHA256(SHA256(SHA256(password)))); return new Bitcoin.Buffer(passwordDigest).toString('hex'); // maybe go with this password digest or something to that effect //return sjcl.codec.base64.fromBits(sjcl.misc.pbkdf2(password, email, 1000)); }; TLCrypto.getPasswordHash = function(password) { var SHA256 = CryptoJS.SHA256; var passwordDigest = TLCrypto.wordArrayToBytes(SHA256(SHA256(SHA256(SHA256(SHA256(password)))))); return new Bitcoin.Buffer(passwordDigest).toString('hex'); }; TLCrypto.encrypt = function(plainText, password) { var passwordDigest = TLCrypto.getPasswordDigest(password); var privData = sjcl.encrypt(passwordDigest, plainText, {ks: 256, ts: 128}); return privData; }; TLCrypto.decrypt = function(cipherText, password) { var passwordDigest = TLCrypto.getPasswordDigest(password); var data = sjcl.decrypt(passwordDigest, cipherText); return data; }; return TLCrypto; });
arcbit/arcbit-web
src/js/model/TLCrypto.js
JavaScript
agpl-3.0
1,918
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // 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-2022 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 android.os.Parcel; import com.google.gson.JsonObject; import com.kaltura.client.Params; 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(WatchLaterUserEntry.Tokenizer.class) public class WatchLaterUserEntry extends UserEntry { public interface Tokenizer extends UserEntry.Tokenizer { } public WatchLaterUserEntry() { super(); } public WatchLaterUserEntry(JsonObject jsonObject) throws APIException { super(jsonObject); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaWatchLaterUserEntry"); return kparams; } public static final Creator<WatchLaterUserEntry> CREATOR = new Creator<WatchLaterUserEntry>() { @Override public WatchLaterUserEntry createFromParcel(Parcel source) { return new WatchLaterUserEntry(source); } @Override public WatchLaterUserEntry[] newArray(int size) { return new WatchLaterUserEntry[size]; } }; public WatchLaterUserEntry(Parcel in) { super(in); } }
kaltura/KalturaGeneratedAPIClientsAndroid
KalturaClient/src/main/java/com/kaltura/client/types/WatchLaterUserEntry.java
Java
agpl-3.0
2,657
/*global plupload */ /*global qiniu */ function FileProgress(file, targetID) { this.fileProgressID = file.id; this.file = file; this.opacity = 100; this.height = 0; this.fileProgressWrapper = $('#' + this.fileProgressID); if (!this.fileProgressWrapper.length) { // <div class="progress"> // <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="20" aria-valuemin="0" aria-valuemax="100" style="width: 20%"> // <span class="sr-only">20% Complete</span> // </div> // </div> this.fileProgressWrapper = $('<tr></tr>'); var Wrappeer = this.fileProgressWrapper; Wrappeer.attr('id', this.fileProgressID).addClass('progressContainer'); var progressText = $("<td/>"); progressText.addClass('progressName').text(file.name); var fileSize = plupload.formatSize(file.size).toUpperCase(); var progressSize = $("<td/>"); progressSize.addClass("progressFileSize").text(fileSize); var progressBarTd = $("<td/>"); var progressBarBox = $("<div/>"); progressBarBox.addClass('info'); var progressBarWrapper = $("<div/>"); progressBarWrapper.addClass("progress progress-striped"); var progressBar = $("<div/>"); progressBar.addClass("progress-bar progress-bar-info") .attr('role', 'progressbar') .attr('aria-valuemax', 100) .attr('aria-valuenow', 0) .attr('aria-valuein', 0) .width('0%'); var progressBarPercent = $('<span class=sr-only />'); progressBarPercent.text(fileSize); var progressCancel = $('<a href=javascript:; />'); progressCancel.show().addClass('progressCancel').text('×'); progressBar.append(progressBarPercent); progressBarWrapper.append(progressBar); progressBarBox.append(progressBarWrapper); progressBarBox.append(progressCancel); var progressBarStatus = $('<div class="status text-center"/>'); progressBarBox.append(progressBarStatus); progressBarTd.append(progressBarBox); Wrappeer.append(progressText); Wrappeer.append(progressSize); Wrappeer.append(progressBarTd); $('#' + targetID).append(Wrappeer); } else { this.reset(); } this.height = this.fileProgressWrapper.offset().top; this.setTimer(null); } FileProgress.prototype.setTimer = function(timer) { this.fileProgressWrapper.FP_TIMER = timer; }; FileProgress.prototype.getTimer = function(timer) { return this.fileProgressWrapper.FP_TIMER || null; }; FileProgress.prototype.reset = function() { this.fileProgressWrapper.attr('class', "progressContainer"); this.fileProgressWrapper.find('td .progress .progress-bar-info').attr('aria-valuenow', 0).width('0%').find('span').text(''); this.appear(); }; FileProgress.prototype.setChunkProgess = function(chunk_size) { var chunk_amount = Math.ceil(this.file.size / chunk_size); if (chunk_amount === 1) { return false; } var viewProgess = $('<button class="btn btn-default">查看分块上传进度</button>'); var progressBarChunkTr = $('<tr class="chunk-status-tr"><td colspan=3></td></tr>'); var progressBarChunk = $('<div/>'); for (var i = 1; i <= chunk_amount; i++) { var col = $('<div class="col-md-2"/>'); var progressBarWrapper = $('<div class="progress progress-striped"></div'); var progressBar = $("<div/>"); progressBar.addClass("progress-bar progress-bar-info text-left") .attr('role', 'progressbar') .attr('aria-valuemax', 100) .attr('aria-valuenow', 0) .attr('aria-valuein', 0) .width('0%') .attr('id', this.file.id + '_' + i) .text(''); var progressBarStatus = $('<span/>'); progressBarStatus.addClass('chunk-status').text(); progressBarWrapper.append(progressBar); progressBarWrapper.append(progressBarStatus); col.append(progressBarWrapper); progressBarChunk.append(col); } if(!this.fileProgressWrapper.find('td:eq(2) .btn-default').length){ this.fileProgressWrapper.find('td>div').append(viewProgess); } progressBarChunkTr.hide().find('td').append(progressBarChunk); progressBarChunkTr.insertAfter(this.fileProgressWrapper); }; FileProgress.prototype.setProgress = function(percentage, speed, chunk_size) { this.fileProgressWrapper.attr('class', "progressContainer green"); var file = this.file; var uploaded = file.loaded; var size = plupload.formatSize(uploaded).toUpperCase(); var formatSpeed = plupload.formatSize(speed).toUpperCase(); var progressbar = this.fileProgressWrapper.find('td .progress').find('.progress-bar-info'); if (this.fileProgressWrapper.find('.status').text() === '取消上传'){ return; } this.fileProgressWrapper.find('.status').text("已上传: " + size + " 上传速度: " + formatSpeed + "/s"); percentage = parseInt(percentage, 10); if (file.status !== plupload.DONE && percentage === 100) { percentage = 99; } progressbar.attr('aria-valuenow', percentage).css('width', percentage + '%'); if (chunk_size) { var chunk_amount = Math.ceil(file.size / chunk_size); if (chunk_amount === 1) { return false; } var current_uploading_chunk = Math.ceil(uploaded / chunk_size); var pre_chunk, text; for (var index = 0; index < current_uploading_chunk; index++) { pre_chunk = $('#' + file.id + "_" + index); pre_chunk.width('100%').removeClass().addClass('alert-success').attr('aria-valuenow', 100); text = "块" + index + "上传进度100%"; pre_chunk.next().html(text); } var currentProgessBar = $('#' + file.id + "_" + current_uploading_chunk); var current_chunk_percent; if (current_uploading_chunk < chunk_amount) { if (uploaded % chunk_size) { current_chunk_percent = ((uploaded % chunk_size) / chunk_size * 100).toFixed(2); } else { current_chunk_percent = 100; currentProgessBar.removeClass().addClass('alert-success'); } } else { var last_chunk_size = file.size - chunk_size * (chunk_amount - 1); var left_file_size = file.size - uploaded; if (left_file_size % last_chunk_size) { current_chunk_percent = ((uploaded % chunk_size) / last_chunk_size * 100).toFixed(2); } else { current_chunk_percent = 100; currentProgessBar.removeClass().addClass('alert-success'); } } currentProgessBar.width(current_chunk_percent + '%'); currentProgessBar.attr('aria-valuenow', current_chunk_percent); text = "块" + current_uploading_chunk + "上传进度" + current_chunk_percent + '%'; currentProgessBar.next().html(text); } this.appear(); }; FileProgress.prototype.setComplete = function(up, info) { var td = this.fileProgressWrapper.find('td:eq(2)'), tdProgress = td.find('.progress'); var res = Qiniu.parseJSON(info); var url; if (res.url) { url = res.url; str = "<div><strong>Link:</strong><a href=" + res.url + " target='_blank' > " + res.url + "</a></div>" + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>"; } else { var domain = up.getOption('domain'); url = domain + encodeURI(res.key); var link = domain + res.key; str = "<div><strong>Link:</strong><a href=" + url + " target='_blank' > " + link + "</a></div>" + "<div class=hash><strong>Hash:</strong>" + res.hash + "</div>"; } tdProgress.html(str).removeClass().next().next('.status').hide(); td.find('.progressCancel').hide(); var progressNameTd = this.fileProgressWrapper.find('.progressName'); var imageView = '?imageView2/1/w/100/h/100'; var isImage = function(url) { var res, suffix = ""; var imageSuffixes = ["png", "jpg", "jpeg", "gif", "bmp"]; var suffixMatch = /\.([a-zA-Z0-9]+)(\?|\@|$)/; if (!url || !suffixMatch.test(url)) { return false; } res = suffixMatch.exec(url); suffix = res[1].toLowerCase(); for (var i = 0, l = imageSuffixes.length; i < l; i++) { if (suffix === imageSuffixes[i]) { return true; } } return false; }; var isImg = isImage(url); var Wrapper = $('<div class="Wrapper"/>'); var imgWrapper = $('<div class="imgWrapper col-md-3"/>'); var linkWrapper = $('<a class="linkWrapper" target="_blank"/>'); var showImg = $('<img src="images/loading.gif"/>'); progressNameTd.append(Wrapper); if (!isImg) { showImg.attr('src', 'images/default.png'); Wrapper.addClass('default'); imgWrapper.append(showImg); Wrapper.append(imgWrapper); } else { linkWrapper.append(showImg); imgWrapper.append(linkWrapper); Wrapper.append(imgWrapper); var img = new Image(); if (!/imageView/.test(url)) { url += imageView } $(img).attr('src', url); var height_space = 340; $(img).on('load', function() { showImg.attr('src', url); linkWrapper.attr('href', url).attr('title', '查看原图'); function initImg(url, key, height) { $('#myModal-img').modal(); var modalBody = $('#myModal-img').find('.modal-body'); if (height <= 300) { $('#myModal-img').find('.text-warning').show(); } var newImg = new Image(); modalBody.find('img').attr('src', 'images/loading.gif'); newImg.onload = function() { modalBody.find('img').attr('src', url).data('key', key).data('h', height); modalBody.find('.modal-body-wrapper').find('a').attr('href', url); }; newImg.src = url; } var infoWrapper = $('<div class="infoWrapper col-md-6"></div>'); var fopLink = $('<a class="fopLink"/>'); fopLink.attr('data-key', res.key).text('查看处理效果'); infoWrapper.append(fopLink); fopLink.on('click', function() { var key = $(this).data('key'); var height = parseInt($(this).parents('.Wrapper').find('.origin-height').text(), 10); if (height > $(window).height() - height_space) { height = parseInt($(window).height() - height_space, 10); } else { height = parseInt(height, 10) || 300; //set a default height 300 for ie9- } var fopArr = []; fopArr.push({ fop: 'imageView2', mode: 3, h: height, q: 100, format: 'png' }); fopArr.push({ fop: 'watermark', mode: 1, image: 'http://www.b1.qiniudn.com/images/logo-2.png', dissolve: 100, gravity: 'SouthEast', dx: 100, dy: 100 }); var url = Qiniu.pipeline(fopArr, key); $('#myModal-img').on('hide.bs.modal', function() { $('#myModal-img').find('.btn-default').removeClass('disabled'); $('#myModal-img').find('.text-warning').hide(); }).on('show.bs.modal', function() { $('#myModal-img').find('.imageView').find('a:eq(0)').addClass('disabled'); $('#myModal-img').find('.watermark').find('a:eq(3)').addClass('disabled'); $('#myModal-img').find('.text-warning').hide(); }); initImg(url, key, height); return false; }); var ie = Qiniu.detectIEVersion(); if (!(ie && ie <= 9)) { var exif = Qiniu.exif(res.key); if (exif) { var exifLink = $('<a href="" target="_blank">查看exif</a>'); exifLink.attr('href', url + '?exif'); infoWrapper.append(exifLink); } var imageInfo = Qiniu.imageInfo(res.key); var infoArea = $('<div/>'); var infoInner = '<div>格式:<span class="origin-format">' + imageInfo.format + '</span></div>' + '<div>宽度:<span class="orgin-width">' + imageInfo.width + 'px</span></div>' + '<div>高度:<span class="origin-height">' + imageInfo.height + 'px</span></div>'; infoArea.html(infoInner); infoWrapper.append(infoArea); } Wrapper.append(infoWrapper); }).on('error', function() { showImg.attr('src', 'default.png'); Wrapper.addClass('default'); }); } }; FileProgress.prototype.setError = function() { this.fileProgressWrapper.find('td:eq(2)').attr('class', 'text-warning'); this.fileProgressWrapper.find('td:eq(2) .progress').css('width', 0).hide(); this.fileProgressWrapper.find('button').hide(); this.fileProgressWrapper.next('.chunk-status-tr').hide(); }; FileProgress.prototype.setCancelled = function(manual) { var progressContainer = 'progressContainer'; if (!manual) { progressContainer += ' red'; } this.fileProgressWrapper.attr('class', progressContainer); this.fileProgressWrapper.find('td .progress').remove(); this.fileProgressWrapper.find('td:eq(2) .btn-default').hide(); this.fileProgressWrapper.find('td:eq(2) .progressCancel').hide(); }; FileProgress.prototype.setStatus = function(status, isUploading) { if (!isUploading) { this.fileProgressWrapper.find('.status').text(status).attr('class', 'status text-left'); } }; // 绑定取消上传事件 FileProgress.prototype.bindUploadCancel = function(up) { var self = this; if (up) { self.fileProgressWrapper.find('td:eq(2) .progressCancel').on('click', function(){ self.setCancelled(false); self.setStatus("取消上传"); self.fileProgressWrapper.find('.status').css('left', '0'); up.removeFile(self.file); }); } }; FileProgress.prototype.appear = function() { if (this.getTimer() !== null) { clearTimeout(this.getTimer()); this.setTimer(null); } if (this.fileProgressWrapper[0].filters) { try { this.fileProgressWrapper[0].filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100; } catch (e) { // If it is not set initially, the browser will throw an error. This will set it if it is not set yet. this.fileProgressWrapper.css('filter', "progid:DXImageTransform.Microsoft.Alpha(opacity=100)"); } } else { this.fileProgressWrapper.css('opacity', 1); } this.fileProgressWrapper.css('height', ''); this.height = this.fileProgressWrapper.offset().top; this.opacity = 100; this.fileProgressWrapper.show(); };
edxzw/edx-platform
cms/static/cms/js/ui.js
JavaScript
agpl-3.0
16,012
OC.L10N.register( "settings", { "Enabled" : "Aktiviert", "Not enabled" : "Nicht aktiviert", "Wrong password" : "Falsches Passwort", "Saved" : "Gespeichert", "No user supplied" : "Kein Benutzer angegeben", "Unable to change password" : "Passwort konnte nicht geändert werden", "Authentication error" : "Authentifizierungsfehler", "Please provide an admin recovery password, otherwise all user data will be lost" : "Bitte geben Sie ein Wiederherstellungspasswort für das Administratorkonto an, da sonst alle Benutzerdaten verlorengehen können", "Wrong admin recovery password. Please check the password and try again." : "Falsches Wiederherstellungspasswort für das Admin-Konto. Bitte überprüfen Sie das Passwort und versuchen Sie es erneut.", "Backend doesn't support password change, but the user's encryption key was successfully updated." : "Das Backend unterstützt die Passwortänderung nicht, aber der Benutzerschlüssel wurde erfolgreich aktualisiert.", "installing and updating apps via the app store or Federated Cloud Sharing" : "Das Installieren und Aktualisieren von Apps durch den App-Store oder durch Federated Cloud Sharing", "Federated Cloud Sharing" : "Federated-Cloud-Sharing", "cURL is using an outdated %s version (%s). Please update your operating system or features such as %s will not work reliably." : "cURL verwendet eine veraltete %s Version (%s). Bitte aktualisieren Sie ihr Betriebssystem, da ansonsten Funktionen, wie z.B. %s, nicht zuverlässig funktionieren werden.", "A problem occurred, please check your log files (Error: %s)" : "Es ist ein Problem aufgetreten, bitte überprüfen Sie Ihre Logdateien (Fehler: %s)", "Migration Completed" : "Migration abgeschlossen", "Group already exists." : "Gruppe existiert bereits.", "Unable to add group." : "Gruppe konnte nicht angelegt werden.", "Unable to delete group." : "Gruppe konnte nicht gelöscht werden.", "test email settings" : "E-Mail-Einstellungen testen", "A problem occurred while sending the email. Please revise your settings. (Error: %s)" : "Beim Senden der E-Mail ist ein Problem aufgetreten. Bitte überprüfen Sie Ihre Einstellungen. (Fehler: %s)", "Email sent" : "E-Mail gesendet", "You need to set your user email before being able to send test emails." : "Sie müssen Ihre Benutzer-E-Mail-Adresse einstellen, bevor Sie Test-E-Mails versenden können.", "Invalid request" : "Ungültige Anforderung", "Invalid mail address" : "Ungültige E-Mail-Adresse", "No valid group selected" : "Keine gültige Gruppe ausgewählt", "A user with that name already exists." : "Ein Benutzer mit diesem Namen existiert bereits.", "To send a password link to the user an email address is required." : "Um einen Passwort-Link an einen Benutzer zu versenden wird eine E-Mail-Adresse benötigt.", "Unable to create user." : "Benutzer konnte nicht erstellt werden.", "Your %s account was created" : "Ihr %s-Konto wurde erstellt", "Unable to delete user." : "Benutzer konnte nicht gelöscht werden.", "Settings saved" : "Einstellungen gespeichert", "Unable to change full name" : "Der vollständige Name konnte nicht geändert werden", "Unable to change email address" : "E-Mail-Adresse konnte nicht geändert werden", "Your full name has been changed." : "Ihr vollständiger Name ist geändert worden.", "Forbidden" : "Verboten", "Invalid user" : "Ungültiger Benutzer", "Unable to change mail address" : "E-Mail-Adresse konnte nicht geändert werden", "Email saved" : "E-Mail-Adresse gespeichert", "Password confirmation is required" : "Passwortbestätigung erforderlich", "Couldn't remove app." : "Die App konnte nicht entfernt werden.", "Couldn't update app." : "Die App konnte nicht aktualisiert werden.", "Are you really sure you want add {domain} as trusted domain?" : "Sind Sie sich wirklich sicher, dass Sie {domain} als vertrauenswürdige Domain hinzufügen möchten?", "Add trusted domain" : "Vertrauenswürdige Domain hinzufügen", "Migration in progress. Please wait until the migration is finished" : "Migration in Arbeit. Bitte warten Sie, bis die Migration beendet ist", "Migration started …" : "Migration begonnen…", "Not saved" : "Nicht gespeichert", "Sending..." : "Wird gesendet…", "Official" : "Offiziell", "All" : "Alle", "Update to %s" : "Aktualisierung auf %s", "_You have %n app update pending_::_You have %n app updates pending_" : ["Es ist %n App-Aktualisierung verfügbar","Es sind %n App-Aktualisierungen verfügbar"], "No apps found for your version" : "Es wurden keine Apps für Ihre Version gefunden", "The app will be downloaded from the app store" : "Die App wird aus dem App-Store heruntergeladen", "Official apps are developed by and within the community. They offer central functionality and are ready for production use." : "Offizielle Apps werden von und innerhalb der Community entwickelt. Sie stellen die zentralen Funktionen bereit und sind für den produktiven Einsatz geeignet.", "Approved apps are developed by trusted developers and have passed a cursory security check. They are actively maintained in an open code repository and their maintainers deem them to be stable for casual to normal use." : "Geprüfte Apps werden von vertrauenswürdigen Entwicklern entwickelt und haben eine oberflächliche Sicherheitsprüfung durchlaufen. Sie werden innerhalb eines offenen Code-Repositorys aktiv gepflegt und ihre Betreuer erachten sie als stabil genug für für den gelegentlichen bis normalen Einsatz.", "This app is not checked for security issues and is new or known to be unstable. Install at your own risk." : "Diese App ist nicht auf Sicherheitsprobleme hin überprüft und ist neu oder bekanntermaßen instabil. Die Installation erfolgt auf eigenes Risiko.", "Disabling app …" : "App wird deaktiviert …", "Error while disabling app" : "Beim Deaktivieren der App ist ein Fehler aufgetreten", "Disable" : "Deaktivieren", "Enable" : "Aktivieren", "Enabling app …" : "Aktiviere App ...", "Error while enabling app" : "Beim Aktivieren der App ist ein Fehler aufgetreten", "Error: this app cannot be enabled because it makes the server unstable" : "Fehler: Diese App kann nicht aktiviert werden, da es den Server instabil macht.", "Error: could not disable broken app" : "Fehler: Die beschädigte Anwendung konnte nicht deaktiviert werden", "Error while disabling broken app" : "Beim Deaktivieren der defekten App ist ein Fehler aufgetreten", "Updating...." : "Aktualisiere…", "Error while updating app" : "Es ist ein Fehler während der Aktualisierung aufgetreten", "Updated" : "Aktualisiert", "Uninstalling ...." : "Wird deinstalliert…", "Error while uninstalling app" : "Fehler beim Deinstallieren der App", "Uninstall" : "Deinstallieren", "The app has been enabled but needs to be updated. You will be redirected to the update page in 5 seconds." : "Die App wurde aktiviert, aber sie benötigt ein Update. Sie werden zur Update Seite in 5 Sekunden weitergeleitet.", "App update" : "App aktualisieren", "Approved" : "Geprüft", "Experimental" : "Experimentell", "No apps found for {query}" : "Keine Applikationen für {query} gefunden", "Allow filesystem access" : "Erlaube Dateisystem-Zugriff", "Disconnect" : "Trennen", "Revoke" : "Widerrufen", "Internet Explorer" : "Internet Explorer", "Edge" : "Edge", "Firefox" : "Firefox", "Google Chrome" : "Google Chrome", "Safari" : "Safari", "Google Chrome for Android" : "Google Chrome für Android", "iPhone iOS" : "iPhone iOS", "iPad iOS" : "iPad iOS", "iOS Client" : "iOS-Client", "Android Client" : "Android-Client", "Sync client - {os}" : "Sync-Client - {os}", "This session" : "Diese Sitzung", "Copy" : "Kopieren", "Copied!" : "Kopiert!", "Not supported!" : "Nicht unterstützt!", "Press ⌘-C to copy." : "⌘-C zum Kopieren drücken.", "Press Ctrl-C to copy." : "Ctrl-C zum Kopieren drücken.", "Error while loading browser sessions and device tokens" : "Fehler beim Laden der Browser-Sitzungen und Geräte-Token", "Error while creating device token" : "Fehler beim Erstellen des Geräte-Tokens", "Error while deleting the token" : "Fehler beim Löschen des Geräte-Tokens", "An error occurred. Please upload an ASCII-encoded PEM certificate." : "Es ist ein Fehler aufgetreten. Bitte laden Sie ein ASCII-kodiertes PEM-Zertifikat hoch.", "Valid until {date}" : "Gültig bis {date}", "Delete" : "Löschen", "Local" : "Lokal", "Private" : "Privat", "Only visible to local users" : "Nur für lokale Benutzer sichtbar", "Only visible to you" : "Nur für Sie sichtbar", "Contacts" : "Kontakte", "Visible to local users and to trusted servers" : "Sichtbar für lokale Nutzer und vertrauenswürdige Server", "Public" : "Öffentlich", "Will be synced to a global and public address book" : "Wird mit einem globalen und einem öffentlichen Adressbuch synchronisiert", "Select a profile picture" : "Wählen Sie ein Profilbild", "Very weak password" : "Sehr schwaches Passwort", "Weak password" : "Schwaches Passwort", "So-so password" : "Akzeptables Passwort", "Good password" : "Gutes Passwort", "Strong password" : "Starkes Passwort", "Groups" : "Gruppen", "Unable to delete {objName}" : "Löschen von {objName} nicht möglich", "Error creating group: {message}" : "Fehler beim Erstellen einer Gruppe: {message}", "A valid group name must be provided" : "Ein gültiger Gruppenname muss angegeben werden", "deleted {groupName}" : "{groupName} gelöscht", "undo" : "rückgängig machen", "never" : "niemals", "deleted {userName}" : "{userName} gelöscht", "Unable to add user to group {group}" : "Benutzer kann nicht zur Gruppe {group} hinzugefügt werden ", "Unable to remove user from group {group}" : "Benutzer kann nicht aus der Gruppe {group} entfernt werden ", "Add group" : "Gruppe hinzufügen", "Invalid quota value \"{val}\"" : "Ungültiger Grenzwert \"{val}\"", "no group" : "Keine Gruppe", "Password successfully changed" : "Das Passwort wurde erfolgreich geändert", "Changing the password will result in data loss, because data recovery is not available for this user" : "Die Änderung des Passworts führt zu Datenverlust, weil die Datenwiederherstellung für diesen Benutzer nicht verfügbar ist", "Could not change the users email" : "Die E-Mail-Adresse des Nutzers konnte nicht geändert werden", "A valid username must be provided" : "Es muss ein gültiger Benutzername angegeben werden", "Error creating user: {message}" : "Fehler beim Erstellen eines Benutzers: {message}", "A valid password must be provided" : "Es muss ein gültiges Passwort angegeben werden", "A valid email must be provided" : "Es muss eine gültige E-Mail-Adresse angegeben werden", "__language_name__" : "Deutsch (Förmlich: Sie)", "Unlimited" : "Unbegrenzt", "Personal info" : "Persönliche Informationen", "Sessions" : "Sitzungen", "App passwords" : "App-PINs", "Sync clients" : "Sync-Clients", "None" : "Keine", "Login" : "Anmelden", "Plain" : "Klartext", "NT LAN Manager" : "NT-LAN-Manager", "SSL/TLS" : "SSL/TLS", "STARTTLS" : "STARTTLS", "Email server" : "E-Mail-Server", "Open documentation" : "Dokumentation öffnen", "This is used for sending out notifications." : "Dies wird für das Senden von Benachrichtigungen verwendet.", "Send mode" : "Sendemodus", "Encryption" : "Verschlüsselung", "From address" : "Absenderadresse", "mail" : "Mail", "Authentication method" : "Authentifizierungsmethode", "Authentication required" : "Authentifizierung benötigt", "Server address" : "Serveradresse", "Port" : "Port", "Credentials" : "Zugangsdaten", "SMTP Username" : "SMTP-Benutzername", "SMTP Password" : "SMTP-Passwort", "Store credentials" : "Anmeldeinformationen speichern", "Test email settings" : "E-Mail-Einstellungen testen", "Send email" : "E-Mail senden", "Server-side encryption" : "Serverseitige Verschlüsselung", "Enable server-side encryption" : "Serverseitige Verschlüsselung aktivieren", "Please read carefully before activating server-side encryption: " : "Bitte lesen Sie ganz genau, bevor Sie die serverseitige Verschlüsselung aktivieren:", "Once encryption is enabled, all files uploaded to the server from that point forward will be encrypted at rest on the server. It will only be possible to disable encryption at a later date if the active encryption module supports that function, and all pre-conditions (e.g. setting a recover key) are met." : "Wird die Verschlüsselung einmal aktiviert, so werden alle ab diesem Zeitpunkt hochgeladene Dateien verschlüsselt. Sie kann nur wieder deaktiviert werden, wenn das Verschlüsselungsmodul dies unterstützt und alle Voraussetzungen (wie das Setzen eines Wiederherstellungsschlüssels) im Vorhinein erfüllt wurden.", "Encryption alone does not guarantee security of the system. Please see documentation for more information about how the encryption app works, and the supported use cases." : "Verschlüsselung alleine garantiert nicht die Systemsicherheit. Bitte lese in der Dokumentation nach, wie die Verschlüsselungs-app funktioniert und welche Anwendungsfälle unterstützt werden.", "Be aware that encryption always increases the file size." : "Bedenken Sie, dass durch die Verschlüsselung die Dateigröße zunimmt. ", "It is always good to create regular backups of your data, in case of encryption make sure to backup the encryption keys along with your data." : "Es ist immer gut, regelmäßig Sicherungskopien von ihren Daten zu machen. Falls Sie die Verschlüsselung nutzen, sollten Sie auch eine Sicherung der Verschlüsselungsschlüssel zusammen mit ihren Daten machen.", "This is the final warning: Do you really want to enable encryption?" : "Dies ist die letzte Warnung: Wollen Sie die Verschlüsselung wirklich aktivieren?", "Enable encryption" : "Verschlüsselung aktivieren", "No encryption module loaded, please enable an encryption module in the app menu." : "Kein Verschlüsselungs-Modul geladen, bitte aktiviere ein Verschlüsselungs-Modul im Anwendungs-Menü.", "Select default encryption module:" : "Standard-Verschlüsselungs-Modul auswählen:", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one. Please enable the \"Default encryption module\" and run 'occ encryption:migrate'" : "Sie müssen Ihre Verschlüsselungsschlüssel von der alten Verschlüsselung (ownCloud <= 8.0) zur Neuen migrieren. Bitte aktivieren Sie das \"Default Encryption Module\" und rufen Sie 'occ encryption:migrate' auf.", "You need to migrate your encryption keys from the old encryption (ownCloud <= 8.0) to the new one." : "Sie müssen Ihre Verschlüsselungsschlüssel von der alten Verschlüsselung (ownCloud <= 8.0) zur Neuen migrieren.", "Start migration" : "Migration beginnen", "Security & setup warnings" : "Sicherheits- & Einrichtungswarnungen", "php does not seem to be setup properly to query system environment variables. The test with getenv(\"PATH\") only returns an empty response." : "PHP scheint zur Abfrage von Systemumgebungsvariablen nicht richtig eingerichtet zu sein. Der Test mit getenv (\"PATH\") liefert nur eine leere Antwort zurück.", "Please check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation documentation ↗</a> for php configuration notes and the php configuration of your server, especially when using php-fpm." : "Bitte schauen Sie in der <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Installationsdokumentation ↗</a>auf Hinweise zur PHP-Konfiguration, sowie die PHP-Konfiguration ihres Servers, insbesondere dann, wenn Sie PHP-FPM einsetzten.", "The Read-Only config has been enabled. This prevents setting some configurations via the web-interface. Furthermore, the file needs to be made writable manually for every update." : "Die schreibgeschützte Konfiguration wurde aktiviert. Dies verhindert das Setzen einiger Einstellungen über die Web-Schnittstelle. Weiterhin muss bei jedem Update der Schreibzugriff auf die Datei händisch aktiviert werden.", "PHP is apparently setup to strip inline doc blocks. This will make several core apps inaccessible." : "PHP ist offenbar so konfiguriert, dass PHPDoc-Blöcke in der Anweisung entfernt werden. Dadurch sind mehrere Kern-Apps nicht erreichbar.", "This is probably caused by a cache/accelerator such as Zend OPcache or eAccelerator." : "Dies wird wahrscheinlich durch Zwischenspeicher/Beschleuniger wie etwa Zend OPcache oder eAccelerator verursacht.", "Your database does not run with \"READ COMMITTED\" transaction isolation level. This can cause problems when multiple actions are executed in parallel." : "Ihre Datenbank läuft nicht mit der \"READ COMMITED\" Transaktionsisolationsstufe. Dies kann Probleme hervorrufen, wenn mehrere Aktionen parallel ausgeführt werden.", "%1$s below version %2$s is installed, for stability and performance reasons we recommend updating to a newer %1$s version." : "%1$s ist in einer älteren Version als %2$s installiert. Aus Stabilitäts- und Performancegründen empfehlen wir eine Aktualisierung auf eine neuere %1$s-Version", "The PHP module 'fileinfo' is missing. We strongly recommend to enable this module to get best results with mime-type detection." : "Das PHP-Modul 'fileinfo' fehlt. Wir empfehlen Ihnen dieses Modul zu aktivieren, um die besten Resultate bei der Bestimmung der Dateitypen zu erzielen.", "Transactional file locking is disabled, this might lead to issues with race conditions. Enable 'filelocking.enabled' in config.php to avoid these problems. See the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a> for more information." : "Transaktionales Sperren ist deaktiviert, was zu Problemen mit Laufzeitbedingungen führen kann. Aktivieren Sie 'filelocking.enabled' in der config.php diese Probleme zu vermeiden. Weitere Informationen findest Sie in unserer <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Dokumentation ↗</a>.", "System locale can not be set to a one which supports UTF-8." : "Es kann kein Systemgebietsschema gesetzt werden, das UTF-8 unterstützt.", "This means that there might be problems with certain characters in file names." : "Dies bedeutet, dass es zu Problemen mit bestimmten Zeichen in Dateinamen kommen kann.", "We strongly suggest installing the required packages on your system to support one of the following locales: %s." : "Wir empfehlen dringend, die erforderlichen Pakete auf Ihrem System zu installieren, damit eines der folgenden Gebietsschemata unterstützt wird: %s.", "If your installation is not installed in the root of the domain and uses system cron, there can be issues with the URL generation. To avoid these problems, please set the \"overwrite.cli.url\" option in your config.php file to the webroot path of your installation (Suggested: \"%s\")" : "Wenn sich Ihre Installation nicht im Wurzelverzeichnis der Domain befindet und Cron aus dem System genutzt wird, kann es zu Fehlern bei der URL-Generierung kommen. Um dies zu verhindern, setzen Sie bitte die „overwrite.cli.url“-Option in Ihrer config.php auf das Web-Wurzelverzeichnis Ihrer Installation (Vorschlag: „%s“).", "It was not possible to execute the cronjob via CLI. The following technical errors have appeared:" : "Die Ausführung des Cron-Jobs über die Kommandozeile war nicht möglich. Die folgenden technischen Fehler sind dabei aufgetreten:", "Please double check the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">installation guides ↗</a>, and check for any errors or warnings in the <a href=\"%s\">log</a>." : "Bitte überprüfen Sie noch einmal die <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Installationsanleitungen ↗</a> und kontrollieren Sie das <a href=\"%s\">Log</a> auf mögliche Fehler oder Warnungen.", "All checks passed." : "Alle Checks bestanden.", "Cron" : "Cron", "Last cron job execution: %s." : "Letzte Cron-Job-Ausführung: %s.", "Last cron job execution: %s. Something seems wrong." : "Letzte Cron-Job-Ausführung: %s. Möglicherweise liegt ein Fehler vor.", "Cron was not executed yet!" : "Cron wurde bislang noch nicht ausgeführt!", "Execute one task with each page loaded" : "Eine Aufgabe bei jedem Laden einer Seite ausführen", "cron.php is registered at a webcron service to call cron.php every 15 minutes over http." : "cron.php ist als Webcron-Dienst registriert, der die cron.php alle 15 Minuten per HTTP aufruft.", "Use system's cron service to call the cron.php file every 15 minutes." : "Benutzen Sie den systemeigenen Cron-Dienst, um die cron.php alle 15 Minuten aufzurufen.", "The cron.php needs to be executed by the system user \"%s\"." : "Die cron.php muss durch den Systemnutzer \"%s\" ausgeführt werden.", "To run this you need the PHP posix extension. See {linkstart}PHP documentation{linkend} for more details." : "Um dies auszuführen, benötigen Sie die PHP-Posix Erweiterung. Weitere Informationen in der {linkstart}PHP-Dokumentation{linkend}.", "Version" : "Version", "Sharing" : "Teilen", "Allow apps to use the Share API" : "Apps die Benutzung der Share-API erlauben", "Allow users to share via link" : "Benutzern erlauben, Inhalte über Links zu teilen", "Allow public uploads" : "Öffentliches Hochladen erlauben", "Enforce password protection" : "Passwortschutz erzwingen", "Set default expiration date" : "Standardmäßiges Ablaufdatum setzen", "Expire after " : "Ablauf nach ", "days" : "Tagen", "Enforce expiration date" : "Ablaufdatum erzwingen", "Allow resharing" : "Weiterteilen erlauben", "Allow sharing with groups" : "Mit Gruppen teilen erlauben", "Restrict users to only share with users in their groups" : "Benutzer auf das Teilen innerhalb ihrer Gruppen beschränken", "Exclude groups from sharing" : "Gruppen von Freigaben ausschließen", "These groups will still be able to receive shares, but not to initiate them." : "Diese Gruppen können weiterhin Freigaben empfangen, aber selbst keine mehr initiieren.", "Allow username autocompletion in share dialog. If this is disabled the full username needs to be entered." : "Die Auto-Vervollständigung von Benutzernamen im Teilen-Dialog erlauben. Wenn dies deaktiviert ist, muss der vollständige Benutzername eingegeben werden.", "Show disclaimer text on the public link upload page. (Only shown when the file list is hidden.)" : "Zeige Haftungsausschluss auf der öffentlichen Upload-Seite. (Wird nur gezeigt wenn die Dateiliste nicht angezeigt wird.) ", "This text will be shown on the public link upload page when the file list is hidden." : "Dieser Text wird auf der öffentlichen Upload-Seite angezeigt wenn die Dateiliste nicht angezeigt wird.", "Tips & tricks" : "Tipps & Tricks", "SQLite is currently being used as the backend database. For larger installations we recommend that you switch to a different database backend." : "SQLite wird als Datenbank verwendet. Bei größeren Installationen empfehlen wir, auf ein anderes Datenbank-Backend zu wechseln.", "This is particularly recommended when using the desktop client for file synchronisation." : "Dies wird insbesondere bei der Benutzung des Dektop-Clients zur Synchronisierung empfohlen.", "To migrate to another database use the command line tool: 'occ db:convert-type', or see the <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">documentation ↗</a>." : "Um zu einer anderen Datenbank zu migrieren, benutzen Sie bitte die Kommandozeile: 'occ db:convert-type', oder in die <a target=\"_blank\" rel=\"noreferrer\" href=\"%s\">Dokumentation ↗</a> schauen.", "How to do backups" : "Wie man Datensicherungen anlegt", "Advanced monitoring" : "Erweitertes Monitoring", "Performance tuning" : "Leistungsoptimierung", "Improving the config.php" : "Die config.php optimieren", "Theming" : "Themes verwenden", "Hardening and security guidance" : "Systemhärtung und Sicherheitsempfehlungen", "Developer documentation" : "Dokumentation für Entwickler", "by %s" : "von %s", "%s-licensed" : "%s-Lizensiert", "Documentation:" : "Dokumentation:", "User documentation" : "Benutzer-Dokumentation", "Admin documentation" : "Administratoren-Dokumentation", "Visit website" : "Webseite besuchen", "Report a bug" : "Melden Sie einen technischen Fehler", "Show description …" : "Beschreibung anzeigen…", "Hide description …" : "Beschreibung ausblenden…", "This app has an update available." : "Für diese Anwendung ist eine Aktualisierung verfügbar.", "This app has no minimum Nextcloud version assigned. This will be an error in the future." : "Für diese App wurde keine untere Versionsgrenze für Nextcloud gesetzt. Dies wird zukünftig als Fehler behandelt.", "This app has no maximum Nextcloud version assigned. This will be an error in the future." : "Für diese App wurde keine obere Versionsgrenze für Nextcloud gesetzt. Dies wird zukünftig als Fehler behandelt.", "This app cannot be installed because the following dependencies are not fulfilled:" : "Diese App kann nicht installiert werden, weil die folgenden Abhängigkeiten nicht erfüllt sind:", "Enable only for specific groups" : "Nur für bestimmte Gruppen aktivieren", "Uninstall app" : "App deinstallieren", "SSL Root Certificates" : "SSL Root Zertifikate", "Common Name" : "Allgemeiner Name", "Valid until" : "Gültig bis", "Issued By" : "Ausgestellt von:", "Valid until %s" : "Gültig bis %s", "Import root certificate" : "Root-Zertifikat importieren", "Hey there,<br><br>just letting you know that you now have a %s account.<br><br>Your username: <strong>%s</strong><br>Access it: <strong><a href=\"%s\">%s</a></strong><br><br>" : "Hallo,<br><br>hier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.<br><br>Ihr Benutzername: <strong>%s</strong><br>Greifen Sie darauf zu: <strong><a href=\"%s\">%s</a></strong><br><br>", "Cheers!" : "Noch einen schönen Tag!", "Hey there,\n\njust letting you know that you now have a %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hallo,\n\nhier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.\n\nIhr Benutzername: %s\nZugriff: %s\n\n", "Administrator documentation" : "Dokumentation für Administratoren", "Online documentation" : "Online-Dokumentation", "Forum" : "Forum", "Getting help" : "Hilfe bekommen", "Commercial support" : "Kommerzieller Support", "You are using <strong>%s</strong> of <strong>%s</strong>" : "Sie verwenden <strong>%s</strong> der verfügbaren <strong>%s</strong>", "Profile picture" : "Profilbild", "Upload new" : "Neues hochladen", "Select from Files" : "Aus Dateien wählen", "Remove image" : "Bild entfernen", "png or jpg, max. 20 MB" : "png oder jpg, max. 20 MB", "Picture provided by original account" : "Bild von Original-Konto zur Verfügung gestellt", "Cancel" : "Abbrechen", "Choose as profile picture" : "Als Profilbild auswählen", "Full name" : "Vollständiger Name", "No display name set" : "Kein Anzeigename angegeben", "Email" : "E-Mail", "Your email address" : "Ihre E-Mail-Adresse", "No email address set" : "Keine E-Mail-Adresse angegeben", "For password reset and notifications" : "Für Passwort-Wiederherstellung und Benachrichtigungen", "Phone number" : "Telefonnummer", "Your phone number" : "Ihre Telefonnummer", "Address" : "Adresse", "Your postal address" : "Ihre Postadresse", "Website" : "Webseite", "Your website" : "Ihre Internetseite", "Twitter" : "Twitter", "Your Twitter handle" : "Ihr Twitter-Handle", "You are member of the following groups:" : "Sie sind Mitglied folgender Gruppen:", "Password" : "Passwort", "Current password" : "Aktuelles Passwort", "New password" : "Neues Passwort", "Change password" : "Passwort ändern", "Language" : "Sprache", "Help translate" : "Helfen Sie bei der Übersetzung", "Get the apps to sync your files" : "Installieren Sie die Anwendungen, um Ihre Dateien zu synchronisieren", "Desktop client" : "Desktop-Client", "Android app" : "Android-App", "iOS app" : "iOS-App", "If you want to support the project {contributeopen}join development{linkclose} or {contributeopen}spread the word{linkclose}!" : "Wenn Sie das Projekt unterstützen wollen {contributeopen} helfen Sie bei der Entwicklung{linkclose} oder {contributeopen} verbreiten Sie es{linkclose}!", "Show First Run Wizard again" : "Den Einrichtungsassistenten erneut anzeigen", "Web, desktop and mobile clients currently logged in to your account." : "Aktuell in Ihrem Konto eingeloggte Web-, Desktop- und Mobil-Clients.", "Device" : "Gerät", "Last activity" : "Letzte Aktivität", "Passcodes that give an app or device permissions to access your account." : "PINs mit denen Apps oder Geräte auf Ihr Konto zugreifen können.", "Name" : "Name", "App name" : "App-Name", "Create new app password" : "Neues App-Passwort erstellen", "Use the credentials below to configure your app or device." : "Nutzen Sie die unten angebenen Anmeldeinformationen, um ihre App oder ihr Gerät zu konfigurieren.", "For security reasons this password will only be shown once." : "Aus Sicherheitsgründen wird das Passwort nur einmal angezeigt.", "Username" : "Benutzername", "Done" : "Erledigt", "Developed by the {communityopen}Nextcloud community{linkclose}, the {githubopen}source code{linkclose} is licensed under the {licenseopen}AGPL{linkclose}." : "Entwickelt von der {communityopen}Nextcloud Community{linkclose}, der {githubopen}Quellcode{linkclose} ist lizensiert unter {licenseopen}AGPL{linkclose}-Lizenz.", "Follow us on Google Plus!" : "Folgen Sie uns zu Google Plus!", "Like our facebook page!" : "Liken Sie uns auf unserer Facebook-Seite!", "Subscribe to our twitter channel!" : "Abonnieren Sie unseren Twitter-Kanal!", "Subscribe to our news feed!" : "Abonnieren Sie unseren RSS-Feed!", "Subscribe to our newsletter!" : "Abonnieren Sie unseren Newsletter!", "Show storage location" : "Speicherort anzeigen", "Show last log in" : "Letzte Anmeldung anzeigen", "Show user backend" : "Benutzer-Backend anzeigen", "Send email to new user" : "E-Mail an neuen Benutzer senden", "When the password of the new user is left empty an activation email with a link to set the password is send to the user" : "Wenn das Passwort für den neuen Benutzer leer gelassen wird, wird an ihn eine Aktivierungs-E-Mail mit einem Link zur Passwortvergabe versandt.", "Show email address" : "E-Mail Adresse anzeigen", "E-Mail" : "E-Mail", "Create" : "Erstellen", "Admin Recovery Password" : "Admin-Passwort-Wiederherstellung", "Enter the recovery password in order to recover the users files during password change" : "Geben Sie das Wiederherstellungspasswort ein, um die Benutzerdateien während der Passwortänderung wiederherzustellen", "Group name" : "Gruppenname", "Everyone" : "Jeder", "Admins" : "Administratoren", "Default quota" : "Standard-Kontingent", "Please enter storage quota (ex: \"512 MB\" or \"12 GB\")" : "Bitte Speicherkontingent eingeben (z.B.: „512 MB“ oder „12 GB“)", "Other" : "Andere", "Group admin for" : "Gruppenadministrator für", "Quota" : "Kontingent", "Storage location" : "Speicherort", "User backend" : "Benutzer-Backend", "Last login" : "Letzte Anmeldung", "change full name" : "Vollständigen Namen ändern", "set new password" : "Neues Passwort setzen", "change email address" : "E-Mail-Adresse ändern", "Default" : "Standard", "log-level out of allowed range" : "Log-Level außerhalb des erlaubten Bereichs", "Language changed" : "Sprache geändert", "Admins can't remove themself from the admin group" : "Administratoren können sich nicht selbst aus der admin-Gruppe löschen", "Unable to add user to group %s" : "Der Benutzer konnte nicht zur Gruppe %s hinzugefügt werden", "Unable to remove user from group %s" : "Der Benutzer konnte nicht aus der Gruppe %s entfernt werden", "Are you really sure you want add \"{domain}\" as trusted domain?" : "Sind Sie sich wirklich sicher, dass Sie \"{domain}\" als vertrauenswürdige Domain hinzufügen möchten?", "Please wait...." : "Bitte warten…", "add group" : "Gruppe hinzufügen", "Everything (fatal issues, errors, warnings, info, debug)" : "Alles (fatale Probleme, Fehler, Warnungen, Infos, Fehlerdiagnose)", "Info, warnings, errors and fatal issues" : "Infos, Warnungen, Fehler und fatale Probleme", "Warnings, errors and fatal issues" : "Warnungen, Fehler und fatale Probleme", "Errors and fatal issues" : "Fehler und fatale Probleme", "Fatal issues only" : "Nur kritische Fehler", "Log" : "Log", "What to log" : "Was geloggt wird", "Download logfile" : "Logdatei herunterladen", "More" : "Mehr", "Less" : "Weniger", "The logfile is bigger than 100 MB. Downloading it may take some time!" : "Die Logdatei ist größer als 100 MB. Es kann etwas Zeit beanspruchen, sie herunterzuladen!", "Allow users to send mail notification for shared files" : "Benutzern erlauben, E-Mail-Benachrichtigungen für freigegebene Dateien zu senden", "Allow users to send mail notification for shared files to other users" : "Benutzern erlauben, E-Mail-Benachrichtigungen für freigegebene Dateien an andere Benutzer zu senden", "SQLite is used as database. For larger installations we recommend to switch to a different database backend." : "SQLite wird als Datenbank verwendet. Bei größeren Installationen wird empfohlen, auf ein anderes Datenbank-Backend zu wechseln.", "Especially when using the desktop client for file syncing the use of SQLite is discouraged." : "Insbesondere bei der Nutzung des Desktop Clients zur Dateisynchronisierung wird vom Einsatz von SQLite abgeraten.", "Experimental applications ahead" : "Experimentelle Apps nachfolgend", "Experimental apps are not checked for security issues, new or known to be unstable and under heavy development. Installing them can cause data loss or security breaches." : "Experimentelle Apps sind nicht auf Sicherheitsprobleme hin überprüft, sind neu oder bekanntermaßen instabil und befinden sich in intensiver Entwicklung. Ihre Installation kann Datenverlust oder Sicherheitslücken hervorrufen.", "Uninstall App" : "App deinstallieren", "Enable experimental apps" : "Experimentelle Apps aktivieren", "Hey there,<br><br>just letting you know that you now have an %s account.<br><br>Your username: %s<br>Access it: <a href=\"%s\">%s</a><br><br>" : "Hallo,<br><br>hier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.<br><br>Ihr Benutzername: %s<br>Greifen Sie darauf zu: <a href=\"%s\">%s</a><br><br>", "Hey there,\n\njust letting you know that you now have an %s account.\n\nYour username: %s\nAccess it: %s\n\n" : "Hallo,\n\nhier nur kurz die Mitteilung, dass Sie jetzt ein %s-Konto haben.\n\nIhr Benutzername: %s\nGreifen Sie darauf zu: %s\n\n", "For password recovery and notifications" : "Für Passwort-Wiederherstellung und Benachrichtigungen", "If you want to support the project\n\t\t<a href=\"https://nextcloud.com/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">join development</a>\n\t\tor\n\t\t<a href=\"https://nextcloud.com/contribute\"\n\t\t\ttarget=\"_blank\" rel=\"noreferrer\">spread the word</a>!" : "Wenn Sie das Projekt unterstützen möchten\n⇥⇥<a href=\"https://nextcloud.com/contribute\"\n⇥⇥⇥target=\"_blank\" rel=\"noreferrer\">helfen Sie bei der Weiterentwicklung</a>\n⇥⇥oder\n⇥⇥<a href=\"https://nextcloud.com/contribute\"\n⇥⇥⇥target=\"_blank\" rel=\"noreferrer\">empfehlen Sie es weiter</a>!", "Add Group" : "Gruppe hinzufügen", "Group" : "Gruppe", "Default Quota" : "Standard-Quota", "Full Name" : "Vollständiger Name", "Group Admin for" : "Gruppenadministrator für", "Storage Location" : "Speicherort", "User Backend" : "Benutzer-Backend", "Last Login" : "Letzte Anmeldung" }, "nplurals=2; plural=(n != 1);");
whitekiba/server
settings/l10n/de_DE.js
JavaScript
agpl-3.0
36,870
<?php namespace SPHERE\Application\People\Relationship; use SPHERE\Application\Corporation\Company\Company; use SPHERE\Application\Corporation\Company\Service\Entity\TblCompany; use SPHERE\Application\People\Meta\Common\Common; use SPHERE\Application\People\Person\Person; use SPHERE\Application\People\Person\Service\Entity\TblPerson; use SPHERE\Application\People\Relationship\Service\Data; use SPHERE\Application\People\Relationship\Service\Entity\TblGroup; use SPHERE\Application\People\Relationship\Service\Entity\TblSiblingRank; use SPHERE\Application\People\Relationship\Service\Entity\TblToCompany; use SPHERE\Application\People\Relationship\Service\Entity\TblToPerson; use SPHERE\Application\People\Relationship\Service\Entity\TblType; use SPHERE\Application\People\Relationship\Service\Entity\ViewRelationshipFromPerson; use SPHERE\Application\People\Relationship\Service\Entity\ViewRelationshipToCompany; use SPHERE\Application\People\Relationship\Service\Entity\ViewRelationshipToPerson; use SPHERE\Application\People\Relationship\Service\Setup; use SPHERE\Common\Frontend\Form\IFormInterface; use SPHERE\Common\Frontend\Form\Structure\FormColumn; use SPHERE\Common\Frontend\Form\Structure\FormGroup; use SPHERE\Common\Frontend\Form\Structure\FormRow; use SPHERE\Common\Frontend\Icon\Repository\Ban; use SPHERE\Common\Frontend\Message\Repository\Danger; use SPHERE\Common\Frontend\Message\Repository\Success; use SPHERE\Common\Window\Redirect; use SPHERE\System\Database\Binding\AbstractService; /** * Class Service * * @package SPHERE\Application\People\Relationship */ class Service extends AbstractService { /** * @return false|ViewRelationshipToPerson[] */ public function viewRelationshipToPerson() { return (new Data($this->getBinding()))->viewRelationshipToPerson(); } /** * @return false|ViewRelationshipFromPerson[] */ public function viewRelationshipFromPerson() { return ( new Data($this->getBinding()) )->viewRelationshipFromPerson(); } /** * @return false|ViewRelationshipToCompany[] */ public function viewRelationshipToCompany() { return ( new Data($this->getBinding()) )->viewRelationshipToCompany(); } /** * @param bool $doSimulation * @param bool $withData * * @return string */ public function setupService($doSimulation, $withData) { $Protocol = (new Setup($this->getStructure()))->setupDatabaseSchema($doSimulation); if (!$doSimulation && $withData) { (new Data($this->getBinding()))->setupDatabaseContent(); } return $Protocol; } /** * @param TblPerson $tblPerson * @param TblType|null $tblType * * @return bool|TblToPerson[] */ public function getPersonRelationshipAllByPerson(TblPerson $tblPerson, TblType $tblType = null) { return (new Data($this->getBinding()))->getPersonRelationshipAllByPerson($tblPerson, $tblType); } /** * @param TblToPerson[] $tblToPersonList * * @return array|TblPerson[] * sortet by Gender (0 => mother - 1 = father - 2... => unknown) * without hits on Mother or Father the unknown get the 0 and 1 */ public function getPersonGuardianAllByToPersonList($tblToPersonList) { $GuardianList = array(); if ($tblToPersonList && !empty($tblToPersonList)) { $i = 2; foreach ($tblToPersonList as $tblToPerson) { $tblPersonGuardian = $tblToPerson->getServiceTblPersonFrom(); // get Gender $Gender = ''; if ($tblPersonGuardian && ($common = Common::useService()->getCommonByPerson($tblPersonGuardian))) { if (($tblCommonBirthDates = $common->getTblCommonBirthDates())) { if (($tblCommonGender = $tblCommonBirthDates->getTblCommonGender())) { $Gender = $tblCommonGender->getName(); } } } if ($Gender == '') { $Salutation = $tblPersonGuardian->getSalutation(); if ($Salutation == 'Frau') { $Gender = 'Weiblich'; } elseif ($Salutation == 'Herr') { $Gender = 'Männlich'; } } // get sorted List (0 => Mother; 1 => Father; 2.. => Other ) if ($Gender == 'Weiblich') { if (isset($GuardianList[0])) { if (!isset($GuardianList[1])) { $GuardianList[1] = $GuardianList[0]; } else { $GuardianList[$i++] = $GuardianList[0]; } } $GuardianList[0] = $tblToPerson->getServiceTblPersonFrom(); } elseif (!isset($GuardianList[1]) && $Gender == 'Männlich') { if (isset($GuardianList[1])) { if (!isset($GuardianList[0])) { $GuardianList[0] = $GuardianList[1]; } else { $GuardianList[$i++] = $GuardianList[1]; } } $GuardianList[1] = $tblToPerson->getServiceTblPersonFrom(); } else { // if no matches set unknown to Mother/Father to keep it running $GuardianList[] = $tblToPerson->getServiceTblPersonFrom(); } } } return $GuardianList; } /** * @param TblPerson $tblPerson * * @return bool|TblToCompany[] */ public function getCompanyRelationshipAllByPerson(TblPerson $tblPerson) { return (new Data($this->getBinding()))->getCompanyRelationshipAllByPerson($tblPerson); } /** * @param TblCompany $tblCompany * * @return bool|TblToCompany[] */ public function getCompanyRelationshipAllByCompany(TblCompany $tblCompany) { return (new Data($this->getBinding()))->getCompanyRelationshipAllByCompany($tblCompany); } /** * @param IFormInterface $Form * @param TblPerson $tblPersonFrom * @param int $tblPersonTo * @param array $Type * * @return IFormInterface|string */ public function createRelationshipToPerson( IFormInterface $Form, TblPerson $tblPersonFrom, $tblPersonTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblPersonTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Person'))))); $Error = true; } else { $tblPersonTo = Person::useService()->getPersonById($tblPersonTo); if (!$tblPersonTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Person'))))); $Error = true; } elseif ($tblPersonFrom->getId() == $tblPersonTo->getId()) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger( 'Eine Person kann nur mit einer anderen Person verknüpft werden'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { if ((new Data($this->getBinding()))->addPersonRelationshipToPerson($tblPersonFrom, $tblPersonTo, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich hinzugefügt') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblPersonFrom->getId())); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht hinzugefügt werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblPersonFrom->getId())); } } return $Form; } /** * @param integer $Id * * @return bool|TblType */ public function getTypeById($Id) { return (new Data($this->getBinding()))->getTypeById($Id); } /** * @param TblGroup|null $tblGroup * * @return bool|TblType[] */ public function getTypeAllByGroup(TblGroup $tblGroup = null) { return (new Data($this->getBinding()))->getTypeAllByGroup($tblGroup); } /** * @param integer $Id * * @return bool|TblGroup */ public function getGroupById($Id) { return (new Data($this->getBinding()))->getGroupById($Id); } /** * @param string $Identifier * * @return bool|TblGroup */ public function getGroupByIdentifier($Identifier) { return (new Data($this->getBinding()))->getGroupByIdentifier($Identifier); } /** * @param IFormInterface $Form * @param TblPerson $tblPersonFrom * @param int $tblCompanyTo * @param array $Type * * @return IFormInterface|string */ public function createRelationshipToCompany( IFormInterface $Form, TblPerson $tblPersonFrom, $tblCompanyTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblCompanyTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } else { $tblCompanyTo = Company::useService()->getCompanyById($tblCompanyTo); if (!$tblCompanyTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { if ((new Data($this->getBinding()))->addCompanyRelationshipToPerson($tblCompanyTo, $tblPersonFrom, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich hinzugefügt') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblPersonFrom->getId())); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht hinzugefügt werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblPersonFrom->getId())); } } return $Form; } /** * @param IFormInterface $Form * @param TblToPerson $tblToPerson * @param TblPerson $tblPersonFrom * @param int $tblPersonTo * @param array $Type * * @return IFormInterface|string */ public function updateRelationshipToPerson( IFormInterface $Form, TblToPerson $tblToPerson, TblPerson $tblPersonFrom, $tblPersonTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblPersonTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger(new Ban() . ' Bitte wählen Sie eine Person'))))); $Error = true; } else { $tblPersonTo = Person::useService()->getPersonById($tblPersonTo); if (!$tblPersonTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Person'))))); $Error = true; } elseif ($tblPersonFrom->getId() == $tblPersonTo->getId()) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger(new Ban() . ' Eine Person kann nur mit einer anderen Person verknüpft werden'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { // Remove current (new Data($this->getBinding()))->removePersonRelationshipToPerson($tblToPerson); // Add new if ((new Data($this->getBinding()))->addPersonRelationshipToPerson($tblPersonFrom, $tblPersonTo, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich geändert') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblToPerson->getServiceTblPersonFrom() ? $tblToPerson->getServiceTblPersonFrom()->getId() : 0)); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht geändert werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblToPerson->getServiceTblPersonFrom() ? $tblToPerson->getServiceTblPersonFrom()->getId() : 0)); } } return $Form; } /** * @param IFormInterface $Form * @param TblToCompany $tblToCompany * @param TblPerson $tblPersonFrom * @param int $tblCompanyTo * @param array $Type * * @return IFormInterface|string */ public function updateRelationshipToCompany( IFormInterface $Form, TblToCompany $tblToCompany, TblPerson $tblPersonFrom, $tblCompanyTo, $Type ) { /** * Skip to Frontend */ if (null === $Type) { return $Form; } $Error = false; if (empty($tblCompanyTo)) { $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } else { $tblCompanyTo = Company::useService()->getCompanyById($tblCompanyTo); if (!$tblCompanyTo){ $Form->appendGridGroup(new FormGroup(new FormRow(new FormColumn(new Danger('Bitte wählen Sie eine Institution'))))); $Error = true; } } if (!($tblType = $this->getTypeById($Type['Type']))){ $Form->setError('Type[Type]', 'Bitte geben Sie einen Typ an'); $Error = true; } else { $Form->setSuccess('Type[Type]'); } if (!$Error) { // Remove current (new Data($this->getBinding()))->removeCompanyRelationshipToPerson($tblToCompany); // Add new if ((new Data($this->getBinding()))->addCompanyRelationshipToPerson($tblCompanyTo, $tblPersonFrom, $tblType, $Type['Remark']) ) { return new Success(new \SPHERE\Common\Frontend\Icon\Repository\Success() . ' Die Beziehung wurde erfolgreich geändert') . new Redirect('/People/Person', Redirect::TIMEOUT_SUCCESS, array('Id' => $tblToCompany->getServiceTblPerson() ? $tblToCompany->getServiceTblPerson()->getId() : 0)); } else { return new Danger(new Ban() . ' Die Beziehung konnte nicht geändert werden') . new Redirect('/People/Person', Redirect::TIMEOUT_ERROR, array('Id' => $tblToCompany->getServiceTblPerson() ? $tblToCompany->getServiceTblPerson()->getId() : 0)); } } return $Form; } /** * @return bool|TblType[] */ public function getTypeAll() { return (new Data($this->getBinding()))->getTypeAll(); } /** * @param $Name * @return false|TblType */ public function getTypeByName($Name) { return (new Data($this->getBinding()))->getTypeByName($Name); } /** * @param TblToPerson $tblToPerson * @param bool $IsSoftRemove * * @return bool */ public function removePersonRelationshipToPerson(TblToPerson $tblToPerson, $IsSoftRemove = false) { return (new Data($this->getBinding()))->removePersonRelationshipToPerson($tblToPerson, $IsSoftRemove); } /** * @param TblToCompany $tblToCompany * @param bool $IsSoftRemove * * @return bool */ public function removeCompanyRelationshipToPerson(TblToCompany $tblToCompany, $IsSoftRemove = false) { return (new Data($this->getBinding()))->removeCompanyRelationshipToPerson($tblToCompany, $IsSoftRemove); } /** * @param integer $Id * * @return bool|TblToPerson */ public function getRelationshipToPersonById($Id) { return (new Data($this->getBinding()))->getRelationshipToPersonById($Id); } /** * @param integer $Id * * @return bool|TblToCompany */ public function getRelationshipToCompanyById($Id) { return (new Data($this->getBinding()))->getRelationshipToCompanyById($Id); } /** * @param TblCompany $tblCompany * @param TblPerson $tblPerson * @param TblType $tblType * @param string $Remark * * @return TblToCompany */ public function addCompanyRelationshipToPerson( TblCompany $tblCompany, TblPerson $tblPerson, TblType $tblType, $Remark = '' ) { return (new Data($this->getBinding()))->addCompanyRelationshipToPerson( $tblCompany, $tblPerson, $tblType, $Remark ); } /** * @param TblPerson $tblPersonFrom * @param TblPerson $tblPersonTo * @param TblType $tblType * @param string $Remark * * @return bool */ public function insertRelationshipToPerson( TblPerson $tblPersonFrom, TblPerson $tblPersonTo, TblType $tblType, $Remark ) { if ((new Data($this->getBinding()))->addPersonRelationshipToPerson($tblPersonFrom, $tblPersonTo, $tblType, $Remark) ) { return true; } else { return false; } } /** * @param integer $Id * * @return bool|TblSiblingRank */ public function getSiblingRankById($Id) { return (new Data($this->getBinding()))->getSiblingRankById($Id); } /** * @return bool|TblSiblingRank[] */ public function getSiblingRankAll() { return (new Data($this->getBinding()))->getSiblingRankAll(); } /** * @param TblPerson $tblPerson * @param bool $IsSoftRemove */ public function removeRelationshipAllByPerson(TblPerson $tblPerson, $IsSoftRemove = false) { if (($tblRelationshipToPersonList = $this->getPersonRelationshipAllByPerson($tblPerson))){ foreach($tblRelationshipToPersonList as $tblToPerson){ $this->removePersonRelationshipToPerson($tblToPerson, $IsSoftRemove); } } if (($tblRelationshipToPersonList = $this->getCompanyRelationshipAllByPerson($tblPerson))){ foreach($tblRelationshipToPersonList as $tblToPerson){ $this->removeCompanyRelationshipToPerson($tblToPerson, $IsSoftRemove); } } } }
hannesk001/SPHERE-Framework
Application/People/Relationship/Service.php
PHP
agpl-3.0
20,135
class ResetSearch025 < ActiveRecord::Migration[5.0] def change UserIndex.reset! end end
myplaceonline/myplaceonline_rails
db/migrate/20170205065206_reset_search025.rb
Ruby
agpl-3.0
96
/** * Copyright (C) 2013 The Language Archive, Max Planck Institute for * Psycholinguistics * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., 59 Temple * Place - Suite 330, Boston, MA 02111-1307, USA. */ package nl.mpi.yams.client.ui; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.text.shared.Renderer; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.HasHorizontalAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ValueListBox; import com.google.gwt.user.client.ui.VerticalPanel; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.logging.Logger; import nl.mpi.yams.client.DatabaseInformation; import nl.mpi.yams.client.controllers.HistoryController; import nl.mpi.yams.client.HistoryListener; import nl.mpi.yams.client.SearchOptionsServiceAsync; import nl.mpi.yams.client.controllers.SearchHandler; import nl.mpi.yams.common.data.QueryDataStructures.CriterionJoinType; import nl.mpi.yams.common.data.QueryDataStructures.SearchOption; import nl.mpi.yams.common.data.SearchParameters; /** * Created on : Jan 29, 2013, 2:50:44 PM * * @author Peter Withers <peter.withers@mpi.nl> */ public class SearchWidgetsPanel extends VerticalPanel implements HistoryListener { private static final Logger logger = Logger.getLogger(""); private static final String SEARCH_LABEL = "Search"; private static final String SEARCHING_LABEL = "<img src='./loader.gif'/>&nbsp;Searching"; private static final String ADD_SEARCH_TERM = "add search term"; private static final String sendButtonStyle = "sendButton"; private static final String NO_VALUE = "<no value>"; private static final String DEMO_LIST_BOX_STYLE = "demo-ListBox"; private final SearchOptionsServiceAsync searchOptionsService; private final HistoryController historyController; private String lastUsedDatabase = ""; private Button searchButton; private SearchHandler searchHandler; private final ResultsPanel resultsPanel; private final ValueListBox<CriterionJoinType> joinTypeListBox; private final VerticalPanel verticalPanel; private final ArrayList<SearchCriterionPanel> criterionPanelList = new ArrayList<SearchCriterionPanel>(); private final DatabaseInformation databaseInfo; public SearchWidgetsPanel(SearchOptionsServiceAsync searchOptionsService, final HistoryController historyController, DatabaseInformation databaseInfo, ResultsPanel resultsPanel, DataNodeTable dataNodeTable, final ArchiveBranchSelectionPanel archiveTreePanel) { this.searchOptionsService = searchOptionsService; this.historyController = historyController; this.databaseInfo = databaseInfo; this.resultsPanel = resultsPanel; verticalPanel = new VerticalPanel(); this.add(verticalPanel); initSearchHandler(); final SearchCriterionPanel searchCriterionPanel = new SearchCriterionPanel(SearchWidgetsPanel.this, searchOptionsService); if (archiveTreePanel != null) { verticalPanel.add(archiveTreePanel); historyController.addHistoryListener(archiveTreePanel); } verticalPanel.add(searchCriterionPanel); criterionPanelList.add(searchCriterionPanel); Button addRowButton = new Button(ADD_SEARCH_TERM, new ClickHandler() { public void onClick(ClickEvent event) { addSearchCriterionPanel(new SearchCriterionPanel(SearchWidgetsPanel.this, SearchWidgetsPanel.this.searchOptionsService)); } }); this.add(addRowButton); final HorizontalPanel buttonsPanel = new HorizontalPanel(); this.add(buttonsPanel); joinTypeListBox = getJoinTypeListBox(); buttonsPanel.add(joinTypeListBox); buttonsPanel.add(searchButton); this.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_RIGHT); } public void userSelectionChange() { final String databaseName = historyController.getDatabaseName(); if (databaseName != null && !databaseName.isEmpty() && !databaseName.equals(lastUsedDatabase)) { historyChange(); } } public void historyChange() { searchHandler.updateDbName(); final CriterionJoinType criterionJoinType = historyController.getCriterionJoinType(); if (criterionJoinType == null) { joinTypeListBox.setValue(CriterionJoinType.values()[0]); } else { joinTypeListBox.setValue(criterionJoinType); } final ArrayList<SearchParameters> searchParametersList = historyController.getSearchParametersList(); if (searchParametersList != null && !searchParametersList.isEmpty()) { while (searchParametersList.size() < criterionPanelList.size()) { removeSearchCriterionPanel(criterionPanelList.get(criterionPanelList.size() - 1)); } while (searchParametersList.size() > criterionPanelList.size()) { addSearchCriterionPanel(new SearchCriterionPanel(SearchWidgetsPanel.this, SearchWidgetsPanel.this.searchOptionsService)); } for (int panelIndex = 0; panelIndex < criterionPanelList.size(); panelIndex++) { final SearchParameters historyValues = searchParametersList.get(panelIndex); criterionPanelList.get(panelIndex).setDefaultValues(historyValues.getFileType(), historyValues.getFieldType(), historyValues.getSearchNegator(), historyValues.getSearchType(), historyValues.getSearchString()); } } else { while (!criterionPanelList.isEmpty()) { removeSearchCriterionPanel(criterionPanelList.get(0)); } if (historyController.getDatabaseName() != null) { final SearchCriterionPanel searchCriterionPanel = new SearchCriterionPanel(SearchWidgetsPanel.this, SearchWidgetsPanel.this.searchOptionsService); addSearchCriterionPanel(searchCriterionPanel); } } final String databaseName = historyController.getDatabaseName(); if (databaseName != null && !databaseName.isEmpty() && !databaseName.equals(lastUsedDatabase)) { lastUsedDatabase = databaseName; for (SearchCriterionPanel eventCriterionPanel : criterionPanelList) { eventCriterionPanel.setDatabase(databaseName); } } } protected void addSearchCriterionPanel(SearchCriterionPanel criterionPanel) { criterionPanelList.add(criterionPanel); verticalPanel.add(criterionPanel); if (!lastUsedDatabase.isEmpty()) { criterionPanel.setDatabase(lastUsedDatabase); } joinTypeListBox.setVisible(criterionPanelList.size() > 1); } protected void removeSearchCriterionPanel(SearchCriterionPanel criterionPanel) { criterionPanelList.remove(criterionPanel); verticalPanel.remove(criterionPanel); joinTypeListBox.setVisible(criterionPanelList.size() > 1); } private void initSearchHandler() { searchButton = new Button(SEARCH_LABEL); searchButton.addStyleName(sendButtonStyle); searchHandler = new SearchHandler(historyController, databaseInfo, searchOptionsService, resultsPanel) { @Override protected void prepareSearch() { searchButton.setEnabled(false); searchButton.setHTML(SEARCHING_LABEL); ArrayList<SearchParameters> searchParametersList = new ArrayList<SearchParameters>(); for (SearchCriterionPanel eventCriterionPanel : criterionPanelList) { //logger.info("eventCriterionPanel"); searchParametersList.add(new SearchParameters(eventCriterionPanel.getMetadataFileType(), eventCriterionPanel.getMetadataFieldType(), eventCriterionPanel.getSearchNegator(), eventCriterionPanel.getSearchType(), eventCriterionPanel.getSearchText())); } historyController.setSearchParameters(joinTypeListBox.getValue(), searchParametersList); } protected @Override void finaliseSearch() { searchButton.setEnabled(true); searchButton.setHTML(SEARCH_LABEL); } }; searchButton.addClickHandler(searchHandler); } protected ValueListBox getSearchOptionsListBox() { final ValueListBox<SearchOption> widget = new ValueListBox<SearchOption>(new Renderer<SearchOption>() { public String render(SearchOption object) { if (object == null) { return NO_VALUE; } else { return object.toString(); } } public void render(SearchOption object, Appendable appendable) throws IOException { if (object != null) { appendable.append(object.toString()); } } }); widget.addStyleName(DEMO_LIST_BOX_STYLE); widget.setValue(SearchOption.equals); widget.setAcceptableValues(Arrays.asList(SearchOption.values())); return widget; } private ValueListBox getJoinTypeListBox() { final ValueListBox<CriterionJoinType> widget = new ValueListBox<CriterionJoinType>(new Renderer<CriterionJoinType>() { public String render(CriterionJoinType object) { if (object == null) { return NO_VALUE; } else { return object.toString(); } } public void render(CriterionJoinType object, Appendable appendable) throws IOException { if (object != null) { appendable.append(object.toString()); } } }); widget.addStyleName(DEMO_LIST_BOX_STYLE); widget.setValue(CriterionJoinType.intersect); widget.setAcceptableValues(Arrays.asList(CriterionJoinType.values())); // widget.addValueChangeHandler(new ValueChangeHandler<CriterionJoinType>() { // // public void onValueChange(ValueChangeEvent<CriterionJoinType> event) { // historyController.setCriterionJoinType(event.getValue()); // } // }); return widget; } public SearchHandler getSearchHandler() { return searchHandler; } }
TheLanguageArchive/YAMS
web/src/main/java/nl/mpi/yams/client/ui/SearchWidgetsPanel.java
Java
agpl-3.0
11,217
package com.welaika.menadi.db; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Select; import java.util.ArrayList; import java.util.List; @Table(name = "RelatorsEvents") public class RelatorEvent extends Model { @Column(name = "IdR") public Integer idR; @Column(name = "Relator") public Relator relator; @Column(name = "IdEInD") public Integer idEInD; @Column(name = "EventInD") public EventInDate eventInD; public RelatorEvent() { super(); } public RelatorEvent(int idR, Relator relator, int idEInD, EventInDate eventInD) { this.idR = idR; this.relator = relator; this.idEInD = idEInD; this.eventInD = eventInD; } public static List<RelatorEvent> getEvents(int idRel) { return new Select() .from(RelatorEvent.class) .where("IdR = ?", idRel) .execute(); } public static List<Relator> getRelators(int idEventInDate) { List<RelatorEvent> list_r2e = new Select() .from(RelatorEvent.class) .where("IdEInD = ?", idEventInDate) .execute(); List<Relator> relators = new ArrayList<Relator>(); for(RelatorEvent r2e : list_r2e){ relators.add(r2e.relator); } return relators; } }
welaika/menadi
Menadi/src/main/java/com/welaika/menadi/db/RelatorEvent.java
Java
agpl-3.0
1,447
#!/usr/bin/python3 ###### Памятка по статусам ##### # OK -- сервис онлайн, обрабатывает запросы, получает и отдает флаги. # MUMBLE -- сервис онлайн, но некорректно работает # CORRUPT -- сервис онлайн, но установленные флаги невозможно получить. # DOWN -- сервис оффлайн. from sys import argv from socket import socket, AF_INET, SOCK_STREAM from string import ascii_letters from random import randint, shuffle from time import sleep from tinfoilhat import Checker, \ ServiceMumbleException, \ ServiceCorruptException, \ ServiceDownException class DummyChecker(Checker): BUFSIZE = 1024 """ Сгенерировать логин @return строка логина из 10 символов английского алфавита """ def random_login(self): symbols = list(ascii_letters) shuffle(symbols) return ''.join(symbols[0:10]) """ Сгенерировать пароль @return строка пароля из 10 цифр """ def random_password(self): return str(randint(100500**2, 100500**3))[0:10] """ Отправить логин и пароль сервису. @param sock сокет @param login логин @param password пароль """ def send_cred(self, s, login, password): s.send(login.encode('utf-8')) if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() s.send(password.encode('utf-8')) if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() """ Положить флаг в сервис @param host адрес хоста @param port порт сервиса @param flag флаг @return состояние, необходимое для получения флага """ def put(self, host, port, flag): try: s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(b'REG\n') if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() login = self.random_login() password = self.random_password() self.send_cred(s, login, password) s.close() s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(b'PUT\n') if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() self.send_cred(s, login, password) s.send(flag.encode('utf-8')) if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() return login + ":" + password except (OSError, IOError) as e: if e.errno == 111: # ConnectionRefusedError raise ServiceDownException() else: raise ServiceMumbleException() """ Получить флаг из сервиса @param host адрес хоста @param port порт сервиса @param state состояние @return флаг """ def get(self, host, port, state): login, password = state.split(':') s = socket(AF_INET, SOCK_STREAM) s.connect((host, port)) s.send(b'GET\n') if b'OK\n' != s.recv(self.BUFSIZE): raise ServiceMumbleException() try: self.send_cred(s, login, password) except ServiceMumbleException: raise ServiceCorruptException() try: flag, ret = s.recv(self.BUFSIZE).split() return flag.decode('utf-8') except ValueError: raise ServiceCorruptException() """ Проверить состояние сервиса @param host адрес хоста @param port порт сервиса """ def chk(self, host, port): # Так как сервис реализует только логику хранилища, # её и проверяем. # Это отличается от put и get тем, что происходит в один момент, # тем самым наличие данных по прошествии времени не проверяется. data = self.random_password() try: state = self.put(host, port, data) new_data = self.get(host, port, state) except (OSError, IOError) as e: if e.errno == 111: # ConnectionRefusedError raise ServiceDownException() else: raise ServiceMumbleException() if data != new_data: raise ServiceMumbleException() if __name__ == '__main__': DummyChecker(argv)
jollheef/tin_foil_hat
checker/python-api/dummy_checker.py
Python
agpl-3.0
4,904
/* * StuReSy - Student Response System * Copyright (C) 2012-2014 StuReSy-Team * * 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 sturesy.util; /** * Contains the current program version * * @author w.posdorfer * */ public class Version { public static final String CURRENTVERSION = "0.6.2"; /** * Checks if provided version is higher than currentversion * * @param version * version to be compared to current version * @return <code>true</code> if version is higher than current version */ public static boolean isHigherVersion(String version) { if (!version.matches("[0-9]*\\.[0-9]*\\.[0-9]*")) { return false; } String[] split = version.split("\\."); String[] current = CURRENTVERSION.split("\\."); for (int i = 0; i < current.length; i++) { int s = Integer.parseInt(split[i]); int c = Integer.parseInt(current[i]); if (s > c) { return true; } else if (s < c) { return false; } // else continue; } return false; } }
sturesy/client
src/src-main/sturesy/util/Version.java
Java
agpl-3.0
1,852
<? /** * Nooku Framework - http://www.nooku.org * * @copyright Copyright (C) 2011 - 2017 Johan Janssens and Timble CVBA. (http://www.timble.net) * @license GNU AGPLv3 <https://www.gnu.org/licenses/agpl.html> * @link https://github.com/timble/openpolice-platform */ ?> <div class="scopebar"> <div class="scopebar__group"> <a class="<?= is_null($state->published) ? 'active' : ''; ?>" href="<?= route('published=' ) ?>"> <?= translate('All') ?> </a> </div> <div class="scopebar__group"> <a class="<?= $state->published === true ? 'active' : ''; ?>" href="<?= route($state->published === true ? 'published=' : 'published=1') ?>"> <?= translate('Published') ?> </a> <a class="<?= $state->published === false ? 'active' : ''; ?>" href="<?= route($state->published === false ? 'published=' : 'published=0' ) ?>"> <?= translate('Unpublished') ?> </a> </div> <div class="scopebar__group"> <a class="<?= $state->access === true ? 'active' : ''; ?>" href="<?= route($state->access === true ? 'access=' : 'access=1' ) ?>"> <?= 'Registered' ?> </a> </div> <div class="scopebar__search"> <?= helper('grid.search') ?> </div> </div>
timble/openpolice-platform
application/admin/component/categories/view/categories/templates/default_scopebar.html.php
PHP
agpl-3.0
1,269
# Fat Free CRM # Copyright (C) 2008-2011 by Michael Dvorkin # # 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/>. #------------------------------------------------------------------------------ class DatePairInput < SimpleForm::Inputs::Base # Output two date fields: start and end #------------------------------------------------------------------------------ def input add_autocomplete! out = "<br />".html_safe field1, field2 = get_fields [field1, field2].compact.each do |field| out << '<div>'.html_safe label = field==field1 ? I18n.t('pair.start') : I18n.t('pair.end') [:required, :disabled].each {|k| input_html_options.delete(k)} # ensure these come from field not default options input_html_options.merge!(field.input_options) input_html_options.merge!(:value => value(field)) out << "<label#{' class="req"' if input_html_options[:required]}>#{label}</label>".html_safe text = @builder.text_field(field.name, input_html_options) out << text << '</div>'.html_safe end out end private # Returns true if either field is required? #------------------------------------------------------------------------------ def required_field? get_fields.map(&:required).any? end # Turns autocomplete off unless told otherwise. #------------------------------------------------------------------------------ def add_autocomplete! input_html_options[:autocomplete] ||= 'off' end # Datepicker latches onto the 'date' class. #------------------------------------------------------------------------------ def input_html_classes super.push('date') end # Returns the pair as [field1, field2] #------------------------------------------------------------------------------ def get_fields @field1 ||= Field.where(:name => attribute_name).first @field2 ||= @field1.try(:paired_with) [@field1, @field2] end # Serialize into a value recognised by datepicker #------------------------------------------------------------------------------ def value(field) val = object.send(field.name) val.present? ? val.strftime('%Y-%m-%d') : nil end end
nazeels/fat_free
app/inputs/date_pair_input.rb
Ruby
agpl-3.0
2,789
package edu.arizona.kfs.sys.dataaccess.impl; import java.util.HashMap; import java.util.Map; import org.kuali.kfs.coreservice.framework.parameter.ParameterService; import edu.arizona.kfs.sys.batch.BuildingImportStep; import edu.arizona.kfs.sys.dataaccess.BuildingAndRoomImportsDao; public class BuildingAndRoomImportsDaoOjb implements BuildingAndRoomImportsDao { private ParameterService parameterService; public void setParameterService(ParameterService parameterService) { this.parameterService = parameterService; } // Returns a list of routeCodes with their respective campusCode public Map<String, String> PopulateRoutecodeToCampusCodeMap() { Map<String, String> routecodeToCampuscodeMap = new HashMap<String, String>(); String[] keyPairs = parameterService.getParameterValueAsString(BuildingImportStep.class, "ROUTE_CODE_BY_CAMPUS_CODE").split(";"); for (String keyValues : keyPairs) { String[] tokens = keyValues.split("="); String campusCode = tokens[0]; String values = tokens[1]; String[] valueTokens = values.split(","); for (String routeCode : valueTokens) { routecodeToCampuscodeMap.put(routeCode, campusCode); } } return routecodeToCampuscodeMap; } }
quikkian-ua-devops/will-financials
kfs-core/src/main/java/edu/arizona/kfs/sys/dataaccess/impl/BuildingAndRoomImportsDaoOjb.java
Java
agpl-3.0
1,215
from django.db import models from submissions.models.utils import strip_punc from django.contrib.auth.models import User from submissions.models.album import Album from django.contrib.contenttypes.models import ContentType class Track(models.Model): """ A single track(song) for an album. """ URL_CHOICES = ( ('download', 'download'), ('stream','stream'), ('buy','buy'), ) title = models.CharField(max_length=255) cleaned_name = models.CharField(max_length=255, blank=True, null=True, editable=False, help_text="A cleaned name without punctuation or weird stuff.") track_number = models.IntegerField(blank=True, null=True) #Replace by regexfield r'[0-9:]+' in forms duration = models.CharField(max_length=255, blank=True, null=True) url = models.URLField('URL', blank=True, null=True) url_type = models.CharField('Type', max_length=255, choices=URL_CHOICES, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) uploader = models.ForeignKey(User, blank=True, null=True, help_text="The uploader of this track.") album = models.ForeignKey(Album, related_name="tracks", help_text="The album to which this track belongs.") mbid = models.CharField(max_length=255, blank=True, null=True) class Meta: app_label = "submissions" ordering = ('track_number', 'title') def __unicode__(self): return self.title @models.permalink def get_absolute_url(self): return ('album-detail', (), {'artist': self.album.artist.slug, 'album': self.album.slug }) def save(self, *args, **kwargs): if not self.cleaned_name: self.cleaned_name = strip_punc(self.title) super(Track, self).save(*args, **kwargs)
tsoporan/tehorng
submissions/models/track.py
Python
agpl-3.0
1,835
import { Pipe, PipeTransform } from '@angular/core'; import { AppLocalization } from '@kaltura-ng/mc-shared'; import { KalturaMediaType } from 'kaltura-ngx-client'; import { KalturaMediaEntry } from 'kaltura-ngx-client'; import { KalturaExternalMediaEntry } from 'kaltura-ngx-client'; @Pipe({ name: 'entryDuration' }) export class EntryDurationPipe implements PipeTransform { constructor(private appLocalization: AppLocalization) { } transform(value: string, entry: KalturaMediaEntry = null): string { let duration = value; if (entry && entry instanceof KalturaExternalMediaEntry && !entry.duration) { duration = this.appLocalization.get('app.common.n_a'); } else if (entry && entry instanceof KalturaMediaEntry && entry.mediaType) { const type = entry.mediaType.toString(); if (type === KalturaMediaType.liveStreamFlash.toString() || type === KalturaMediaType.liveStreamQuicktime.toString() || type === KalturaMediaType.liveStreamRealMedia.toString() || type === KalturaMediaType.liveStreamWindowsMedia.toString() ) { duration = this.appLocalization.get('app.common.n_a'); } } return duration; } }
kaltura/kmc-ng
src/shared/content-shared/entries/pipes/entry-duration.pipe.ts
TypeScript
agpl-3.0
1,191
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Deck' db.create_table(u'djecks_anki_deck', ( (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('title', self.gf('django.db.models.fields.CharField')(max_length=255, blank=True)), ('description', self.gf('django.db.models.fields.TextField')(blank=True)), ('apkg', self.gf('django.db.models.fields.files.FileField')(max_length=100, blank=True)), )) db.send_create_signal(u'djecks_anki', ['Deck']) def backwards(self, orm): # Deleting model 'Deck' db.delete_table(u'djecks_anki_deck') models = { u'djecks_anki.deck': { 'Meta': {'object_name': 'Deck'}, 'apkg': ('django.db.models.fields.files.FileField', [], {'max_length': '100', 'blank': 'True'}), 'description': ('django.db.models.fields.TextField', [], {'blank': 'True'}), u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}), 'title': ('django.db.models.fields.CharField', [], {'max_length': '255', 'blank': 'True'}) } } complete_apps = ['djecks_anki']
bdunnette/djecks_anki
migrations/0002_auto__add_deck.py
Python
agpl-3.0
1,388
<?php # FFMPEG SETTING 404_pal $vb = '960k'; # video rate kbs $s = '540x404'; # scale $g = 75; # keyframes interval (gob) $vcodec = 'libx264'; # default libx264 $progresivo = "-vf yadif"; # desentrelazar $gamma_y = "0.97"; # correccion de luminancia $gamma_u = "1.01"; # correccion de B-y $gamma_v = "0.98"; # correccion de R-y $gammma = "-vf lutyuv=\"u=gammaval($gamma_u):v=gammaval($gamma_v):y=gammaval($gamma_y)\""; # corrección de gamma $force = 'mp4'; # default mp4 $ar = 44100; # audio sample rate (22050) $ab = '64k'; # adio rate kbs $ac = "1"; # numero de canales de audio 2 = stereo, 1 = nomo $acodec = 'libvo_aacenc'; # default libvo_aacenc $target_path = "404"; # like '404' ?>
renderpci/dedalo-4
lib/dedalo/media_engine/lib/ffmpeg_settings/404_pal_4x3.php
PHP
agpl-3.0
752
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.calcium.system; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import org.apache.log4j.Logger; import org.objectweb.proactive.core.util.log.Loggers; import org.objectweb.proactive.core.util.log.ProActiveLogger; import org.objectweb.proactive.extensions.calcium.environment.FileServerClient; import org.objectweb.proactive.extensions.calcium.environment.StoredFile; import org.objectweb.proactive.extensions.calcium.statistics.Timer; /** * This class is a Proxy for the real File class. * * @author The ProActive Team */ public class ProxyFile extends File { private static final long serialVersionUID = 54L; static Logger logger = ProActiveLogger.getLogger(Loggers.SKELETONS_SYSTEM); File wspace; public File relative; File current; //current = wspace+"/"+relative StoredFile remote; FileServerClient fserver; long lastmodified; long cachedSize; public long blockedFetchingTime; public long downloadedBytes; public long uploadedBytes; public int refCBefore; public int refCAfter; public ProxyFile(File wspace, File relative) { super(relative.getName()); this.current = new File(wspace, relative.getPath()); this.relative = relative; this.remote = null; setWSpace(null, wspace); this.lastmodified = this.cachedSize = 0; this.blockedFetchingTime = this.uploadedBytes = this.downloadedBytes = 0; this.refCBefore = this.refCAfter = 0; } public ProxyFile(File wspace, String name) { this(wspace, new File(name)); } public void setWSpace(FileServerClient fserver, File wspace) { this.fserver = fserver; this.wspace = wspace; } public void store(FileServerClient fserver, int refCount) throws IOException { this.cachedSize = current.length(); this.uploadedBytes += current.length(); this.remote = fserver.store(current, refCount); this.lastmodified = current.lastModified(); } public void saveRemoteDataInWSpace() throws IOException { int i = 1; if (isLocallyStored()) { return; //Nothing to do, data already donwloaded } current = new File(wspace, relative.getPath()); while (current.exists()) { current = new File(wspace, relative.getPath() + "-" + i++); } if (logger.isDebugEnabled()) { logger.debug("Fetching data into:" + this.current); } fserver.fetch(remote, this.current); this.lastmodified = this.current.lastModified(); this.downloadedBytes += current.length(); } public boolean isRemotelyStored() { return remote != null; } public boolean isLocallyStored() { return current != null; } public boolean hasBeenModified() { /* TODO improve by: * * 1. Also considering the hashcode. * 2. Keeping track of lastModified access. */ if (current == null) { return false; } return lastmodified != current.lastModified(); } public void handleStageOut(FileServerClient fserver) throws IOException { if (isNew()) { if (logger.isDebugEnabled()) { logger.debug("Storing new file: [" + refCBefore + "," + refCAfter + "] " + relative + " (" + current + ")"); } store(fserver, refCAfter); return; } if (isModified()) { if (logger.isDebugEnabled()) { logger.debug("Storing modified file: [" + refCBefore + "," + refCAfter + "] " + relative + " (" + current + ")"); } fserver.commit(remote.fileId, -refCBefore); store(fserver, refCAfter); return; } if (isNormal()) { //&& (refCAfter - refCBefore !=0)){ if (logger.isDebugEnabled()) { logger.debug("Updating normal file: [" + refCBefore + "," + refCAfter + "] " + "name=" + relative + " id=" + remote.fileId + " (" + current + ")"); } fserver.commit(remote.fileId, refCAfter - refCBefore); return; } logger.error("Illegal ProxyFile state: " + refCAfter + "a " + refCBefore + "b" + " data modified=" + hasBeenModified()); //Reached here, not good! throw new IOException("ProxyFile reached illegal state:" + this); } public void setStageOutState() { this.current = null; this.wspace = null; this.fserver = null; this.blockedFetchingTime = this.uploadedBytes = this.downloadedBytes = 0; this.refCBefore = this.refCAfter = 0; } private boolean isNew() { return (this.refCBefore == 0) && (this.refCAfter != 0); } private boolean isNormal() { return (this.refCBefore != 0) && !hasBeenModified(); } private boolean isModified() { return (this.refCBefore != 0) && (this.refCAfter != 0) && hasBeenModified(); } public File getWSpaceFile() { return wspace; } public File getCurrent() { if (current == null) { Timer t = new Timer(); t.start(); logger.debug("Blocking waiting for file's data:" + wspace + "/" + relative); /* try{ throw new Exception(); }catch(Exception e){ e.printStackTrace(); } */ try { saveRemoteDataInWSpace(); } catch (IOException e) { throw new IllegalArgumentException(e); //TODO change this exception type } t.stop(); this.blockedFetchingTime = 1 + t.getTime(); } return current; } /* *********************************************************** * * BEGIN EXTENDED FILE METHODS * * ***********************************************************/ @Override public String getName() { return relative.getName(); } @Override public String getParent() { return getCurrent().getParent(); } @Override public File getParentFile() { return getCurrent().getParentFile(); } @Override public String getPath() { return getCurrent().getPath(); } @Override public boolean isAbsolute() { return getCurrent().isAbsolute(); } @Override public String getAbsolutePath() { return getCurrent().getAbsolutePath(); } @Override public File getAbsoluteFile() { return getCurrent().getAbsoluteFile(); } @Override public String getCanonicalPath() throws IOException { return getCurrent().getCanonicalPath(); } @Override public File getCanonicalFile() throws IOException { return getCurrent().getCanonicalFile(); } @Deprecated @Override public URL toURL() throws MalformedURLException { return getCurrent().toURL(); } @Override public URI toURI() { return getCurrent().toURI(); } @Override public boolean canRead() { return getCurrent().canRead(); } @Override public boolean canWrite() { return getCurrent().canWrite(); } @Override public boolean exists() { return getCurrent().exists(); } @Override public boolean isDirectory() { return getCurrent().isDirectory(); } @Override public boolean isFile() { return getCurrent().isFile(); } @Override public boolean isHidden() { return getCurrent().isHidden(); } @Override public long lastModified() { return getCurrent().lastModified(); } @Override public long length() { if (!isLocallyStored()) { return cachedSize; } return getCurrent().length(); } @Override public boolean createNewFile() throws IOException { return getCurrent().createNewFile(); } @Override public boolean delete() { return getCurrent().delete(); } @Override public void deleteOnExit() { getCurrent().deleteOnExit(); } @Override public String[] list() { return getCurrent().list(); } @Override public String[] list(FilenameFilter filter) { return getCurrent().list(); } @Override public File[] listFiles() { return getCurrent().listFiles(); } @Override public File[] listFiles(FilenameFilter filter) { return getCurrent().listFiles(filter); } @Override public File[] listFiles(FileFilter filter) { return getCurrent().listFiles(filter); } @Override public boolean mkdir() { return getCurrent().mkdir(); } @Override public boolean mkdirs() { return getCurrent().mkdirs(); } @Override public boolean renameTo(File dest) { //TODO check this method boolean res = getCurrent().renameTo(new File(wspace, dest.getPath())); if (res) { relative = dest; } return res; } @Override public boolean setLastModified(long time) { return getCurrent().setLastModified(time); } @Override public boolean setReadOnly() { return getCurrent().setReadOnly(); } @Override public int compareTo(File pathname) { return getCurrent().compareTo(pathname); } @Override public boolean equals(Object obj) { return getCurrent().equals(obj); } @Override public int hashCode() { return getCurrent().hashCode(); } @Override public String toString() { return getCurrent().toString(); } public static void main(String[] args) throws Exception { WSpaceImpl wspace = new WSpaceImpl(new File("/tmp/calcium")); File f = wspace.copyInto(new File("/home/mleyton/IMG00070.jpg")); } }
nmpgaspar/PainlessProActive
src/Extensions/org/objectweb/proactive/extensions/calcium/system/ProxyFile.java
Java
agpl-3.0
11,732
from bottle import request class BottleHelper: """map Apify methods to Bottle magic and other helpers""" def __init__(self, app): self.app = app def route(self, path, function, methods=['GET']): self.app.route(path, method=methods, callback=function) def request(self, items=None): if request.json is not None: datas = request.json else: if hasattr(request, 'params'): datas = request.params.dict else: return None if items is None: return datas elif isinstance(items, list): ret = {} for i in items: data = datas.get(i) ret[i] = data return ret else: return datas.get(items)
abondis/api-hi
api_hi/helpers/bottle.py
Python
agpl-3.0
816
<?php namespace Minds\Core\Payments\Stripe\Customers; use Minds\Core\Di\Di; use Minds\Core\Payments\Stripe\Instances\CustomerInstance; use Minds\Core\Payments\Stripe\Instances\PaymentMethodInstance; class Manager { /** @var Lookup $lookup */ private $lookup; private $customerInstance; private $paymentMethodInstance; public function __construct($lookup = null, $customerInstance = null, $paymentMethodInstance = null) { $this->lookup = $lookup ?: Di::_()->get('Database\Cassandra\Lookup'); $this->customerInstance = $customerInstance ?? new CustomerInstance(); $this->paymentMethodInstance = $paymentMethodInstance ?? new PaymentMethodInstance(); } /** * Return a Customer from user guid * @param string $userGuid * @return Customer */ public function getFromUserGuid($userGuid): ?Customer { $customerId = $this->lookup->get("{$userGuid}:payments")['customer_id']; if (!$customerId) { return null; } $stripeCustomer = \Stripe\Customer::retrieve($customerId); if (!$stripeCustomer) { return null; } $customer = new Customer(); $customer->setPaymentSource($stripeCustomer->default_source) ->setUserGuid($userGuid) ->setId($customerId); return $customer; } /** * Add a customer to stripe * @param Customer $customer * @return boolean */ public function add(Customer $customer) : Customer { $stripeCustomer = $this->customerInstance->create([ 'payment_method' => $customer->getPaymentMethod(), ]); $this->lookup->set("{$customer->getUserGuid()}:payments", [ 'customer_id' => (string) $stripeCustomer->id ]); $customer->setId($stripeCustomer->id); return $customer; } }
Minds/engine
Core/Payments/Stripe/Customers/Manager.php
PHP
agpl-3.0
1,899
import mongoose from 'mongoose'; import Boom from 'boom'; import Bounce from 'bounce'; import { log, logErr } from '../../shared/utils'; import eventStore from '../stores/eventStore'; import alertStore from '../stores/alertStore'; import userStore from '../stores/userStore'; const ObjectId = mongoose.Types.ObjectId; const alertController = { async createAlert(req, h) { let alert = null; let user; let payloadEvent; try { if (!ObjectId.isValid(req.payload.event)) throw new Error("Event ID is not valid."); payloadEvent = await eventStore.getEvent(req.payload.event); if (!payloadEvent) throw new Error("Event not found."); if (req.payload && req.payload["sent.by"]) { if (!ObjectId.isValid(req.payload["sent.by"])) throw new Error("Sent by user ID is not valid."); user = await userStore.getUser(ObjectId(req.payload["sent.by"])); if (!user) throw new Error("Sent by user not found."); } const newLoad = { ...payloadEvent.toObject(), // TO-DO: add parser with string formatting type: payloadEvent.type.toString(), event: ObjectId(req.payload.event), sent: { by: (req.payload["sent.by"]) ? req.payload["sent.by"] : null, at: Date.now() } }; delete newLoad["id"]; alert = await alertStore.createAlert(newLoad); if (!alert) throw new Error("Alert returned empty."); const response = h.response(alert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController createAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error creating alert."); } }, async updateAlert(req, h) { // updateAlert just sets expireNow to true let alert; let updatedAlert; try { alert = await alertStore.updateAlert(req.params.alertID); if (!alert) throw new Error("Alert not found."); updatedAlert = await alertStore.getAlert(alert.id); const response = h.response(updatedAlert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController updateAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error updating alert."); } }, async getAlerts(req, h) { // only fetches unexpired alerts let alerts; try { alerts = await alertStore.getAlerts(); if (!alerts) throw new Error("No alerts found."); const response = h.response(alerts); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAlerts error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alerts."); } }, async getAlert(req, h) { let alert; try { alert = await alertStore.getAlert(ObjectId(req.params.alertID)); if (!alert) throw new Error("Alert not found."); const response = h.response(alert); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAlert error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alert."); } }, async getAllAlerts(req, h) { let alerts; try { alerts = await alertStore.getAllAlerts(); if (!alerts) throw new Error("No alerts found."); const response = h.response(alerts); return response; } catch (err) { if (Bounce.isSystem(err)) logErr("alertController getAllAlerts error: ", err.message || err); return Boom.badRequest(err.message || "Error retrieving alerts."); } }, }; export default alertController;
Cosecha/redadalertas-api
src/server/app/api/controllers/alertController.js
JavaScript
agpl-3.0
3,644
namespace IntranetGJAK.Models { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using IntranetGJAK.Models.JSON.Blueimp_FileUpload; using IntranetGJAK; public class File { [Key] [Required] public string Id { get; set; } [Required] [Display(Name = "Název souboru")] public string Name { get; set; } [Required] public string Path { get; set; } [Required] [Display(Name = "Velikost")] public long Size { get; set; } [Required] [Display(Name = "Odesílatel")] public string Uploader { get; set; } [Required] [Display(Name = "Datum")] public DateTime DateUploaded { get; set; } public UploadSucceeded ToSerializeable() { return new UploadSucceeded { name = this.Name, size = this.Size, url = "/api/files/" + this.Id, thumbnailUrl = Thumbnails.GetThumbnail(this.Name), deleteUrl = "/api/files/" + this.Id, deleteType = "DELETE" }; } } public interface IFileRepository { void Add(File item); IEnumerable<File> GetAll(); File Find(string key); File Remove(string key); void Update(File item); } public class FileRepository : IFileRepository { private static ConcurrentDictionary<string, File> _Files = new ConcurrentDictionary<string, File>(); public FileRepository() { } public IEnumerable<File> GetAll() { return _Files.Values; } public void Add(File item) { item.Id = Guid.NewGuid().ToString(); _Files[item.Id] = item; } public File Find(string key) { File item; _Files.TryGetValue(key, out item); return item; } public File Remove(string key) { File item; _Files.TryGetValue(key, out item); _Files.TryRemove(key, out item); return item; } public void Update(File item) { _Files[item.Id] = item; } } }
j2ghz/IntranetGJAK
IntranetGJAK/Models/File.cs
C#
agpl-3.0
2,432
from django.core.management.base import BaseCommand, CommandError from voty.initproc.models import Quorum, IssueSupportersQuorum, IssueVotersQuorum from django.contrib.auth import get_user_model from django.utils import timezone from datetime import date from math import ceil """ - Bis 99 Abstimmungsberechtigten 10 Personen - ab 100 bis 299 Abstimmungsberechtigten 15 Personen - ab 300 bis 599 Abstimmungsberechtigten 20 Personen - ab 600 bis 999 Abstimmungsberechtigten 30 Personen - ab 1000 bis 1999 Abstimmungsberechtigten 35 Personen - ab 2000 bis 4999 Abstimmungsberechtigten 50 Personen - ab 5000 Abstimmungsberechtigten 1% der Abstimmungsberechtigten """ class Command(BaseCommand): help = "Calculate the next quorum and set it" def handle(self, *args, **options): now = timezone.now() year = now.year month = now.month # round to turn of month if now.day > 15: month += 1 month -= 6 if month < 1: year -= 1 month += 12 threshold = timezone.datetime(year=year, month=month, day=1, tzinfo=now.tzinfo) total = get_user_model().objects.filter(is_active=True, config__last_activity__gt=threshold).count() totalpartymembers = get_user_model().objects.filter(is_active=True, config__is_party_member=True, config__last_activity__gt=threshold).count() print("Total active users: {}".format(total)) print("Total active party members: {}".format(totalpartymembers)) #Quorum for Issue Support quorum = ceil(total / 20.0) if quorum < 5: quorum = 5 IssueSupportersQuorum(value=quorum).save() print("Issue Support Quorum set to {}".format(quorum)) #Quorum for Issue Voting quorum = ceil(totalpartymembers / 10.0) if quorum < 5: quorum = 5 #commented out because it is now set manually, 10% of all party members, not only of those who have a login or are active in Plenum #IssueVotersQuorum(value=quorum).save() #print("Issue Voting Quorum set to {}".format(quorum)) quorum = ceil(total / 100.0) if total < 100: quorum = 10 elif total < 300: quorum = 15 elif total < 600: quorum = 20 elif total < 1000: quorum = 30 elif total < 2000: quorum = 35 elif total < 5000: quorum = 50 Quorum(quorum=quorum).save() print("Initiatives Quorum set to {}".format(quorum))
DemokratieInBewegung/abstimmungstool
voty/initproc/management/commands/set_quorum.py
Python
agpl-3.0
2,590
/* * Axelor Business Solutions * * Copyright (C) 2019 Axelor (<http://axelor.com>). * * 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/>. */ package com.axelor.apps.bankpayment.db.repo; import com.axelor.apps.account.db.Move; import com.axelor.apps.account.db.MoveLine; import com.axelor.apps.account.db.repo.MoveManagementRepository; import java.math.BigDecimal; import java.util.List; public class MoveBankPaymentRepository extends MoveManagementRepository { @Override public Move copy(Move entity, boolean deep) { Move copy = super.copy(entity, deep); List<MoveLine> moveLineList = copy.getMoveLineList(); if (moveLineList != null) { moveLineList.forEach(moveLine -> moveLine.setBankReconciledAmount(BigDecimal.ZERO)); } return copy; } }
ama-axelor/axelor-business-suite
axelor-bank-payment/src/main/java/com/axelor/apps/bankpayment/db/repo/MoveBankPaymentRepository.java
Java
agpl-3.0
1,337
<?php declare(strict_types=1); /** * @author Nicolas CARPi <nico-git@deltablot.email> * @copyright 2012 Nicolas CARPi * @see https://www.elabftw.net Official website * @license AGPL-3.0 * @package elabftw */ namespace Elabftw\Services; use function dirname; use Elabftw\Exceptions\DatabaseErrorException; use Elabftw\Exceptions\FilesystemErrorException; use League\Flysystem\Adapter\Local; use League\Flysystem\Filesystem; /** * This is used to find out if there are untracked files that should have been deleted * but were not deleted because of a bug fixed in 2.0.7 */ require_once dirname(__DIR__, 2) . '/vendor/autoload.php'; require_once dirname(__DIR__, 2) . '/config.php'; try { $uploadsDir = dirname(__DIR__, 2) . '/uploads'; $UploadsCleaner = new UploadsCleaner(new Filesystem(new Local($uploadsDir))); $deleted = $UploadsCleaner->cleanup(); printf("Deleted %d files\n", $deleted); } catch (FilesystemErrorException | DatabaseErrorException $e) { echo $e->getMessage(); }
elabftw/elabftw
src/tools/cleanup.php
PHP
agpl-3.0
1,014
package mkl.testarea.itext5.content; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.junit.BeforeClass; import org.junit.Test; import com.itextpdf.text.BaseColor; import com.itextpdf.text.Chunk; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Font.FontFamily; import com.itextpdf.text.Phrase; import com.itextpdf.text.pdf.PdfPCell; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfWriter; /** * @author mkl */ public class CellsWithPercentileBackground { final static File RESULT_FOLDER = new File("target/test-outputs", "content"); @BeforeClass public static void setUpBeforeClass() throws Exception { RESULT_FOLDER.mkdirs(); } /** * <a href="https://stackoverflow.com/questions/46869670/itext-5-create-pdfpcell-containing-2-background-colors-with-text-overlap"> * iText 5: create PdfPcell containing 2 background colors with text overlap * </a> * <p> * This test creates a table with cells that have backgrounds * which represent percentile values. To do so it makes use of the * {@link PercentileCellBackground} cell event listener. * </p> * * @author mkl */ @Test public void testCreateTableWithCellsWithPercentileBackground() throws DocumentException, IOException { Document document = new Document(); try (OutputStream os = new FileOutputStream(new File(RESULT_FOLDER, "TableWithCellsWithPercentileBackground.pdf"))) { PdfWriter.getInstance(document, os); document.open(); Font font = new Font(FontFamily.UNDEFINED, Font.UNDEFINED, Font.UNDEFINED, BaseColor.WHITE); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(40); PdfPCell cell = new PdfPCell(new Phrase("Group A")); table.addCell(cell); cell = new PdfPCell(new Phrase(new Chunk("60 Pass, 40 Fail", font))); cell.setCellEvent(new PercentileCellBackground(60, BaseColor.GREEN, BaseColor.RED)); table.addCell(cell); cell = new PdfPCell(new Phrase("Group B")); table.addCell(cell); cell = new PdfPCell(new Phrase(new Chunk("70 Pass, 30 Fail", font))); cell.setCellEvent(new PercentileCellBackground(70, BaseColor.GREEN, BaseColor.RED)); table.addCell(cell); cell = new PdfPCell(new Phrase("Group C")); table.addCell(cell); cell = new PdfPCell(new Phrase(new Chunk("50 Pass, 50 Fail", font))); cell.setCellEvent(new PercentileCellBackground(50, BaseColor.GREEN, BaseColor.RED)); table.addCell(cell); document.add(table); document.close(); } } }
mkl-public/testarea-itext5
src/test/java/mkl/testarea/itext5/content/CellsWithPercentileBackground.java
Java
agpl-3.0
2,894
using Pathfindax.Nodes; namespace Pathfindax.Factories { public class NodeGridCollisionMask { public int Width { get; private set; } public int Height { get; private set; } public NodeGridCollisionLayer[] Layers { get; private set; } public NodeGridCollisionMask(PathfindaxCollisionCategory collisionCategory, int width, int height) { Initialize(new []{collisionCategory}, width, height); } public NodeGridCollisionMask(PathfindaxCollisionCategory[] collisionCategories, int width, int height) { Initialize(collisionCategories, width, height); } private void Initialize(PathfindaxCollisionCategory[] collisionCategories, int width, int height) { Width = width; Height = height; Layers = new NodeGridCollisionLayer[collisionCategories.Length]; for (int i = 0; i < Layers.Length; i++) { Layers[i] = new NodeGridCollisionLayer(collisionCategories[i], width, height); } } } }
Barsonax/Pathfindax
src/Pathfindax/Factories/NodeGridCollisionMask.cs
C#
agpl-3.0
933
package main import ( "github.com/datatogether/api/apiutil" "github.com/datatogether/core" "net/http" ) func CollectionHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "OPTIONS": EmptyOkHandler(w, r) case "GET": GetCollectionHandler(w, r) default: NotFoundHandler(w, r) } } func CollectionsHandler(w http.ResponseWriter, r *http.Request) { switch r.Method { case "GET": ListCollectionsHandler(w, r) default: NotFoundHandler(w, r) } } func GetCollectionHandler(w http.ResponseWriter, r *http.Request) { res := &core.Collection{} args := &CollectionsGetParams{ Id: r.URL.Path[len("/collections/"):], // Collection: r.FormValue("collection"), // Hash: r.FormValue("hash"), } err := new(Collections).Get(args, res) if err != nil { apiutil.WriteErrResponse(w, http.StatusInternalServerError, err) return } apiutil.WriteResponse(w, res) } func ListCollectionsHandler(w http.ResponseWriter, r *http.Request) { p := apiutil.PageFromRequest(r) res := make([]*core.Collection, p.Size) args := &CollectionsListParams{ Limit: p.Limit(), Offset: p.Offset(), OrderBy: "created", } err := new(Collections).List(args, &res) if err != nil { apiutil.WriteErrResponse(w, http.StatusInternalServerError, err) return } apiutil.WritePageResponse(w, res, r, p) }
archivers-space/archivers-api
collection_handlers.go
GO
agpl-3.0
1,335
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.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/. */ package com.rapidminer.gui.viewer; import com.rapidminer.operator.visualization.dependencies.ANOVAMatrix; import com.rapidminer.tools.Tools; import javax.swing.table.AbstractTableModel; /** * The model for the {@link com.rapidminer.gui.viewer.ANOVAMatrixViewerTable}. * * @author Ingo Mierswa */ public class ANOVAMatrixViewerTableModel extends AbstractTableModel { private static final long serialVersionUID = -5732155307505605893L; private ANOVAMatrix matrix; /** * Instantiates a new Anova matrix viewer table model. * * @param matrix the matrix */ public ANOVAMatrixViewerTableModel(ANOVAMatrix matrix) { this.matrix = matrix; } @Override public int getRowCount() { return matrix.getAnovaAttributeNames().size(); } @Override public int getColumnCount() { return matrix.getGroupingAttributeNames().size() + 1; } @Override public String getColumnName(int col) { if (col == 0) { return "ANOVA Attribute"; } else { return "group " + matrix.getGroupingAttributeNames().get(col - 1); } } @Override public Object getValueAt(int row, int col) { if (col == 0) { return matrix.getAnovaAttributeNames().get(row); } else { return Tools.formatNumber(matrix.getProbabilities()[row][col - 1]); } } }
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/gui/viewer/ANOVAMatrixViewerTableModel.java
Java
agpl-3.0
2,174
import ENV from 'irene/config/environment'; class ENVHandler { constructor(envHandlerConst) { this.envHandlerConst = envHandlerConst; } isRuntimeAvailable() { return !(typeof runtimeGlobalConfig == 'undefined'); } getEnv(env_key) { const host_key = 'IRENE_API_HOST'; this.assertEnvKey(env_key); if (this.isAvailableInRuntimeENV(env_key)) { const runtimeValue = this.getRuntimeObject()[env_key]; if (env_key === host_key) { if (runtimeValue === '/') { return ''; } } return runtimeValue; } if (this.isAvailableInProcessENV(env_key)) { const processValue = this.envHandlerConst.processENV[env_key]; if (env_key === host_key) { if (processValue === '/') { return ''; } } return processValue; } return this.getDefault(env_key); } isRegisteredEnv(env_key) { return this.envHandlerConst.possibleENVS.indexOf(env_key) > -1; } isAvailableInENV(env_key) { return ( this.isAvailableInRuntimeENV(env_key) || this.isAvailableInProcessENV(env_key) ); } getRuntimeObject() { if (this.isRuntimeAvailable()) { return runtimeGlobalConfig; // eslint-disable-line } return {}; } isAvailableInRuntimeENV(env_key) { const runtimeObj = this.getRuntimeObject(); return env_key in runtimeObj; } isAvailableInProcessENV(env_key) { return env_key in this.envHandlerConst.processENV; } assertEnvKey(env_key) { if (!this.isRegisteredEnv(env_key)) { throw new Error(`ENV: ${env_key} not registered`); } } isTrue(value) { value = String(value).toLowerCase(); return value === 'true'; } getBoolean(env_key) { return this.isTrue(this.getEnv(env_key)); } getDefault(env_key) { this.assertEnvKey(env_key); return this.envHandlerConst.defaults[env_key]; } getValueForPlugin(env_key) { const enterpriseKey = 'ENTERPRISE'; this.assertEnvKey(enterpriseKey); this.assertEnvKey(env_key); if (this.isAvailableInENV(env_key)) { return this.getBoolean(env_key); } if (this.isAvailableInENV(enterpriseKey)) { return !this.getBoolean(enterpriseKey); } return this.getDefault(env_key); } } const handler = new ENVHandler(ENV.ENVHandlerCONST); const initialize = function (application) { // inject Ajax application.inject('route', 'ajax', 'service:ajax'); application.inject('component', 'ajax', 'service:ajax'); // Inject notify application.inject('route', 'notify', 'service:notifications'); application.inject('component', 'notify', 'service:notifications'); application.inject('authenticator', 'notify', 'service:notifications'); // Inject realtime application.inject('component', 'realtime', 'service:realtime'); // Inject Store application.inject('component', 'store', 'service:store'); ENV.host = handler.getEnv('IRENE_API_HOST'); ENV.devicefarmHost = handler.getEnv('IRENE_DEVICEFARM_HOST'); ENV.isEnterprise = handler.getBoolean('ENTERPRISE'); ENV.showLicense = handler.getBoolean('IRENE_SHOW_LICENSE'); ENV.whitelabel = Object.assign({}, ENV.whitelabel, { enabled: handler.getBoolean('WHITELABEL_ENABLED'), }); if (ENV.whitelabel.enabled) { ENV.whitelabel = Object.assign({}, ENV.whitelabel, { enabled: handler.getBoolean('WHITELABEL_ENABLED'), // adding for consistency name: handler.getEnv('WHITELABEL_NAME'), logo: handler.getEnv('WHITELABEL_LOGO'), theme: handler.getEnv('WHITELABEL_THEME'), favicon: handler.getEnv('WHITELABEL_FAVICON'), }); } ENV.enableHotjar = handler.getValueForPlugin('IRENE_ENABLE_HOTJAR'); ENV.enablePendo = handler.getValueForPlugin('IRENE_ENABLE_PENDO'); ENV.enableCSB = handler.getValueForPlugin('IRENE_ENABLE_CSB'); ENV.enableMarketplace = handler.getValueForPlugin('IRENE_ENABLE_MARKETPLACE'); ENV.emberRollbarClient = { enabled: handler.getValueForPlugin('IRENE_ENABLE_ROLLBAR'), }; // Inject ENV if (ENV.environment !== 'test') { // FIXME: Fix this test properly application.register('env:main', ENV, { singleton: true, instantiate: false, }); return application.inject('component', 'env', 'env:main'); } }; const IreneInitializer = { name: 'irene', initialize, }; export { initialize }; export default IreneInitializer;
appknox/irene
app/initializers/irene.js
JavaScript
agpl-3.0
4,399
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-833 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2011.12.12 at 03:51:35 PM CET // package org.dmtf.schemas.wbem.wscim._1.cim_schema._2.cim_softwarefeature; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.dmtf.schemas.wbem.wscim._1.common.CimString; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;simpleContent> * &lt;restriction base="&lt;http://schemas.dmtf.org/wbem/wscim/1/common>cimString"> * &lt;anyAttribute processContents='lax'/> * &lt;/restriction> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") @XmlRootElement(name = "ProductName") public class ProductName extends CimString { }
StratusLab/claudia
clotho/src/main/java/org/dmtf/schemas/wbem/wscim/_1/cim_schema/_2/cim_softwarefeature/ProductName.java
Java
agpl-3.0
1,261
# Copyright (c) 2015 Ultimaker B.V. # Cura is released under the terms of the AGPLv3 or higher. from UM.Scene.SceneNode import SceneNode from UM.Resources import Resources from UM.Math.Color import Color from UM.Math.Vector import Vector from UM.Mesh.MeshData import MeshData import numpy class ConvexHullNode(SceneNode): def __init__(self, node, hull, parent = None): super().__init__(parent) self.setCalculateBoundingBox(False) self._material = None self._original_parent = parent self._inherit_orientation = False self._inherit_scale = False self._node = node self._node.transformationChanged.connect(self._onNodePositionChanged) self._node.parentChanged.connect(self._onNodeParentChanged) #self._onNodePositionChanged(self._node) self._hull = hull hull_points = self._hull.getPoints() center = (hull_points.min(0) + hull_points.max(0)) / 2.0 mesh = MeshData() mesh.addVertex(center[0], 0.1, center[1]) for point in hull_points: mesh.addVertex(point[0], 0.1, point[1]) indices = [] for i in range(len(hull_points) - 1): indices.append([0, i + 1, i + 2]) indices.append([0, mesh.getVertexCount() - 1, 1]) mesh.addIndices(numpy.array(indices, numpy.int32)) self.setMeshData(mesh) def getWatchedNode(self): return self._node def render(self, renderer): if not self._material: self._material = renderer.createMaterial(Resources.getPath(Resources.ShadersLocation, "basic.vert"), Resources.getPath(Resources.ShadersLocation, "color.frag")) self._material.setUniformValue("u_color", Color(35, 35, 35, 128)) renderer.queueNode(self, material = self._material, transparent = True) return True def _onNodePositionChanged(self, node): #self.setPosition(node.getWorldPosition()) if hasattr(node, "_convex_hull"): delattr(node, "_convex_hull") self.setParent(None) #self._node.transformationChanged.disconnect(self._onNodePositionChanged) #self._node.parentChanged.disconnect(self._onNodeParentChanged) def _onNodeParentChanged(self, node): if node.getParent(): self.setParent(self._original_parent) else: self.setParent(None)
quillford/Cura
cura/ConvexHullNode.py
Python
agpl-3.0
2,406
# Copyright (C) 2015 Linaro Limited # # Author: Stevan Radakovic <stevan.radakovic@linaro.org> # # This file is part of Lava Server. # # Lava Server 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 # # Lava Server 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 Lava Server. If not, see <http://www.gnu.org/licenses/>. from django import forms from lava_results_app.models import ( Chart, ChartQuery, ChartQueryUser, TestCase, ) class ChartForm(forms.ModelForm): class Meta: model = Chart exclude = ('is_published', 'chart_group', 'group', 'queries') widgets = {'owner': forms.HiddenInput} def __init__(self, owner, *args, **kwargs): super(ChartForm, self).__init__(*args, **kwargs) def save(self, commit=True, **kwargs): instance = super(ChartForm, self).save(commit=commit, **kwargs) return instance class ChartQueryForm(forms.ModelForm): class Meta: model = ChartQuery exclude = () widgets = {'chart': forms.HiddenInput, 'query': forms.HiddenInput, 'relative_index': forms.HiddenInput} def __init__(self, user, *args, **kwargs): super(ChartQueryForm, self).__init__(*args, **kwargs) def save(self, commit=True, **kwargs): instance = super(ChartQueryForm, self).save(commit=commit, **kwargs) return instance def clean(self): form_data = self.cleaned_data try: # Chart type validation. if form_data["query"].content_type.model_class() == TestCase and \ form_data["chart_type"] == "pass/fail": self.add_error( "chart_type", "Pass/fail is incorrect value for 'chart_type' with TestCase based queries.") except KeyError: # form_data will pick up the rest of validation errors. pass return form_data class ChartQueryUserForm(forms.ModelForm): class Meta: model = ChartQueryUser exclude = ['user', 'chart_query'] def __init__(self, user, *args, **kwargs): super(ChartQueryUserForm, self).__init__(*args, **kwargs)
Linaro/lava-server
lava_results_app/views/chart/forms.py
Python
agpl-3.0
2,583
<?php /* Smarty version Smarty-3.1.12, created on 2015-11-09 19:00:26 compiled from "/home/gam/themes/Frontend/Bare/frontend/listing/filter/facet-value-list.tpl" */ ?> <?php /*%%SmartyHeaderCode:11956854235640df3a270b21-87257079%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed'); $_valid = $_smarty_tpl->decodeProperties(array ( 'file_dependency' => array ( '977cfeb9bb070320a1c6f58c27362cf6c3284590' => array ( 0 => '/home/gam/themes/Frontend/Bare/frontend/listing/filter/facet-value-list.tpl', 1 => 1445520152, 2 => 'file', ), ), 'nocache_hash' => '11956854235640df3a270b21-87257079', 'function' => array ( ), 'variables' => array ( 'facet' => 0, 'option' => 0, ), 'has_nocache_code' => false, 'version' => 'Smarty-3.1.12', 'unifunc' => 'content_5640df3a37bfc8_73766854', ),false); /*/%%SmartyHeaderCode%%*/?> <?php if ($_valid && !is_callable('content_5640df3a37bfc8_73766854')) {function content_5640df3a37bfc8_73766854($_smarty_tpl) {?> <div class="filter-panel filter--property facet--<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFacetName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " data-filter-type="value-list" data-field-name="<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> "> <div class="filter-panel--flyout"> <label class="filter-panel--title"> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getLabel(), ENT_QUOTES, 'utf-8', true);?> </label> <span class="filter-panel--icon"></span> <div class="filter-panel--content"> <ul class="filter-panel--option-list"> <?php $_smarty_tpl->tpl_vars['option'] = new Smarty_Variable; $_smarty_tpl->tpl_vars['option']->_loop = false; $_from = $_smarty_tpl->tpl_vars['facet']->value->getValues(); if (!is_array($_from) && !is_object($_from)) { settype($_from, 'array');} foreach ($_from as $_smarty_tpl->tpl_vars['option']->key => $_smarty_tpl->tpl_vars['option']->value){ $_smarty_tpl->tpl_vars['option']->_loop = true; ?> <li class="filter-panel--option"> <div class="option--container"> <span class="filter-panel--checkbox"> <input type="checkbox" id="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> __<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " name="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> __<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " value="<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> " <?php if ($_smarty_tpl->tpl_vars['option']->value->isActive()){?>checked="checked" <?php }?>/> <span class="checkbox--state">&nbsp;</span> </span> <label class="filter-panel--label" for="__<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['facet']->value->getFieldName(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> __<?php echo mb_convert_encoding(htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getId(), ENT_QUOTES, 'utf-8', true), "HTML-ENTITIES", 'utf-8');?> "> <?php echo htmlspecialchars($_smarty_tpl->tpl_vars['option']->value->getLabel(), ENT_QUOTES, 'utf-8', true);?> </label> </div> </li> <?php } ?> </ul> </div> </div> </div> <?php }} ?>
gamchantoi/AgroSHop-UTUAWARDS
var/cache/production_201510221322/templates/frontend_Responsive_id_ID_1/97/7c/fe/977cfeb9bb070320a1c6f58c27362cf6c3284590.snippet.facet-value-list.tpl.php
PHP
agpl-3.0
5,114
# # Copyright (C) 2011 - 2015 Instructure, Inc. # # This file is part of Canvas. # # Canvas is free software: you can redistribute it and/or modify it under # the terms of the GNU Affero General Public License as published by the Free # Software Foundation, version 3 of the License. # # Canvas 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/>. # # @API Moderated Grading # @subtopic Provisional Grades # @beta # # API for manipulating provisional grades # # Provisional grades are created by using the Submissions API endpoint "Grade or comment on a submission" with `provisional=true`. # They can be viewed by using "List assignment submissions", "Get a single submission", or "List gradeable students" with `include[]=provisional_grades`. # This API performs other operations on provisional grades for use with the Moderated Grading feature. # # @model ProvisionalGrade # { # "id": "ProvisionalGrade", # "description": "", # "properties": { # "provisional_grade_id": { # "description": "The identifier for the provisional grade", # "example": 23, # "type": "integer" # }, # "score": { # "description": "The numeric score", # "example": 90, # "type": "integer" # }, # "grade": { # "description": "The grade", # "example": "A-", # "type": "string" # }, # "grade_matches_current_submission": { # "description": "Whether the grade was applied to the most current submission (false if the student resubmitted after grading)", # "example": true, # "type": "boolean" # }, # "graded_at": { # "description": "When the grade was given", # "example": "2015-11-01T00:03:21-06:00", # "type": "datetime" # }, # "final": { # "description": "Whether this is the 'final' provisional grade created by the moderator", # "example": false, # "type": "boolean" # }, # "speedgrader_url": { # "description": "A link to view this provisional grade in SpeedGrader™", # "example": "http://www.example.com/courses/123/gradebook/speed_grader?...", # "type": "string" # } # } # } class ProvisionalGradesController < ApplicationController before_filter :require_user before_filter :load_assignment include Api::V1::Submission # @API Show provisional grade status for a student # # @argument student_id [Integer] # The id of the student to show the status for # # @example_request # # curl 'https://<canvas>/api/v1/courses/1/assignments/2/provisional_status?student_id=1' \ # -X POST # # @example_response # # { "needs_provisional_grade": false } # def status if authorized_action(@context, @current_user, [:manage_grades, :view_all_grades]) unless @context.feature_enabled?(:moderated_grading) && @assignment.moderated_grading? return render :json => { :message => "Assignment does not use moderated grading" }, :status => :bad_request end if @assignment.grades_published? return render :json => { :message => "Assignment grades have already been published" }, :status => :bad_request end # in theory we could apply visibility here, but for now we would rather be performant # e.g. @assignment.students_with_visibility(@context.students_visible_to(@current_user)).find(params[:student_id]) student = @context.students.find(params[:student_id]) render :json => { :needs_provisional_grade => @assignment.student_needs_provisional_grade?(student) } end end # @API Select provisional grade # # Choose which provisional grade the student should receive for a submission. # The caller must have :moderate_grades rights. # # @example_response # { # "assignment_id": 867, # "student_id": 5309, # "selected_provisional_grade_id": 53669 # } # def select if authorized_action(@context, @current_user, :moderate_grades) pg = @assignment.provisional_grades.find(params[:provisional_grade_id]) selection = @assignment.moderated_grading_selections.where(student_id: pg.submission.user_id).first return render :json => { :message => 'student not in moderation set' }, :status => :bad_request unless selection selection.provisional_grade = pg selection.save! render :json => selection.as_json(:include_root => false, :only => %w(assignment_id student_id selected_provisional_grade_id)) end end # @API Copy provisional grade # # Given a provisional grade, copy the grade (and associated submission comments and rubric assessments) # to a "final" mark which can be edited or commented upon by a moderator prior to publication of grades. # # Notes: # * The student must be in the moderation set for the assignment. # * The newly created grade will be selected. # * The caller must have "Moderate Grades" rights in the course. # # @returns ProvisionalGrade def copy_to_final_mark if authorized_action @context, @current_user, :moderate_grades pg = @assignment.provisional_grades.find(params[:provisional_grade_id]) return render :json => { :message => 'provisional grade is already final' }, :status => :bad_request if pg.final selection = @assignment.moderated_grading_selections.where(student_id: pg.submission.user_id).first return render :json => { :message => 'student not in moderation set' }, :status => :bad_request unless selection final_mark = pg.copy_to_final_mark!(@current_user) selection.provisional_grade = final_mark selection.save! render :json => provisional_grade_json(final_mark, pg.submission, @assignment, @current_user, %w(submission_comments rubric_assessment)) end end # @API Publish provisional grades for an assignment # # Publish the selected provisional grade for all submissions to an assignment. # Use the "Select provisional grade" endpoint to choose which provisional grade to publish # for a particular submission. # # Students not in the moderation set will have their one and only provisional grade published. # # WARNING: This is irreversible. This will overwrite existing grades in the gradebook. # # @example_request # # curl 'https://<canvas>/api/v1/courses/1/assignments/2/provisional_grades/publish' \ # -X POST # def publish if authorized_action(@context, @current_user, :moderate_grades) unless @context.feature_enabled?(:moderated_grading) && @assignment.moderated_grading? return render :json => { :message => "Assignment does not use moderated grading" }, :status => :bad_request end if @assignment.grades_published? return render :json => { :message => "Assignment grades have already been published" }, :status => :bad_request end submissions = @assignment.submissions.preload(:all_submission_comments, { :provisional_grades => :rubric_assessments }) selections = @assignment.moderated_grading_selections.index_by(&:student_id) submissions.each do |submission| if (selection = selections[submission.user_id]) # student in moderation: choose the selected provisional grade selected_provisional_grade = submission.provisional_grades .detect { |pg| pg.id == selection.selected_provisional_grade_id } else # student not in moderation: choose the first one with a grade (there should only be one) selected_provisional_grade = submission.provisional_grades .select { |pg| pg.graded_at.present? } .sort_by { |pg| pg.created_at } .first end if selected_provisional_grade selected_provisional_grade.publish! end end @assignment.update_attribute(:grades_published_at, Time.now.utc) render :json => { :message => "OK" } end end private def load_assignment @context = api_find(Course, params[:course_id]) @assignment = @context.assignments.active.find(params[:assignment_id]) end end
AndranikMarkosyan/lms
app/controllers/provisional_grades_controller.rb
Ruby
agpl-3.0
8,598
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // 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/>. #include "stdpch.h" #include "reflect.h" // Yoyo: Act like a singleton, else registerClass may crash. CReflectSystem::TClassMap *CReflectSystem::_ClassMap= NULL; // hack to register the root class at startup static const struct CRootReflectableClassRegister { CRootReflectableClassRegister() { TReflectedProperties props; CReflectSystem::registerClass("CReflectable", "", props); } } _RootReflectableClassRegisterInstance; //=================================================================================== // release memory void CReflectSystem::release() { delete _ClassMap; _ClassMap = NULL; } //=================================================================================== void CReflectSystem::registerClass(const std::string &className, const std::string &parentName, const TReflectedProperties properties) { if(!_ClassMap) _ClassMap= new TClassMap; TClassMap::const_iterator it = _ClassMap->find(className); if (it != _ClassMap->end()) { nlerror("CReflectSystem::registerClass : Class registered twice : %s!", className.c_str()); } CClassInfo &ci = (*_ClassMap)[className]; ci.Properties = properties; ci.ClassName = className; for(uint k = 0; k < ci.Properties.size(); ++k) { ci.Properties[k].ParentClass = &ci; } if (parentName.empty()) { ci.ParentClass = NULL; } else { it = _ClassMap->find(parentName); if (it == _ClassMap->end()) { nlerror("CReflectSystem::registerClass : Parent class %s not found", parentName.c_str()); } ci.ParentClass = &(it->second); } } //=================================================================================== const CReflectedProperty *CReflectSystem::getProperty(const std::string &className, const std::string &propertyName, bool dspWarning) { if(!_ClassMap) _ClassMap= new TClassMap; TClassMap::const_iterator it = _ClassMap->find(className); if (it == _ClassMap->end()) { nlwarning("CReflectSystem::getProperty : Unkwown class : %s", className.c_str()); return NULL; } const CClassInfo *ci = &it->second; while (ci) { // Linear search should suffice for now for(uint k = 0; k < ci->Properties.size(); ++k) { if (ci->Properties[k].Name == propertyName) { return &(ci->Properties[k]); } } // search in parent ci = ci->ParentClass; } //\ TODO nico : possible optimization : instead of going up in the parents when // searching for a property, it would be simpler to concatenate properties // from parent class at registration. // All that would be left at the end would be a hash_map of properties ... if(dspWarning) nlwarning("CReflectSystem::getProperty : %s is not a property of class : %s", propertyName.c_str(), className.c_str()); return NULL; } //=================================================================================== const CClassInfo *CReflectable::getClassInfo() { if (!CReflectSystem::getClassMap()) return NULL; // TODO nico : a possible optimization would be to use the address of the static function // 'getReflectedProperties' as a key into the CClassInfo map. This pointer uniquely identify // classes that export properties CReflectSystem::TClassMap::const_iterator it = CReflectSystem::getClassMap()->find(this->getReflectedClassName()); if (it == CReflectSystem::getClassMap()->end()) { return NULL; } return &(it->second); } //=================================================================================== const CReflectedProperty *CReflectable::getReflectedProperty(const std::string &propertyName, bool dspWarning) const { return CReflectSystem::getProperty(this->getReflectedClassName(), propertyName, dspWarning); }
osgcc/ryzom
ryzom/client/src/interface_v3/reflect.cpp
C++
agpl-3.0
4,462
OC.L10N.register( "deck", { "Deck" : "Deck", "Personal" : "Personal", "Finished" : "Terminado", "To review" : "Para revisar", "Action needed" : "Acción requerida", "Later" : "Después", "copy" : "copiar", "Done" : "Hecho", "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form" : "El archivo subido sobrepasa el valor MAX_FILE_SIZE especificada en el formulario HTML", "No file was uploaded" : "No se subió ningún archivo ", "Missing a temporary folder" : "Falta un directorio temporal", "Add board" : "Nuevo Tablero", "Cancel" : "Cancelar", "Hide archived cards" : "Ocultar tarjetas archivadas", "Show archived cards" : "Mostrar tarjetas archivadas", "Details" : "Detalles", "Sharing" : "Compartiendo", "Tags" : "Etiquetas", "Undo" : "Deshacer", "Can edit" : "Puede editar", "Can share" : "Puede compartir", "Delete" : "Eliminar", "Edit" : "Editar", "Members" : "Miembros", "Attachments" : "Adjuntos", "Comments" : "Comentarios", "Modified" : "Modificado", "Created" : "Creado", "Due date" : "Fecha de vencimiento", "Select Date" : "Seleccionar fecha", "Today" : "Hoy", "Tomorrow" : "Mañana", "Save" : "Guardar", "Reply" : "Responder", "Update" : "Actualizar", "Description" : "Descripción", "Formatting help" : "Ayuda de formato", "(group)" : "(grupo)", "seconds ago" : "segundos", "All boards" : "Todos los Tableros", "Shared with you" : "Compartido con usted", "Board details" : "Detalles del tablero", "Edit board" : "Editar Tablero", "Clone board" : "Clonar Tablero", "Delete board" : "Eliminar Tablero", "An error occurred" : "Ocurrió un error", "This week" : "Esta semana" }, "nplurals=2; plural=(n != 1);");
nextcloud/deck
l10n/es_AR.js
JavaScript
agpl-3.0
1,856
<?php /** * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Joas Schilling <coding@schilljs.com> * @author Morris Jobke <hey@morrisjobke.de> * * @license AGPL-3.0 * * This code is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License, version 3, * along with this program. If not, see <http://www.gnu.org/licenses/> * */ namespace OCA\UpdateNotification\Notification; use OCP\IConfig; use OCP\IGroupManager; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Notification\IManager; use OCP\Notification\INotification; use OCP\Notification\INotifier; class Notifier implements INotifier { /** @var IURLGenerator */ protected $url; /** @var IConfig */ protected $config; /** @var IManager */ protected $notificationManager; /** @var IFactory */ protected $l10NFactory; /** @var IUserSession */ protected $userSession; /** @var IGroupManager */ protected $groupManager; /** @var string[] */ protected $appVersions; /** * Notifier constructor. * * @param IURLGenerator $url * @param IConfig $config * @param IManager $notificationManager * @param IFactory $l10NFactory * @param IUserSession $userSession * @param IGroupManager $groupManager */ public function __construct(IURLGenerator $url, IConfig $config, IManager $notificationManager, IFactory $l10NFactory, IUserSession $userSession, IGroupManager $groupManager) { $this->url = $url; $this->notificationManager = $notificationManager; $this->config = $config; $this->l10NFactory = $l10NFactory; $this->userSession = $userSession; $this->groupManager = $groupManager; $this->appVersions = $this->getAppVersions(); } /** * @param INotification $notification * @param string $languageCode The code of the language that should be used to prepare the notification * @return INotification * @throws \InvalidArgumentException When the notification was not prepared by a notifier * @since 9.0.0 */ public function prepare(INotification $notification, $languageCode) { if ($notification->getApp() !== 'updatenotification') { throw new \InvalidArgumentException(); } $l = $this->l10NFactory->get('updatenotification', $languageCode); if ($notification->getSubject() === 'connection_error') { $errors = (int) $this->config->getAppValue('updatenotification', 'update_check_errors', 0); if ($errors === 0) { $this->notificationManager->markProcessed($notification); throw new \InvalidArgumentException(); } $notification->setParsedSubject($l->t('The update server could not be reached since %d days to check for new updates.', [$errors])) ->setParsedMessage($l->t('Please check the nextcloud and server log files for errors.')); } elseif ($notification->getObjectType() === 'core') { $this->updateAlreadyInstalledCheck($notification, $this->getCoreVersions()); $parameters = $notification->getSubjectParameters(); $notification->setParsedSubject($l->t('Update to %1$s is available.', [$parameters['version']])); if ($this->isAdmin()) { $notification->setLink($this->url->linkToRouteAbsolute('settings.AdminSettings.index') . '#updater'); } } else { $appInfo = $this->getAppInfo($notification->getObjectType()); $appName = ($appInfo === null) ? $notification->getObjectType() : $appInfo['name']; if (isset($this->appVersions[$notification->getObjectType()])) { $this->updateAlreadyInstalledCheck($notification, $this->appVersions[$notification->getObjectType()]); } $notification->setParsedSubject($l->t('Update for %1$s to version %2$s is available.', [$appName, $notification->getObjectId()])) ->setRichSubject($l->t('Update for {app} to version %s is available.', $notification->getObjectId()), [ 'app' => [ 'type' => 'app', 'id' => $notification->getObjectType(), 'name' => $appName, ] ]); if ($this->isAdmin()) { $notification->setLink($this->url->linkToRouteAbsolute('settings.AppSettings.viewApps') . '#app-' . $notification->getObjectType()); } } $notification->setIcon($this->url->getAbsoluteURL($this->url->imagePath('updatenotification', 'notification.svg'))); return $notification; } /** * Remove the notification and prevent rendering, when the update is installed * * @param INotification $notification * @param string $installedVersion * @throws \InvalidArgumentException When the update is already installed */ protected function updateAlreadyInstalledCheck(INotification $notification, $installedVersion) { if (version_compare($notification->getObjectId(), $installedVersion, '<=')) { $this->notificationManager->markProcessed($notification); throw new \InvalidArgumentException(); } } /** * @return bool */ protected function isAdmin() { $user = $this->userSession->getUser(); if ($user instanceof IUser) { return $this->groupManager->isAdmin($user->getUID()); } return false; } protected function getCoreVersions() { return implode('.', \OCP\Util::getVersion()); } protected function getAppVersions() { return \OC_App::getAppVersions(); } protected function getAppInfo($appId) { return \OC_App::getAppInfo($appId); } }
Ardinis/server
apps/updatenotification/lib/Notification/Notifier.php
PHP
agpl-3.0
5,672
var error = require('parts/error'); exports.create = function(callback, millisec, cyclic){ if(typeof(setInterval) == 'undefined' &&typeof(setTimeout) == 'undefined') return new error('not supported', 'this platform is not supported timer functionality'); var id = cyclic ? setInterval(callback, millisec) : setTimeout(callback, millisec); return { destroy : function(){ cyclic ? clearInterval(id) : clearTimeout(id); } }; }
ixdu/capsule
modules/timer.js
JavaScript
agpl-3.0
457
# coding: utf-8 from django.contrib.auth.models import User, Permission from django.urls import reverse from django.utils import timezone from rest_framework import status from kpi.constants import ( ASSET_TYPE_COLLECTION, PERM_CHANGE_ASSET, PERM_MANAGE_ASSET, PERM_VIEW_ASSET, ) from kpi.models import Asset, ObjectPermission from kpi.tests.kpi_test_case import KpiTestCase from kpi.urls.router_api_v2 import URL_NAMESPACE as ROUTER_URL_NAMESPACE from kpi.utils.object_permission import get_anonymous_user class ApiAnonymousPermissionsTestCase(KpiTestCase): URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): self.anon = get_anonymous_user() self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' # This was written when we allowed anons to create assets, but I'll # leave it here just to make sure it has no effect permission = Permission.objects.get(codename='add_asset') self.anon.user_permissions.add(permission) # Log in and create an asset that anon can access self.client.login(username=self.someuser.username, password=self.someuser_password) self.anon_accessible = self.create_asset('Anonymous can access this!') self.add_perm(self.anon_accessible, self.anon, 'view_') # Log out and become anonymous again self.client.logout() response = self.client.get(reverse('currentuser-detail')) self.assertFalse('username' in response.data) def test_anon_list_assets(self): # `view_` granted to anon means detail access, NOT list access self.assert_object_in_object_list(self.anon_accessible, in_list=False) def test_anon_asset_detail(self): self.assert_detail_viewable(self.anon_accessible) def test_cannot_create_asset(self): url = reverse(self._get_endpoint('asset-list')) data = {'name': 'my asset', 'content': ''} response = self.client.post(url, data, format='json') self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN, msg="anonymous user cannot create a asset") class ApiPermissionsPublicAssetTestCase(KpiTestCase): URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): KpiTestCase.setUp(self) self.anon = get_anonymous_user() self.admin = User.objects.get(username='admin') self.admin_password = 'pass' self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' self.login(self.admin.username, self.admin_password) self.admins_public_asset = self.create_asset('admins_public_asset') self.add_perm(self.admins_public_asset, self.anon, 'view') self.login(self.someuser.username, self.someuser_password) self.someusers_public_asset = self.create_asset('someusers_public_asset') self.add_perm(self.someusers_public_asset, self.anon, 'view') def test_user_can_view_public_asset(self): self.assert_detail_viewable(self.admins_public_asset, self.someuser, self.someuser_password) def test_public_asset_not_in_list_user(self): self.assert_object_in_object_list(self.admins_public_asset, self.someuser, self.someuser_password, in_list=False) def test_public_asset_not_in_list_admin(self): self.assert_object_in_object_list(self.someusers_public_asset, self.admin, self.admin_password, in_list=False) def test_revoke_anon_from_asset_in_public_collection(self): self.login(self.someuser.username, self.someuser_password) public_collection = self.create_collection('public_collection') child_asset = self.create_asset('child_asset_in_public_collection') self.add_to_collection(child_asset, public_collection) child_asset.refresh_from_db() # Anon should have no access at this point self.client.logout() self.assert_viewable(child_asset, viewable=False) # Grant anon access to the parent collection self.login(self.someuser.username, self.someuser_password) self.add_perm(public_collection, self.anon, 'view_') # Verify anon can access the child asset self.client.logout() # Anon can only see a public asset by accessing the detail view # directly; `assert_viewble()` will always fail because it expects the # asset to be in the list view as well self.assert_detail_viewable(child_asset) # Revoke anon's access to the child asset self.login(self.someuser.username, self.someuser_password) self.remove_perm_v2_api(child_asset, self.anon, PERM_VIEW_ASSET) # Make sure anon cannot access the child asset any longer self.client.logout() self.assert_viewable(child_asset, viewable=False) class ApiPermissionsTestCase(KpiTestCase): fixtures = ['test_data'] URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): self.admin = User.objects.get(username='admin') self.admin_password = 'pass' self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' self.anotheruser = User.objects.get(username='anotheruser') self.anotheruser_password = 'anotheruser' self.assertTrue(self.client.login(username=self.admin.username, password=self.admin_password)) self.admin_asset = self.create_asset('admin_asset') self.admin_collection = self.create_collection('admin_collection') self.child_collection = self.create_collection('child_collection') self.add_to_collection(self.child_collection, self.admin_collection) self.client.logout() ################# Asset tests ##################### def test_own_asset_in_asset_list(self): self.assert_viewable(self.admin_asset, self.admin, self.admin_password) def test_viewable_asset_in_asset_list(self): # Give "someuser" view permissions on an asset owned by "admin". self.add_perm(self.admin_asset, self.someuser, 'view_') # Test that "someuser" can now view the asset. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password) def test_non_viewable_asset_not_in_asset_list(self): # Wow, that's quite a function name... # Ensure that "someuser" doesn't have permission to view the survey # asset owned by "admin". perm_name = self._get_perm_name('view_', self.admin_asset) self.assertFalse(self.someuser.has_perm(perm_name, self.admin_asset)) # Verify they can't view the asset through the API. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password, viewable=False) def test_inherited_viewable_assets_in_asset_list(self): # Give "someuser" view permissions on a collection owned by "admin" and # add an asset also owned by "admin" to that collection. self.add_perm(self.admin_asset, self.someuser, 'view_') self.add_to_collection(self.admin_asset, self.admin_collection, self.admin, self.admin_password) # Test that "someuser" can now view the asset. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password) def test_viewable_asset_inheritance_conflict(self): # Log in as "admin", create a new child collection, and add an asset to # that collection. self.add_to_collection(self.admin_asset, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on 'child_collection'. self.add_perm(self.child_collection, self.someuser, 'view_') # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on the parent collection. self.remove_perm(self.admin_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can view the contents of 'child_collection'. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password) def test_non_viewable_asset_inheritance_conflict(self): # Log in as "admin", create a new child collection, and add an asset to # that collection. self.add_to_collection(self.admin_asset, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on the child collection. self.remove_perm(self.child_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can't view the contents of 'child_collection'. self.assert_viewable(self.admin_asset, self.someuser, self.someuser_password, viewable=False) def test_viewable_asset_not_deletable(self): # Give "someuser" view permissions on an asset owned by "admin". self.add_perm(self.admin_asset, self.someuser, 'view_') # Confirm that "someuser" is not allowed to delete the asset. delete_perm = self._get_perm_name('delete_', self.admin_asset) self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_asset)) # Test that "someuser" can't delete the asset. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_asset.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_inherited_viewable_asset_not_deletable(self): # Give "someuser" view permissions on a collection owned by "admin" and # add an asset also owned by "admin" to that collection. self.add_perm(self.admin_asset, self.someuser, 'view_') self.add_to_collection(self.admin_asset, self.admin_collection, self.admin, self.admin_password) # Confirm that "someuser" is not allowed to delete the asset. delete_perm = self._get_perm_name('delete_', self.admin_asset) self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_asset)) # Test that "someuser" can't delete the asset. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_asset.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_shared_asset_remove_own_permissions_allowed(self): """ Ensuring that a non-owner who has been shared an asset is able to remove themselves from that asset if they want. """ self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, ) perm = new_asset.assign_perm(self.anotheruser, 'view_asset') kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove themselves from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_204_NO_CONTENT assert not self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset) assert len(new_asset.get_perms(self.anotheruser)) == 0 def test_shared_asset_non_owner_remove_owners_permissions_not_allowed(self): """ Ensuring that a non-owner who has been shared an asset is not able to remove permissions from the owner of that asset """ self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, ) # Getting existing permission for the owner of the asset perm = ObjectPermission.objects.filter(asset=new_asset).get( user=self.someuser, permission__codename=PERM_VIEW_ASSET ) new_asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert self.someuser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove `someuser` from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_403_FORBIDDEN assert self.someuser.has_perm(PERM_VIEW_ASSET, new_asset) def test_shared_asset_non_owner_remove_another_non_owners_permissions_not_allowed(self): """ Ensuring that a non-owner who has an asset shared with them cannot remove permissions from another non-owner with that same asset shared with them. """ yetanotheruser = User.objects.create( username='yetanotheruser', ) self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, owner_password=self.someuser_password, ) new_asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) perm = new_asset.assign_perm(yetanotheruser, PERM_VIEW_ASSET) kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove `yetanotheruser` from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_404_NOT_FOUND assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) def test_shared_asset_manage_asset_remove_another_non_owners_permissions_allowed(self): """ Ensure that a non-owner who has an asset shared with them and has `manage_asset` permissions is able to remove permissions from another non-owner with that same asset shared with them. """ yetanotheruser = User.objects.create( username='yetanotheruser', ) self.client.login( username=self.someuser.username, password=self.someuser_password, ) new_asset = self.create_asset( name='a new asset', owner=self.someuser, owner_password=self.someuser_password, ) new_asset.assign_perm(self.anotheruser, PERM_MANAGE_ASSET) perm = new_asset.assign_perm(yetanotheruser, PERM_VIEW_ASSET) kwargs = { 'parent_lookup_asset': new_asset.uid, 'uid': perm.uid, } url = reverse( 'api_v2:asset-permission-assignment-detail', kwargs=kwargs ) self.client.logout() self.client.login( username=self.anotheruser.username, password=self.anotheruser_password, ) assert yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) # `anotheruser` attempting to remove `yetanotheruser` from the asset res = self.client.delete(url) assert res.status_code == status.HTTP_204_NO_CONTENT assert not yetanotheruser.has_perm(PERM_VIEW_ASSET, new_asset) def test_copy_permissions_between_assets(self): # Give "someuser" edit permissions on an asset owned by "admin" self.add_perm(self.admin_asset, self.someuser, 'change_') # Confirm that "someuser" has received the implied permissions expected_perms = [PERM_CHANGE_ASSET, PERM_VIEW_ASSET] self.assertListEqual( sorted(self.admin_asset.get_perms(self.someuser)), expected_perms ) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Add some extraneous permissions to the destination asset; these # should be removed by the copy operation self.add_perm(new_asset, self.anotheruser, 'view_') self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, new_asset)) # Perform the permissions copy via the API endpoint self.client.login( username=self.admin.username, password=self.admin_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) # TODO: check that `clone_from` can also be a URL. # You know, Roy Fielding and all that. self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) # Check the result; since the source and destination have the same # owner, the permissions should be identical self.assertDictEqual( self.admin_asset.get_users_with_perms(attach_perms=True), new_asset.get_users_with_perms(attach_perms=True) ) def test_cannot_copy_permissions_between_non_owned_assets(self): # Give "someuser" view permissions on an asset owned by "admin" self.add_perm(self.admin_asset, self.someuser, 'view_') self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset)) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Give "someuser" edit permissions on the new asset owned by "admin" self.add_perm(new_asset, self.someuser, 'change_') self.assertTrue(self.someuser.has_perm(PERM_CHANGE_ASSET, new_asset)) new_asset_perms_before_copy_attempt = new_asset.get_users_with_perms( attach_perms=True ) # Perform the permissions copy via the API endpoint self.client.login( username=self.someuser.username, password=self.someuser_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) response = self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Check the result; nothing should have changed self.assertDictEqual( new_asset_perms_before_copy_attempt, new_asset.get_users_with_perms(attach_perms=True) ) def test_user_cannot_copy_permissions_from_non_viewable_asset(self): # Make sure "someuser" cannot view the asset owned by "admin" self.assertFalse( self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset) ) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Take note of the destination asset's permissions to make sure they # are *not* changed later dest_asset_original_perms = new_asset.get_users_with_perms( attach_perms=True ) # Perform the permissions copy via the API endpoint self.client.login( username=self.someuser.username, password=self.someuser_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) response = self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) # Make sure no permissions were changed on the destination asset self.assertDictEqual( dest_asset_original_perms, new_asset.get_users_with_perms(attach_perms=True) ) def test_user_cannot_copy_permissions_to_non_editable_asset(self): # Give "someuser" view permissions on an asset owned by "admin" self.add_perm(self.admin_asset, self.someuser, 'view_') self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, self.admin_asset)) # Create another asset to receive the copied permissions new_asset = self.create_asset( name='destination asset', owner=self.admin, owner_password=self.admin_password ) # Give "someuser" view permissions on the new asset owned by "admin" self.add_perm(new_asset, self.someuser, 'view_') self.assertTrue(self.someuser.has_perm(PERM_VIEW_ASSET, new_asset)) # Take note of the destination asset's permissions to make sure they # are *not* changed later dest_asset_original_perms = new_asset.get_users_with_perms( attach_perms=True ) # Perform the permissions copy via the API endpoint self.client.login( username=self.someuser.username, password=self.someuser_password ) if self.URL_NAMESPACE is None: dest_asset_perm_url = reverse( 'asset-permissions', kwargs={'uid': new_asset.uid} ) else: dest_asset_perm_url = reverse( 'api_v2:asset-permission-assignment-clone', kwargs={'parent_lookup_asset': new_asset.uid} ) response = self.client.patch( dest_asset_perm_url, data={'clone_from': self.admin_asset.uid} ) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) # Make sure no permissions were changed on the destination asset self.assertDictEqual( dest_asset_original_perms, new_asset.get_users_with_perms(attach_perms=True) ) ############# Collection tests ############### def test_own_collection_in_collection_list(self): self.assert_viewable(self.admin_collection, self.admin, self.admin_password) def test_viewable_collection_in_collection_list(self): # Give "someuser" view permissions on a collection owned by "admin". self.add_perm(self.admin_collection, self.someuser, 'view_') # Test that "someuser" can now view the collection. self.assert_viewable(self.admin_collection, self.someuser, self.someuser_password) def test_non_viewable_collection_not_in_collection_list(self): # Wow, that's quite a function name... # Ensure that "someuser" doesn't have permission to view the survey # collection owned by "admin". perm_name = self._get_perm_name('view_', self.admin_collection) self.assertFalse(self.someuser.has_perm(perm_name, self.admin_collection)) # Verify they can't view the collection through the API. self.assert_viewable(self.admin_collection, self.someuser, self.someuser_password, viewable=False) def test_inherited_viewable_collections_in_collection_list(self): # Give "someuser" view permissions on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Test that "someuser" can now view the child collection. self.assert_viewable(self.child_collection, self.someuser, self.someuser_password) def test_viewable_collection_inheritance_conflict(self): grandchild_collection = self.create_collection('grandchild_collection', self.admin, self.admin_password) self.add_to_collection(grandchild_collection, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on 'child_collection'. self.add_perm(self.child_collection, self.someuser, 'view_') # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on 'parent_collection'. self.remove_perm(self.admin_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can view 'grandchild_collection'. self.assert_viewable(grandchild_collection, self.someuser, self.someuser_password) def test_non_viewable_collection_inheritance_conflict(self): grandchild_collection = self.create_collection('grandchild_collection', self.admin, self.admin_password) self.add_to_collection(grandchild_collection, self.child_collection, self.admin, self.admin_password) # Give "someuser" view permission on the parent collection. self.add_perm(self.admin_collection, self.someuser, 'view_') # Revoke the view permissions of "someuser" on the child collection. self.remove_perm(self.child_collection, self.admin, self.admin_password, self.someuser, self.someuser_password, 'view_') # Confirm that "someuser" can't view 'grandchild_collection'. self.assert_viewable(grandchild_collection, self.someuser, self.someuser_password, viewable=False) def test_viewable_collection_not_deletable(self): # Give "someuser" view permissions on a collection owned by "admin". self.add_perm(self.admin_collection, self.someuser, 'view_') # Confirm that "someuser" is not allowed to delete the collection. delete_perm = self._get_perm_name('delete_', self.admin_collection) self.assertFalse(self.someuser.has_perm(delete_perm, self.admin_collection)) # Test that "someuser" can't delete the collection. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.admin_collection.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_inherited_viewable_collection_not_deletable(self): # Give "someuser" view permissions on a collection owned by "admin". self.add_perm(self.admin_collection, self.someuser, 'view_') # Confirm that "someuser" is not allowed to delete the child collection. delete_perm = self._get_perm_name('delete_', self.child_collection) self.assertFalse(self.someuser.has_perm(delete_perm, self.child_collection)) # Test that "someuser" can't delete the child collection. self.client.login(username=self.someuser.username, password=self.someuser_password) url = reverse(self._get_endpoint('asset-detail'), kwargs={'uid': self.child_collection.uid}) response = self.client.delete(url) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) class ApiAssignedPermissionsTestCase(KpiTestCase): """ An obnoxiously large amount of code to test that the endpoint for listing assigned permissions complies with the following rules: * Superusers see it all (and there is *no* pagination) * Anonymous users see nothing * Regular users see everything that concerns them, namely all their own permissions and all the owners' permissions for all objects to which they have been assigned any permission See also kpi.utils.object_permission.get_user_permission_assignments_queryset """ # TODO: does this duplicate stuff in # test_api_asset_permission_assignment.py / should it be moved there? URL_NAMESPACE = ROUTER_URL_NAMESPACE def setUp(self): super().setUp() self.anon = get_anonymous_user() self.super = User.objects.get(username='admin') self.super_password = 'pass' self.someuser = User.objects.get(username='someuser') self.someuser_password = 'someuser' self.anotheruser = User.objects.get(username='anotheruser') self.anotheruser_password = 'anotheruser' self.collection = Asset.objects.create( asset_type=ASSET_TYPE_COLLECTION, owner=self.someuser ) self.asset = Asset.objects.create(owner=self.someuser) def test_anon_only_sees_owner_and_anon_permissions(self): self.asset.assign_perm(self.anon, PERM_VIEW_ASSET) self.assertTrue(self.anon.has_perm(PERM_VIEW_ASSET, self.asset)) url = self.get_asset_perm_assignment_list_url(self.asset) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) user_urls = [] for username in [self.asset.owner.username, self.anon.username]: user_urls.append( self.absolute_reverse( self._get_endpoint('user-detail'), kwargs={'username': username}, ) ) self.assertSetEqual( set((a['user'] for a in response.data)), set(user_urls) ) def test_user_sees_relevant_permissions_on_assigned_objects(self): # A user with explicitly-assigned permissions should see their # own permissions and the owner's permissions, but not permissions # assigned to other users self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset)) irrelevant_user = User.objects.create(username='mindyourown') self.asset.assign_perm(irrelevant_user, PERM_VIEW_ASSET) self.client.login(username=self.anotheruser.username, password=self.anotheruser_password) url = self.get_asset_perm_assignment_list_url(self.asset) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) returned_urls = [r['url'] for r in response.data] all_obj_perms = self.asset.permissions.all() relevant_obj_perms = all_obj_perms.filter( user__in=(self.asset.owner, self.anotheruser), permission__codename__in=self.asset.get_assignable_permissions( with_partial=False ), ) self.assertListEqual( sorted(returned_urls), sorted( self.get_urls_for_asset_perm_assignment_objs( relevant_obj_perms, asset=self.asset ) ), ) def test_user_cannot_see_permissions_on_unassigned_objects(self): self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset)) self.client.login(username=self.anotheruser.username, password=self.anotheruser_password) url = self.get_asset_perm_assignment_list_url(self.collection) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_superuser_sees_all_permissions(self): self.asset.assign_perm(self.anotheruser, PERM_VIEW_ASSET) self.assertTrue(self.anotheruser.has_perm(PERM_VIEW_ASSET, self.asset)) self.client.login(username=self.super.username, password=self.super_password) url = self.get_asset_perm_assignment_list_url(self.asset) response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) returned_urls = [r['url'] for r in response.data] all_obj_perms = self.asset.permissions.all() self.assertListEqual( sorted(returned_urls), sorted( self.get_urls_for_asset_perm_assignment_objs( all_obj_perms, asset=self.asset ) ), )
kobotoolbox/kpi
kpi/tests/api/v2/test_api_permissions.py
Python
agpl-3.0
34,731
class CreateExports < ActiveRecord::Migration[4.2] def change create_table :exports do |t| t.references :organization, index: true t.references :user, index: true t.text :file t.integer :file_format, default: 0 t.integer :kind, default: 0 t.integer :progress, default: 0 t.integer :rows t.jsonb :options, default: {} t.timestamps null: false end end end
bikeindex/bike_index
db/migrate/20180918220604_create_exports.rb
Ruby
agpl-3.0
421
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package netkuliTesting; /** * * @author Phildor92 <phillip.evans09@hotmail.com> */ public class NetkulixGUI extends javax.swing.JFrame { /** * Creates new form NetkulixGUI */ public NetkulixGUI() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jInternalFrame1 = new javax.swing.JInternalFrame(); jLabel2 = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jTextArea1 = new javax.swing.JTextArea(); jTextField1 = new javax.swing.JTextField(); jButton1 = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); jSeparator1 = new javax.swing.JSeparator(); jRadioButton1 = new javax.swing.JRadioButton(); jRadioButton2 = new javax.swing.JRadioButton(); jRadioButton3 = new javax.swing.JRadioButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); jInternalFrame1.setBorder(javax.swing.BorderFactory.createTitledBorder("Main.VERSION")); jInternalFrame1.setVisible(true); jLabel2.setText("Sanity Testing"); jButton2.setText("Start!"); jScrollPane1.setToolTipText("Fill in comments"); jTextArea1.setColumns(19); jTextArea1.setFont(new java.awt.Font("Monospaced", 0, 12)); // NOI18N jTextArea1.setLineWrap(true); jTextArea1.setRows(5); jTextArea1.setText("Comments (e.g. Mac DUT, mobile device, etc...)"); jTextArea1.setToolTipText(""); jScrollPane1.setViewportView(jTextArea1); jTextField1.setText("SW version"); jTextField1.setToolTipText("Fill in the AUT version"); jButton1.setText("Start!"); jLabel1.setText("TestRail testing"); jRadioButton1.setText("Mac"); jRadioButton2.setText("Windows"); jRadioButton3.setText("Android/iOS"); javax.swing.GroupLayout jInternalFrame1Layout = new javax.swing.GroupLayout(jInternalFrame1.getContentPane()); jInternalFrame1.getContentPane().setLayout(jInternalFrame1Layout); jInternalFrame1Layout.setHorizontalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addContainerGap() .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jInternalFrame1Layout.createSequentialGroup() .addGap(0, 0, Short.MAX_VALUE) .addComponent(jLabel2) .addGap(6, 6, 6) .addComponent(jButton2)) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 139, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 62, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(6, 6, 6) .addComponent(jButton1)) .addComponent(jSeparator1) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jRadioButton1) .addComponent(jRadioButton2) .addComponent(jRadioButton3)) .addGap(0, 0, Short.MAX_VALUE))) .addContainerGap()) ); jInternalFrame1Layout.setVerticalGroup( jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addContainerGap(39, Short.MAX_VALUE) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton2) .addComponent(jLabel2)) .addGap(18, 18, 18) .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(39, 39, 39) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jInternalFrame1Layout.createSequentialGroup() .addComponent(jRadioButton1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jRadioButton3))) .addGap(8, 8, 8) .addGroup(jInternalFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jButton1) .addComponent(jLabel1)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jInternalFrame1) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jInternalFrame1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(NetkulixGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> final String VERSION = "NetkuliGUI 0.2";//version 0.2-16.08.30-A /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new NetkulixGUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JInternalFrame jInternalFrame1; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JRadioButton jRadioButton1; private javax.swing.JRadioButton jRadioButton2; private javax.swing.JRadioButton jRadioButton3; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JSeparator jSeparator1; private javax.swing.JTextArea jTextArea1; private javax.swing.JTextField jTextField1; // End of variables declaration//GEN-END:variables }
RealN-RnD/Test-Automation-C
src/netkuliTesting/NetkulixGUI.java
Java
agpl-3.0
9,645
/* * Copyright (C) 2000 - 2021 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: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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/>. */ /*--- formatted by Jindent 2.1, (www.c-lab.de/~jindent) ---*/ package org.silverpeas.web.notificationserver.channel.silvermail.requesthandlers; import org.silverpeas.core.util.logging.SilverLogger; import org.silverpeas.core.web.mvc.controller.ComponentSessionController; import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILRequestHandler; import org.silverpeas.web.notificationserver.channel.silvermail.SILVERMAILSessionController; import javax.inject.Named; import javax.inject.Singleton; import javax.servlet.http.HttpServletRequest; @Singleton @Named("ReadMessage") public class ReadMessage implements SILVERMAILRequestHandler { @Override public String handleRequest(ComponentSessionController componentSC, HttpServletRequest request) { try { String sId = request.getParameter("ID"); long id = Long.parseLong(sId); ((SILVERMAILSessionController) componentSC).setCurrentMessageId(id); } catch (NumberFormatException e) { SilverLogger.getLogger(this).error(e.getMessage(), e); } return "/SILVERMAIL/jsp/readMessage.jsp"; } }
SilverDav/Silverpeas-Core
core-war/src/main/java/org/silverpeas/web/notificationserver/channel/silvermail/requesthandlers/ReadMessage.java
Java
agpl-3.0
2,242
/******************************************************************************* * gvGeoportal is sponsored by the General Directorate for Information * Technologies (DGTI) of the Regional Ministry of Finance and Public * Administration of the Generalitat Valenciana (Valencian Community, * Spain), managed by gvSIG Association and led by DISID Corporation. * * Copyright (C) 2016 DGTI - Generalitat Valenciana * * 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 es.gva.dgti.gvgeoportal.security; import org.gvnix.addon.gva.security.providers.safe.GvNIXSafeLoginController; import org.springframework.stereotype.Controller; @GvNIXSafeLoginController @Controller public class SafeLoginController { }
gvSIGAssociation/gvsig-web
src/main/java/es/gva/dgti/gvgeoportal/security/SafeLoginController.java
Java
agpl-3.0
1,419
require 'spec_helper' describe Email do describe "create!" do it "should set the default app if none is given" do email = FactoryGirl.create(:email, app_id: nil) email.app.should be_default_app end context "One email is created" do before :each do FactoryGirl.create(:email, from: "matthew@foo.com", to: "foo@bar.com", data: "From: contact@openaustraliafoundation.org.au\nTo: Matthew Landauer\nSubject: This is a subject\nMessage-ID: <5161ba1c90b10_7837557029c754c8@kedumba.mail>\n\nHello!" ) end it "should set the message-id based on the email content" do Email.first.message_id.should == "5161ba1c90b10_7837557029c754c8@kedumba.mail" end it "should set a hash of the full email content" do Email.first.data_hash.should == "d096b1b1dfbcabf6bd4ef4d4b0ad88f562eedee9" end it "should have an identical hash to another email with identical content" do first_email = Email.first email = FactoryGirl.create(:email, from: "geoff@foo.com", to: "people@bar.com", data: first_email.data) email.data_hash.should == first_email.data_hash end it "should have a different hash to another email with different content" do first_email = Email.first email = FactoryGirl.create(:email, from: "geoff@foo.com", to: "people@bar.com", data: "Something else") email.data_hash.should_not == first_email.data_hash end it "should set the subject of the email based on the data" do Email.first.subject.should == "This is a subject" end end end describe "#from" do it "should return a string for the from email address" do email = FactoryGirl.create(:email, from_address: Address.create!(text: "matthew@foo.com")) email.from.should == "matthew@foo.com" end it "should allow the from_address to be set by a string" do email = FactoryGirl.create(:email, from: "matthew@foo.com") email.from.should == "matthew@foo.com" end end describe "#from_address" do it "should return an Address object" do email = FactoryGirl.create(:email, from: "matthew@foo.org") a1 = Address.find_by_text("matthew@foo.org") a1.should_not be_nil email.from_address.should == a1 end end describe "#to" do it "should return an array for all the email addresses" do email = FactoryGirl.create(:email, to: ["mlandauer@foo.org", "matthew@bar.com"]) email.to.should == ["mlandauer@foo.org", "matthew@bar.com"] end it "should be able to give just a single recipient" do email = Email.new(to: "mlandauer@foo.org") email.to.should == ["mlandauer@foo.org"] end it "should set created_at for deliveries too" do email = FactoryGirl.create(:email, to: "mlandauer@foo.org") email.deliveries.first.created_at.should_not be_nil end end describe "#to_addresses" do it "should return an array of Address objects" do email = FactoryGirl.create(:email, to: ["mlandauer@foo.org", "matthew@bar.com"]) a1 = Address.find_by_text("mlandauer@foo.org") a2 = Address.find_by_text("matthew@bar.com") a1.should_not be_nil a2.should_not be_nil email.to_addresses.should == [a1, a2] end end describe "#data" do context "one email" do before :each do FactoryGirl.create(:email, id: 10, data: "This is a main data section") end let(:email) { Email.find(10) } it "should be able to read in the data again" do email.data.should == "This is a main data section" end it "should be able to read in the data again even after being saved again" do email.save! email.data.should == "This is a main data section" end end it "should only keep the full data of a certain number of the emails around" do EmailDataCache.stub!(:max_no_emails_to_store_data).and_return(2) 4.times { FactoryGirl.create(:email, data: "This is a main section") } Dir.glob(File.join(EmailDataCache.data_filesystem_directory, "*")).count.should == 2 end end context "an email with a text part and an html part" do let(:mail) do Mail.new do text_part do body 'This is plain text' end html_part do content_type 'text/html; charset=UTF-8' body '<h1>This is HTML</h1>' end end end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should == "<h1>This is HTML</h1>" } end describe "#text_part" do it { email.text_part.should == "This is plain text" } end end context "an email which just consistents of a single text part" do let(:mail) do Mail.new do body 'This is plain text' end end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should be_nil } end describe "#text_part" do it { email.text_part.should == "This is plain text" } end end context "an email which just consistents of a single html part" do let(:mail) do Mail.new do content_type 'text/html; charset=UTF-8' body '<p>This is some html</p>' end end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should == "<p>This is some html</p>" } end describe "#text_part" do it { email.text_part.should be_nil } end end context "an email which consistents of a part that is itself multipart" do let(:html_part) do Mail::Part.new do content_type 'text/html; charset=UTF-8' body '<p>This is some html</p>' end end let(:text_part) do Mail::Part.new do body 'This is plain text' end end let(:mail) do mail = Mail.new mail.part :content_type => "multipart/alternative" do |p| p.html_part = html_part p.text_part = text_part end mail end let(:email) do Email.new(data: mail.encoded) end describe "#html_part" do it { email.html_part.should == "<p>This is some html</p>" } end describe "#text_part" do it { email.text_part.should == 'This is plain text' } end end end
WebsterFolksLabs/cuttlefish
spec/models/email_spec.rb
Ruby
agpl-3.0
6,425
/* Copyright (C) 2006-2016 Patrick G. Durand * * 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. * * You may obtain a copy of the License at * * https://www.gnu.org/licenses/agpl-3.0.txt * * 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. */ package bzh.plealog.bioinfo.ui.feature; import java.awt.BorderLayout; import java.text.SimpleDateFormat; import java.util.Locale; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import bzh.plealog.bioinfo.api.data.feature.FeatureTable; /** * This component is used to display the status information of a FeatureTable. * * @author Patrick G. Durand */ public class FeatureStatusViewer extends JPanel { private static final long serialVersionUID = 9153946953865147941L; private JTextField _date; private JTextField _source; private JTextField _status; private JTextField _message; private static final SimpleDateFormat DATE_FOMATTER1 = new SimpleDateFormat("dd-MMM-yyyy", Locale.UK); private static final SimpleDateFormat DATE_FOMATTER2 = new SimpleDateFormat("yyyyMMdd"); public FeatureStatusViewer(){ JLabel lbl; JPanel pnl1, pnl2, pnl3, pnl4, pnl5; pnl1 = new JPanel(new BorderLayout()); lbl = new JLabel("Retrieval date:"); _date = createTextField(); pnl1.add(lbl, BorderLayout.WEST); pnl1.add(_date, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl1.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl2 = new JPanel(new BorderLayout()); lbl = new JLabel("Feature source:"); _source = createTextField(); pnl2.add(lbl, BorderLayout.WEST); pnl2.add(_source, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl2.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl3 = new JPanel(new BorderLayout()); lbl = new JLabel("Message:"); _message = createTextField(); pnl3.add(lbl, BorderLayout.WEST); pnl3.add(_message, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl3.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl4 = new JPanel(new BorderLayout()); lbl = new JLabel("Feature status:"); _status = createTextField(); pnl4.add(lbl, BorderLayout.WEST); pnl4.add(_status, BorderLayout.CENTER); lbl.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 5)); pnl4.setBorder(BorderFactory.createEmptyBorder(2, 5, 2, 0)); pnl5 = new JPanel(); pnl5.setLayout(new BoxLayout(pnl5, BoxLayout.Y_AXIS)); pnl5.add(pnl1); pnl5.add(pnl2); pnl5.add(pnl4); pnl5.add(pnl3); this.setLayout(new BorderLayout()); this.add(pnl5, BorderLayout.NORTH); } /** * Utility method to create a JTextField. */ private JTextField createTextField(){ JTextField tf; tf = new JTextField(); tf.setEditable(false); tf.setBorder(null); tf.setOpaque(false); //tf.setForeground(DDResources.getSystemTextColor()); return tf; } /** * Reset the viewer. */ public void clear(){ setData(null); } /** * Utility method to conevert date formats. */ private String transformDate(String d){ String date="-"; try { date = DATE_FOMATTER1.format(DATE_FOMATTER2.parse(d)); } catch (Exception e) { } return date; } /** * Sets a new FeatureTable. * * @param fTable the feature table to display in this component. */ public void setData(FeatureTable fTable){ String val; if (fTable==null){ _date.setText(""); _source.setText(""); _status.setText(""); _message.setText(""); } else{ val = fTable.getDate(); _date.setText(val!=null?transformDate(val):"?"); val = fTable.getSource(); _source.setText(val!=null?val:"?"); _status.setText(fTable.getStatus()!=FeatureTable.ERROR_STATUS ? FeatureTable.OK_STATUS_S : FeatureTable.ERROR_STATUS_S); val = fTable.getMessage(); _message.setText((val!=null && !val.equals("-"))?val:"None"); } } }
pgdurand/Bioinformatics-UI-API
src/bzh/plealog/bioinfo/ui/feature/FeatureStatusViewer.java
Java
agpl-3.0
4,589
<?php /** * Copyright (c) 2015 ScientiaMobile, 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. * * Refer to the COPYING.txt file distributed with this package. * * * @category WURFL * @copyright ScientiaMobile, Inc. * @license GNU Affero General Public License */ namespace Wurfl\Configuration; use Noodlehaus\Config as ConfigLoader; /** * XML Configuration */ class FileConfig extends Config { /** * Creates a new WURFL Configuration object from $configFilePath * * @param string $configFilePath Complete filename of configuration file * * @throws \InvalidArgumentException */ public function __construct($configFilePath) { if (!file_exists($configFilePath)) { throw new \InvalidArgumentException('The configuration file ' . $configFilePath . ' does not exist.'); } $this->configFilePath = $configFilePath; $this->configurationFileDir = dirname($this->configFilePath); $configLoader = new ConfigLoader($this->configFilePath); $this->initialize($configLoader->all()); } /** * WURFL XML Schema * * @var string */ const WURFL_CONF_SCHEMA = "<?xml version='1.0' encoding='utf-8' ?> <element name='wurfl-config' xmlns='http://relaxng.org/ns/structure/1.0'> <element name='wurfl'> <element name='main-file'><text/></element> <element name='patches'> <zeroOrMore> <element name='patch'><text/></element> </zeroOrMore> </element> </element> <optional> <element name='allow-reload'><text/></element> </optional> <optional> <element name='match-mode'><text/></element> </optional> <optional> <element name='logDir'><text/></element> </optional> <element name='persistence'> <element name='provider'><text/></element> <optional> <element name='params'><text/></element> </optional> </element> <element name='cache'> <element name='provider'><text/></element> <optional> <element name='params'><text/></element> </optional> </element> </element>"; }
mimmi20/Wurfl
src/Configuration/FileConfig.php
PHP
agpl-3.0
2,589
// Copyright 2010-2012 RethinkDB, all rights reserved. #ifndef RDB_PROTOCOL_EXCEPTIONS_HPP_ #define RDB_PROTOCOL_EXCEPTIONS_HPP_ #include <string> #include "utils.hpp" #include "rdb_protocol/bt.hpp" #include "rpc/serialize_macros.hpp" namespace query_language { /* Thrown if the client sends a malformed or nonsensical query (e.g. a protocol buffer that doesn't match our schema or STOP for an unknown token). */ class broken_client_exc_t : public std::exception { public: explicit broken_client_exc_t(const std::string &_what) : message(_what) { } ~broken_client_exc_t() throw () { } const char *what() const throw () { return message.c_str(); } std::string message; }; /* `bad_query_exc_t` is thrown if the user writes a query that accesses undefined variables or that has mismatched types. The difference between this and `broken_client_exc_t` is that `broken_client_exc_t` is the client's fault and `bad_query_exc_t` is the client's user's fault. */ class bad_query_exc_t : public std::exception { public: bad_query_exc_t(const std::string &s, const backtrace_t &bt) : message(s), backtrace(bt) { } ~bad_query_exc_t() throw () { } const char *what() const throw () { return message.c_str(); } std::string message; backtrace_t backtrace; }; class runtime_exc_t { public: runtime_exc_t() { } runtime_exc_t(const std::string &_what, const backtrace_t &bt) : message(_what), backtrace(bt) { } std::string what() const throw() { return message; } std::string as_str() const throw() { return strprintf("%s\nBacktrace:\n%s", message.c_str(), backtrace.print().c_str()); } std::string message; backtrace_t backtrace; RDB_MAKE_ME_SERIALIZABLE_2(message, backtrace); }; }// namespace query_language #endif /* RDB_PROTOCOL_EXCEPTIONS_HPP_ */
AtnNn/rethinkdb
src/rdb_protocol/exceptions.hpp
C++
agpl-3.0
1,921
/* * Copyright (C) 2000 - 2021 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: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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.silverpeas.core.security.authentication.password; import org.silverpeas.core.security.authentication.password.encryption.UnixSHA512Encryption; import org.silverpeas.core.util.ServiceProvider; import java.util.Set; /** * Factory of password encryption objects implementing a given algorithm. It wraps the concrete * implementation of the <code>PasswordEncryption</code> interface used for encrypting a password * according to a chosen algorithm. * <p> * This factory provides all of the available password encryption supported by Silverpeas, * nevertheless it returns only the main encryption used by default in Silverpeas (the one that is * considered as the more robust and secure) with the <code>getDefaultPasswordEncryption()</code> * method. Getting others encryption can be done in order to work with passwords encrypted with * old (and then deprecated) algorithms with the <code>getPasswordEncryption(digest)</code> * method. * @author mmoquillon */ public class PasswordEncryptionProvider { /** * Gets the password encryption that is used by default in Silverpeas to encrypt the user * passwords and to check them. * @return the current default password encryption. */ public static PasswordEncryption getDefaultPasswordEncryption() { return ServiceProvider.getService(UnixSHA512Encryption.class); } /** * Gets the encryption that has computed the specified digest. * <p> * As digests in password encryption are usually made up of an encryption algorithm identifier, * the factory can then find the algorithm that matches the specified digest. If the digest * doesn't contain any algorithm identifier, then the UnixDES is returned (yet it is the only one * supported by Silverpeas that doesn't generate an algorithm identifier in the digest). In the * case the identifier in the digest isn't known, then a exception is thrown. * @param digest the digest from which the password encryption has be found. * @return the password encryption that has computed the specified digest. * @throws IllegalArgumentException if the digest was not computed by any of the password * encryption supported in Silverpeas. */ public static PasswordEncryption getPasswordEncryption(String digest) throws IllegalArgumentException { Set<PasswordEncryption> availableEncrypts = ServiceProvider.getAllServices(PasswordEncryption.class); PasswordEncryption encryption = availableEncrypts.stream() .filter(encrypt -> encrypt.doUnderstandDigest(digest)) .findFirst() .orElseThrow(() -> new IllegalArgumentException("Digest '" + digest + "' not understand by any of the available encryption in Silverpeas")); return encryption; } private PasswordEncryptionProvider() { } }
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/security/authentication/password/PasswordEncryptionProvider.java
Java
agpl-3.0
3,947
__author__ = 'c.brett'
Spycho/aimmo
aimmo-game/simulation/test/__init__.py
Python
agpl-3.0
23
import Ember from 'ember'; import _validate from 'ember-simple-validate/utils/validate'; import Validator from 'ember-simple-validate/lib/validator'; var get = Ember.get; var set = Ember.set; var validValidator = function(validator) { return validator instanceof Validator; }; export default Ember.Mixin.create({ init: function() { this._super(); set(this, 'isValid', undefined); }, validate: function() { set(this, 'validationErrors', {}); if(!this.canValidate()) { set(this, 'isValid', true); } else { var self = this; var validators = get(this, 'validators'); set(this, 'isValid', _validate(this, validators)); Ember.keys(validators).forEach(function(key) { Ember.makeArray(validators[key]).forEach(function(validator) { self.addErrors(key, get(validator, 'errors')); }); }); } return this.get('isValid'); }, canValidate: function() { var validators = get(this, 'validators') || {}; var canValidate = true; var keys = Ember.keys(validators); if(keys && keys.length) { keys.forEach(function(key) { var validatorList = Ember.makeArray(validators[key]); validatorList.forEach(function(validator) { if(!validValidator(validator)) { canValidate = false; return false; } }); }); } else { canValidate = false; } return canValidate; }, addErrors: function(key, errors) { var self = this; Ember.makeArray(errors).forEach(function(error) { self.addError(key, error); }); }, addError: function(key, error) { var self = this; var keyParts = key.split('.'); var path = 'validationErrors'; keyParts.forEach(function(key, i) { path += '.' + key; if(!get(self, path)) { var blank = i === keyParts.length - 1 ? Ember.A() : {}; set(self, path, blank); } }); get(this, 'validationErrors.' + key).pushObject(error); } });
ChinookBook/ember-simple-validate
addon/mixins/simple-validation-mixin.js
JavaScript
agpl-3.0
2,032
# -*- coding: utf-8 -*- # setup.py # Copyright (C) 2013 LEAP # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. """ setup file for leap.mx """ import os from setuptools import setup, find_packages import versioneer versioneer.versionfile_source = 'src/leap/mx/_version.py' versioneer.versionfile_build = 'leap/mx/_version.py' versioneer.tag_prefix = '' # tags are like 1.2.0 versioneer.parentdir_prefix = 'leap.mx-' from pkg.utils.reqs import parse_requirements trove_classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: No Input/Output (Daemon)', 'Framework :: Twisted', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU Affero General Public License v3' ' or later (AGPLv3+)', 'Natural Language :: English', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Topic :: Communications :: Email', 'Topic :: Security :: Cryptography', ] if os.environ.get("VIRTUAL_ENV", None): data_files = None else: # XXX use a script entrypoint for mx instead, it will # be automatically # placed by distutils, using whatever interpreter is # available. data_files = [("/usr/local/bin/", ["pkg/mx.tac"]), ("/etc/init.d/", ["pkg/leap_mx"])] setup( name='leap.mx', version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), url="http://github.com/leapcode/leap_mx", license='AGPLv3+', author='The LEAP Encryption Access Project', author_email='info@leap.se', description=("An asynchronous, transparently-encrypting remailer " "for the LEAP platform"), long_description=( "An asynchronous, transparently-encrypting remailer " "using BigCouch/CouchDB and PGP/GnuPG, written in Twisted Python." ), namespace_packages=["leap"], package_dir={'': 'src'}, packages=find_packages('src'), #test_suite='leap.mx.tests', install_requires=parse_requirements(), classifiers=trove_classifiers, data_files=data_files )
kalikaneko/leap_mx
setup.py
Python
agpl-3.0
2,678
module FeatureFlags # TODO: remove unused feature flags after like December 2019 AVAILABLE_FRONTEND_FEATURES = ['subscriptions', 'assessments', 'custom_sidebar', 'canvas_render', 'snapshots', 'enable_all_buttons', 'video_recording', 'goals', 'app_connections', 'translation', 'geo_sidebar', 'modeling', 'edit_before_copying', 'core_reports', 'lessonpix', 'audio_recordings', 'fast_render', 'badge_progress', 'board_levels', 'premium_symbols', 'find_multiple_buttons', 'new_speak_menu', 'native_keyboard', 'inflections_overlay', 'app_store_purchases', 'emergency_boards', 'evaluations', 'swipe_pages', 'app_store_monthly_purchases', 'ios_head_tracking', 'vertical_ios_head_tracking', 'auto_inflections', 'remote_modeling', 'focus_word_highlighting', 'profiles', 'skin_tones'] ENABLED_FRONTEND_FEATURES = ['subscriptions', 'assessments', 'custom_sidebar', 'snapshots', 'video_recording', 'goals', 'modeling', 'geo_sidebar', 'edit_before_copying', 'core_reports', 'lessonpix', 'translation', 'fast_render', 'audio_recordings', 'app_connections', 'enable_all_buttons', 'badge_progress', 'premium_symbols', 'board_levels', 'native_keyboard', 'app_store_purchases', 'find_multiple_buttons', 'new_speak_menu', 'swipe_pages', 'inflections_overlay', 'ios_head_tracking', 'emergency_boards', 'evaluations', 'vertical_ios_head_tracking', 'remote_modeling', 'auto_inflections', 'focus_word_highlighting'] DISABLED_CANARY_FEATURES = [] FEATURE_DATES = { 'word_suggestion_images' => 'Jan 21, 2017', 'hidden_buttons' => 'Feb 2, 2017', 'browser_no_autosync' => 'Feb 22, 2017', 'folder_icons' => 'Mar 7, 2017', 'symbol_background' => 'May 10, 2017', 'new_index' => 'Feb 17, 2018', 'click_buttons' => 'May 1, 2019', 'token_refresh' => 'July 4, 2019', 'battery_sounds' => 'February 25, 2020', 'auto_capitalize' => 'May 1, 2021', 'utterance_interruptions' => 'May 15, 2021', 'utterance_core_access' => 'May 1, 2021', 'recent_cleared_phrases' => 'Sep 1, 2021', 'skin_tones' => 'Feb 14, 2022' } def self.frontend_flags_for(user) flags = {} AVAILABLE_FRONTEND_FEATURES.each do |feature| if ENABLED_FRONTEND_FEATURES.include?(feature) flags[feature] = true elsif user && user.settings && user.settings['feature_flags'] && user.settings['feature_flags'][feature] flags[feature] = true elsif user && user.settings && user.settings['feature_flags'] && user.settings['feature_flags']['canary'] && !DISABLED_CANARY_FEATURES.include?(feature) flags[feature] = true end end flags end def self.user_created_after?(user, feature) return false unless FEATURE_DATES[feature] date = Date.parse(FEATURE_DATES[feature]) rescue Date.today created = (user.created_at || Time.now).to_date return !!(created >= date) end def self.feature_enabled_for?(feature, user) flags = frontend_flags_for(user) !!flags[feature] end end
CoughDrop/coughdrop
lib/feature_flags.rb
Ruby
agpl-3.0
3,182
<?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point'); /********************************************************************************* * SugarCRM Community Edition is a customer relationship management program developed by * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM 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 with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road, * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Powered by * SugarCRM" logo. If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by SugarCRM". ********************************************************************************/ $dictionary['Administration'] = array('table' => 'config_eurivex', 'comment' => 'System table containing system-wide definitions' ,'fields' => array ( 'category' => array ( 'name' => 'category', 'vname' => 'LBL_LIST_SYMBOL', 'type' => 'varchar', 'len' => '32', 'comment' => 'Settings are grouped under this category; arbitraily defined based on requirements' ), 'name' => array ( 'name' => 'name', 'vname' => 'LBL_LIST_NAME', 'type' => 'varchar', 'len' => '32', 'comment' => 'The name given to the setting' ), 'value' => array ( 'name' => 'value', 'vname' => 'LBL_LIST_RATE', 'type' => 'text', 'comment' => 'The value given to the setting' ), ), 'indices'=>array( array('name'=>'idx_config_cat', 'type'=>'index', 'fields'=>array('category')),) ); $dictionary['UpgradeHistory'] = array( 'table' => 'upgrade_history', 'comment' => 'Tracks Sugar upgrades made over time; used by Upgrade Wizard and Module Loader', 'fields' => array ( 'id' => array ( 'name' => 'id', 'type' => 'id', 'required' => true, 'reportable' => false, 'comment' => 'Unique identifier' ), 'filename' => array ( 'name' => 'filename', 'type' => 'varchar', 'len' => '255', 'comment' => 'Cached filename containing the upgrade scripts and content' ), 'md5sum' => array ( 'name' => 'md5sum', 'type' => 'varchar', 'len' => '32', 'comment' => 'The MD5 checksum of the upgrade file' ), 'type' => array ( 'name' => 'type', 'type' => 'varchar', 'len' => '30', 'comment' => 'The upgrade type (module, patch, theme, etc)' ), 'status' => array ( 'name' => 'status', 'type' => 'varchar', 'len' => '50', 'comment' => 'The status of the upgrade (ex: "installed")', ), 'version' => array ( 'name' => 'version', 'type' => 'varchar', 'len' => '64', 'comment' => 'Version as contained in manifest file' ), 'name' => array ( 'name' => 'name', 'type' => 'varchar', 'len' => '255', ), 'description' => array ( 'name' => 'description', 'type' => 'text', ), 'id_name' => array ( 'name' => 'id_name', 'type' => 'varchar', 'len' => '255', 'comment' => 'The unique id of the module' ), 'manifest' => array ( 'name' => 'manifest', 'type' => 'longtext', 'comment' => 'A serialized copy of the manifest file.' ), 'date_entered' => array ( 'name' => 'date_entered', 'type' => 'datetime', 'required'=>true, 'comment' => 'Date of upgrade or module load' ), 'enabled' => array( 'name' => 'enabled', 'type' => 'bool', 'len' => '1', 'default' => '1', ), ), 'indices' => array( array('name'=>'upgrade_history_pk', 'type'=>'primary', 'fields'=>array('id')), array('name'=>'upgrade_history_md5_uk', 'type'=>'unique', 'fields'=>array('md5sum')), ), ); ?>
hirakc/eur_crm
modules/Administration/vardefs.php
PHP
agpl-3.0
5,819
<?php // 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. return [ 'discussion-votes' => [ 'update' => [ 'error' => 'נכשל בעדכון הצבעה', ], ], 'discussions' => [ 'allow_kudosu' => 'אפשר kudosu', 'beatmap_information' => 'דף מפות', 'delete' => 'מחק', 'deleted' => 'נמחק על ידי :editor :delete_time.', 'deny_kudosu' => 'דחה kudosu', 'edit' => 'ערוך', 'edited' => 'נערך לאחרונה על ידי :editor :update_time.', 'guest' => '', 'kudosu_denied' => 'נדחה מקבלת kudosu.', 'message_placeholder_deleted_beatmap' => 'רמת הקושי הזאת נמחקה לכן לא ניתן לדון בה.', 'message_placeholder_locked' => 'דיון למפה זו בוטל.', 'message_placeholder_silenced' => "לא ניתן לדון בזמן שמושתק.", 'message_type_select' => 'בחר סוג תגובה', 'reply_notice' => 'הקש על Enter כדי להגיב.', 'reply_placeholder' => 'הקלד את תגובתך כאן', 'require-login' => 'אנא התחבר על מנת לפרסם הודעה או להגיב', 'resolved' => 'נפתר', 'restore' => 'שחזר', 'show_deleted' => 'הצג שנמחק', 'title' => 'דיונים', 'collapse' => [ 'all-collapse' => 'סגור הכל', 'all-expand' => 'הרחב הכל', ], 'empty' => [ 'empty' => 'עדיין אין דיונים!', 'hidden' => 'אין דיון שמתאים לסינון שנבחר.', ], 'lock' => [ 'button' => [ 'lock' => 'נעל דיון', 'unlock' => 'פתח דיון', ], 'prompt' => [ 'lock' => 'סיבת הנעילה', 'unlock' => 'האם אתה בטוח שברצונך לפתוח?', ], ], 'message_hint' => [ 'in_general' => 'פוסט זה יעבור לדיוני beatmapset כללים. כדי לעשות mod ל- beatmap זה, התחל הודעה עם חותמת זמן (למשל 00:12:345).', 'in_timeline' => 'כדי לבצע mod לחותמות זמן מרובות, פרסם הודעה מספר פעמים (הודעה אחת לחותמת זמן).', ], 'message_placeholder' => [ 'general' => 'הקלד כאן כדי לפרסם הודעה ל- כללי (:version)', 'generalAll' => 'הקלד כאן כדי לפרסם הודעה ל- כללי (כל רמות הקושי)', 'review' => 'הקלד כאן כדי לפרסם ביקורת', 'timeline' => 'הקלד כאן כדי לפרסם הודעה ל- "ציר זמן" (:version)', ], 'message_type' => [ 'disqualify' => 'פסול', 'hype' => 'הייפ!', 'mapper_note' => 'הערה', 'nomination_reset' => 'איפוס מועמדות', 'praise' => 'שבח', 'problem' => 'בעיה', 'review' => 'ביקורת', 'suggestion' => 'הצעה', ], 'mode' => [ 'events' => 'היסטוריה', 'general' => 'כללי :scope', 'reviews' => 'ביקורות', 'timeline' => 'ציר זמן', 'scopes' => [ 'general' => 'רמת הקושי הזאת', 'generalAll' => 'כל רמות הקושי', ], ], 'new' => [ 'pin' => 'נעץ', 'timestamp' => 'חותמת זמן', 'timestamp_missing' => 'העתק במצב עריכה והדבק בהודעה שלך כדי להוסיף חותמת זמן!', 'title' => 'דיון חדש', 'unpin' => 'בטל נעיצה', ], 'review' => [ 'new' => 'ביקורת חדשה', 'embed' => [ 'delete' => 'מחק', 'missing' => '[ביקורת נמחקה]', 'unlink' => 'בטל קישור', 'unsaved' => 'לא שמור', 'timestamp' => [ 'all-diff' => 'פוסים ב "כל דרגות הקושי" לא יכול להיות תמידיים.', 'diff' => 'אם :type יתחיל בזמן מסוים, הוא יהיה נראה מתחת ציר הזמן.', ], ], 'insert-block' => [ 'paragraph' => 'הוסף פסקה', 'praise' => 'הוסף שיבוח', 'problem' => 'הוסף תקלה', 'suggestion' => 'הוסף הצעה', ], ], 'show' => [ 'title' => ':title ממופה על ידי :mapper', ], 'sort' => [ 'created_at' => 'זמן יצירה', 'timeline' => 'ציר זמן', 'updated_at' => 'עידכון אחרון', ], 'stats' => [ 'deleted' => 'נמחק', 'mapper_notes' => 'הערות', 'mine' => 'מוקש', 'pending' => 'ממתין', 'praises' => 'שבחים', 'resolved' => 'נפתר', 'total' => 'הכל', ], 'status-messages' => [ 'approved' => 'Beatmap זו אושרה ב :date!', 'graveyard' => "Beatmap זו לא עודכנה מאז :date וקרוב לוודאי שננטשה על ידי היוצר...", 'loved' => 'Beatmap זו הוספה ל "אהובות" ב- :date!', 'ranked' => 'Beatmap זו דורגה ב :date!', 'wip' => 'הערה: Beatmap זו מסומנת כ "עבודה בתהליך" על ידי היוצר.', ], 'votes' => [ 'none' => [ 'down' => 'עדיין אין מצביעים', 'up' => 'אין הצבעטת עדיין', ], 'latest' => [ 'down' => 'ההצבעות האחרונות', 'up' => 'ההצבעות האחרונות', ], ], ], 'hype' => [ 'button' => 'הייפ Beatmap!', 'button_done' => 'כבר Hyped!', 'confirm' => "אתה בטוח? זה ישתמש באחד מ- :n ההייפים הנותרים שלך ולא ניתן לבטל זאת.", 'explanation' => 'תן הייפ ל beatmap הזו כדי להפוך אותה לגלויה יותר להיות מועמדת ומדורגת!', 'explanation_guest' => 'התחבר ותן הייף ל beatmap זו כדי להפוך אותה לגלויה יותר להיות מועמדת ומדורגת!', 'new_time' => "תקבל הייפ אחר :new_time.", 'remaining' => 'יש לך :remaining הייפים נותרים.', 'required_text' => 'הייפ: :current/:required', 'section_title' => 'רכבת הייפ', 'title' => 'הייפ', ], 'feedback' => [ 'button' => 'השאר משוב', ], 'nominations' => [ 'delete' => 'מחק', 'delete_own_confirm' => 'אתה בטוח? Beatmap זו תימחק ואתה תועבר חזרה לפרופיל שלך.', 'delete_other_confirm' => 'אתה בטוח? Beatmap זו תימחק ואתה תועבר חזרה לפרופיל של המשתמש.', 'disqualification_prompt' => 'סיבת הפסילה?', 'disqualified_at' => 'נפסלה :time_ago (:reason).', 'disqualified_no_reason' => 'לא פורטה הסיבה', 'disqualify' => 'פסול', 'incorrect_state' => 'שגיאה בעת ביצוע פעולה זו, נסה לרענן את הדף.', 'love' => 'אוהב', 'love_choose' => '', 'love_confirm' => 'לאהוב מפה זו?', 'nominate' => 'למנות', 'nominate_confirm' => 'למנות מפה זו?', 'nominated_by' => 'מונתה על ידי :users', 'not_enough_hype' => "אין כאן מספיק התעניינות.", 'remove_from_loved' => 'הורד סטטוס ה-Loved', 'remove_from_loved_prompt' => 'סיבה הורדת סטטוס ה-Loved:', 'required_text' => 'מינויים: :current/:required', 'reset_message_deleted' => 'נמחק', 'title' => 'סטטוס המינוי', 'unresolved_issues' => 'ישנן עדיין בעיות שלא נפתרו שחייבות טיפול קודם.', 'rank_estimate' => [ '_' => 'מפה זאת תקבל סטטוס Ranked ב:date במידה ולא ימצאו שגיעות. המפה נמצא ב#:position ב:queue.', 'queue' => 'נבדקת לקבלת Ranking', 'soon' => 'בקרוב', ], 'reset_at' => [ 'nomination_reset' => 'תהליך המינוי התאפס :time_ago על ידי :user עם בעיה חדשה :discussion (:message).', 'disqualify' => 'נפסלה :time_ago על ידי :user עם בעיה חדשה :discussion (:message).', ], 'reset_confirm' => [ 'nomination_reset' => 'אתה בטוח? פרסום בעיה חדשה יאפס את תהליך המינוי.', 'disqualify' => 'אתה בטוח? זה יסיר את המפה מ- "מוקדמות" ויאפס את תהליך המינוי.', ], ], 'listing' => [ 'search' => [ 'prompt' => 'הקלד מילות מפתח...', 'login_required' => 'התחבר כדי לחפש.', 'options' => 'אפשרויות חיפוש נוספות', 'supporter_filter' => 'סינון לפי :filters דורש תג osu!supporter פעיל', 'not-found' => 'אין תוצאות', 'not-found-quote' => '... לא, לא נמצא כלום.', 'filters' => [ 'extra' => 'נוסף', 'general' => 'כללי', 'genre' => 'ז\'אנר', 'language' => 'שפה', 'mode' => 'מצב', 'nsfw' => '', 'played' => 'שוחקה', 'rank' => 'דרגה הושגה', 'status' => 'קטגוריות', ], 'sorting' => [ 'title' => 'כותרת', 'artist' => 'אמן', 'difficulty' => 'דרגת קושי', 'favourites' => 'מועדפות', 'updated' => 'עודכנה', 'ranked' => 'מדורגת', 'rating' => 'דירוג', 'plays' => 'שיחוקים', 'relevance' => 'רלוונטיות', 'nominations' => 'מינויים', ], 'supporter_filter_quote' => [ '_' => 'סינון לפי :filters דורש :link פעיל', 'link_text' => 'תג osu!supporter', ], ], ], 'general' => [ 'converts' => 'כלול מפות מומרות', 'featured_artists' => '', 'follows' => '', 'recommended' => 'דרגת קושי מומלצת', ], 'mode' => [ 'all' => 'הכל', 'any' => 'הכל', 'osu' => '', 'taiko' => '', 'fruits' => '', 'mania' => '', ], 'status' => [ 'any' => 'הכל', 'approved' => 'מאושרת', 'favourites' => 'מועדפים', 'graveyard' => 'קבורה', 'leaderboard' => 'יש לוח מובילים', 'loved' => 'אהובה', 'mine' => 'המפות שלי', 'pending' => 'בתהליך * WIP', 'qualified' => 'מוסמכת', 'ranked' => 'מדורג', ], 'genre' => [ 'any' => 'הכל', 'unspecified' => 'לא מוגדר', 'video-game' => 'משחק וידאו', 'anime' => 'אנימה', 'rock' => 'רוק', 'pop' => 'פופ', 'other' => 'אחר', 'novelty' => 'Novelty', 'hip-hop' => 'היפ הופ', 'electronic' => 'אלקטרוני', 'metal' => 'מטאל', 'classical' => 'קלאסי', 'folk' => 'פולק', 'jazz' => 'ג\'אז', ], 'mods' => [ '4K' => '', '5K' => '', '6K' => '', '7K' => '', '8K' => '', '9K' => '', 'AP' => '', 'DT' => '', 'EZ' => '', 'FI' => '', 'FL' => '', 'HD' => '', 'HR' => '', 'HT' => '', 'MR' => '', 'NC' => '', 'NF' => '', 'NM' => '', 'PF' => '', 'RX' => '', 'SD' => '', 'SO' => '', 'TD' => '', 'V2' => '', ], 'language' => [ 'any' => '', 'english' => 'אנגלית', 'chinese' => 'סינית', 'french' => 'צרפתית', 'german' => 'גרמנית', 'italian' => 'איטלקית', 'japanese' => 'יפנית', 'korean' => 'קוריאנית', 'spanish' => 'ספרדית', 'swedish' => 'שוודית', 'russian' => 'רוסית', 'polish' => 'פולנית', 'instrumental' => 'אינסטרומנטלי', 'other' => 'אחר', 'unspecified' => 'לא מוגדר', ], 'nsfw' => [ 'exclude' => '', 'include' => '', ], 'played' => [ 'any' => 'הכל', 'played' => 'שוחקה', 'unplayed' => 'לא שוחקה', ], 'extra' => [ 'video' => 'יש וידאו', 'storyboard' => 'יש Storyboard', ], 'rank' => [ 'any' => 'הכל', 'XH' => 'SS כסוף', 'X' => '', 'SH' => 'S כסוף', 'S' => '', 'A' => '', 'B' => '', 'C' => '', 'D' => '', ], 'panel' => [ 'playcount' => 'מספר משחקים: :count', 'favourites' => 'מועדפות: :count', ], 'variant' => [ 'mania' => [ '4k' => '4K', '7k' => '7K', 'all' => 'הכל', ], ], ];
LiquidPL/osu-web
resources/lang/he-IL/beatmaps.php
PHP
agpl-3.0
14,321
import _ from 'lodash'; import React from 'react'; import {PreviewModal} from '../previewModal'; SendItem.$inject = ['$q', 'api', 'desks', 'notify', 'authoringWorkspace', 'superdeskFlags', '$location', 'macros', '$rootScope', 'deployConfig', 'authoring', 'send', 'editorResolver', 'confirm', 'archiveService', 'preferencesService', 'multi', 'datetimeHelper', 'config', 'privileges', 'storage', 'modal', 'gettext', 'urls']; export function SendItem($q, api, desks, notify, authoringWorkspace, superdeskFlags, $location, macros, $rootScope, deployConfig, authoring, send, editorResolver, confirm, archiveService, preferencesService, multi, datetimeHelper, config, privileges, storage, modal, gettext, urls) { return { scope: { item: '=', view: '=', orig: '=', _beforeSend: '&beforeSend', _editable: '=editable', _publish: '&publish', _action: '=action', mode: '@', }, controller: function() { this.userActions = { send_to: 'send_to', publish: 'publish', duplicate_to: 'duplicate_to', externalsource_to: 'externalsource_to', }; }, controllerAs: 'vm', templateUrl: 'scripts/apps/authoring/views/send-item.html', link: function sendItemLink(scope, elem, attrs, ctrl) { scope.mode = scope.mode || 'authoring'; scope.desks = null; scope.stages = null; scope.macros = null; scope.userDesks = null; scope.allDesks = null; scope.task = null; scope.selectedDesk = null; scope.selectedStage = null; scope.selectedMacro = null; scope.beforeSend = scope._beforeSend || $q.when; scope.destination_last = {send_to: null, publish: null, duplicate_to: null}; scope.origItem = angular.extend({}, scope.item); scope.subscribersWithPreviewConfigured = []; // key for the storing last desk/stage in the user preferences for send action. var PREFERENCE_KEY = 'destination:active'; // key for the storing last user action (send to/publish) in the storage. var USER_ACTION_KEY = 'send_to_user_action'; scope.$watch('item', activateItem); scope.$watch(send.getConfig, activateConfig); scope.publish = function() { scope.loading = true; var result = scope._publish(); return $q .resolve(result) .then(null, (e) => $q.reject(false)) .finally(() => { scope.loading = false; }); }; function activateConfig(config, oldConfig) { if (scope.mode !== 'authoring' && config !== oldConfig) { scope.isActive = !!config; scope.item = scope.isActive ? {} : null; scope.multiItems = multi.count ? multi.getItems() : null; scope.config = config; activate(); } } function activateItem(item) { if (scope.mode === 'monitoring') { superdeskFlags.flags.fetching = !!item; } scope.isActive = !!item; activate(); } function activate() { if (scope.isActive) { api.query('subscribers') .then((res) => { const allSubscribers = res['_items']; scope.subscribersWithPreviewConfigured = allSubscribers .map( (subscriber) => { subscriber.destinations = subscriber.destinations.filter( (destination) => typeof destination.preview_endpoint_url === 'string' && destination.preview_endpoint_url.length > 0 ); return subscriber; } ) .filter((subscriber) => subscriber.destinations.length > 0); }); desks .initialize() .then(fetchDesks) .then(initialize) .then(setDesksAndStages); } } scope.preview = function() { if (scope.$parent.save_enabled() === true) { modal.alert({ headerText: gettext('Preview'), bodyText: gettext( 'In order to preview the item, save the changes first.' ), }); } else { modal.createCustomModal() .then(({openModal, closeModal}) => { openModal( <PreviewModal subscribersWithPreviewConfigured={scope.subscribersWithPreviewConfigured} documentId={scope.item._id} urls={urls} closeModal={closeModal} gettext={gettext} /> ); }); } }; scope.close = function() { if (scope.mode === 'monitoring') { superdeskFlags.flags.fetching = false; } if (scope.$parent.views) { scope.$parent.views.send = false; } else if (scope.item) { scope.item = null; } $location.search('fetch', null); if (scope.config) { scope.config.reject(); } }; scope.selectDesk = function(desk) { scope.selectedDesk = _.cloneDeep(desk); scope.selectedStage = null; fetchStages(); fetchMacros(); }; scope.selectStage = function(stage) { scope.selectedStage = stage; }; scope.selectMacro = function(macro) { if (scope.selectedMacro === macro) { scope.selectedMacro = null; } else { scope.selectedMacro = macro; } }; scope.send = function(open) { updateLastDestination(); return runSend(open); }; scope.$on('item:nextStage', (_e, data) => { if (scope.item && scope.item._id === data.itemId) { var oldStage = scope.selectedStage; scope.selectedStage = data.stage; scope.send().then((sent) => { if (!sent) { scope.selectedStage = oldStage; } }); } }); // events on which panel should close var closePanelEvents = ['item:spike', 'broadcast:preview']; angular.forEach(closePanelEvents, (event) => { scope.$on(event, shouldClosePanel); }); /** * @description Closes the opened 'duplicate/send To' panel if the same item getting * spiked or any item is opening for authoring. * @param {Object} event * @param {Object} data - contains the item(=itemId) that was spiked or {item: null} when * any item opened for authoring (utilising, 'broadcast:preview' with {item: null}) */ function shouldClosePanel(event, data) { if ( (scope.config != null && data != null && _.includes(scope.config.itemIds, data.item)) || (data == null || data.item == null) ) { scope.close(); } } /* * Returns true if Destination field and Send button needs to be displayed, false otherwise. * @returns {Boolean} */ scope.showSendButtonAndDestination = function() { if (scope.itemActions) { var preCondition = scope.mode === 'ingest' || scope.mode === 'personal' || scope.mode === 'monitoring' || scope.mode === 'authoring' && scope.isSendEnabled() && scope.itemActions.send || scope.mode === 'spike'; if (scope.currentUserAction === ctrl.userActions.publish) { return preCondition && scope.showSendAndPublish(); } return preCondition; } }; /* * Returns true if Send and Send and Continue button needs to be disabled, false otherwise. * @returns {Boolean} */ scope.disableSendButton = function() { return !scope.selectedDesk || scope.mode !== 'ingest' && scope.selectedStage && scope.mode !== 'spike' && (_.get(scope, 'item.task.stage') === scope.selectedStage._id || _.includes(_.map(scope.multiItems, 'task.stage'), scope.selectedStage._id)); }; /* * Returns true if user is not a member of selected desk, false otherwise. * @returns {Boolean} */ scope.disableFetchAndOpenButton = function() { if (scope.selectedDesk) { var _isNonMember = _.isEmpty(_.find(desks.userDesks, {_id: scope.selectedDesk._id})); return _isNonMember; } }; /** * Returns true if Publish Schedule needs to be displayed, false otherwise. */ scope.showPublishSchedule = function() { return scope.item && archiveService.getType(scope.item) !== 'ingest' && scope.item.type !== 'composite' && !scope.item.embargo_date && !scope.item.embargo_time && ['published', 'killed', 'corrected', 'recalled'].indexOf(scope.item.state) === -1 && canPublishOnDesk(); }; /** * Returns true if timezone needs to be displayed, false otherwise. */ scope.showTimezone = function() { return (scope.item.publish_schedule || scope.item.embargo) && (scope.showPublishSchedule() || scope.showEmbargo()); }; /** * Returns true if Embargo needs to be displayed, false otherwise. */ scope.showEmbargo = function() { // If user doesn't have embargo privilege then don't display embargo fields if (!privileges.privileges.embargo) { return false; } if (config.ui && config.ui.publishEmbargo === false) { return false; } var prePublishCondition = scope.item && archiveService.getType(scope.item) !== 'ingest' && scope.item.type !== 'composite' && !scope.item.publish_schedule_date && !scope.item.publish_schedule_time; if (prePublishCondition && authoring.isPublished(scope.item)) { if (['published', 'corrected'].indexOf(scope.item.state) >= 0) { return scope.origItem.embargo; } // for published states other than 'published', 'corrected' return false; } return prePublishCondition; }; /** * Returns true if Embargo needs to be displayed, false otherwise. */ scope.isEmbargoEditable = function() { var publishedCondition = authoring.isPublished(scope.item) && scope.item.schedule_settings && scope.item.schedule_settings.utc_embargo && datetimeHelper.greaterThanUTC(scope.item.schedule_settings.utc_embargo); return scope.item && scope.item._editable && (!authoring.isPublished(scope.item) || publishedCondition); }; /** * Send the content to different desk/stage * @param {Boolean} open - True to open the item. * @return {Object} promise */ function runSend(open) { scope.loading = true; scope.item.sendTo = true; var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; if (scope.mode === 'authoring') { return sendAuthoring(deskId, stageId, scope.selectedMacro); } else if (scope.mode === 'archive') { return sendContent(deskId, stageId, scope.selectedMacro, open); } else if (scope.config) { scope.config.promise.finally(() => { scope.loading = false; }); return scope.config.resolve({ desk: deskId, stage: stageId, macro: scope.selectedMacro ? scope.selectedMacro.name : null, open: open, }); } else if (scope.mode === 'ingest') { return sendIngest(deskId, stageId, scope.selectedMacro, open); } } /** * Enable Disable the Send and Publish button. * Send And Publish is enabled using `superdesk.config.js`. */ scope.showSendAndPublish = () => !config.ui || angular.isUndefined(config.ui.sendAndPublish) || config.ui.sendAndPublish; /** * Check if the Send and Publish is allowed or not. * Following conditions are to met for Send and Publish action * - Item is not Published i.e. not state Published, Corrected, Killed or Scheduled * - Selected destination (desk/stage) should be different from item current location (desk/stage) * - Mode should be authoring * - Publish Action is allowed on that item. * @return {Boolean} */ scope.canSendAndPublish = function() { if (scope.mode !== 'authoring' || !scope.item) { return false; } // Selected destination desk should be different from item current location desk var isDestinationChanged = scope.selectedDesk && scope.item.task.desk !== scope.selectedDesk._id; return scope.showSendAndPublish() && !authoring.isPublished(scope.item) && isDestinationChanged && scope.mode === 'authoring' && scope.itemActions.publish; }; /** * Returns true if 'send' button should be displayed. Otherwise, returns false. * @return {boolean} */ scope.isSendEnabled = () => scope.item && !authoring.isPublished(scope.item); /* * Send the current item to different desk or stage and publish the item from new location. */ scope.sendAndPublish = function() { return runSendAndPublish(); }; /* * Returns true if 'send' action is allowed, otherwise false * @returns {Boolean} */ scope.canSendItem = function() { var itemType = [], typesList; if (scope.multiItems) { angular.forEach(scope.multiItems, (item) => { itemType[item._type] = 1; }); typesList = Object.keys(itemType); itemType = typesList.length === 1 ? typesList[0] : null; } return scope.mode === 'authoring' || itemType === 'archive' || scope.mode === 'spike' || (scope.mode === 'monitoring' && _.get(scope, 'config.action') === scope.vm.userActions.send_to); }; /** * Check if it is allowed to publish on current desk * @returns {Boolean} */ function canPublishOnDesk() { return !(isAuthoringDesk() && config.features.noPublishOnAuthoringDesk); } /** * If the action is correct and kill then the publish privilege needs to be checked. */ scope.canPublishItem = function() { if (!scope.itemActions || !canPublishOnDesk()) { return false; } if (scope._action === 'edit') { return scope.item ? !scope.item.flags.marked_for_not_publication && scope.itemActions.publish : scope.itemActions.publish; } else if (scope._action === 'correct') { return privileges.privileges.publish && scope.itemActions.correct; } else if (scope._action === 'kill') { return privileges.privileges.publish && scope.itemActions.kill; } return false; }; /** * Set the User Action. */ scope.setUserAction = function(action) { if (scope.currentUserAction === action) { return; } scope.currentUserAction = action; storage.setItem(USER_ACTION_KEY, action); setDesksAndStages(); }; /** * Checks if a given item is valid to publish * * @param {Object} item story to be validated * @return {Object} promise */ const validatePublish = (item) => api.save('validate', {act: 'publish', type: item.type, validate: item}); /** * Sends and publishes the current item in scope * First checks if the item is dirty and pops up save dialog if needed * Then checks if the story is valid to publish before sending * Then sends the story to the destination * Then publishes it * * @param {Object} item story to be validated * @return {Object} promise */ const runSendAndPublish = () => { var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; // send releases lock, increment version. return scope.beforeSend({action: 'Send and Publish'}) .then(() => validatePublish(scope.item) .then((validationResult) => { if (_.get(validationResult, 'errors.length')) { for (var i = 0; i < validationResult.errors.length; i++) { notify.error('\'' + _.trim(validationResult.errors[i]) + '\''); } return $q.reject(); } return sendAuthoring(deskId, stageId, scope.selectedMacro, true) .then((item) => { scope.loading = true; // open the item for locking and publish return authoring.open(scope.item._id, false); }) .then((item) => { // update the original item to avoid 412 error. scope.orig._etag = scope.item._etag = item._etag; scope.orig._locked = scope.item._locked = item._locked; scope.orig.task = scope.item.task = item.task; // change the desk location. $rootScope.$broadcast('desk_stage:change'); // if locked then publish if (item._locked) { return scope.publish(); } return $q.reject(); }) .then((result) => { if (result) { authoringWorkspace.close(false); } }) .catch((error) => { notify.error(gettext('Failed to send and publish.')); }); }) .finally(() => { scope.loading = false; }) ); }; /** * Run the macro and returns to the modified item. * @param {Object} item * @param {String} macro * @return {Object} promise */ function runMacro(item, macro) { if (macro) { return macros.call(macro, item, true).then((res) => angular.extend(item, res)); } return $q.when(item); } /** * Send to different location from authoring. * @param {String} deskId - selected desk Id * @param {String} stageId - selected stage Id * @param {String} macro - macro to apply * @return {Object} promise */ function sendAuthoring(deskId, stageId, macro) { var msg; scope.loading = true; return runMacro(scope.item, macro) .then((item) => api.find('tasks', scope.item._id) .then((task) => { scope.task = task; msg = 'Send'; return scope.beforeSend({action: msg}); }) .then((result) => { if (result && result._etag) { scope.task._etag = result._etag; } return api.save('move', {}, {task: {desk: deskId, stage: stageId}}, scope.item); }) .then((value) => { notify.success(gettext('Item sent.')); if (scope.currentUserAction === ctrl.userActions.send_to) { // Remember last destination desk and stage for send_to. var lastDestination = scope.destination_last[scope.currentUserAction]; if (!lastDestination || (lastDestination.desk !== deskId || lastDestination.stage !== stageId)) { updateLastDestination(); } } authoringWorkspace.close(true); return true; }, (err) => { if (err) { if (angular.isDefined(err.data._message)) { notify.error(err.data._message); } else if (angular.isDefined(err.data._issues['validator exception'])) { notify.error(err.data._issues['validator exception']); } } })) .finally(() => { scope.loading = false; }); } /** * Update the preferences to store last destinations * @param {String} key */ function updateLastDestination() { var updates = {}; var deskId = scope.selectedDesk._id; var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage; updates[PREFERENCE_KEY] = {desk: deskId, stage: stageId}; preferencesService.update(updates, PREFERENCE_KEY); } /** * Send content to different desk and stage * @param {String} deskId * @param {String} stageId * @param {String} macro * @param {Boolean} open - If true open the item. */ function sendContent(deskId, stageId, macro, open) { var finalItem; scope.loading = true; return api.save('duplicate', {}, {desk: scope.item.task.desk}, scope.item) .then((item) => api.find('archive', item._id)) .then((item) => runMacro(item, macro)) .then((item) => { finalItem = item; return api.find('tasks', item._id); }) .then((_task) => { scope.task = _task; api.save('tasks', scope.task, { task: _.extend(scope.task.task, {desk: deskId, stage: stageId}), }); }) .then(() => { notify.success(gettext('Item sent.')); scope.close(); if (open) { $location.url('/authoring/' + finalItem._id); } else { $rootScope.$broadcast('item:fetch'); } }) .finally(() => { scope.loading = false; }); } /** * Fetch content from ingest to a different desk and stage * @param {String} deskId * @param {String} stageId * @param {String} macro * @param {Boolean} open - If true open the item. */ function sendIngest(deskId, stageId, macro, open) { scope.loading = true; return send.oneAs(scope.item, { desk: deskId, stage: stageId, macro: macro ? macro.name : macro, }).then((finalItem) => { notify.success(gettext('Item fetched.')); if (open) { authoringWorkspace.edit(finalItem); } else { $rootScope.$broadcast('item:fetch'); } }) .finally(() => { scope.loading = false; }); } /** * Fetch desk and last selected desk and stage for send_to and publish action * @return {Object} promise */ function fetchDesks() { return desks.initialize() .then(() => { // get all desks scope.allDesks = desks.desks._items; // get user desks return desks.fetchCurrentUserDesks(); }) .then((deskList) => { scope.userDesks = deskList; return preferencesService.get(PREFERENCE_KEY); }) .then((result) => { if (result) { scope.destination_last.send_to = { desk: result.desk, stage: result.stage, }; scope.destination_last.duplicate_to = { desk: result.desk, stage: result.stage, }; } }); } /** * Set the last selected desk based on the user action. * To be called after currentUserAction is set */ function setDesksAndStages() { if (!scope.currentUserAction) { return; } // set the desks for desk filter if (scope.currentUserAction === ctrl.userActions.publish) { scope.desks = scope.userDesks; } else { scope.desks = scope.allDesks; } if (scope.mode === 'ingest') { scope.selectDesk(desks.getCurrentDesk()); } else { // set the last selected desk or current desk var itemDesk = desks.getItemDesk(scope.item); var lastDestination = scope.destination_last[scope.currentUserAction]; if (itemDesk) { if (lastDestination && !_.isNil(lastDestination.desk)) { scope.selectDesk(desks.deskLookup[lastDestination.desk]); } else { scope.selectDesk(itemDesk); } } else if (lastDestination && !_.isNil(lastDestination.desk)) { scope.selectDesk(desks.deskLookup[lastDestination.desk]); } else { scope.selectDesk(desks.getCurrentDesk()); } } } /** * Set stages and last selected stage. */ function fetchStages() { if (!scope.selectedDesk) { return; } scope.stages = desks.deskStages[scope.selectedDesk._id]; var stage = null; if (scope.currentUserAction === ctrl.userActions.send_to || scope.currentUserAction === ctrl.userActions.duplicate_to) { var lastDestination = scope.destination_last[scope.currentUserAction]; if (lastDestination) { stage = _.find(scope.stages, {_id: lastDestination.stage}); } else if (scope.item.task && scope.item.task.stage) { stage = _.find(scope.stages, {_id: scope.item.task.stage}); } } if (!stage) { stage = _.find(scope.stages, {_id: scope.selectedDesk.incoming_stage}); } scope.selectedStage = stage; } /** * Fetch macros for the selected desk. */ function fetchMacros() { if (!scope.selectedDesk) { return; } macros.getByDesk(scope.selectedDesk.name) .then((_macros) => { scope.macros = _macros; }); } /** * Initialize Item Actios and User Actions. */ function initialize() { initializeItemActions(); initializeUserAction(); } /** * Initialize User Action */ function initializeUserAction() { // default user action scope.currentUserAction = storage.getItem(USER_ACTION_KEY) || ctrl.userActions.send_to; if (scope.orig || scope.item) { if (scope.config && scope.config.action === 'externalsourceTo') { scope.currentUserAction = ctrl.userActions.externalsource_to; } // if the last action is send to but item is published open publish tab. if (scope.config && scope.config.action === 'duplicateTo') { scope.currentUserAction = ctrl.userActions.duplicate_to; } if (scope.currentUserAction === ctrl.userActions.send_to && scope.canPublishItem() && !scope.isSendEnabled()) { scope.currentUserAction = ctrl.userActions.publish; } else if (scope.currentUserAction === ctrl.userActions.publish && !scope.canPublishItem() && scope.showSendButtonAndDestination()) { scope.currentUserAction = ctrl.userActions.send_to; } else if (scope.currentUserAction === ctrl.userActions.publish && isAuthoringDesk() && noPublishOnAuthoringDesk()) { scope.currentUserAction = ctrl.userActions.send_to; } } } /** * The itemActions defined in parent scope (Authoring Directive) is made accessible via this method. * scope.$parent isn't used as send-item directive is used in multiple places and has different * hierarchy. */ function initializeItemActions() { if (scope.orig || scope.item) { scope.itemActions = authoring.itemActions(scope.orig || scope.item); } } /** * Test if desk of current item is authoring type. * * @return {Boolean} */ function isAuthoringDesk() { if (!_.get(scope, 'item.task.desk')) { return false; } const desk = desks.getItemDesk(scope.item); return desk && desk.desk_type === 'authoring'; } /** * Test if noPublishOnAuthoringDesk config is active. * * @return {Boolean} */ function noPublishOnAuthoringDesk() { return config.features.noPublishOnAuthoringDesk; } // update actions on item save scope.$watch('orig._current_version', initializeItemActions); }, }; }
jerome-poisson/superdesk-client-core
scripts/apps/authoring/authoring/directives/SendItem.js
JavaScript
agpl-3.0
35,674
<?php declare(strict_types=1); /** * @copyright Copyright (c) 2019, Roeland Jago Douma <roeland@famdouma.nl> * * @author Christoph Wurst <christoph@winzerhof-wurst.at> * @author John Molakvoæ (skjnldsv) <skjnldsv@protonmail.com> * @author Roeland Jago Douma <roeland@famdouma.nl> * * @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 <http://www.gnu.org/licenses/>. * */ namespace OCA\Files_Versions\Listener; use OCA\Files\Event\LoadSidebar; use OCA\Files_Versions\AppInfo\Application; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; use OCP\Util; class LoadSidebarListener implements IEventListener { public function handle(Event $event): void { if (!($event instanceof LoadSidebar)) { return; } // TODO: make sure to only include the sidebar script when // we properly split it between files list and sidebar Util::addScript(Application::APP_ID, 'files_versions'); } }
andreas-p/nextcloud-server
apps/files_versions/lib/Listener/LoadSidebarListener.php
PHP
agpl-3.0
1,562
/** The FlamingLayer Class **/ /** * @constructor * @augments Layer * @description The superclass for all flamingolayers * @param id The id of the layer * @param options The options to be given to the layer * @param flamingoObject The flamingo object of the layer * */ Ext.define("viewer.viewercontroller.flamingo.FlamingoLayer",{ enabledEvents: null, type: null, constructor :function (config){ if (config.id){ this.id = config.viewerController.mapComponent.makeFlamingoAcceptableId(config.id); config.id = this.id; } this.enabledEvents=new Object(); this.map = this.viewerController ? this.viewerController.mapComponent.getMap() : null; return this; }, /** * Get's the frameworklayer: the viewer specific layer. */ getFrameworkLayer : function(){ if (this.map==null){ return null; } return this.map.getFrameworkMap(); }, toXML : function(){ Ext.Error.raise({msg: "FlamingoLayer.toXML(): .toXML() must be made!"}); }, getTagName : function(){ Ext.Error.raise({msg: "FlamingoLayer.getTagName: .getTagName() must be made!"}); }, setOption : function(optionKey,optionValue){ this.options[optionKey]=optionValue; }, getId : function(){ return this.id; }, getFrameworkId: function(){ return this.map.getId()+"_"+this.getId(); }, setAlpha : function (alpha){ // Fixup wrong Flash alpha, it thinks 0 is transparent and 100 is opaque if(this.map) { this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"setAlpha",alpha) } }, getAlpha : function (){ return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getAlpha"); }, /** * Get the last getMap request array * @see viewer.viewerController.controller.Layer#getLastMapRequest */ getLastMapRequest: function(){ var request=this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"getLastGetMapRequest"); if (request==null){ return null; } return [request]; }, /** * Returns the type of the layer. */ getType: function(){ return this.type; }, /** * reloads the framework map */ reload: function(){ if (this.map !=null && this.map.getFrameworkMap()){ return this.map.getFrameworkMap().callMethod(this.getFrameworkId(),"update"); } }, /** * Overwrites the addListener function. Add's the event to allowexternalinterface of flamingo * so flamingo is allowed to broadcast the event. */ addListener : function(event,handler,scope){ //enable flamingo event broadcasting var flamEvent=this.viewerController.mapComponent.eventList[event]; if (flamEvent!=undefined){ //if not enabled yet, add it if (this.enabledEvents[flamEvent]==undefined){ this.map.getFrameworkMap().callMethod(this.viewerController.mapComponent.getId(),"addAllowExternalInterface",this.getFrameworkId()+"."+flamEvent); this.enabledEvents[flamEvent]=true; } } /* fix for infinite loop: * If this is called from a layer that extends the FlamingoArcLayer the superclass is * that FlamingoArcLayer and this function is called again when this.superclass.function is called **/ if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){ this.superclass.superclass.addListener.call(this,event,handler,scope); }else{ this.superclass.addListener.call(this,event,handler,scope); } //viewer.viewercontroller.controller.Layer.superclass.addListener.call(this,event,handler,scope); }, setVisible : function (visible){ this.visible = visible; if (this.options!=null){ this.options["visible"] = visible; } if (this.map !=null){ this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "setVisible", visible); } }, /** * Get the visibility */ getVisible : function (){ if (this.map !=null){ this.visible = this.map.getFrameworkMap().callMethod(this.map.id + "_" + this.id, "getVisible"); } if (this.options!=null) this.options["visible"] = this.visible; return this.visible; }, /** * Overwrite destroy, clear Listeners and forward to super.destroy */ destroy: function(){ /* fix for infinite loop: * If this is called from a layer that extends the FlamingoArcLayer the superclass is * that FlamingoArcLayer and this function is called again when this.superclass.function is called **/ if (this.superclass.$className == "viewer.viewercontroller.flamingo.FlamingoArcLayer"){ this.superclass.superclass.destroy.call(this); }else{ this.superclass.destroy.call(this); } } });
mvdstruijk/flamingo
viewer/src/main/webapp/viewer-html/common/viewercontroller/flamingo/FlamingoLayer.js
JavaScript
agpl-3.0
5,324
<?php namespace ShiftBundle\Controller\Admin; use Laminas\Mail\Message; use Laminas\View\Model\ViewModel; use ShiftBundle\Entity\RegistrationShift; use ShiftBundle\Entity\Shift\Registered; /** * RegistrationSubscriptionController * * @author Pieter Maene <pieter.maene@litus.cc> */ class RegistrationSubscriptionController extends \CommonBundle\Component\Controller\ActionController\AdminController { public function manageAction() { $shift = $this->getRegistrationShiftEntity(); if ($shift === null) { return new ViewModel(); } $registered = $shift->getRegistered(); $form = $this->getForm('shift_registrationSubscription_add'); if ($this->getRequest()->isPost()) { $form->setData($this->getRequest()->getPost()); if ($form->isValid()) { $subscriber = $form->hydrateObject($shift); if ($subscriber === null) { $this->flashMessenger()->error( 'Error', 'Unable to add the given person to the registration shift!' ); $this->redirect()->toRoute( 'shift_admin_registration_shift_subscription', array( 'action' => 'manage', 'id' => $shift->getId(), ) ); return new ViewModel(); } $this->getEntityManager()->persist($subscriber); $this->getEntityManager()->flush(); $this->redirect()->toRoute( 'shift_admin_registration_shift_subscription', array( 'action' => 'manage', 'id' => $shift->getId(), ) ); return new ViewModel(); } } return new ViewModel( array( 'form' => $form, 'shift' => $shift, 'registered' => $registered, ) ); } public function deleteAction() { $this->initAjax(); $subscription = $this->getSubscriptionEntity(); if ($subscription === null) { return new ViewModel(); } $repository = $this->getEntityManager() ->getRepository('ShiftBundle\Entity\RegistrationShift'); $shift = $repository->findOneByRegistered($subscription->getId()); $shift->removeRegistered($subscription->getPerson()); $mailAddress = $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('shift.mail'); $mailName = $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('shift.mail_name'); $language = $subscription->getPerson()->getLanguage(); if ($language === null) { $language = $this->getEntityManager()->getRepository('CommonBundle\Entity\General\Language') ->findOneByAbbrev('en'); } $mailData = unserialize( $this->getEntityManager() ->getRepository('CommonBundle\Entity\General\Config') ->getConfigValue('shift.subscription_deleted_mail') ); $message = $mailData[$language->getAbbrev()]['content']; $subject = $mailData[$language->getAbbrev()]['subject']; $shiftString = $shift->getName() . ' from ' . $shift->getStartDate()->format('d/m/Y h:i') . ' to ' . $shift->getEndDate()->format('d/m/Y h:i'); $mail = new Message(); $mail->setEncoding('UTF-8') ->setBody(str_replace('{{ shift }}', $shiftString, $message)) ->setFrom($mailAddress, $mailName) ->addTo($subscription->getPerson()->getEmail(), $subscription->getPerson()->getFullName()) ->setSubject($subject); if (getenv('APPLICATION_ENV') != 'development') { $this->getMailTransport()->send($mail); } $this->getEntityManager()->remove($subscription); $this->getEntityManager()->flush(); return new ViewModel( array( 'result' => array( 'status' => 'success', ), ) ); } /** * @return Registered|null */ private function getSubscriptionEntity() { $subscription = $this->getEntityManager() ->getRepository('ShiftBundle\Entity\Shift\Registered') ->findOneById($this->getParam('id', 0)); if ($subscription === null) { $this->flashMessenger()->error( 'Error', 'No subscription with the given ID was found!' ); $this->redirect()->toRoute( 'shift_admin_registration_shift', array( 'action' => 'manage', 'shift' => $this->getEntityById('ShiftBundle\Entity\RegistrationShift', 'shift'), ) ); return; } return $subscription; } /** * @return RegistrationShift|null */ private function getRegistrationShiftEntity() { $shift = $this->getEntityById('ShiftBundle\Entity\RegistrationShift', 'shift'); if (!($shift instanceof RegistrationShift)) { $this->flashMessenger()->error( 'Error', 'No registration shift was found!' ); $this->redirect()->toRoute( 'shift_admin_registration_shift', array( 'action' => 'manage', ) ); return; } return $shift; } }
LitusProject/Litus
module/ShiftBundle/Controller/Admin/RegistrationSubscriptionController.php
PHP
agpl-3.0
5,908
namespace '/storages' do get do @storages = Storage.all return_resource object: @storages end post do @storage = Storage.create!(params[:storage]) return_resource object: @storage end before %r{\A/(?<id>\d+)/?.*} do @storage = Storage.find(params[:id]) end namespace '/:id' do delete do return_resource object: @storage.delete end patch do @storage.assign_attributes(params[:storage]).save! return_resource object: @storage end get do return_resource object: @storage end end end
virtapi/virtapi
controllers/storage_controller.rb
Ruby
agpl-3.0
569
<?php # # Copyright (c) 2000-2003 University of Utah and the Flux Group. # # {{{EMULAB-LICENSE # # This file is part of the Emulab network testbed software. # # This file 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 file 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 file. If not, see <http://www.gnu.org/licenses/>. # # }}} # require("defs.php3"); # # A shameless plug for the web crawlers. # PAGEHEADER("Network Emulation using the Utah Network Testbed"); echo "<br> Emulab.Net provides a great network emulation environment! <br> Please see our <a href=\"$TBDOCBASE\">Home Page</a> for more information.<br><br>\n"; echo "<a href='pix/side-crop-big.jpg'> <img src='pix/side-crop-med.jpg' align=center></a>\n"; PAGEFOOTER(); ?>
nmc-probe/emulab-nome
www/netemu.php3
PHP
agpl-3.0
1,261
from django import template register = template.Library() @register.simple_tag def keyvalue(dict, key): return dict[key]
routetopa/tet
tet/browser/templatetags/keyvalue.py
Python
agpl-3.0
127
<?php namespace Zco\Bundle\GroupesBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\CheckboxType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Validator\Constraints as Assert; final class GroupType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('nom', TextType::class, [ 'label' => 'Nom du groupe', 'constraints' => [new Assert\NotBlank()], ]); $builder->add('logo', TextType::class, [ 'label' => 'URL du logo masculin', 'required' => false, ]); $builder->add('logo_feminin', TextType::class, [ 'label' => 'URL du logo féminin', 'required' => false, ]); $builder->add('sanction', CheckboxType::class, [ 'label' => 'Sanction', 'required' => false, ]); $builder->add('team', CheckboxType::class, [ 'label' => 'Équipe', 'required' => false, ]); $builder->add('secondaire', CheckboxType::class, [ 'label' => 'Groupe secondaire', 'required' => false, ]); } }
zcorrecteurs/zcorrecteurs.fr
src/Zco/Bundle/GroupesBundle/Form/GroupType.php
PHP
agpl-3.0
1,347
/* * TeleStax, Open Source Cloud Communications * Copyright 2012, Telestax Inc and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.cap.api.service.circuitSwitchedCall.primitive; import java.io.Serializable; /** * <code> CollectedInfo ::= CHOICE { collectedDigits [0] CollectedDigits } </code> * * * * @author sergey vetyutnev * */ public interface CollectedInfo extends Serializable { CollectedDigits getCollectedDigits(); }
RestComm/jss7
cap/cap-api/src/main/java/org/restcomm/protocols/ss7/cap/api/service/circuitSwitchedCall/primitive/CollectedInfo.java
Java
agpl-3.0
1,352
# This file is part of Shuup. # # Copyright (c) 2012-2016, Shoop Commerce Ltd. All rights reserved. # # This source code is licensed under the AGPLv3 license found in the # LICENSE file in the root directory of this source tree. import re def camelcase_to_snakecase(string_to_convert): """ Convert CamelCase string to snake_case Original solution in http://stackoverflow.com/questions/1175208/elegant-python-function-to-convert-camelcase-to-snake-case """ s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', string_to_convert) return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
suutari/shoop
shuup/admin/utils/str_utils.py
Python
agpl-3.0
605
package com.tesora.dve.errmap; /* * #%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% */ public class OneParamErrorCode<First> extends ErrorCode { public OneParamErrorCode(String name, boolean logError) { super(name, logError); } }
Tesora/tesora-dve-pub
tesora-dve-common/src/main/java/com/tesora/dve/errmap/OneParamErrorCode.java
Java
agpl-3.0
910
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, 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/>. */ package org.kuali.kra.iacuc; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.common.framework.module.CoeusModule; import org.kuali.coeus.common.framework.person.KcPerson; import org.kuali.coeus.common.notification.impl.NotificationHelper; import org.kuali.coeus.sys.framework.service.KcServiceLocator; import org.kuali.kra.authorization.KraAuthorizationConstants; import org.kuali.kra.iacuc.actions.IacucActionHelper; import org.kuali.kra.iacuc.customdata.IacucProtocolCustomDataHelper; import org.kuali.kra.iacuc.noteattachment.IacucNotesAttachmentsHelper; import org.kuali.kra.iacuc.notification.IacucProtocolNotificationContext; import org.kuali.kra.iacuc.onlinereview.IacucOnlineReviewsActionHelper; import org.kuali.kra.iacuc.onlinereview.IacucProtocolOnlineReviewService; import org.kuali.kra.iacuc.permission.IacucPermissionsHelper; import org.kuali.kra.iacuc.personnel.IacucPersonnelHelper; import org.kuali.kra.iacuc.procedures.IacucProtocolProcedureService; import org.kuali.kra.iacuc.procedures.IacucProtocolProceduresHelper; import org.kuali.kra.iacuc.protocol.IacucProtocolHelper; import org.kuali.kra.iacuc.protocol.reference.IacucProtocolReferenceBean; import org.kuali.kra.iacuc.questionnaire.IacucQuestionnaireHelper; import org.kuali.kra.iacuc.specialreview.IacucProtocolSpecialReviewHelper; import org.kuali.kra.iacuc.species.IacucProtocolSpeciesHelper; import org.kuali.kra.iacuc.species.exception.IacucProtocolExceptionHelper; import org.kuali.kra.iacuc.threers.IacucAlternateSearchHelper; import org.kuali.kra.infrastructure.Constants; import org.kuali.kra.protocol.ProtocolFormBase; import org.kuali.kra.protocol.actions.ActionHelperBase; import org.kuali.kra.protocol.actions.ProtocolStatusBase; import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase; import org.kuali.kra.protocol.customdata.ProtocolCustomDataHelperBase; import org.kuali.kra.protocol.onlinereview.OnlineReviewsActionHelperBase; import org.kuali.kra.protocol.onlinereview.ProtocolOnlineReviewService; import org.kuali.kra.protocol.protocol.ProtocolHelperBase; import org.kuali.kra.protocol.protocol.reference.ProtocolReferenceBeanBase; import org.kuali.kra.protocol.questionnaire.QuestionnaireHelperBase; import org.kuali.kra.protocol.specialreview.ProtocolSpecialReviewHelperBase; import org.kuali.rice.kew.api.WorkflowDocument; import org.kuali.rice.kns.datadictionary.HeaderNavigation; import org.kuali.rice.kns.util.ActionFormUtilMap; import org.kuali.rice.kns.web.ui.HeaderField; import org.kuali.rice.krad.util.GlobalVariables; import javax.servlet.http.HttpServletRequest; import java.util.ArrayList; import java.util.List; public class IacucProtocolForm extends ProtocolFormBase { private static final long serialVersionUID = -535557943052220820L; private IacucProtocolSpeciesHelper iacucProtocolSpeciesHelper; private IacucAlternateSearchHelper iacucAlternateSearchHelper; private IacucProtocolExceptionHelper iacucProtocolExceptionHelper; private IacucProtocolProceduresHelper iacucProtocolProceduresHelper; private boolean defaultOpenCopyTab = false; private boolean reinitializeModifySubmissionFields = true; public IacucProtocolForm() throws Exception { super(); initializeIacucProtocolSpecies(); initializeIacucAlternateSearchHelper(); initializeIacucProtocolException(); initializeIacucProtocolProcedures(); } public void initializeIacucProtocolSpecies() throws Exception { setIacucProtocolSpeciesHelper(new IacucProtocolSpeciesHelper(this)); } public void initializeIacucProtocolProcedures() throws Exception { setIacucProtocolProceduresHelper(new IacucProtocolProceduresHelper(this)); } public void initializeIacucProtocolException() throws Exception { setIacucProtocolExceptionHelper(new IacucProtocolExceptionHelper(this)); } protected void initializeIacucAlternateSearchHelper() throws Exception { setIacucAlternateSearchHelper(new IacucAlternateSearchHelper(this)); } @Override public String getActionName() { return "iacucProtocol"; } @Override protected String getDefaultDocumentTypeName() { return "IacucProtocolDocument"; } /** * Gets a {@link IacucProtocolDocument ProtocolDocument}. * @return {@link IacucProtocolDocument ProtocolDocument} */ public IacucProtocolDocument getIacucProtocolDocument() { return (IacucProtocolDocument) super.getProtocolDocument(); } @Override protected String getLockRegion() { return KraAuthorizationConstants.LOCK_DESCRIPTOR_IACUC_PROTOCOL; } public IacucProtocolHelper getProtocolHelper() { return (IacucProtocolHelper)super.getProtocolHelper(); } @Override protected ProtocolHelperBase createNewProtocolHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucProtocolHelper((IacucProtocolForm) protocolForm); } public IacucPermissionsHelper getPermissionsHelper(ProtocolFormBase protocolForm) { return (IacucPermissionsHelper)super.getPermissionsHelper(); } @Override protected IacucPermissionsHelper createNewPermissionsHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucPermissionsHelper((IacucProtocolForm) protocolForm); } public IacucPersonnelHelper getPersonnelHelper(ProtocolFormBase protocolForm) { return (IacucPersonnelHelper)super.getPersonnelHelper(); } @Override protected IacucPersonnelHelper createNewPersonnelHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucPersonnelHelper((IacucProtocolForm)protocolForm); } public IacucNotesAttachmentsHelper getNotesAttachmentHelper(ProtocolFormBase form) { return (IacucNotesAttachmentsHelper)super.getNotesAttachmentsHelper(); } @Override protected IacucNotesAttachmentsHelper createNewNotesAttachmentsHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucNotesAttachmentsHelper((IacucProtocolForm)protocolForm); } protected QuestionnaireHelperBase createNewQuestionnaireHelper(ProtocolFormBase form) { return new IacucQuestionnaireHelper(form); } @Override public String getModuleCode() { return CoeusModule.IACUC_PROTOCOL_MODULE_CODE; } public IacucProtocolSpeciesHelper getIacucProtocolSpeciesHelper() { return iacucProtocolSpeciesHelper; } public void setIacucProtocolSpeciesHelper(IacucProtocolSpeciesHelper iacucProtocolSpeciesHelper) { this.iacucProtocolSpeciesHelper = iacucProtocolSpeciesHelper; } public IacucAlternateSearchHelper getIacucAlternateSearchHelper() { return iacucAlternateSearchHelper; } public void setIacucAlternateSearchHelper(IacucAlternateSearchHelper iacucAlternateSearchHelper) { this.iacucAlternateSearchHelper = iacucAlternateSearchHelper; } @Override protected ProtocolReferenceBeanBase createNewProtocolReferenceBeanInstance() { return new IacucProtocolReferenceBean(); } public IacucProtocolExceptionHelper getIacucProtocolExceptionHelper() { return iacucProtocolExceptionHelper; } public void setIacucProtocolExceptionHelper(IacucProtocolExceptionHelper iacucProtocolExceptionHelper) { this.iacucProtocolExceptionHelper = iacucProtocolExceptionHelper; } @Override public void populate(HttpServletRequest request) { super.populate(request); // Temporary hack for KRACOEUS-489 if (getActionFormUtilMap() instanceof ActionFormUtilMap) { ((ActionFormUtilMap) getActionFormUtilMap()).clear(); } getIacucProtocolDocument().getIacucProtocol().setIacucProtocolStudyGroupBeans(getIacucProtocolProcedureService().getRevisedStudyGroupBeans(getIacucProtocolDocument().getIacucProtocol(), getIacucProtocolProceduresHelper().getAllProcedures())); } @Override public void populateHeaderFields(WorkflowDocument workflowDocument) { super.populateHeaderFields(workflowDocument); IacucProtocolDocument pd = getIacucProtocolDocument(); HeaderField documentNumber = getDocInfo().get(0); documentNumber.setDdAttributeEntryName("DataDictionary.IacucProtocolDocument.attributes.documentNumber"); ProtocolStatusBase protocolStatus = (pd == null) ? null : pd.getIacucProtocol().getProtocolStatus(); HeaderField docStatus = new HeaderField("DataDictionary.AttributeReference.attributes.workflowDocumentStatus", protocolStatus == null? "" : protocolStatus.getDescription()); getDocInfo().set(1, docStatus); String lastUpdatedDateStr = null; if(pd != null && pd.getUpdateTimestamp() != null) { lastUpdatedDateStr = getFormattedDateTime(pd.getUpdateTimestamp()); } if(getDocInfo().size() > 2) { KcPerson initiator = getKcPersonService().getKcPersonByPersonId(pd.getDocumentHeader().getWorkflowDocument().getInitiatorPrincipalId()); String modifiedInitiatorFieldStr = initiator == null ? "" : initiator.getUserName(); if(StringUtils.isNotBlank(lastUpdatedDateStr)) { modifiedInitiatorFieldStr += (" : " + lastUpdatedDateStr); } getDocInfo().set(2, new HeaderField("DataDictionary.IacucProtocol.attributes.initiatorLastUpdated", modifiedInitiatorFieldStr)); } String protocolSubmissionStatusStr = null; if(pd != null && pd.getIacucProtocol() != null && pd.getIacucProtocol().getProtocolSubmission() != null) { pd.getIacucProtocol().getProtocolSubmission().refreshReferenceObject("submissionStatus"); protocolSubmissionStatusStr = pd.getIacucProtocol().getProtocolSubmission().getSubmissionStatus().getDescription(); } HeaderField protocolSubmissionStatus = new HeaderField("DataDictionary.IacucProtocol.attributes.protocolSubmissionStatus", protocolSubmissionStatusStr); getDocInfo().set(3, protocolSubmissionStatus); getDocInfo().add(new HeaderField("DataDictionary.IacucProtocol.attributes.protocolNumber", (pd == null) ? null : pd.getIacucProtocol().getProtocolNumber())); String expirationDateStr = null; if(pd != null && pd.getProtocol().getExpirationDate() != null) { expirationDateStr = getFormattedDate(pd.getIacucProtocol().getExpirationDate()); } HeaderField expirationDate = new HeaderField("DataDictionary.IacucProtocol.attributes.expirationDate", expirationDateStr); getDocInfo().add(expirationDate); } @Override public HeaderNavigation[] getHeaderNavigationTabs() { HeaderNavigation[] navigation = super.getHeaderNavigationTabs(); ProtocolOnlineReviewService onlineReviewService = getProtocolOnlineReviewService(); List<HeaderNavigation> resultList = new ArrayList<HeaderNavigation>(); boolean onlineReviewTabEnabled = false; if (getProtocolDocument() != null && getProtocolDocument().getProtocol() != null) { String principalId = GlobalVariables.getUserSession().getPrincipalId(); ProtocolSubmissionBase submission = getProtocolDocument().getProtocol().getProtocolSubmission(); boolean isUserOnlineReviewer = onlineReviewService.isProtocolReviewer(principalId, false, submission); boolean isUserIacucAdmin = getSystemAuthorizationService().hasRole(GlobalVariables.getUserSession().getPrincipalId(), "KC-UNT", "IACUC Administrator"); onlineReviewTabEnabled = (isUserOnlineReviewer || isUserIacucAdmin) && onlineReviewService.isProtocolInStateToBeReviewed((IacucProtocol)getProtocolDocument().getProtocol()); } //We have to copy the HeaderNavigation elements into a new collection as the //List returned by DD is it's cached copy of the header navigation list. for (HeaderNavigation nav : navigation) { if (StringUtils.equals(nav.getHeaderTabNavigateTo(),ONLINE_REVIEW_NAV_TO)) { nav.setDisabled(!onlineReviewTabEnabled); if (onlineReviewTabEnabled || ((!onlineReviewTabEnabled) && (!HIDE_ONLINE_REVIEW_WHEN_DISABLED))) { resultList.add(nav); } } else { resultList.add(nav); } } HeaderNavigation[] result = new HeaderNavigation[resultList.size()]; resultList.toArray(result); return result; } protected ProtocolOnlineReviewService getProtocolOnlineReviewService() { return KcServiceLocator.getService(IacucProtocolOnlineReviewService.class); } @Override protected QuestionnaireHelperBase createNewQuestionnaireHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucQuestionnaireHelper((IacucProtocolForm) protocolForm); } @Override protected ActionHelperBase createNewActionHelperInstanceHook(ProtocolFormBase protocolForm, boolean initializeActions) throws Exception{ IacucActionHelper iacucActionHelper = new IacucActionHelper((IacucProtocolForm) protocolForm); if(initializeActions) { iacucActionHelper.initializeProtocolActions(); } return iacucActionHelper; } @Override protected ProtocolSpecialReviewHelperBase createNewSpecialReviewHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucProtocolSpecialReviewHelper((IacucProtocolForm) protocolForm); } @Override protected ProtocolCustomDataHelperBase createNewCustomDataHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucProtocolCustomDataHelper((IacucProtocolForm) protocolForm); } @Override protected OnlineReviewsActionHelperBase createNewOnlineReviewsActionHelperInstanceHook(ProtocolFormBase protocolForm) { return new IacucOnlineReviewsActionHelper((IacucProtocolForm) protocolForm); } public IacucProtocolProceduresHelper getIacucProtocolProceduresHelper() { return iacucProtocolProceduresHelper; } public void setIacucProtocolProceduresHelper(IacucProtocolProceduresHelper iacucProtocolProceduresHelper) { this.iacucProtocolProceduresHelper = iacucProtocolProceduresHelper; } @Override protected NotificationHelper<IacucProtocolNotificationContext> getNotificationHelperHook() { return new NotificationHelper<IacucProtocolNotificationContext>(); } protected IacucProtocolProcedureService getIacucProtocolProcedureService() { return (IacucProtocolProcedureService) KcServiceLocator.getService("iacucProtocolProcedureService"); } public boolean isReinitializeModifySubmissionFields() { return reinitializeModifySubmissionFields; } public void setReinitializeModifySubmissionFields(boolean reinitializeModifySubmissionFields) { this.reinitializeModifySubmissionFields = reinitializeModifySubmissionFields; } public boolean isDefaultOpenCopyTab() { return defaultOpenCopyTab; } public void setDefaultOpenCopyTab(boolean defaultOpenCopyTab) { this.defaultOpenCopyTab = defaultOpenCopyTab; } @Override protected List<String> getTerminalNodeNamesHook() { List<String> retVal = new ArrayList<String>(); retVal.add(Constants.IACUC_PROTOCOL_IACUCREVIEW_ROUTE_NODE_NAME); return retVal; } public String getShortUrl() { return getBaseShortUrl() + "/kc-common/iacuc-protocols/" + getIacucProtocolDocument().getProtocol().getProtocolNumber(); } }
mukadder/kc
coeus-impl/src/main/java/org/kuali/kra/iacuc/IacucProtocolForm.java
Java
agpl-3.0
16,703
<?php class sfGuardGroupUtf8Table extends sfGuardGroupTable { public static function getInstance() { return Doctrine_Core::getTable('sfGuardGroupUtf8'); } }
simonoche/wterritoires
lib/model/doctrine/sfGuardGroupUtf8Table.class.php
PHP
agpl-3.0
183
<?php require_once("conf.php"); $text = $head; $text .= $body; $text .= menu(""); $text .= main(); $text .= $foot; echo gzipoutput($text); // =========================================================================== function main() { global $email, $pass, $pass2, $mysql_db, $name; if (($email != "") and ($pass != "")) { // Variablen nicht leer? if ((validateEmail($email))) { // Email in Ordnung? if ($pass == $pass2) { // Passwort nicht verschrieben? $lk = connect(); $db = mysql_db_query($mysql_db, "SELECT * FROM pricewatch_user WHERE EMAIL=\"" . trim(addslashes(strtolower($email))) . "\" LIMIT 1", $lk); if (!$arr = mysql_fetch_array($db, MYSQL_ASSOC)) { // E-Mail schon eingetragen? $db = mysql_db_query($mysql_db, "INSERT pricewatch_user (EMAIL, PASSWORT) VALUES (\"" . trim(addslashes(strtolower($email))) . "\", \"" . addslashes($pass) . "\")", $lk); if ($db == true) { // DB Eintrag erfolgreich? sendemail ($email, "Anmeldung bei $name", anmeldetext($email, $pass)); $str .= "<br><br><table width='400' align='center' class='rand'>"; $str .= "<tr><td>"; $str .= "<p align='center'><b>Anmeldung erfolgreich abgeschlossen!</b></p>"; $str .= "<p align='justify'>Sie k&ouml;nnen sich jetzt mit ihrer E-Mail und Passwort auf der Startseite einloggen. Zur Best&auml;tigung haben wir ihnen eine E-Mail mit den angegeben Daten geschickt.</p>"; $str .= "<p align='center'><a href='index.php'>Zur&uuml;ck zur Startseite</a></p>"; $str .= "</td></tr></table><br><br>"; } else { // DB Eintrag erfolgreich? $fehler = "Es ist ein Datenbankproblem aufgetreten. Bitte probieren sie es sp&auml;ter noch einmal."; } //DB Eintrag erfolgreich? - Else } else { // E-Mail schon eingetragen? $fehler = "Die E-Mail Adresse ist bereits bei uns angemeldet!"; } // E-Mail schon eingetragen? - Else mysql_close($lk); } else { // Passwort nicht verschrieben? $fehler = "Das Feld Passwort und das Feld Passwort Wiederholung stimmen nicht &uuml;berein!"; } // Passwort nicht verschrieben? - Else } else { // Email in Ordnung? $fehler = "Bitte geben sie eine echte E-Mail Adresse an!"; } // Email in Ordnung? - Else } // Variablen nicht leer? if ((isset($fehler)) OR ($email == "") OR ($pass == "")) { $str = "<br><br>"; if (isset($fehler)) { $str .= "<table width='400' align='center' class='rand'>"; $str .= "<tr><td>"; $str .= "<p align='center'><b>Es ist ein Fehler aufgetreten!</b></p><p align='justify'>$fehler</p></td></tr>"; $str .= "</table><br>"; } $str .= "<table width='400' align='center' class='rand'>"; $str .= "<tr><td>"; $str .= "<p align='justify'>Bitte f&uuml;llen sie das folgende Formular <b>komplett</b> aus und klicken sie auf anmelden! Nach ihrer Anmeldung wird ihnen eine Best&auml;tigungs per E-Mail zugesandt.<br><br></p></td></tr>"; $str .= "<tr><td><table width='75%' align='center'>"; $str .= "<form method='post' action='anmelden.php'>"; $str .= "<tr><td>E-Mail:</td>"; $str .= "<td align='center'><input type='text' name='email' class='input' value='$email'></td></tr>"; $str .= "<tr><td>Passwort:</td>"; $str .= "<td align='center'><input type='password' name='pass' class='input'></td></tr>"; $str .= "<tr><td>Passwort Wdh.:</td>"; $str .= "<td align='center'><input type='password' name='pass2' class='input'></td></tr>"; $str .= "<tr><td colspan='2' align='center'><br><input type='submit' name='Anmelden' class='forminput' value=' Anmelden '></fotm></td></tr>"; $str .= "</table></td></tr>"; $str .= "</table>"; $str .= "<br><br><br>"; } return $str; } ?>
jbreitbart/priceguard_classic
branches/first/anmelden.php
PHP
agpl-3.0
4,179
import * as React from 'react'; import _ from 'lodash'; import { civicSortValue, DEFAULT_ANNOTATION_DATA, GenericAnnotation, IAnnotation, USE_DEFAULT_PUBLIC_INSTANCE_FOR_ONCOKB, oncoKbAnnotationSortValue, } from 'react-mutation-mapper'; import { CancerStudy, StructuralVariant } from 'cbioportal-ts-api-client'; import { IAnnotationColumnProps } from 'shared/components/mutationTable/column/AnnotationColumnFormatter'; import { CancerGene, IndicatorQueryResp } from 'oncokb-ts-api-client'; import { RemoteData, IOncoKbData, generateQueryStructuralVariantId, OncoKbCardDataType, calculateOncoKbAvailableDataType, } from 'cbioportal-utils'; import AnnotationHeader from 'shared/components/mutationTable/column/annotation/AnnotationHeader'; export default class AnnotationColumnFormatter { public static getData( structuralVariantData: StructuralVariant[] | undefined, oncoKbCancerGenes?: RemoteData<CancerGene[] | Error | undefined>, oncoKbData?: RemoteData<IOncoKbData | Error | undefined>, usingPublicOncoKbInstance?: boolean, uniqueSampleKeyToTumorType?: { [sampleId: string]: string }, studyIdToStudy?: { [studyId: string]: CancerStudy } ) { let value: IAnnotation; if (structuralVariantData) { let oncoKbIndicator: IndicatorQueryResp | undefined = undefined; let oncoKbStatus: IAnnotation['oncoKbStatus'] = 'complete'; let oncoKbGeneExist = false; let isOncoKbCancerGene = false; let isSite1GeneOncoKbAnnotated = false; let isSite1oncoKbCancerGene = false; let isSite2GeneOncoKbAnnotated = false; let isSite2oncoKbCancerGene = false; if ( oncoKbCancerGenes && !(oncoKbCancerGenes instanceof Error) && !(oncoKbCancerGenes.result instanceof Error) ) { const oncoKbCancerGeneSetByEntrezGeneId = _.keyBy( oncoKbCancerGenes.result, gene => gene.entrezGeneId ); isSite1oncoKbCancerGene = oncoKbCancerGeneSetByEntrezGeneId[ structuralVariantData[0].site1EntrezGeneId ] !== undefined; isSite2oncoKbCancerGene = oncoKbCancerGeneSetByEntrezGeneId[ structuralVariantData[0].site2EntrezGeneId ] !== undefined; isSite1GeneOncoKbAnnotated = isSite1oncoKbCancerGene && oncoKbCancerGeneSetByEntrezGeneId[ structuralVariantData[0].site1EntrezGeneId ].oncokbAnnotated; isSite2GeneOncoKbAnnotated = isSite2oncoKbCancerGene && oncoKbCancerGeneSetByEntrezGeneId[ structuralVariantData[0].site2EntrezGeneId ].oncokbAnnotated; oncoKbGeneExist = isSite1GeneOncoKbAnnotated || isSite2GeneOncoKbAnnotated; isOncoKbCancerGene = isSite1oncoKbCancerGene || isSite2oncoKbCancerGene; } // Always show oncogenicity icon even when the indicatorMapResult is empty. // We want to show an icon for genes that haven't been annotated by OncoKB let oncoKbAvailableDataTypes: OncoKbCardDataType[] = [ OncoKbCardDataType.BIOLOGICAL, ]; // oncoKbData may exist but it might be an instance of Error, in that case we flag the status as error if (oncoKbData && oncoKbData.result instanceof Error) { oncoKbStatus = 'error'; } else if (oncoKbGeneExist) { // actually, oncoKbData.result shouldn't be an instance of Error in this case (we already check it above), // but we need to check it again in order to avoid TS errors/warnings if ( oncoKbData && oncoKbData.result && !(oncoKbData.result instanceof Error) && oncoKbData.isComplete ) { oncoKbIndicator = this.getIndicatorData( structuralVariantData, oncoKbData.result, uniqueSampleKeyToTumorType, studyIdToStudy ); oncoKbAvailableDataTypes = _.uniq([ ...oncoKbAvailableDataTypes, ...calculateOncoKbAvailableDataType( _.values(oncoKbData.result.indicatorMap) ), ]); } oncoKbStatus = oncoKbData ? oncoKbData.status : 'pending'; } const site1HugoSymbol = structuralVariantData[0].site1HugoSymbol; const site2HugoSymbol = structuralVariantData[0].site2HugoSymbol; let hugoGeneSymbol = site1HugoSymbol; if (oncoKbGeneExist) { hugoGeneSymbol = isSite1GeneOncoKbAnnotated ? site1HugoSymbol : site2HugoSymbol; } else if (isOncoKbCancerGene) { hugoGeneSymbol = isSite1oncoKbCancerGene ? site1HugoSymbol : site2HugoSymbol; } value = { hugoGeneSymbol, oncoKbStatus, oncoKbIndicator, oncoKbGeneExist, isOncoKbCancerGene, usingPublicOncoKbInstance: usingPublicOncoKbInstance === undefined ? USE_DEFAULT_PUBLIC_INSTANCE_FOR_ONCOKB : usingPublicOncoKbInstance, civicEntry: undefined, civicStatus: 'complete', hasCivicVariants: false, myCancerGenomeLinks: [], hotspotStatus: 'complete', isHotspot: false, is3dHotspot: false, oncoKbAvailableDataTypes, }; } else { value = DEFAULT_ANNOTATION_DATA; } return value; } public static getIndicatorData( structuralVariantData: StructuralVariant[], oncoKbData: IOncoKbData, uniqueSampleKeyToTumorType?: { [sampleId: string]: string }, studyIdToStudy?: { [studyId: string]: CancerStudy } ): IndicatorQueryResp | undefined { if ( uniqueSampleKeyToTumorType === null || oncoKbData.indicatorMap === null ) { return undefined; } const id = generateQueryStructuralVariantId( structuralVariantData[0].site1EntrezGeneId, structuralVariantData[0].site2EntrezGeneId, uniqueSampleKeyToTumorType![ structuralVariantData[0].uniqueSampleKey ], structuralVariantData[0].variantClass.toUpperCase() as any ); if (oncoKbData.indicatorMap[id]) { let indicator = oncoKbData.indicatorMap[id]; if (indicator.query.tumorType === null && studyIdToStudy) { const studyMetaData = studyIdToStudy[structuralVariantData[0].studyId]; if (studyMetaData.cancerTypeId !== 'mixed') { indicator.query.tumorType = studyMetaData.cancerType.name; } } return indicator; } else { return undefined; } } public static sortValue( data: StructuralVariant[], oncoKbCancerGenes?: RemoteData<CancerGene[] | Error | undefined>, usingPublicOncoKbInstance?: boolean, oncoKbData?: RemoteData<IOncoKbData | Error | undefined>, uniqueSampleKeyToTumorType?: { [sampleId: string]: string } ): number[] { const annotationData: IAnnotation = this.getData( data, oncoKbCancerGenes, oncoKbData, usingPublicOncoKbInstance, uniqueSampleKeyToTumorType ); return _.flatten([ oncoKbAnnotationSortValue(annotationData.oncoKbIndicator), civicSortValue(annotationData.civicEntry), annotationData.isOncoKbCancerGene ? 1 : 0, ]); } public static headerRender( name: string, width: number, mergeOncoKbIcons?: boolean, onOncoKbIconToggle?: (mergeIcons: boolean) => void ) { return ( <AnnotationHeader name={name} width={width} mergeOncoKbIcons={mergeOncoKbIcons} onOncoKbIconToggle={onOncoKbIconToggle} /> ); } public static renderFunction( data: StructuralVariant[], columnProps: IAnnotationColumnProps ) { const annotation: IAnnotation = this.getData( data, columnProps.oncoKbCancerGenes, columnProps.oncoKbData, columnProps.usingPublicOncoKbInstance, columnProps.uniqueSampleKeyToTumorType, columnProps.studyIdToStudy ); return <GenericAnnotation {...columnProps} annotation={annotation} />; } }
cBioPortal/cbioportal-frontend
src/pages/patientView/structuralVariant/column/AnnotationColumnFormatter.tsx
TypeScript
agpl-3.0
9,418
# frozen_string_literal: true require 'rails_helper' RSpec.describe 'repository/tag query' do let(:context) { {} } let(:query_string) do <<-QUERY query ($repositoryId: ID!, $name: String!) { repository(id: $repositoryId) { tag(name: $name) { name target { id } annotation } } } QUERY end let(:repository) do create(:repository_compound, :not_empty, public_access: false, owner: current_user) end let(:git) { repository.git } let!(:tag) { create(:tag, repository: repository, message: message) } let(:current_user) { create(:user) } let(:variables_base) { {'repositoryId' => repository.to_param} } let(:variables_existent) { variables_base.merge('name' => tag.name) } let(:variables_not_existent) { variables_base.merge('name' => 'bad') } let(:expectation_signed_in_existent) do tag_data = { 'name' => tag.name, 'annotation' => message, 'target' => {'id' => git.commit(tag.target).id}, } match('data' => {'repository' => {'tag' => tag_data}}) end let(:expectation_signed_in_not_existent) do match('data' => {'repository' => {'tag' => nil}}) end let(:expectation_not_signed_in_existent) do match('data' => {'repository' => nil}) end let(:expectation_not_signed_in_not_existent) do expectation_not_signed_in_existent end context 'with annotation' do let(:message) { 'message' } it_behaves_like 'a GraphQL query', %w(repository tag) end context 'without annotation' do let(:message) { nil } it_behaves_like 'a GraphQL query', %w(repository tag) end end
ontohub/ontohub-backend
spec/graphql/queries/repository/tag_query_spec.rb
Ruby
agpl-3.0
1,684
<?php /* Question2Answer (c) Gideon Greenspan http://www.question2answer.org/ File: qa-include/qa-ajax-version.php Version: See define()s at top of qa-include/qa-base.php Description: Server-side response to Ajax version check requests This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. More about this license: http://www.question2answer.org/license.php */ require_once QA_INCLUDE_DIR.'qa-app-admin.php'; $uri=qa_post_text('uri'); $versionkey=qa_post_text('versionkey'); $urikey=qa_post_text('urikey'); $version=qa_post_text('version'); $metadata=qa_admin_addon_metadata(qa_retrieve_url($uri), array( 'version' => $versionkey, 'uri' => $urikey, // these two elements are only present for plugins, not themes, so we can hard code them here 'min_q2a' => 'Plugin Minimum Question2Answer Version', 'min_php' => 'Plugin Minimum PHP Version', )); if (strlen(@$metadata['version'])) { if (strcmp($metadata['version'], $version)) { if (qa_qa_version_below(@$metadata['min_q2a'])) $response=strtr(qa_lang_html('admin/version_requires_q2a'), array( '^1' => qa_html('v'.$metadata['version']), '^2' => qa_html($metadata['min_q2a']), )); elseif (qa_php_version_below(@$metadata['min_php'])) $response=strtr(qa_lang_html('admin/version_requires_php'), array( '^1' => qa_html('v'.$metadata['version']), '^2' => qa_html($metadata['min_php']), )); else { $response=qa_lang_html_sub('admin/version_get_x', qa_html('v'.$metadata['version'])); if (strlen(@$metadata['uri'])) $response='<A HREF="'.qa_html($metadata['uri']).'" STYLE="color:#d00;">'.$response.'</A>'; } } else $response=qa_lang_html('admin/version_latest'); } else $response=qa_lang_html('admin/version_latest_unknown'); echo "QA_AJAX_RESPONSE\n1\n".$response; /* Omit PHP closing tag to help avoid accidental output */
teleiakaipavla/diafthoratelos.gr
php/wordpress/qa/qa-include/qa-ajax-version.php
PHP
agpl-3.0
2,412
# -*- coding: utf-8 -*- import os.path import posixpath import re import urllib from docutils import nodes from sphinx import addnodes, util from sphinx.locale import admonitionlabels def _parents(node): while node.parent: node = node.parent yield node class BootstrapTranslator(nodes.NodeVisitor, object): head_prefix = 'head_prefix' head = 'head' stylesheet = 'stylesheet' body_prefix = 'body_prefix' body_pre_docinfo = 'body_pre_docinfo' docinfo = 'docinfo' body_suffix = 'body_suffix' subtitle = 'subtitle' header = 'header' footer = 'footer' html_prolog = 'html_prolog' html_head = 'html_head' html_title = 'html_title' html_subtitle = 'html_subtitle' # <meta> tags meta = [ '<meta http-equiv="X-UA-Compatible" content="IE=edge">', '<meta name="viewport" content="width=device-width, initial-scale=1">' ] def __init__(self, builder, document): super(BootstrapTranslator, self).__init__(document) self.builder = builder self.body = [] self.fragment = self.body self.html_body = self.body # document title self.title = [] self.start_document_title = 0 self.first_title = False self.context = [] self.section_level = 0 self.highlightlang = self.highlightlang_base = self.builder.config.highlight_language self.highlightopts = getattr(builder.config, 'highlight_options', {}) self.first_param = 1 self.optional_param_level = 0 self.required_params_left = 0 self.param_separator = ',' def encode(self, text): return unicode(text).translate({ ord('&'): u'&amp;', ord('<'): u'&lt;', ord('"'): u'&quot;', ord('>'): u'&gt;', 0xa0: u'&nbsp;' }) def starttag(self, node, tagname, **attributes): tagname = unicode(tagname).lower() # extract generic attributes attrs = {name.lower(): value for name, value in attributes.iteritems()} attrs.update( (name, value) for name, value in node.attributes.iteritems() if name.startswith('data-') ) prefix = [] postfix = [] # handle possibly multiple ids assert 'id' not in attrs, "starttag can't be passed a single id attribute, use a list of ids" ids = node.get('ids', []) + attrs.pop('ids', []) if ids: _ids = iter(ids) attrs['id'] = next(_ids) postfix.extend(u'<i id="{}"></i>'.format(_id) for _id in _ids) # set CSS class classes = set(node.get('classes', []) + attrs.pop('class', '').split()) if classes: attrs['class'] = u' '.join(classes) return u'{prefix}<{tag} {attrs}>{postfix}'.format( prefix=u''.join(prefix), tag=tagname, attrs=u' '.join(u'{}="{}"'.format(name, self.attval(value)) for name, value in attrs.iteritems()), postfix=u''.join(postfix), ) # only "space characters" SPACE, CHARACTER TABULATION, LINE FEED, # FORM FEED and CARRIAGE RETURN should be collapsed, not al White_Space def attval(self, value, whitespace=re.compile(u'[ \t\n\f\r]')): return self.encode(whitespace.sub(u' ', unicode(value))) def astext(self): return u''.join(self.body) def unknown_visit(self, node): print "unknown node", node.__class__.__name__ self.body.append(u'[UNKNOWN NODE {}]'.format(node.__class__.__name__)) raise nodes.SkipNode def visit_highlightlang(self, node): self.highlightlang = node['lang'] def depart_highlightlang(self, node): pass def visit_document(self, node): self.first_title = True def depart_document(self, node): pass def visit_section(self, node): # close "parent" or preceding section, unless this is the opening of # the first section if self.section_level: self.body.append(u'</section>') self.section_level += 1 self.body.append(self.starttag(node, 'section')) def depart_section(self, node): self.section_level -= 1 # close last section of document if not self.section_level: self.body.append(u'</section>') def is_compact_paragraph(self, node): parent = node.parent if isinstance(parent, (nodes.document, nodes.compound, addnodes.desc_content, addnodes.versionmodified)): # Never compact paragraphs in document or compound. return False for key, value in node.attlist(): # we can ignore a few specific classes, all other non-default # attributes require that a <p> node remains if key != 'classes' or value not in ([], ['first'], ['last'], ['first', 'last']): return False first = isinstance(node.parent[0], nodes.label) for child in parent.children[first:]: # only first paragraph can be compact if isinstance(child, nodes.Invisible): continue if child is node: break return False parent_length = len([ 1 for n in parent if not isinstance(n, (nodes.Invisible, nodes.label)) ]) return parent_length == 1 def visit_paragraph(self, node): if self.is_compact_paragraph(node): self.context.append(u'') return self.body.append(self.starttag(node, 'p')) self.context.append(u'</p>') def depart_paragraph(self, node): self.body.append(self.context.pop()) def visit_compact_paragraph(self, node): pass def depart_compact_paragraph(self, node): pass def visit_literal_block(self, node): if node.rawsource != node.astext(): # most probably a parsed-literal block -- don't highlight self.body.append(self.starttag(node, 'pre')) return lang = self.highlightlang highlight_args = node.get('highlight_args', {}) if 'language' in node: # code-block directives lang = node['language'] highlight_args['force'] = True linenos = node.get('linenos', False) if lang is self.highlightlang_base: # only pass highlighter options for original language opts = self.highlightopts else: opts = {} def warner(msg): self.builder.warn(msg, (self.builder.current_docname, node.line)) highlighted = self.builder.highlighter.highlight_block( node.rawsource, lang, opts=opts, warn=warner, linenos=linenos, **highlight_args) self.body.append(self.starttag(node, 'div', CLASS='highlight-%s' % lang)) self.body.append(highlighted) self.body.append(u'</div>\n') raise nodes.SkipNode def depart_literal_block(self, node): self.body.append(u'</pre>') def visit_bullet_list(self, node): self.body.append(self.starttag(node, 'ul')) def depart_bullet_list(self, node): self.body.append(u'</ul>') def visit_enumerated_list(self, node): self.body.append(self.starttag(node, 'ol')) def depart_enumerated_list(self, node): self.body.append(u'</ol>') def visit_list_item(self, node): self.body.append(self.starttag(node, 'li')) def depart_list_item(self, node): self.body.append(u'</li>') def visit_definition_list(self, node): self.body.append(self.starttag(node, 'dl')) def depart_definition_list(self, node): self.body.append(u'</dl>') def visit_definition_list_item(self, node): pass def depart_definition_list_item(self, node): pass def visit_term(self, node): self.body.append(self.starttag(node, 'dt')) def depart_term(self, node): self.body.append(u'</dt>') def visit_termsep(self, node): self.body.append(self.starttag(node, 'br')) raise nodes.SkipNode def visit_definition(self, node): self.body.append(self.starttag(node, 'dd')) def depart_definition(self, node): self.body.append(u'</dd>') def visit_admonition(self, node, type=None): clss = { # ???: 'alert-success', 'note': 'alert-info', 'hint': 'alert-info', 'tip': 'alert-info', 'seealso': 'alert-info', 'warning': 'alert-warning', 'attention': 'alert-warning', 'caution': 'alert-warning', 'important': 'alert-warning', 'danger': 'alert-danger', 'error': 'alert-danger', 'exercise': 'alert-exercise', } self.body.append(self.starttag(node, 'div', role='alert', CLASS='alert {}'.format( clss.get(type, '') ))) if 'alert-dismissible' in node.get('classes', []): self.body.append( u'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' u'<span aria-hidden="true">&times;</span>' u'</button>') if type: node.insert(0, nodes.title(type, admonitionlabels[type])) def depart_admonition(self, node): self.body.append(u'</div>') visit_note = lambda self, node: self.visit_admonition(node, 'note') visit_warning = lambda self, node: self.visit_admonition(node, 'warning') visit_attention = lambda self, node: self.visit_admonition(node, 'attention') visit_caution = lambda self, node: self.visit_admonition(node, 'caution') visit_danger = lambda self, node: self.visit_admonition(node, 'danger') visit_error = lambda self, node: self.visit_admonition(node, 'error') visit_hint = lambda self, node: self.visit_admonition(node, 'hint') visit_important = lambda self, node: self.visit_admonition(node, 'important') visit_tip = lambda self, node: self.visit_admonition(node, 'tip') visit_exercise = lambda self, node: self.visit_admonition(node, 'exercise') visit_seealso = lambda self, node: self.visit_admonition(node, 'seealso') depart_note = depart_admonition depart_warning = depart_admonition depart_attention = depart_admonition depart_caution = depart_admonition depart_danger = depart_admonition depart_error = depart_admonition depart_hint = depart_admonition depart_important = depart_admonition depart_tip = depart_admonition depart_exercise = depart_admonition depart_seealso = depart_admonition def visit_versionmodified(self, node): self.body.append(self.starttag(node, 'div', CLASS=node['type'])) def depart_versionmodified(self, node): self.body.append(u'</div>') def visit_title(self, node): parent = node.parent closing = u'</p>' if isinstance(parent, nodes.Admonition): self.body.append(self.starttag(node, 'p', CLASS='alert-title')) elif isinstance(node.parent, nodes.document): self.body.append(self.starttag(node, 'h1')) closing = u'</h1>' self.start_document_title = len(self.body) else: assert isinstance(parent, nodes.section), "expected a section node as parent to the title, found {}".format(parent) if self.first_title: self.first_title = False raise nodes.SkipNode() nodename = 'h{}'.format(self.section_level) self.body.append(self.starttag(node, nodename)) closing = u'</{}>'.format(nodename) self.context.append(closing) def depart_title(self, node): self.body.append(self.context.pop()) if self.start_document_title: self.title = self.body[self.start_document_title:-1] self.start_document_title = 0 del self.body[:] # the rubric should be a smaller heading than the current section, up to # h6... maybe "h7" should be a ``p`` instead? def visit_rubric(self, node): self.body.append(self.starttag(node, 'h{}'.format(min(self.section_level + 1, 6)))) def depart_rubric(self, node): self.body.append(u'</h{}>'.format(min(self.section_level + 1, 6))) def visit_block_quote(self, node): self.body.append(self.starttag(node, 'blockquote')) def depart_block_quote(self, node): self.body.append(u'</blockquote>') def visit_attribution(self, node): self.body.append(self.starttag(node, 'footer')) def depart_attribution(self, node): self.body.append(u'</footer>') def visit_container(self, node): self.body.append(self.starttag(node, 'div')) def depart_container(self, node): self.body.append(u'</div>') def visit_compound(self, node): self.body.append(self.starttag(node, 'div')) def depart_compound(self, node): self.body.append(u'</div>') def visit_image(self, node): uri = node['uri'] if uri in self.builder.images: uri = posixpath.join(self.builder.imgpath, self.builder.images[uri]) attrs = {'src': uri, 'class': 'img-responsive'} if 'alt' in node: attrs['alt'] = node['alt'] # todo: explicit width/height/scale? self.body.append(self.starttag(node, 'img', **attrs)) def depart_image(self, node): pass def visit_figure(self, node): self.body.append(self.starttag(node, 'div')) def depart_figure(self, node): self.body.append(u'</div>') def visit_caption(self, node): # first paragraph of figure content self.body.append(self.starttag(node, 'h4')) def depart_caption(self, node): self.body.append(u'</h4>') def visit_legend(self, node): pass def depart_legend(self, node): pass def visit_line(self, node): self.body.append(self.starttag(node, 'div', CLASS='line')) # ensure the line still takes the room it needs if not len(node): self.body.append(u'<br />') def depart_line(self, node): self.body.append(u'</div>') def visit_line_block(self, node): self.body.append(self.starttag(node, 'div', CLASS='line-block')) def depart_line_block(self, node): self.body.append(u'</div>') def visit_table(self, node): self.body.append(self.starttag(node, 'table', CLASS='table')) def depart_table(self, node): self.body.append(u'</table>') def visit_tgroup(self, node): pass def depart_tgroup(self, node): pass def visit_colspec(self, node): raise nodes.SkipNode def visit_thead(self, node): self.body.append(self.starttag(node, 'thead')) def depart_thead(self, node): self.body.append(u'</thead>') def visit_tbody(self, node): self.body.append(self.starttag(node, 'tbody')) def depart_tbody(self, node): self.body.append(u'</tbody>') def visit_row(self, node): self.body.append(self.starttag(node, 'tr')) def depart_row(self, node): self.body.append(u'</tr>') def visit_entry(self, node): if isinstance(node.parent.parent, nodes.thead): tagname = 'th' else: tagname = 'td' self.body.append(self.starttag(node, tagname)) self.context.append(tagname) def depart_entry(self, node): self.body.append(u'</{}>'.format(self.context.pop())) def visit_Text(self, node): self.body.append(self.encode(node.astext())) def depart_Text(self, node): pass def visit_literal(self, node): self.body.append(self.starttag(node, 'code')) def depart_literal(self, node): self.body.append(u'</code>') visit_literal_emphasis = visit_literal depart_literal_emphasis = depart_literal def visit_emphasis(self, node): self.body.append(self.starttag(node, 'em')) def depart_emphasis(self, node): self.body.append(u'</em>') def visit_strong(self, node): self.body.append(self.starttag(node, 'strong')) def depart_strong(self, node): self.body.append(u'</strong>') visit_literal_strong = visit_strong depart_literal_strong = depart_strong def visit_inline(self, node): self.body.append(self.starttag(node, 'span')) def depart_inline(self, node): self.body.append(u'</span>') def visit_abbreviation(self, node): attrs = {} if 'explanation' in node: attrs['title'] = node['explanation'] self.body.append(self.starttag(node, 'abbr', **attrs)) def depart_abbreviation(self, node): self.body.append(u'</abbr>') def visit_reference(self, node): attrs = { 'class': 'reference', 'href': node['refuri'] if 'refuri' in node else '#' + node['refid'] } attrs['class'] += ' internal' if (node.get('internal') or 'refuri' not in node) else ' external' if any(isinstance(ancestor, nodes.Admonition) for ancestor in _parents(node)): attrs['class'] += ' alert-link' if 'reftitle' in node: attrs['title'] = node['reftitle'] self.body.append(self.starttag(node, 'a', **attrs)) def depart_reference(self, node): self.body.append(u'</a>') def visit_target(self, node): pass def depart_target(self, node): pass def visit_footnote(self, node): self.body.append(self.starttag(node, 'div', CLASS='footnote')) self.footnote_backrefs(node) def depart_footnote(self, node): self.body.append(u'</div>') def visit_footnote_reference(self, node): self.body.append(self.starttag( node, 'a', href='#' + node['refid'], CLASS="footnote-ref")) def depart_footnote_reference(self, node): self.body.append(u'</a>') def visit_label(self, node): self.body.append(self.starttag(node, 'span', CLASS='footnote-label')) self.body.append(u'%s[' % self.context.pop()) def depart_label(self, node): # Context added in footnote_backrefs. self.body.append(u']%s</span> %s' % (self.context.pop(), self.context.pop())) def footnote_backrefs(self, node): # should store following data on context stack (in that order since # they'll be popped so LIFO) # # * outside (after) label # * after label text # * before label text backrefs = node['backrefs'] if not backrefs: self.context.extend(['', '', '']) elif len(backrefs) == 1: self.context.extend([ '', '</a>', '<a class="footnote-backref" href="#%s">' % backrefs[0] ]) else: backlinks = ( '<a class="footnote-backref" href="#%s">%s</a>' % (backref, i) for i, backref in enumerate(backrefs, start=1) ) self.context.extend([ '<em class="footnote-backrefs">(%s)</em> ' % ', '.join(backlinks), '', '' ]) def visit_desc(self, node): self.body.append(self.starttag(node, 'section', CLASS='code-' + node['objtype'])) def depart_desc(self, node): self.body.append(u'</section>') def visit_desc_signature(self, node): self.body.append(self.starttag(node, 'h6')) self.body.append(u'<code>') def depart_desc_signature(self, node): self.body.append(u'</code>') self.body.append(u'</h6>') def visit_desc_addname(self, node): pass def depart_desc_addname(self, node): pass def visit_desc_type(self, node): pass def depart_desc_type(self, node): pass def visit_desc_returns(self, node): self.body.append(u' → ') def depart_desc_returns(self, node): pass def visit_desc_name(self, node): pass def depart_desc_name(self, node): pass def visit_desc_parameterlist(self, node): self.body.append(u'(') self.first_param = True self.optional_param_level = 0 # How many required parameters are left. self.required_params_left = sum(isinstance(c, addnodes.desc_parameter) for c in node.children) self.param_separator = node.child_text_separator def depart_desc_parameterlist(self, node): self.body.append(u')') # If required parameters are still to come, then put the comma after # the parameter. Otherwise, put the comma before. This ensures that # signatures like the following render correctly (see issue #1001): # # foo([a, ]b, c[, d]) # def visit_desc_parameter(self, node): if self.first_param: self.first_param = 0 elif not self.required_params_left: self.body.append(self.param_separator) if self.optional_param_level == 0: self.required_params_left -= 1 if 'noemph' not in node: self.body.append(u'<em>') def depart_desc_parameter(self, node): if 'noemph' not in node: self.body.append(u'</em>') if self.required_params_left: self.body.append(self.param_separator) def visit_desc_optional(self, node): self.optional_param_level += 1 self.body.append(u'[') def depart_desc_optional(self, node): self.optional_param_level -= 1 self.body.append(u']') def visit_desc_annotation(self, node): self.body.append(self.starttag(node, 'em')) def depart_desc_annotation(self, node): self.body.append(u'</em>') def visit_desc_content(self, node): pass def depart_desc_content(self, node): pass def visit_field_list(self, node): self.body.append(self.starttag(node, 'div', CLASS='code-fields')) def depart_field_list(self, node): self.body.append(u'</div>') def visit_field(self, node): self.body.append(self.starttag(node, 'div', CLASS='code-field')) def depart_field(self, node): self.body.append(u'</div>') def visit_field_name(self, node): self.body.append(self.starttag(node, 'div', CLASS='code-field-name')) def depart_field_name(self, node): self.body.append(u'</div>') def visit_field_body(self, node): self.body.append(self.starttag(node, 'div', CLASS='code-field-body')) def depart_field_body(self, node): self.body.append(u'</div>') def visit_glossary(self, node): pass def depart_glossary(self, node): pass def visit_comment(self, node): raise nodes.SkipNode def visit_toctree(self, node): # div class=row {{ section_type }} # h2 class=col-sm-12 # {{ section title }} # div class=col-sm-6 col-md-3 # figure class=card # a href=current_link style=background-image: document-image-attribute class=card-img # figcaption # {{ card title }} env = self.builder.env conf = self.builder.app.config for title, ref in ((e[0], e[1]) for e in node['entries']): # external URL, no toc, can't recurse into if ref not in env.tocs: continue toc = env.tocs[ref].traverse(addnodes.toctree) classes = env.metadata[ref].get('types', 'tutorials') classes += ' toc-single-entry' if not toc else ' toc-section' self.body.append(self.starttag(node, 'div', CLASS="row " + classes)) self.body.append(u'<h2 class="col-sm-12">') self.body.append(title if title else util.nodes.clean_astext(env.titles[ref])) self.body.append(u'</h2>') entries = [(title, ref)] if not toc else ((e[0], e[1]) for e in toc[0]['entries']) for subtitle, subref in entries: baseuri = self.builder.get_target_uri(node['parent']) if subref in env.metadata: cover = env.metadata[subref].get('banner', conf.odoo_cover_default) elif subref in conf.odoo_cover_external: cover = conf.odoo_cover_external[subref] else: cover = conf.odoo_cover_default_external if cover: banner = '_static/' + cover base, ext = os.path.splitext(banner) small = "{}.small{}".format(base, ext) if os.path.isfile(urllib.url2pathname(small)): banner = small style = u"background-image: url('{}')".format( util.relative_uri(baseuri, banner) or '#') else: style = u'' self.body.append(u""" <div class="col-sm-6 col-md-3"> <figure class="card"> <a href="{link}" class="card-img"> <span style="{style}"></span> <figcaption>{title}</figcaption> </a> </figure> </div> """.format( link=subref if util.url_re.match(subref) else util.relative_uri( baseuri, self.builder.get_target_uri(subref)), style=style, title=subtitle if subtitle else util.nodes.clean_astext(env.titles[subref]), )) self.body.append(u'</div>') raise nodes.SkipNode def visit_index(self, node): raise nodes.SkipNode def visit_raw(self, node): if 'html' in node.get('format', '').split(): t = 'span' if isinstance(node.parent, nodes.TextElement) else 'div' if node['classes']: self.body.append(self.starttag(node, t)) self.body.append(node.astext()) if node['classes']: self.body.append('</%s>' % t) # Keep non-HTML raw text out of output: raise nodes.SkipNode
xujb/odoo
doc/_extensions/odoo/translator.py
Python
agpl-3.0
26,143
"""Laposte XML -> Python.""" from datetime import datetime from lxml import objectify from ...codec import DecoderGetLabel from ...codec import DecoderGetPackingSlip import base64 class _UNSPECIFIED: pass def _get_text(xml, tag, default=_UNSPECIFIED): """ Returns the text content of a tag to avoid returning an lxml instance If no default is specified, it will raises the original exception of accessing to an inexistant tag """ if not hasattr(xml, tag): if default is _UNSPECIFIED: # raise classic attr error return getattr(xml, tag) return default return getattr(xml, tag).text def _get_cid(tag, tree): element = tree.find(tag) if element is None: return None href = element.getchildren()[0].attrib["href"] # href contains cid:236212...-38932@cfx.apache.org return href[len("cid:") :] # remove prefix class LaposteFrDecoderGetLabel(DecoderGetLabel): """Laposte XML -> Python.""" def decode(self, response, input_payload): """Laposte XML -> Python.""" body = response["body"] parts = response["parts"] output_format = input_payload["output_format"] xml = objectify.fromstring(body) msg = xml.xpath("//return")[0] rep = msg.labelV2Response cn23_cid = _get_cid("cn23", rep) label_cid = _get_cid("label", rep) annexes = [] if cn23_cid: data = parts.get(cn23_cid) annexes.append( {"name": "cn23", "data": base64.b64encode(data), "type": "pdf"} ) if rep.find("pdfUrl"): annexes.append({"name": "label", "data": rep.find("pdfUrl"), "type": "url"}) parcel = { "id": 1, # no multi parcel management for now. "reference": self._get_parcel_number(input_payload), "tracking": { # we need to force to real string because of those data can be reused # and cerberus won't accept an ElementString insteadof a string. "number": _get_text(rep, "parcelNumber"), "url": "", "partner": _get_text(rep, "parcelNumberPartner", ""), }, "label": { "data": base64.b64encode(parts.get(label_cid)), "name": "label_1", "type": output_format, }, } if hasattr(rep, "fields") and hasattr(rep.fields, "field"): for field in rep.fields.field: parcel["tracking"][_get_text(field, "key")] = _get_text(field, "value") self.result["parcels"].append(parcel) self.result["annexes"] += annexes class LaposteFrDecoderGetPackingSlip(DecoderGetPackingSlip): """Laposte Bordereau Response XML -> Python.""" def decode(self, response, input_payload): body = response["body"] parts = response["parts"] xml = objectify.fromstring(body) msg = xml.xpath("//return")[0] header = msg.bordereau.bordereauHeader published_dt = _get_text(header, "publishingDate", None) if published_dt: if "." in published_dt: # get packing slip with it's number does not return microseconds # but when creating a new one, it does... We remove microseconds in result # to have a better homogeneity published_dt = published_dt.split(".") published_dt = "%s+%s" % ( published_dt[0], published_dt[1].split("+")[1], ) published_datetime = datetime.strptime(published_dt, "%Y-%m-%dT%H:%M:%S%z") self.result["packing_slip"] = { "number": _get_text(header, "bordereauNumber", None), "published_datetime": published_datetime, "number_of_parcels": int(_get_text(header, "numberOfParcels", 0)), "site_pch": { "code": _get_text(header, "codeSitePCH", None), "name": _get_text(header, "nameSitePCH", None), }, "client": { "number": _get_text(header, "clientNumber", None), "adress": _get_text(header, "Address", None), "company": _get_text(header, "Company", None), }, } packing_slip_cid = _get_cid("bordereauDataHandler", msg.bordereau) if packing_slip_cid: self.result["annexes"].append( { "name": "packing_slip", "data": base64.b64encode(parts.get(packing_slip_cid)), "type": "pdf", } ) return self.result
akretion/roulier
roulier/carriers/laposte_fr/decoder.py
Python
agpl-3.0
4,729
"""alloccli subcommand for editing alloc reminders.""" from alloc import alloc import re class reminder(alloc): """Add or edit a reminder.""" # Setup the options that this cli can accept ops = [] ops.append(('', 'help ', 'Show this help.')) ops.append(('q', 'quiet ', 'Run with less output.\n')) ops.append(('r.', ' ', 'Edit a reminder. Specify an ID or omit -r to create.')) ops.append(('t.', 'task=ID|NAME ', 'A task ID, or a fuzzy match for a task name.')) ops.append(('p.', 'project=ID|NAME', 'A project ID, or a fuzzy match for a project name.')) ops.append(('c.', 'client=ID|NAME ', 'A client ID, or a fuzzy match for a client name.')) ops.append(('s.', 'subject=TEXT ', 'The subject line of the reminder.')) ops.append(('b.', 'body=TEXT ', 'The text body of the reminder.')) ops.append(('', 'frequency=FREQ ', 'How often this reminder is to recur.\n' 'Specify as [number][unit], where unit is one of:\n' '[h]our, [d]ay, [w]eek, [m]onth, [y]ear.')) ops.append(('', 'notice=WARNING ', 'Advance warning for this reminder. Same format as frequency.')) ops.append(('d.', 'date=DATE ', 'When this reminder is to trigger.')) ops.append(('', 'active=1|0 ', 'Whether this reminder is active or not.')) ops.append(('T:', 'to=PEOPLE ', 'Recipients. Can be usernames, full names and/or email.')) ops.append(('D:', 'remove=PEOPLE ', 'Recipients to remove.')) # Specify some header and footer text for the help text help_text = "Usage: %s [OPTIONS]\n" help_text += __doc__ help_text += """\n\n%s This program allows editing of the fields on a reminder. Examples: # Edit a particular reminder. alloc reminder -r 1234 --title 'Name for the reminder.' --to alla # Omit -r to create a new reminder alloc reminder --title 'Name for the reminder.' --to alla""" def run(self, command_list): """Execute subcommand.""" # Get the command line arguments into a dictionary o, remainder_ = self.get_args(command_list, self.ops, self.help_text) # Got this far, then authenticate self.authenticate() personID = self.get_my_personID() args = {} if not o['r']: o['r'] = 'new' args['entity'] = 'reminder' args['id'] = o['r'] if o['date']: o['date'] = self.parse_date(o['date']) if o['project'] and not self.is_num(o['project']): o['project'] = self.search_for_project(o['project'], personID) if o['task'] and not self.is_num(o['task']): o['task'] = self.search_for_task({'taskName': o['task']}) if o['client'] and not self.is_num(o['client']): o['client'] = self.search_for_client({'clientName': o['client']}) if o['frequency'] and not re.match(r'\d+[hdwmy]', o['frequency'], re.IGNORECASE): self.die("Invalid frequency specification") if o['notice'] and not re.match(r'\d+[hdwmy]', o['notice'], re.IGNORECASE): self.die("Invalid advance notice specification") if o['to']: o['recipients'] = [x['personID'] for x in self.get_people(o['to']).values()] if o['remove']: o['recipients_remove'] = [x['personID'] for x in self.get_people(o['remove']).values()] package = {} for key, val in o.items(): if val: package[key] = val if isinstance(val, str) and val.lower() == 'null': package[key] = '' package['command'] = 'edit_reminder' args['options'] = package args['method'] = 'edit_entity' rtn = self.make_request(args) self.handle_server_response(rtn, not o['quiet'])
mattcen/alloc
bin/alloccli/reminder.py
Python
agpl-3.0
3,917
import React from 'react'; import { DragSource, DropTarget } from 'react-dnd'; import { compose } from 'redux'; import DragDropItemTypes from './DragDropItemTypes'; import { HeaderDeleted, HeaderNormal } from './SampleDetailsContainersAux'; const orderSource = { beginDrag(props) { const { container, sample } = props; return { cId: container.id, sId: sample.id }; }, }; const orderTarget = { drop(targetProps, monitor) { const { container, sample, handleMove } = targetProps; const tgTag = { cId: container.id, sId: sample.id }; const scTag = monitor.getItem(); if (tgTag.sId === scTag.sId && tgTag.cId !== scTag.cId) { handleMove(scTag, tgTag); } }, }; const orderDragCollect = (connect, monitor) => ({ connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), }); const orderDropCollect = (connect, monitor) => ({ connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop(), }); const ContainerRow = ({ sample, container, mode, readOnly, isDisabled, handleRemove, handleSubmit, handleAccordionOpen, toggleAddToReport, handleUndo, connectDragSource, connectDropTarget, isDragging, isOver, canDrop, }) => { const style = {}; if (canDrop) { style.borderStyle = 'dashed'; style.borderWidth = 2; } if (isOver) { style.borderColor = '#337ab7'; } if (isDragging) { style.opacity = 0.2; } const oPanelCN = container.is_deleted ? "order-panel-delete" : "order-panel"; return compose(connectDragSource, connectDropTarget)( <div className={oPanelCN} style={style}> <div className="dnd-btn"> <span className="text-info fa fa-arrows" /> </div> { container.is_deleted ? <HeaderDeleted container={container} handleUndo={handleUndo} mode={mode} /> : <HeaderNormal sample={sample} container={container} mode={mode} handleUndo={handleUndo} readOnly={readOnly} isDisabled={isDisabled} handleRemove={handleRemove} handleSubmit={handleSubmit} handleAccordionOpen={handleAccordionOpen} toggleAddToReport={toggleAddToReport} /> } </div>, ); }; export default compose( DragSource(DragDropItemTypes.CONTAINER, orderSource, orderDragCollect), DropTarget(DragDropItemTypes.CONTAINER, orderTarget, orderDropCollect), )(ContainerRow);
ComPlat/chemotion_ELN
app/packs/src/components/SampleDetailsContainersDnd.js
JavaScript
agpl-3.0
2,510
<?php /** * @author Jaap Jansma <jaap.jansma@civicoop.org> * @license AGPL-3.0 */ class CRM_Oppgavexml_LoadQueue { const QUEUE_NAME = 'no.maf.oppgavexml.load.queue'; private $queue; static $singleton; /** * @return CRM_Queuehowto_Helper */ public static function singleton() { if (!self::$singleton) { self::$singleton = new CRM_Oppgavexml_LoadQueue(); } return self::$singleton; } private function __construct() { $this->queue = CRM_Queue_Service::singleton()->create(array( 'type' => 'Sql', 'name' => self::QUEUE_NAME, 'reset' => true, //do not flush queue upon creation )); } public function getQueue() { return $this->queue; } }
CiviCooP/no.maf.oppgavexml
CRM/Oppgavexml/LoadQueue.php
PHP
agpl-3.0
716
# -*- coding: utf-8 -*- # (c) 2017 Daniel Campos - AvanzOSC # (c) 2017 Alfredo de la Fuente - AvanzOSC # License AGPL-3 - See http://www.gnu.org/licenses/agpl-3.0.html from openerp import fields, models, api, exceptions, _ import base64 import cStringIO import tempfile import csv class ImportPriceFile(models.TransientModel): _name = 'import.price.file' _description = 'Wizard for import price list file' data = fields.Binary(string='File', required=True) name = fields.Char(string='Filename', required=False) delimeter = fields.Char( string='Delimeter', default=',', help='Default delimeter is ","') file_type = fields.Selection([('csv', 'CSV'), ('xls', 'XLS')], string='File type', required=True, default='csv') def _prepare_data_dict(self, data_dict): return data_dict def _import_csv(self, load_id, file_data, delimeter=';'): """ Imports data from a CSV file in defined object. @param load_id: Loading id @param file_data: Input data to load @param delimeter: CSV file data delimeter @return: Imported file number """ file_line_obj = self.env['product.supplierinfo.load.line'] data = base64.b64decode(file_data) file_input = cStringIO.StringIO(data) file_input.seek(0) reader_info = [] reader = csv.reader(file_input, delimiter=str(delimeter), lineterminator='\r\n') try: reader_info.extend(reader) except Exception: raise exceptions.Warning(_("Not a valid file!")) keys = reader_info[0] counter = 0 if not isinstance(keys, list): raise exceptions.Warning(_("Not a valid file!")) del reader_info[0] for i in range(len(reader_info)): field = reader_info[i] values = dict(zip(keys, field)) data_dict = self._prepare_data_dict( {'supplier': values.get('Supplier', ''), 'code': values.get('ProductCode', ''), 'sequence': values.get('Sequence', 0), 'supplier_code': values.get('ProductSupplierCode', ''), 'info': values.get('ProductSupplierName', ''), 'delay': values.get('Delay', 0), 'price': values.get('Price', 0.00).replace(',', '.'), 'min_qty': values.get('MinQty', 0.00), 'fail': True, 'fail_reason': _('No processed'), 'file_load': load_id}) file_line_obj.create(data_dict) counter += 1 return counter def _import_xls(self, load_id, file_data): """ Imports data from a XLS file in defined object. @param load_id: Loading id @param file_data: Input data to load @return: Imported file number """ try: import xlrd except ImportError: exceptions.Warning(_("xlrd python lib not installed")) file_line_obj = self.env['product.supplierinfo.load.line'] file_1 = base64.decodestring(file_data) (fileno, fp_name) = tempfile.mkstemp('.xls', 'openerp_') openfile = open(fp_name, "w") openfile.write(file_1) openfile.seek(0) book = xlrd.open_workbook(fp_name) sheet = book.sheet_by_index(0) values = {} keys = sheet.row_values(0, 0, end_colx=sheet.ncols) for counter in range(sheet.nrows - 1): # grab the current row rowValues = sheet.row_values(counter + 1, 0, end_colx=sheet.ncols) row_lst = [] for val in rowValues: # codification format control if isinstance(val, unicode): valor = val.encode('utf8') row_lst.append(valor) elif isinstance(val, float): if float(val) % 1 == 0.0: row_lst.append( '{0:.5f}'.format(float(val)).split('.')[0]) else: row_lst.append('{0:g}'.format(float(val))) else: row_lst.append(val) row = map(lambda x: str(x), row_lst) values = dict(zip(keys, row)) data_dict = self._prepare_data_dict( {'supplier': values.get('Supplier', ''), 'code': values.get('ProductCode', ''), 'sequence': values.get('Sequence', 0), 'supplier_code': values.get('ProductSupplierCode', ''), 'info': values.get('ProductSupplierName', ''), 'delay': values.get('Delay', 0), 'price': values.get('Price', 0.00).replace(',', '.'), 'min_qty': values.get('MinQty', 0.00), 'fail': True, 'fail_reason': _('No processed'), 'file_load': load_id }) file_line_obj.create(data_dict) counter += 1 return counter @api.multi def action_import(self): file_load_obj = self.env['product.supplierinfo.load'] if self.env.context.get('active_id', False): load_id = self.env.context.get('active_id') file_load = file_load_obj.browse(load_id) for line in file_load.file_lines: line.unlink() for wiz in self: if not wiz.data: raise exceptions.Warning(_("You need to select a file!")) date_hour = fields.datetime.now() actual_date = fields.date.today() filename = wiz.name if wiz.file_type == 'csv': counter = self._import_csv(load_id, wiz.data, wiz.delimeter) elif wiz.file_type == 'xls': counter = self._import_xls(load_id, wiz.data) else: raise exceptions.Warning(_("Not a .csv/.xls file found")) file_load.write({'name': ('%s_%s') % (filename, actual_date), 'date': date_hour, 'fails': counter, 'file_name': filename, 'process': counter}) return counter
esthermm/odoo-addons
product_supplierinfo_import/wizard/import_price_files.py
Python
agpl-3.0
6,282
package gdev.gawt; import gdev.gawt.utils.ItemList; import gdev.gen.AssignValueException; import gdev.gen.IComponentData; import gdev.gen.IComponentListener; import gdev.gen.NotValidValueException; import gdev.gfld.GFormEnumerated; import gdev.gfld.GFormField; import java.awt.Dimension; import java.awt.Font; import java.awt.ItemSelectable; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import java.awt.event.KeyListener; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.Vector; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import dynagent.common.communication.docServer; import dynagent.common.utils.IUserMessageListener; import dynagent.common.utils.IdObjectForm; /** * Esta clase extiende a GComponent y creará una lista seleccionable. * Una vez creada se podrá representar en la interfaz gráfica. * @author Juan * @author Francisco */ public class GListBox implements IComponentData,/*field,*/ ItemListener { String m_id2; String m_id; ItemList currentValidatedValue=null;//un valor de un item nunca puede ser 0 que corresponde a null /*fieldControl m_control;*/ public Vector<ItemList> m_listaInicial; String m_label; boolean m_nullable, m_modoConsulta, m_modoFilter; Font m_font; ItemSelectable m_select; JComponent m_comp; docServer m_server; Dimension m_dim; /*session m_session;*/ GComponent m_component; GFormEnumerated m_ff; boolean m_multivalued; IComponentListener m_componentListener; boolean inicializationState; ItemList[] m_currentListItemList; boolean itemEvent; IUserMessageListener m_messageListener; KeyListener m_keyListener; public GListBox(GFormField ff,/*session ses,*/docServer server,/*fieldControl control,*/IComponentListener controlValue,IUserMessageListener messageListener,KeyListener keyListener,Font fuente,boolean modoConsulta,boolean modoFilter) { /*m_session=ses;*/ m_server=server; /*m_dim=dim;*/ m_modoConsulta=modoConsulta; m_multivalued=ff.isMultivalued(); m_font=fuente; m_nullable= ff.isNullable(); m_label=ff.getLabel(); /*m_listaInicial= (Vector)lista.clone();*/ /*m_listaInicial= (Vector)((GFormEnumerated)ff).getValues().clone();*/ /*m_control= control;*/ m_id= ff.getId(); m_id2=ff.getId2(); ////////////////////////////////////////////////////// m_componentListener=controlValue; m_messageListener=messageListener; m_keyListener=keyListener; m_modoFilter=modoFilter; m_ff=(GFormEnumerated)ff; inicializationState=true; itemEvent=false; /////////////YA ESTABA COMENTADO///////////////// //System.out.println("LB_"+getValue()); /*if(color!=null){ if(color.equals("BLUE")) m_comp.setForeground(Color.blue); if(color.equals("GREEN")) m_comp.setForeground(Color.green); if(color.equals("RED")) m_comp.setForeground(Color.red); }*/ //////////////////////////////////////////////// /* System.out.println("Modo filtro GListBox "+m_modoFilter); if( m_modoFilter ){ /*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) ); m_comp= ((GList)m_select).getComponent();*/ /* GList list=new GList(ff,com,fuente,colorFondo); m_select=list; m_comp=list.getComponent(); //m_select=m_comp; }else{ GComboBox comboBox=new GComboBox(ff); comboBox.create(); m_select= (JComboBox)comboBox.getComponent(); m_comp=comboBox; /*m_select= new JComboBox(lista); m_comp=(JComponent)m_select;*/ /* } m_select.addItemListener(this); */ /* m_comp.setFont(m_font.deriveFont(Font.BOLD));*/ initLista(); /* setInitialSelection();*/ //System.out.println("LB_2"+getValue()); } /* protected void createComponent() { /*LISTA TIENE QUE LEERSE DE LOS ATRIBUTOS DE FF*/ /* Vector lista=new Vector();//Esto es provisional /*initLista( lista );*/ ///////////////////////////////////////////////// /* if( m_modoFilter ){ /*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) ); m_comp= ((GList)m_select).getComponent();*/ /* }else{ m_component=new GComboBox(ff); /*m_select= new JComboBox(lista); m_comp=(JComponent)m_select;*/ /* } m_select.addItemListener(this); } */ /*public JComponent getComponent(){ return (JComponent)m_select; }*/ public GComponent getComponent(){ /*if( m_select instanceof GComponent ) return (GComponent)m_select; if( m_comp instanceof GComponent )*/ return (GComponent)m_comp; /*return null;*/ } public void setItemSelectable(ItemSelectable itemSelectable){ m_select=itemSelectable; } public void setComponent(GComponent component){ m_comp=component; } private void initLista(){ if( m_modoFilter || m_multivalued ){ /*m_select= new GList( m_dim,lista, new ImageIcon( m_com.getImage("list")) ); m_comp= ((GList)m_select).getComponent();*/ GList list=new GList(m_ff,m_server,m_font,m_modoConsulta,m_modoFilter,this); /*m_select=list; m_comp=list.getComponent();*///Ultimo //m_select=m_comp; m_listaInicial=list.getListaInicial(); currentValidatedValue=list.getValorInicial().get(0); //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[] //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos: // Object[] o=new Object[] No se puede castear directamente a ItemList[] // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[] Object[] selected=list.getValorInicial().toArray(); if(selected instanceof ItemList[]) m_currentListItemList=(ItemList[])selected; else m_currentListItemList= Arrays.copyOf(selected,selected.length,ItemList[].class); }else{ GComboBox comboBox=new GComboBox(m_ff,m_font,m_modoConsulta,m_modoFilter,this); /*m_select= (JComboBox)comboBox.getComponent(); m_comp=comboBox;*///Ultimo /*m_select= new JComboBox(lista); m_comp=(JComponent)m_select;*/ m_listaInicial=comboBox.getListaInicial(); currentValidatedValue=comboBox.getValorInicial(); m_currentListItemList=new ItemList[1]; m_currentListItemList[0]=comboBox.getValorInicial(); } /*m_select.addItemListener(this);*/ } public String getLabel(){ return m_label; } public void commitValorInicial(){ if( /*m_modoFilter*/m_multivalued ) return; Iterator itr= m_listaInicial.iterator(); while(itr.hasNext()){ ItemList it= (ItemList) itr.next(); it.initialSelection=false; } ItemList current= (ItemList)m_select.getSelectedObjects()[0]; current.initialSelection=true; } private void setSelectedItem( ItemList[] lista ){ Vector<ItemList> v=new Vector<ItemList>(); int size=lista.length; for(int i=0;i<size;i++) v.addElement(lista[i]); setSelectedItem(v); } private void setSelectedItem( Vector<ItemList> lista ){ //System.out.println("PRE SETSEL "+lista.size()); if( lista==null || lista.size()==0 ) return; if( m_select instanceof JComboBox ) ((JComboBox)m_select).setSelectedItem(lista.get(0)); if( m_select instanceof GList ){ //System.out.println("ES BOX FILTER"); ((GList)m_select).setSelectedValue(lista); } } private boolean isPopupVisible(){ boolean visible=false; if( m_select instanceof JComboBox ) visible=((JComboBox)m_select).isPopupVisible(); if( m_select instanceof GList ){ //System.out.println("ES BOX FILTER"); visible=((GList)m_select).isPopupVisible(); } return visible; } private void setSelectedItem( ItemList it ){ if( m_select instanceof JComboBox ) ((JComboBox)m_select).setSelectedItem(it); if( m_select instanceof GList ) ((GList)m_select).setSelectedValue(it); } public int getSize(){ if( m_select instanceof JComboBox ) return ((JComboBox)m_select).getModel().getSize(); if( m_select instanceof GList ){ //System.outprintln("VALORES "+m_select+" "+(((GList)m_select).getComponent()).getModel()); //System.outprintln("VALORES TAMANO"+(((GList)m_select).getComponent()).getModel().getSize()); return (((GList)m_select).getComponent()).getModel().getSize(); } return 0; } public ItemList getItemAt(int i){ if( m_select instanceof JComboBox ) return (ItemList)((JComboBox)m_select).getItemAt(i); if( m_select instanceof GList ) return (ItemList)(((GList)m_select).getComponent()).getModel().getElementAt(i); return null; } public void setValue(Object newValue,Object oldValue) throws AssignValueException{ //TODO Cuando estamos aun gestionando un itemStateChanged si se llama a este metodo desde el metodo se produce inconsistencia. //if(!itemEvent) setValue( false, newValue, oldValue ); } //Si new es null y old es null entonces no mantenemos ningun valor de la lista private void setValue(boolean notificar,Object value,Object oldValue) throws AssignValueException{ //TODO Cambiar Object de value por String¿?¿ /*if( value!=null && !(value instanceof Integer)){ System.out.println("LIST BOX: setValue: error en cast"); return; }*/ //System.out.println("LIST BOX:PRE SET"); // if( (m_modoFilter || m_multivalued) && m_select instanceof GList ){ // //System.out.println("LIST BOX:RESET"); // ((GList)m_select).initLista(m_listaInicial); // } int valor= value!=null?(Integer)value:0; int valorOld= oldValue!=null?(Integer)oldValue:0; //Si ya esta seleccionado no hacemos nada Object[] lista= m_select.getSelectedObjects(); int size=lista.length; for(int i=0;i<size;i++) if(((ItemList)lista[i]).getIntId()==valor) return; Vector<ItemList> addItemList=new Vector<ItemList>(); if(! (valor==0 && valorOld==0)){ for(int i=0;i<size;i++){ if(((ItemList)lista[i]).getIntId()!=valorOld/* && ((ItemList)lista[i]).getIntId()!=0 Esto no es necesario si viene bien el valor y el valorOld en todo momento*/) addItemList.addElement((ItemList)lista[i]); } } if(valor!=0 || (valor==0 && addItemList.isEmpty())){ //System.err.println("ListaInicial:"+m_listaInicial.toString()); int sizePossibleValues=m_listaInicial.size(); for(int i=0;i<sizePossibleValues;i++){ ItemList it=m_listaInicial.get(i); //System.err.println("Compara: it.getIntId:"+it.getIntId()+" valor:"+valor); if(it.getIntId()==valor) addItemList.addElement(it); } } // try{ // for(int i=0;i< getSize();i++){ // ItemList it= getItemAt(i); // if(it.getIntId()==valor){ // // if( /*m_control*/m_controlValue!=null ){ // // if( /*m_control.estateInicialization()*/inicializationState){ // // System.out.println("WARNING:Entra en GListBox.setValue.inicializationState"); // // // // m_select.removeItemListener(this); // // setSelectedItem(it); // // m_select.addItemListener(this); // // currentValidatedValue = it; // // inicializationState=false; // // return; // // } // if(notificar && !m_modoConsulta){ // /*if(m_control.changeRequest(m_session,-1,-1,m_idForm, value)) // m_control.eventDataChanged(m_session,-1,-1,m_idForm); // else{ // String msg="Error, ha sido asignado un valor incorrecto."; // if(!isNullable() && isNull()) // msg+=" El campo " + getLabel() + " no admite valores nulos"; // m_messageListener.showMessage(msg); // setSelectedItem(currentValidatedValue); // }*/ // /*String[] buf = m_id.split(":"); // Integer valueCls = !buf[2].equals("null")?Integer.parseInt(buf[0]):null;*/ // IdObjectForm idObjectForm=new IdObjectForm(m_id); // Integer valueCls = idObjectForm.getValueCls(); // String valueOld=null; // /*String value=currValue;*/ // if(valueOld!=null){ // if(value!=null) // m_controlValue.setValueField(m_id,(String)value,valueOld, valueCls, valueCls); // else m_controlValue.removeValueField(m_id,valueOld, valueCls); // }else{ // if(value!=null) // m_controlValue.addValueField(m_id,(String)value,valueCls); // //else m_controlValue.removeValueField(m_id, value, valueCls); // } // } // } // m_select.removeItemListener(this); // setSelectedItem(it); // m_select.addItemListener(this); // // currentValidatedValue = it; // /*for(int i=0;i<size;i++) // m_currentListItemList[i]=(ItemList)lista[i];*/ // // Object[] listaSelect= m_select.getSelectedObjects(); // int sizeSelect=listaSelect.length; // //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear // //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[] // //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos: // // Object[] o=new Object[] No se puede castear directamente a ItemList[] // // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[] // if(listaSelect instanceof ItemList[]) // m_currentListItemList=(ItemList[])listaSelect; // else m_currentListItemList= Arrays.copyOf(listaSelect,sizeSelect,ItemList[].class); // } // } // }catch(NotValidValueException ex){ // m_messageListener.showErrorMessage(ex.getUserMessage()); // } m_select.removeItemListener(this); setSelectedItem(addItemList); m_select.addItemListener(this); // Para asignar el current se hace esto porque si en GList solo se deseleccionan valores usando control no habra valor, por lo que tendriamos current currentValidatedValue= lista.length>0?(ItemList)lista[0]:null; /*for(int i=0;i<size;i++) m_currentListItemList[i]=(ItemList)lista[i];*/ Object[] listaSelect= m_select.getSelectedObjects(); int sizeSelect=listaSelect.length; //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[] //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos: // Object[] o=new Object[] No se puede castear directamente a ItemList[] // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[] if(listaSelect instanceof ItemList[]) m_currentListItemList=(ItemList[])listaSelect; else m_currentListItemList= Arrays.copyOf(listaSelect,sizeSelect,ItemList[].class); } boolean hasNullItem(){ ItemList it= getItemAt(0); return it.getId().equals(0); } String getId2(){ return m_id2; } /* public String getValueToString(){ Object[] lista= m_select.getSelectedObjects(); if( lista.length==0 ) return null; for( int i=0;i<lista.length;i++) lista[i]=((ItemList)lista[i]).getId(); return jdomParser.buildMultivalue(lista); } public Object getValue(){ if( m_select.getSelectedObjects().length==0 ) return null; if(m_select.getSelectedObjects().length==1){ ItemList it = (ItemList) m_select.getSelectedObjects()[0]; return new Integer(it.getId()); }else{ ArrayList res= new ArrayList(); for( int i=0;i<m_select.getSelectedObjects().length;i++) res.add(new Integer((((ItemList)m_select.getSelectedObjects()[i]).getIntId()))); return res; } } */ public String getId(){ return m_id; } public boolean isNull(){ Object[] lista=m_select.getSelectedObjects(); if(lista == null || lista.length==0 ) return true; return (((ItemList)m_select.getSelectedObjects()[0]).getIntId()==0); } public boolean isNull(Object val){ if( val instanceof Integer ) return ((Integer)val).intValue()==0; if( val instanceof ItemList ) return ((ItemList)val).getIntId()==0; return true; } public boolean isNullable(){ return m_nullable; } public void itemStateChanged(ItemEvent e){ //System.err.println(e); itemEvent=true; ItemList[] listItemListOld=null; try{ //Este metodo es llamado tanto para indicar el item seleccionado y para indicar el item que ha sido quitado //Asi que solo nos interesa uno de ellos, en este caso el seleccionado if(e.getStateChange()==ItemEvent.SELECTED/* && !isPopupVisible()*/){ if( /*m_control*/m_componentListener==null || m_modoConsulta){ itemEvent=false; return; } // if( /*m_control*/m_controlValue!=null ){ // if( /*m_control.estateInicialization()*/inicializationState){ // currentValidatedValue= (ItemList)m_select.getSelectedObjects()[0]; // /*for(int i=0;i<size;i++) // m_currentListItemList[i]=(ItemList)lista[i];*/ // Object[] selected=m_select.getSelectedObjects(); // // //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear // //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[] // //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos: // // Object[] o=new Object[] No se puede castear directamente a ItemList[] // // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[] // if(selected instanceof ItemList[]) // m_currentListItemList=(ItemList[])selected; // else m_currentListItemList= Arrays.copyOf(selected,selected.length,ItemList[].class); // // inicializationState=false; // return; // } // } // Obtenemos los objetos seleccionados Object[] lista= m_select.getSelectedObjects(); int size=lista.length; listItemListOld=m_currentListItemList.clone(); ArrayList<ItemList> addItemList=new ArrayList<ItemList>(); for(int i=0;i<size;i++){ addItemList.add((ItemList)lista[i]); } IdObjectForm idObjectForm=new IdObjectForm(m_id); Integer valueCls = idObjectForm.getValueCls(); ArrayList<ItemList> replacedItemList=new ArrayList<ItemList>(); for( int i=0;i<size;i++){ ItemList it=(ItemList)lista[i]; /*if(!m_control.changeRequest(m_session,-1,-1,m_idForm,new Integer(it.getIntId()))){ String msg = "Ha escrito un valor incorrecto."; if (!isNullable() && isNull()) msg += " El campo " + getLabel() + " no admite valores nulos"; m_messageListener.showErrorMessage(msg); setSelectedItem(currentValidatedValue); return; }*/ /*String[] buf = m_id.split(":"); Integer valueCls = !buf[2].equals("null")?Integer.parseInt(buf[0]):null;; String value=String.valueOf(it.getIntId()); */ if(!hasValue(it)){ Integer value=it.getIntId(); if(value.equals(0)) value=null; Integer valueOld=getNextValueOld(addItemList,replacedItemList); if(valueOld!=null && valueOld.equals(0)) valueOld=null; /*if(value.equals("")) value=null;*/ if(!m_multivalued){ if(valueOld!=null){ if(value!=null) m_componentListener.setValueField(m_id,value,valueOld, valueCls, valueCls); else m_componentListener.removeValueField(m_id,valueOld, valueCls); }else{ if(value!=null) m_componentListener.addValueField(m_id,value,valueCls); //else m_controlValue.removeValueField(m_id, value, valueCls); } }else{ /*Si es multivalued no reutilizamos el fact haciendo un set como para los de un unico valor ya que: Si, por ejemplo, tenemos dos valores, primero quitamos uno, y luego sustituimos el dejado por el quitado, se estaría enviando a base de datos un del y un set, procesando base de datos antes el set que el del por lo que finalmente se quedaría sin ningun valor */ if(valueOld!=null) m_componentListener.removeValueField(m_id,valueOld, valueCls); if(value!=null) m_componentListener.addValueField(m_id,value,valueCls); } } } int sizeOld=listItemListOld.length; if(size<sizeOld){ for(int i=0;i<sizeOld;i++){ ItemList itemList=listItemListOld[i]; if(!replacedItemList.contains(itemList) && !addItemList.contains(itemList)){ Integer value=itemList.getIntId(); m_componentListener.removeValueField(m_id,value, valueCls); } } } lista= m_select.getSelectedObjects();//Volvemos a pedir los objetos seleccionados porque las acciones anteriores han podido provocar cambios // Para asignar el current se hace esto porque si en GList solo se deseleccionan valores usando control no habra valor, por lo que tendriamos current currentValidatedValue= lista.length>0?(ItemList)lista[0]:null; /*for(int i=0;i<size;i++) m_currentListItemList[i]=(ItemList)lista[i];*/ //Esto lo comprobamos porque segun como se haya construido los datos pasados a la lista no se puede castear //directamente de Object[] a ItemList[]. Por ejemplo si se ha pasado un vector este internamente crea un new Object[] //por lo que luego no podemos hacer el casting a ItemList. Ejemplos de creacion de los datos: // Object[] o=new Object[] No se puede castear directamente a ItemList[] // Object[] o=new ItemList[] Si se puede castear directamente a ItemList[] if(lista instanceof ItemList[]) m_currentListItemList=(ItemList[])lista; else m_currentListItemList= Arrays.copyOf(lista,lista.length,ItemList[].class); itemEvent=false; /*m_control.eventDataChanged(m_session,-1,-1,m_idForm);*/ } }catch(NotValidValueException ex){ m_messageListener.showErrorMessage(ex.getUserMessage(),SwingUtilities.getWindowAncestor(this.getComponent())); setSelectedItem(listItemListOld); }catch(Exception ex){ m_server.logError(SwingUtilities.getWindowAncestor(this.getComponent()),ex,"Error al seleccionar elemento"); setSelectedItem(listItemListOld); ex.printStackTrace(); } } /* Obtiene el siguiente valueOld que se puede utilizar para hacer un setValueField. Si en la lista de los anteriores valores hay un valor que no aparece en addItemList(nuevos valores) ni en replacedItemList(valores ya usados) sera el valueOld que utilizaremos. Una vez elegido se añade a la lista replacedItemList para que en las llamadas de los otros values de addItemList no se utilicen los mismos antiguos valores. Si no hay valores para elegir se devuelve null. */ private Integer getNextValueOld(ArrayList<ItemList> addItemList,ArrayList<ItemList> replacedItemList){ Integer valueOld=null; if(m_currentListItemList!=null){//Si hay alguna seleccion ArrayList<ItemList> currentList=new ArrayList<ItemList>(); int size=m_currentListItemList.length; for(int i=0;i<size;i++){ currentList.add(m_currentListItemList[i]); } Iterator<ItemList> itr=currentList.iterator(); boolean found=false; while(!found && itr.hasNext()){ ItemList itemL=itr.next(); if(!addItemList.contains(itemL) && !replacedItemList.contains(itemL)){ valueOld=itemL.getIntId(); replacedItemList.add(itemL); found=true; } } } return valueOld; } private boolean hasValue(ItemList it){ int size=m_currentListItemList.length; for(int i=0;i<size;i++){ if(m_currentListItemList[i].equals(it)) return true; } return false; } public boolean hasChanged() { //int seleccion= getSelectedIndex(); // ItemList itemSelected= (ItemList)m_select.getSelectedObjects()[0]; // return !itemSelected.isInitialSelected(); /*for(int i= 0; i< seleccion.length; i++){ if(((itemList)getModel().getElementAt(seleccion[i])).isInitialSelected()!= isSelectedIndex(seleccion[i])) return true; }*/ ArrayList<ItemList> arrayOld=new ArrayList<ItemList>(); Object[] selected=m_select.getSelectedObjects(); int sizeOld=m_currentListItemList.length; int size=selected.length; if(size!=sizeOld) return true; for(int i=0;i<sizeOld;i++) arrayOld.add(m_currentListItemList[i]); for(int i=0;i<size;i++){ ItemList itemList=(ItemList)selected[i]; if(!arrayOld.contains(itemList)) return true; } return false; } public void initValue() { // if( /*m_modoFilter*/m_multivalued ) return; // Iterator itr= m_listaInicial.iterator(); // while(itr.hasNext()){ // ItemList it= (ItemList) itr.next(); // it.initialSelection=false; // } // ItemList current= (ItemList)m_select.getSelectedObjects()[0]; // current.initialSelection=true; if(m_modoFilter || m_multivalued) ((GList)getComponent()).initValue(); else ((GComboBox)getComponent()).initValue(); } public Object getValue() { String values=null; int size=m_currentListItemList.length; if(size!=0) values=m_currentListItemList[0].getId(); for(int i=1;i<size;i++) values+=":"+m_currentListItemList[i].getId(); //System.err.println("WARNING: Llamada al metodo GListBox.getValue() el cual no esta implementado"); return null; } public void clean() throws ParseException, AssignValueException { setValue(false, null, null); } public IComponentListener getComponentListener() { return m_componentListener; } }
semantic-web-software/dynagent
Elecom/src/gdev/gawt/GListBox.java
Java
agpl-3.0
26,370
var round = function(number, increment, offset) { return Math.ceil((number - offset) / increment) * increment + offset; }; Partup.client.chatmessages = { groupByDelay: function(messages, options) { var delay = options.seconds ? options.seconds * 1000 : 1000; var outputArray = []; messages.forEach(function(item, index) { var outputLastIndex = outputArray.length - 1; var lastCreatedAt; if (outputArray[outputLastIndex]) { lastCreatedAt = new Date(outputArray[outputLastIndex].messages[outputArray[outputLastIndex].messages.length - 1].created_at).getTime(); } var currentCreatedAt = new Date(item.created_at).getTime(); if (outputArray[outputLastIndex] && lastCreatedAt && (currentCreatedAt - lastCreatedAt) < delay) { outputArray[outputLastIndex].messages.push(item); } else { outputArray.push({ messages: [item] }); } }); return outputArray.reverse(); }, groupByCreationDay: function(messages) { var outputArray = []; messages.forEach(function(item, index) { var outputLastIndex = outputArray.length - 1; if (outputArray[outputLastIndex] && outputArray[outputLastIndex].day === new Date(item.created_at).setHours(0, 0, 0, 0, 0)) { outputArray[outputLastIndex].messages.push(item); } else { outputArray.push({ day: new Date(item.created_at).setHours(0, 0, 0, 0, 0), messages: [item] }); } }); return outputArray.reverse(); }, groupByCreatorId: function(messages) { var outputArray = []; messages.forEach(function(item, index) { var outputLastIndex = outputArray.length - 1; if (outputArray[outputLastIndex] && outputArray[outputLastIndex].creator_id === item.creator_id) { outputArray[outputLastIndex].messages.push(item); } else { outputArray.push({ creator_id: item.creator_id, messages: [item] }); } }); return outputArray.reverse(); }, groupByChat: function(messages) { var outputObject = {}; messages.forEach(function(item, index) { if (outputObject[item.chat_id] && outputObject[item.chat_id].chat_id === item.chat_id) { outputObject[item.chat_id].messages.push(item); } else { outputObject[item.chat_id] = { chat_id: item.chat_id, messages: [item] }; } }); var outputArray = _.values(outputObject); return outputArray; } };
part-up/part-up
app/packages/partup-client-base/client/chatmessages.js
JavaScript
agpl-3.0
2,893
/* * DataCruncher * Copyright (c) Mario Altimari. All rights reserved. * * 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 com.datacruncher.datastreams; import com.datacruncher.datastreams.threads.PersistStreamsAndSendAlertsThread; import com.datacruncher.constants.GenericType; import com.datacruncher.constants.SchemaType; import com.datacruncher.constants.StreamType; import com.datacruncher.fileupload.FileExtensionType; import com.datacruncher.fileupload.FileReadObject; import com.datacruncher.fileupload.FileReadObjectFactory; import com.datacruncher.jpa.ReadList; import com.datacruncher.jpa.dao.DaoSet; import com.datacruncher.jpa.entity.ApplicationEntity; import com.datacruncher.jpa.entity.EventTriggerEntity; import com.datacruncher.jpa.entity.SchemaEntity; import com.datacruncher.jpa.entity.TasksEntity; import com.datacruncher.utils.generic.CommonUtils; import com.datacruncher.utils.generic.I18n; import com.datacruncher.validation.Logical; import com.datacruncher.validation.ResultStepValidation; import com.datacruncher.validation.Temporary; import org.apache.log4j.Logger; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.*; public class DatastreamsInput implements DaoSet { private final static Logger log = Logger.getLogger(DatastreamsInput.class); private String uploadedFileName; List<EventTriggerEntity> okEventList; List<EventTriggerEntity> koEventList; List<EventTriggerEntity> warnEventList; private boolean okEvent = false; private boolean koEvent = false; private boolean warnEvent = false; private boolean bTotalSuccess; private String resultMsg = ""; public final static String _SINGLE_SUCC_RESP = "bTotalSuccess"; public final static String _SINGLE_STR_RESP = "bTotalResultString"; public final static String _SINGLE_STREAMENT_RESP = "streamEntityResonse"; private static int poolSize = 7; static { Properties properties = new Properties(); InputStream in = DatastreamsInput.class.getClassLoader().getResourceAsStream("main.properties"); try { properties.load(in); poolSize = Integer.parseInt(properties.get("validation.pool_size").toString()); } catch (IOException e) { log.error("error reading main.properties", e); } } public void setUploadedFileName(String uploadedFileName) { this.uploadedFileName = uploadedFileName; } public DatastreamsInput() { } public String datastreamsInput(String datastream, Long idSchema,byte[] bytes){ return datastreamsInput(datastream, idSchema, bytes, null); } public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, Object object) { SchemaEntity schemaEntity = schemasDao.find(idSchema); if (schemaEntity != null && schemaEntity.getIsPlanned() && schemaEntity.getPlannedName() > 0) { TasksEntity tasksEntity = tasksDao.find(schemaEntity.getPlannedName()); boolean isPlanned = true; Calendar calendar = Calendar.getInstance(); if (tasksEntity != null) { if (tasksEntity.getIsOneShoot()) { Date shootDate = tasksEntity.getShootDate(); String shootTime = tasksEntity.getShootTime(); Calendar shootDateTime = Calendar.getInstance(); shootDateTime.setTime(shootDate); if (calendar.get(Calendar.YEAR) != shootDateTime.get(Calendar.YEAR)) { isPlanned = false; } else if (calendar.get(Calendar.MONTH) != shootDateTime.get(Calendar.MONTH)) { isPlanned = false; } else if (calendar.get(Calendar.DAY_OF_MONTH) != shootDateTime.get(Calendar.DAY_OF_MONTH)) { isPlanned = false; } else if (shootTime.trim().length() > 0 && !shootTime.equalsIgnoreCase("hh:mm")) { int hour = Integer.parseInt(shootTime.substring(0, shootTime.indexOf(":"))); int min = Integer.parseInt(shootTime.substring(shootTime.indexOf(":") + 1)); if (calendar.get(Calendar.HOUR_OF_DAY) != hour) { isPlanned = false; } else if (calendar.get(Calendar.MINUTE) != min) { isPlanned = false; } } } else if (tasksEntity.getIsPeriodically()) { if (tasksEntity.getMonth() >= 0 && (calendar.get(Calendar.MONTH) + 1) != tasksEntity.getMonth()) { isPlanned = false; } else if (tasksEntity.getDay() >= 0 && calendar.get(Calendar.DAY_OF_MONTH) != tasksEntity.getDay()) { isPlanned = false; } else if (tasksEntity.getWeek() >= 0 && calendar.get(Calendar.DAY_OF_WEEK) != tasksEntity.getWeek()) { isPlanned = false; } else if (tasksEntity.getHour() >= 0 && calendar.get(Calendar.HOUR_OF_DAY) != tasksEntity.getHour()) { isPlanned = false; } else if (tasksEntity.getMinute() >= 0 && calendar.get(Calendar.MINUTE) != tasksEntity.getMinute()) { isPlanned = false; } } } if (!isPlanned) { return I18n.getMessage("error.datastreamnotplanned.invalid"); } } return datastreamsInput(datastream, idSchema, bytes, false, object); } public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, boolean isUnitTest){ return datastreamsInput(datastream, idSchema, bytes, isUnitTest, null); } public String datastreamsInput(String datastream, Long idSchema, byte[] bytes, boolean isUnitTest, Object object){ String resultMsg = ""; SchemaEntity schemaEntity = schemasDao.find(idSchema); if (schemaEntity == null) { resultMsg = I18n.getMessage("error.schema.invalid"); return isUnitTest ? "false" : resultMsg; } int idStreamType = schemaEntity.getIdStreamType(); ApplicationEntity appEntity = appDao.find(schemaEntity.getIdApplication()); Temporary temporary = new Temporary(); ResultStepValidation resultValidation = temporary.temporaryValidation(schemaEntity, appEntity); if (resultValidation.isValid()) { List<String> streamsList = parseStream(datastream, bytes, idSchema, idStreamType); int i = 1; if (streamsList.size() > 0) { long numEvents = schemaTriggerStatusDao.findEventByIdSchema(idSchema); bTotalSuccess = true; if (numEvents > 0) { checkEventTrigger(idSchema); } ExecutorService executor = Executors.newFixedThreadPool(poolSize); // On case of IndexIncrement thread executor is forced to be // single thred to guarantee order of task executions if ( schemaEntity.getIsIndexedIncrement() ) { executor = Executors.newSingleThreadExecutor(); } long numElemChecked = schemaFieldsDao.findNumExtraCheck(idSchema); String defaultNsLib = schemaEntity.getIdSchemaLib() == 0 ? null : schemaLibDao.find(schemaEntity.getIdSchemaLib()).getDefaultNsLib(); List<Future<Map<String, Object>>> list = new ArrayList<Future<Map<String, Object>>>(); boolean skipHeader = schemaEntity.getIdStreamType() == StreamType.flatFileDelimited && schemaEntity.getIdSchemaType() == SchemaType.VALIDATION && schemaEntity.isNoHeader(); int index = -1; for (String stream : streamsList) { index ++; if ( index == 0 && skipHeader ) { continue; } Callable<Map<String, Object>> callee = new ValidationCallable( idSchema, schemaEntity, stream, bytes, isUnitTest, okEvent, koEvent, warnEvent, okEventList, koEventList, warnEventList, object, numElemChecked, appEntity, defaultNsLib, index == streamsList.size() - 1, skipHeader ? index == 1 : index == 0 ); Future<Map<String, Object>> submit = executor.submit(callee); list.add(submit); } Map<String, Object> futureRes; try { if (!isUnitTest) { PersistStreamsAndSendAlertsThread persStreams = new PersistStreamsAndSendAlertsThread(list, executor); persStreams.start(); persStreams.join(); } for (Future<Map<String, Object>> future : list) { try { futureRes = future.get(); resultMsg += (streamsList.size() == 1 ? "" : i++ + ".Stream: ") + futureRes.get(_SINGLE_STR_RESP) + "<br><br>"; bTotalSuccess = bTotalSuccess && (Boolean) futureRes.get(_SINGLE_SUCC_RESP); } catch (ExecutionException e) { log.error("ExecutionException", e); } } } catch (InterruptedException e1) { log.error("InterruptedException", e1); } executor.shutdown(); Logical.mapExtraCheck = new HashMap<String, Set<String>>(); } else { bTotalSuccess = false; resultMsg = I18n.getMessage("error.validationTraceNoValid"); } } else { bTotalSuccess = false; resultMsg = resultValidation.getMessageResult(); } this.resultMsg = resultMsg; return isUnitTest ? String.valueOf(bTotalSuccess) : resultMsg; } @SuppressWarnings("unchecked") private void checkEventTrigger(Long idSchema){ ReadList readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema, GenericType.okEvent); if (readList.getResults() != null && readList.getResults().size() > 0) { okEvent = true; okEventList = (List<EventTriggerEntity>) readList.getResults(); }else{ okEvent = false; } readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema,GenericType.koEvent); if (readList.getResults() != null && readList.getResults().size() > 0) { koEvent = true; koEventList = (List<EventTriggerEntity>) readList.getResults(); }else{ koEvent = false; } readList = eventTriggerDao.findByIdSchemaAndIdStatus(idSchema,GenericType.warnEvent); if (readList.getResults() != null && readList.getResults().size() > 0) { warnEvent = true; warnEventList = (List<EventTriggerEntity>) readList.getResults(); }else{ warnEvent = false; } } /** * Parses current multi datastream. * * @param datastream DataStream * @param idStreamType * - xml/exi/.. * @return separated streams */ private List<String> parseStream(String datastream, byte[] bytes, Long idSchema, int idStreamType) { List<String> streamsList = new ArrayList<String>(); try { if(schemasDao.find(idSchema).getIdSchemaType() == SchemaType.STANDARD){ String defNameSpace = schemaLibDao.find(schemasDao.find(idSchema).getIdSchemaLib()).getDefaultNsLib(); String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim(); if (str.startsWith("<?xml")) { // xml prolog remove str = str.replaceFirst("<\\?xml .*\\?>", ""); str = str.trim(); } if (str.startsWith("<")) { int r= str.lastIndexOf("</"); String closingNode = str.substring(r); closingNode = closingNode.trim(); String nodeName = closingNode.substring(closingNode.indexOf("/")+1, closingNode.length()-1); streamsList = Arrays.asList(str.split(closingNode)); for (int i = 0; i < streamsList.size(); i++) { String stream=streamsList.get(i).replaceFirst(nodeName,nodeName+" xmlns="+ defNameSpace +" "); streamsList.set(i, stream + closingNode); } } }else{ if (idStreamType == StreamType.XML ) { String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim(); if (str.startsWith("<?xml")) { // xml prolog remove str = str.replaceFirst("<\\?xml .*\\?>", ""); str = str.trim(); } if (str.startsWith("<")) { int r= str.lastIndexOf("</"); String closingNode = str.substring(r); closingNode = closingNode.trim(); streamsList = Arrays.asList(str.split(closingNode)); for (int i = 0; i < streamsList.size(); i++) { streamsList.set(i, streamsList.get(i) + closingNode); } } }else if (idStreamType == StreamType.flatFileFixedPosition) { datastream= datastream.replaceAll("\\r\\n", "\\\n"); datastream= datastream.replaceAll("\\r", "\\\n"); streamsList = Arrays.asList(datastream.split("\\n")); for (int i = 0; i < streamsList.size(); i++) { // '/r' appear in file with '/r/n' but in textarea appear // only '/n' streamsList .set(i, streamsList.get(i).replaceAll("\\r", "")); } } else if (idStreamType == StreamType.flatFileDelimited) { datastream= datastream.replaceAll("\\r\\n", "\\\n"); datastream= datastream.replaceAll("\\r", "\\\n"); Character chrDelim = schemasDao.find(idSchema).getChrDelimiter().charAt(0); if (chrDelim.toString().trim().length() == 1) { streamsList = Arrays.asList(CommonUtils.lineSplit(datastream, schemasDao.find(idSchema).getDelimiter(),chrDelim)); }else{ streamsList = Arrays.asList(datastream.split("\\n")); } for (int i = 0; i < streamsList.size(); i++) { // '/r' appear in file with '/r/n' but in textarea appear // only '/n' streamsList.set(i, streamsList.get(i).replaceAll("\\r", "")); } } else if (idStreamType == StreamType.XMLEXI) { streamsList.add(datastream); } else if (idStreamType == StreamType.JSON) { String str = datastream.replaceAll("\\r|\\n|\\t", "").trim(); datastream = str.replaceAll("\\}\\{", "\\}--\\{"); streamsList = Arrays.asList(datastream.split("--")); for (int i = 0; i < streamsList.size(); i++) { streamsList.set(i, streamsList.get(i)); } } else if (idStreamType == StreamType.EXCEL) { if (!(uploadedFileName.endsWith(FileExtensionType.EXCEL_97 .getAbbreviation()) || uploadedFileName .endsWith(FileExtensionType.EXCEL_2007 .getAbbreviation()))) { streamsList.add("File is not a MS Excel file."); return streamsList; } FileReadObject fileReadObject = FileReadObjectFactory .getFileReadObject(uploadedFileName); datastream = fileReadObject.parseStream(idSchema, new ByteArrayInputStream(bytes)); String str = datastream.replaceAll("\\r|\\n|\\t", " ").trim(); if (str.startsWith("<?xml")) { // xml prolog remove str = str.replaceFirst("<\\?xml .*\\?>", ""); str = str.trim(); } if (str.startsWith("<")) { String rootNodeName = str.substring(1, str.indexOf(">")); String closingNode = "</" + rootNodeName + ">"; streamsList = Arrays.asList(str.split(closingNode)); for (int i = 0; i < streamsList.size(); i++) { streamsList.set(i, streamsList.get(i) + closingNode); } } else { streamsList.add(datastream); } } } } catch (Exception e) { log.error("Error while parsing stream", e); } return streamsList; } public boolean getTotalSuccess() { return bTotalSuccess; } public String getResultMsg() { return resultMsg; } }
see-r/SeerDataCruncher
src/main/java/com/datacruncher/datastreams/DatastreamsInput.java
Java
agpl-3.0
18,067
<?php /** * Copyright 2015-2018 ppy Pty. Ltd. * * This file is part of osu!web. osu!web is distributed with the hope of * attracting more community contributions to the core ecosystem of osu!. * * osu!web is free software: you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License version 3 * as published by the Free Software Foundation. * * osu!web is distributed 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 osu!web. If not, see <http://www.gnu.org/licenses/>. */ return [ 'discussion-posts' => [ 'store' => [ 'error' => '保存失败', ], ], 'discussion-votes' => [ 'update' => [ 'error' => '更新投票失败', ], ], 'discussions' => [ 'allow_kudosu' => '给予 kudosu', 'delete' => '删除', 'deleted' => '被 :editor 于 :delete_time 删除。', 'deny_kudosu' => '收回 kudosu', 'edit' => '编辑', 'edited' => '最后由 :editor 编辑于 :update_time 。', 'kudosu_denied' => 'kudosu 被收回', 'message_placeholder_deleted_beatmap' => '该难度已被删除,无法继续讨论', 'message_type_select' => '选择回复类型', 'reply_notice' => '按下回车以提交', 'reply_placeholder' => '在此处输入您的回复', 'require-login' => '登录以继续', 'resolved' => '已解决', 'restore' => '已修复', 'title' => '讨论', 'collapse' => [ 'all-collapse' => '全部折叠', 'all-expand' => '全部展开', ], 'empty' => [ 'empty' => '还没有讨论!', 'hidden' => '没有符合过滤条件的讨论。', ], 'message_hint' => [ 'in_general' => '这个信息将提交到整个谱面讨论中。如果需要单独针对某处,请在开头使用时间戳 (例如: 00:12:345)。', 'in_timeline' => '需要 Mod 多处,请在每一个时间戳后写下意见并发表。', ], 'message_placeholder' => [ 'general' => '在此处输入以发布到常规 (:version)', 'generalAll' => '在此处输入以发布到常规 (所有难度)', 'timeline' => '在此处输入以发布到时间线 (:version)', ], 'message_type' => [ 'disqualify' => '取消提名', 'hype' => '推荐!', 'mapper_note' => '备注', 'nomination_reset' => '重置提名', 'praise' => '赞', 'problem' => '问题', 'suggestion' => '建议', ], 'mode' => [ 'events' => '历史', 'general' => '常规 :scope', 'timeline' => '时间线', 'scopes' => [ 'general' => '当前难度', 'generalAll' => '所有难度', ], ], 'new' => [ 'timestamp' => '时间戳', 'timestamp_missing' => '在编辑模式下按 Ctrl+C 然后在您的输入框中粘贴以添加时间戳!', 'title' => '新的讨论', ], 'show' => [ 'title' => '由 :mapper 制作的 :title', ], 'sort' => [ '_' => '排序:', 'created_at' => '创建时间', 'timeline' => '时间轴', 'updated_at' => '最后更新时间', ], 'stats' => [ 'deleted' => '已删除', 'mapper_notes' => '备注', 'mine' => '我的', 'pending' => '未解决', 'praises' => '赞', 'resolved' => '已解决', 'total' => '所有', ], 'status-messages' => [ 'approved' => '这张谱面于 :date 被 Approved !', 'graveyard' => "这张谱面自 :date 就未更新了,或许它已经被作者抛弃了 ;w;", 'loved' => '这张谱面于 :date 被 Loved !', 'ranked' => '这张谱面于 :date 被 Ranked !', 'wip' => '注意:这张谱面被作者标记为 WIP(work-in-progress)', ], ], 'hype' => [ 'button' => '推荐谱面!', 'button_done' => '已经推荐!', 'confirm' => "你确定吗?这将会使用你剩下的 :n 次推荐次数并且无法撤销。", 'explanation' => '推荐这张谱面让它更容易被提名然后 ranked !', 'explanation_guest' => '登录并推荐这张谱面让它更容易被提名然后 ranked !', 'new_time' => "你将在 :new_time 后获得新的推荐次数。", 'remaining' => '你还可以推荐 :remaining 次。', 'required_text' => '推荐进度: :current/:required', 'section_title' => '推荐进度', 'title' => '推荐', ], 'feedback' => [ 'button' => '留下建议', ], 'nominations' => [ 'disqualification_prompt' => 'DQ 的理由?', 'disqualified_at' => '于 :time_ago 被 DQ (:reason)。', 'disqualified_no_reason' => '没有指定原因', 'disqualify' => 'Disqualify', 'incorrect_state' => '操作出错了,请刷新页面。', 'love' => '喜欢', 'love_confirm' => '喜欢这张谱面吗?', 'nominate' => '提名', 'nominate_confirm' => '提名这张谱面?', 'nominated_by' => '被 :users 提名', 'qualified' => '如果没有问题,预计将于 :date 被 Ranked 。', 'qualified_soon' => '如果没有问题,预计不久将被 Ranked 。', 'required_text' => '提名数: :current/:required', 'reset_message_deleted' => '已删除', 'title' => '提名状态', 'unresolved_issues' => '仍然有需解决的问题 。', 'reset_at' => [ 'nomination_reset' => '提名于 :time_ago 被新问题 :discussion 重置。', 'disqualify' => ':time_ago 被 :user 因为新问题 :discussion (:message) 而 DQ.', ], 'reset_confirm' => [ 'nomination_reset' => '你确定吗?提出新的问题会重置提名。', ], ], 'listing' => [ 'search' => [ 'prompt' => '输入关键字...', 'login_required' => '登录以搜索。', 'options' => '更多搜索选项', 'supporter_filter' => '按 :filters 筛选需要成为支持者', 'not-found' => '没有结果', 'not-found-quote' => '呃,什么也没有...', 'filters' => [ 'general' => '常规', 'mode' => '模式', 'status' => '分类', 'genre' => '流派', 'language' => '语言', 'extra' => '额外', 'rank' => '有成绩', 'played' => '玩过', ], 'sorting' => [ 'title' => '标题', 'artist' => '艺术家', 'difficulty' => '难度', 'updated' => '更新时间', 'ranked' => 'rank时间', 'rating' => '评分', 'plays' => '游玩次数', 'relevance' => '相关性', 'nominations' => '提名状态', ], 'supporter_filter_quote' => [ '_' => '按 :filters 筛选需要成为 :link', 'link_text' => '支持者', ], ], ], 'general' => [ 'recommended' => '推荐难度', 'converts' => '包括转谱', ], 'mode' => [ 'any' => '所有', 'osu' => 'osu!', 'taiko' => 'osu!taiko', 'fruits' => 'osu!catch', 'mania' => 'osu!mania', ], 'status' => [ 'any' => '所有', 'ranked-approved' => 'Ranked & Approved', 'approved' => 'Approved', 'qualified' => 'Qualified', 'loved' => 'Loved', 'faves' => 'Favourites', 'pending' => 'Pending & WIP', 'graveyard' => 'Graveyard', 'my-maps' => '我的', ], 'genre' => [ 'any' => '所有', 'unspecified' => '尚未指定', 'video-game' => '电子游戏', 'anime' => '动漫', 'rock' => '摇滚', 'pop' => '流行乐', 'other' => '其他', 'novelty' => '新奇', 'hip-hop' => '嘻哈', 'electronic' => '电子', ], 'mods' => [ '4K' => '4K', '5K' => '5K', '6K' => '6K', '7K' => '7K', '8K' => '8K', '9K' => '9K', 'AP' => 'Auto Pliot', 'DT' => 'Double Time', 'EZ' => 'Easy Mode', 'FI' => 'Fade In', 'FL' => 'Flashlight', 'HD' => 'Hidden', 'HR' => 'Hard Rock', 'HT' => 'Half Time', 'NC' => 'Nightcore', 'NF' => 'No Fail', 'NM' => 'No mods', 'PF' => 'Perfect', 'Relax' => 'Relax', 'SD' => 'Sudden Death', 'SO' => 'Spun Out', 'TD' => 'Touch Device', ], 'language' => [ 'any' => '所有', 'english' => '英语', 'chinese' => '汉语', 'french' => '法语', 'german' => '德语', 'italian' => '意大利语', 'japanese' => '日语', 'korean' => '韩语', 'spanish' => '西班牙语', 'swedish' => '瑞典语', 'instrumental' => '器乐', 'other' => '其他', ], 'played' => [ 'any' => '任意', 'played' => '玩过', 'unplayed' => '没玩过', ], 'extra' => [ 'video' => '有视频', 'storyboard' => '有 Storyboard', ], 'rank' => [ 'any' => '任意', 'XH' => '白银 SS', 'X' => 'SS', 'SH' => '白银 S', 'S' => 'S', 'A' => 'A', 'B' => 'B', 'C' => 'C', 'D' => 'D', ], ];
kj415j45/osu-web
resources/lang/zh/beatmaps.php
PHP
agpl-3.0
10,212
""" IMAPClient wrapper for the Nilas Sync Engine. """ import contextlib import re import time import imaplib import imapclient # Even though RFC 2060 says that the date component must have two characters # (either two digits or space+digit), it seems that some IMAP servers only # return one digit. Fun times. imaplib.InternalDate = re.compile( r'.*INTERNALDATE "' r'(?P<day>[ 0123]?[0-9])-' # insert that `?` to make first digit optional r'(?P<mon>[A-Z][a-z][a-z])-' r'(?P<year>[0-9][0-9][0-9][0-9])' r' (?P<hour>[0-9][0-9]):' r'(?P<min>[0-9][0-9]):' r'(?P<sec>[0-9][0-9])' r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])' r'"') import functools import threading from email.parser import HeaderParser from collections import namedtuple, defaultdict import gevent from gevent import socket from gevent.lock import BoundedSemaphore from gevent.queue import Queue from inbox.util.concurrency import retry from inbox.util.itert import chunk from inbox.util.misc import or_none from inbox.basicauth import GmailSettingError from inbox.models.session import session_scope from inbox.models.account import Account from nylas.logging import get_logger log = get_logger() __all__ = ['CrispinClient', 'GmailCrispinClient'] # Unify flags API across IMAP and Gmail Flags = namedtuple('Flags', 'flags') # Flags includes labels on Gmail because Gmail doesn't use \Draft. GmailFlags = namedtuple('GmailFlags', 'flags labels') GMetadata = namedtuple('GMetadata', 'g_msgid g_thrid size') RawMessage = namedtuple( 'RawImapMessage', 'uid internaldate flags body g_thrid g_msgid g_labels') RawFolder = namedtuple('RawFolder', 'display_name role') # Lazily-initialized map of account ids to lock objects. # This prevents multiple greenlets from concurrently creating duplicate # connection pools for a given account. _lock_map = defaultdict(threading.Lock) CONN_DISCARD_EXC_CLASSES = (socket.error, imaplib.IMAP4.error) class FolderMissingError(Exception): pass def _get_connection_pool(account_id, pool_size, pool_map, readonly): with _lock_map[account_id]: if account_id not in pool_map: pool_map[account_id] = CrispinConnectionPool( account_id, num_connections=pool_size, readonly=readonly) return pool_map[account_id] def connection_pool(account_id, pool_size=3, pool_map=dict()): """ Per-account crispin connection pool. Use like this: with crispin.connection_pool(account_id).get() as crispin_client: # your code here pass Note that the returned CrispinClient could have ANY folder selected, or none at all! It's up to the calling code to handle folder sessions properly. We don't reset to a certain select state because it's slow. """ return _get_connection_pool(account_id, pool_size, pool_map, True) def writable_connection_pool(account_id, pool_size=1, pool_map=dict()): """ Per-account crispin connection pool, with *read-write* connections. Use like this: conn_pool = crispin.writable_connection_pool(account_id) with conn_pool.get() as crispin_client: # your code here pass """ return _get_connection_pool(account_id, pool_size, pool_map, False) class CrispinConnectionPool(object): """ Connection pool for Crispin clients. Connections in a pool are specific to an IMAPAccount. Parameters ---------- account_id : int Which IMAPAccount to open up a connection to. num_connections : int How many connections in the pool. readonly : bool Is the connection to the IMAP server read-only? """ def __init__(self, account_id, num_connections, readonly): log.info('Creating Crispin connection pool for account {} with {} ' 'connections'.format(account_id, num_connections)) self.account_id = account_id self.readonly = readonly self._queue = Queue(num_connections, items=num_connections * [None]) self._sem = BoundedSemaphore(num_connections) self._set_account_info() @contextlib.contextmanager def get(self): """ Get a connection from the pool, or instantiate a new one if needed. If `num_connections` connections are already in use, block until one is available. """ # A gevent semaphore is granted in the order that greenlets tried to # acquire it, so we use a semaphore here to prevent potential # starvation of greenlets if there is high contention for the pool. # The queue implementation does not have that property; having # greenlets simply block on self._queue.get(block=True) could cause # individual greenlets to block for arbitrarily long. self._sem.acquire() client = self._queue.get() try: if client is None: client = self._new_connection() yield client except CONN_DISCARD_EXC_CLASSES as exc: # Discard the connection on socket or IMAP errors. Technically this # isn't always necessary, since if you got e.g. a FETCH failure you # could reuse the same connection. But for now it's the simplest # thing to do. log.info('IMAP connection error; discarding connection', exc_info=True) if client is not None: try: client.logout() except: log.error('Error on IMAP logout', exc_info=True) client = None raise exc except: raise finally: self._queue.put(client) self._sem.release() def _set_account_info(self): with session_scope() as db_session: account = db_session.query(Account).get(self.account_id) self.sync_state = account.sync_state self.provider_info = account.provider_info self.email_address = account.email_address self.auth_handler = account.auth_handler if account.provider == 'gmail': self.client_cls = GmailCrispinClient else: self.client_cls = CrispinClient def _new_raw_connection(self): """Returns a new, authenticated IMAPClient instance for the account.""" with session_scope() as db_session: account = db_session.query(Account).get(self.account_id) return self.auth_handler.connect_account(account) def _new_connection(self): conn = self._new_raw_connection() return self.client_cls(self.account_id, self.provider_info, self.email_address, conn, readonly=self.readonly) def _exc_callback(): log.info('Connection broken with error; retrying with new connection', exc_info=True) gevent.sleep(5) retry_crispin = functools.partial( retry, retry_classes=CONN_DISCARD_EXC_CLASSES, exc_callback=_exc_callback) class CrispinClient(object): """ Generic IMAP client wrapper. One thing to note about crispin clients is that *all* calls operate on the currently selected folder. Crispin will NEVER implicitly select a folder for you. This is very important! IMAP only guarantees that folder message UIDs are valid for a "session", which is defined as from the time you SELECT a folder until the connection is closed or another folder is selected. Crispin clients *always* return long ints rather than strings for number data types, such as message UIDs, Google message IDs, and Google thread IDs. All inputs are coerced to strings before being passed off to the IMAPClient connection. You should really be interfacing with this class via a connection pool, see `connection_pool()`. Parameters ---------- account_id : int Database id of the associated IMAPAccount. conn : IMAPClient Open IMAP connection (should be already authed). readonly : bool Whether or not to open IMAP connections as readonly. """ def __init__(self, account_id, provider_info, email_address, conn, readonly=True): self.account_id = account_id self.provider_info = provider_info self.email_address = email_address # IMAP isn't stateless :( self.selected_folder = None self._folder_names = None self.conn = conn self.readonly = readonly def _fetch_folder_list(self): """ NOTE: XLIST is deprecated, so we just use LIST. An example response with some other flags: * LIST (\HasNoChildren) "/" "INBOX" * LIST (\Noselect \HasChildren) "/" "[Gmail]" * LIST (\HasNoChildren \All) "/" "[Gmail]/All Mail" * LIST (\HasNoChildren \Drafts) "/" "[Gmail]/Drafts" * LIST (\HasNoChildren \Important) "/" "[Gmail]/Important" * LIST (\HasNoChildren \Sent) "/" "[Gmail]/Sent Mail" * LIST (\HasNoChildren \Junk) "/" "[Gmail]/Spam" * LIST (\HasNoChildren \Flagged) "/" "[Gmail]/Starred" * LIST (\HasNoChildren \Trash) "/" "[Gmail]/Trash" IMAPClient parses this response into a list of (flags, delimiter, name) tuples. """ return self.conn.list_folders() def select_folder(self, folder, uidvalidity_cb): """ Selects a given folder. Makes sure to set the 'selected_folder' attribute to a (folder_name, select_info) pair. Selecting a folder indicates the start of an IMAP session. IMAP UIDs are only guaranteed valid for sessions, so the caller must provide a callback that checks UID validity. Starts a new session even if `folder` is already selected, since this does things like e.g. makes sure we're not getting cached/out-of-date values for HIGHESTMODSEQ from the IMAP server. """ try: select_info = self.conn.select_folder( folder, readonly=self.readonly) except imapclient.IMAPClient.Error as e: # Specifically point out folders that come back as missing by # checking for Yahoo / Gmail / Outlook (Hotmail) specific errors: if '[NONEXISTENT] Unknown Mailbox:' in e.message or \ 'does not exist' in e.message or \ "doesn't exist" in e.message: raise FolderMissingError(folder) # We can't assume that all errors here are caused by the folder # being deleted, as other connection errors could occur - but we # want to make sure we keep track of different providers' # "nonexistent" messages, so log this event. log.error("IMAPClient error selecting folder. May be deleted", error=str(e)) raise select_info['UIDVALIDITY'] = long(select_info['UIDVALIDITY']) self.selected_folder = (folder, select_info) # Don't propagate cached information from previous session self._folder_names = None return uidvalidity_cb(self.account_id, folder, select_info) @property def selected_folder_name(self): return or_none(self.selected_folder, lambda f: f[0]) @property def selected_folder_info(self): return or_none(self.selected_folder, lambda f: f[1]) @property def selected_uidvalidity(self): return or_none(self.selected_folder_info, lambda i: i['UIDVALIDITY']) @property def selected_uidnext(self): return or_none(self.selected_folder_info, lambda i: i.get('UIDNEXT')) def sync_folders(self): """ List of folders to sync. In generic IMAP, the 'INBOX' folder is required. Returns ------- list Folders to sync (as strings). """ to_sync = [] have_folders = self.folder_names() assert 'inbox' in have_folders, \ "Missing required 'inbox' folder for account_id: {}".\ format(self.account_id) for names in have_folders.itervalues(): to_sync.extend(names) return to_sync def folder_names(self, force_resync=False): """ Return the folder names for the account as a mapping from recognized role: list of folder names, for example: 'sent': ['Sent Items', 'Sent']. The list of recognized folder roles is in: inbox/models/constants.py Folders that do not belong to a recognized role are mapped to None, for example: None: ['MyFolder', 'OtherFolder']. The mapping is also cached in self._folder_names Parameters: ----------- force_resync: boolean Return the cached mapping or return a refreshed mapping (after refetching from the remote). """ if force_resync or self._folder_names is None: self._folder_names = defaultdict(list) raw_folders = self.folders() for f in raw_folders: self._folder_names[f.role].append(f.display_name) return self._folder_names def folders(self): """ Fetch the list of folders for the account from the remote, return as a list of RawFolder objects. NOTE: Always fetches the list of folders from the remote. """ raw_folders = [] folders = self._fetch_folder_list() for flags, delimiter, name in folders: if u'\\Noselect' in flags or u'\\NoSelect' in flags \ or u'\\NonExistent' in flags: # Special folders that can't contain messages continue raw_folder = self._process_folder(name, flags) raw_folders.append(raw_folder) return raw_folders def _process_folder(self, display_name, flags): """ Determine the role for the remote folder from its `name` and `flags`. Returns ------- RawFolder representing the folder """ # TODO[[k]: Important/ Starred for generic IMAP? # Different providers have different names for folders, here # we have a default map for common name mapping, additional # mappings can be provided via the provider configuration file default_folder_map = { 'inbox': 'inbox', 'drafts': 'drafts', 'draft': 'drafts', 'junk': 'spam', 'spam': 'spam', 'archive': 'archive', 'sent': 'sent', 'trash': 'trash'} # Additionally we provide a custom mapping for providers that # don't fit into the defaults. folder_map = self.provider_info.get('folder_map', {}) # Some providers also provide flags to determine common folders # Here we read these flags and apply the mapping flag_map = {'\\Trash': 'trash', '\\Sent': 'sent', '\\Drafts': 'drafts', '\\Junk': 'spam', '\\Inbox': 'inbox', '\\Spam': 'spam'} role = default_folder_map.get(display_name.lower()) if not role: role = folder_map.get(display_name) if not role: for flag in flags: role = flag_map.get(flag) return RawFolder(display_name=display_name, role=role) def create_folder(self, name): self.conn.create_folder(name) def condstore_supported(self): # Technically QRESYNC implies CONDSTORE, although this is unlikely to # matter in practice. capabilities = self.conn.capabilities() return 'CONDSTORE' in capabilities or 'QRESYNC' in capabilities def idle_supported(self): return 'IDLE' in self.conn.capabilities() def search_uids(self, criteria): """ Find UIDs in this folder matching the criteria. See http://tools.ietf.org/html/rfc3501.html#section-6.4.4 for valid criteria. """ return sorted([long(uid) for uid in self.conn.search(criteria)]) def all_uids(self): """ Fetch all UIDs associated with the currently selected folder. Returns ------- list UIDs as integers sorted in ascending order. """ # Note that this list may include items which have been marked for # deletion with the \Deleted flag, but not yet actually removed via # an EXPUNGE command. I choose to include them here since most clients # will still display them (sometimes with a strikethrough). If showing # these is a problem, we can either switch back to searching for # 'UNDELETED' or doing a fetch for ['UID', 'FLAGS'] and filtering. try: t = time.time() fetch_result = self.conn.search(['ALL']) except imaplib.IMAP4.error as e: if e.message.find('UID SEARCH wrong arguments passed') >= 0: # Mail2World servers fail for the otherwise valid command # 'UID SEARCH ALL' but strangely pass for 'UID SEARCH ALL UID' log.debug("Getting UIDs failed when using 'UID SEARCH " "ALL'. Switching to alternative 'UID SEARCH " "ALL UID", exception=e) t = time.time() fetch_result = self.conn.search(['ALL', 'UID']) else: raise elapsed = time.time() - t log.debug('Requested all UIDs', selected_folder=self.selected_folder_name, search_time=elapsed, total_uids=len(fetch_result)) return sorted([long(uid) for uid in fetch_result]) def uids(self, uids): uid_set = set(uids) messages = [] raw_messages = {} for uid in uid_set: try: raw_messages.update(self.conn.fetch( uid, ['BODY.PEEK[]', 'INTERNALDATE', 'FLAGS'])) except imapclient.IMAPClient.Error as e: if ('[UNAVAILABLE] UID FETCH Server error ' 'while fetching messages') in str(e): log.info('Got an exception while requesting an UID', uid=uid, error=e, logstash_tag='imap_download_exception') continue else: log.info(('Got an unhandled exception while ' 'requesting an UID'), uid=uid, error=e, logstash_tag='imap_download_exception') raise for uid in sorted(raw_messages.iterkeys(), key=long): # Skip handling unsolicited FETCH responses if uid not in uid_set: continue msg = raw_messages[uid] if msg.keys() == ['SEQ']: log.error('No data returned for UID, skipping', uid=uid) continue messages.append(RawMessage(uid=long(uid), internaldate=msg['INTERNALDATE'], flags=msg['FLAGS'], body=msg['BODY[]'], # TODO: use data structure that isn't # Gmail-specific g_thrid=None, g_msgid=None, g_labels=None)) return messages def flags(self, uids): if len(uids) > 100: # Some backends abort the connection if you give them a really # long sequence set of individual UIDs, so instead fetch flags for # all UIDs greater than or equal to min(uids). seqset = '{}:*'.format(min(uids)) else: seqset = uids data = self.conn.fetch(seqset, ['FLAGS']) uid_set = set(uids) return {uid: Flags(ret['FLAGS']) for uid, ret in data.items() if uid in uid_set} def delete_uids(self, uids): uids = [str(u) for u in uids] self.conn.delete_messages(uids) self.conn.expunge() def set_starred(self, uids, starred): if starred: self.conn.add_flags(uids, ['\\Flagged']) else: self.conn.remove_flags(uids, ['\\Flagged']) def set_unread(self, uids, unread): uids = [str(u) for u in uids] if unread: self.conn.remove_flags(uids, ['\\Seen']) else: self.conn.add_flags(uids, ['\\Seen']) def save_draft(self, message, date=None): assert self.selected_folder_name in self.folder_names()['drafts'], \ 'Must select a drafts folder first ({0})'.\ format(self.selected_folder_name) self.conn.append(self.selected_folder_name, message, ['\\Draft', '\\Seen'], date) def create_message(self, message, date=None): """ Create a message on the server. Only used to fix server-side bugs, like iCloud not saving Sent messages. """ assert self.selected_folder_name in self.folder_names()['sent'], \ 'Must select sent folder first ({0})'.\ format(self.selected_folder_name) return self.conn.append(self.selected_folder_name, message, [], date) def fetch_headers(self, uids): """ Fetch headers for the given uids. Chunked because certain providers fail with 'Command line too large' if you feed them too many uids at once. """ headers = {} for uid_chunk in chunk(uids, 100): headers.update(self.conn.fetch( uid_chunk, ['BODY.PEEK[HEADER]'])) return headers def find_by_header(self, header_name, header_value): """Find all uids in the selected folder with the given header value.""" all_uids = self.all_uids() # It would be nice to just search by header too, but some backends # don't support that, at least not if you want to search by X-INBOX-ID # header. So fetch the header for each draft and see if we # can find one that matches. # TODO(emfree): are there other ways we can narrow the result set a # priori (by subject or date, etc.) matching_draft_headers = self.fetch_headers(all_uids) results = [] for uid, response in matching_draft_headers.iteritems(): headers = response['BODY[HEADER]'] parser = HeaderParser() header = parser.parsestr(headers).get(header_name) if header == header_value: results.append(uid) return results def delete_draft(self, inbox_uid, message_id_header): """ Delete a draft, as identified either by its X-Inbox-Id or by its Message-Id header. We first delete the message from the Drafts folder, and then also delete it from the Trash folder if necessary. """ drafts_folder_name = self.folder_names()['drafts'][0] self.conn.select_folder(drafts_folder_name) self._delete_message(inbox_uid, message_id_header) trash_folder_name = self.folder_names()['trash'][0] self.conn.select_folder(trash_folder_name) self._delete_message(inbox_uid, message_id_header) def _delete_message(self, inbox_uid, message_id_header): """ Delete a message from the selected folder, using either the X-Inbox-Id header or the Message-Id header to locate it. Does nothing if no matching messages are found, or if more than one matching message is found. """ assert inbox_uid or message_id_header, 'Need at least one header' if inbox_uid: matching_uids = self.find_by_header('X-Inbox-Id', inbox_uid) else: matching_uids = self.find_by_header('Message-Id', message_id_header) if not matching_uids: log.error('No remote messages found to delete', inbox_uid=inbox_uid, message_id_header=message_id_header) return if len(matching_uids) > 1: log.error('Multiple remote messages found to delete', inbox_uid=inbox_uid, message_id_header=message_id_header, uids=matching_uids) return self.conn.delete_messages(matching_uids) self.conn.expunge() def logout(self): self.conn.logout() def idle(self, timeout): """Idle for up to `timeout` seconds. Make sure we take the connection back out of idle mode so that we can reuse this connection in another context.""" log.info('Idling', timeout=timeout) self.conn.idle() try: with self._restore_timeout(): r = self.conn.idle_check(timeout) except: self.conn.idle_done() raise self.conn.idle_done() return r @contextlib.contextmanager def _restore_timeout(self): # IMAPClient.idle_check() calls setblocking(1) on the underlying # socket, erasing any previously set timeout. So make sure to restore # the timeout. sock = getattr(self.conn._imap, 'sslobj', self.conn._imap.sock) timeout = sock.gettimeout() try: yield finally: sock.settimeout(timeout) def condstore_changed_flags(self, modseq): data = self.conn.fetch('1:*', ['FLAGS'], modifiers=['CHANGEDSINCE {}'.format(modseq)]) return {uid: Flags(ret['FLAGS']) for uid, ret in data.items()} class GmailCrispinClient(CrispinClient): PROVIDER = 'gmail' def sync_folders(self): """ Gmail-specific list of folders to sync. In Gmail, every message is in `All Mail`, with the exception of messages in the Trash and Spam folders. So we only sync the `All Mail`, Trash and Spam folders. Returns ------- list Folders to sync (as strings). """ present_folders = self.folder_names() if 'all' not in present_folders: raise GmailSettingError( "Account {} ({}) is missing the 'All Mail' folder. This is " "probably due to 'Show in IMAP' being disabled. " "Please enable at " "https://mail.google.com/mail/#settings/labels" .format(self.account_id, self.email_address)) # If the account has Trash, Spam folders, sync those too. to_sync = [] for folder in ['all', 'trash', 'spam']: if folder in present_folders: to_sync.append(present_folders[folder][0]) return to_sync def flags(self, uids): """ Gmail-specific flags. Returns ------- dict Mapping of `uid` : GmailFlags. """ data = self.conn.fetch(uids, ['FLAGS', 'X-GM-LABELS']) uid_set = set(uids) return {uid: GmailFlags(ret['FLAGS'], ret['X-GM-LABELS']) for uid, ret in data.items() if uid in uid_set} def condstore_changed_flags(self, modseq): data = self.conn.fetch('1:*', ['FLAGS', 'X-GM-LABELS'], modifiers=['CHANGEDSINCE {}'.format(modseq)]) results = {} for uid, ret in data.items(): if 'FLAGS' not in ret or 'X-GM-LABELS' not in ret: # We might have gotten an unsolicited fetch response that # doesn't have all the data we asked for -- if so, explicitly # fetch flags and labels for that UID. log.info('Got incomplete response in flags fetch', uid=uid, ret=str(ret)) data_for_uid = self.conn.fetch(uid, ['FLAGS', 'X-GM-LABELS']) if not data_for_uid: continue ret = data_for_uid[uid] results[uid] = GmailFlags(ret['FLAGS'], ret['X-GM-LABELS']) return results def g_msgids(self, uids): """ X-GM-MSGIDs for the given UIDs. Returns ------- dict Mapping of `uid` (long) : `g_msgid` (long) """ data = self.conn.fetch(uids, ['X-GM-MSGID']) uid_set = set(uids) return {uid: ret['X-GM-MSGID'] for uid, ret in data.items() if uid in uid_set} def folder_names(self, force_resync=False): """ Return the folder names ( == label names for Gmail) for the account as a mapping from recognized role: list of folder names in the role, for example: 'sent': ['Sent Items', 'Sent']. The list of recognized categories is in: inbox/models/constants.py Folders that do not belong to a recognized role are mapped to None, for example: None: ['MyFolder', 'OtherFolder']. The mapping is also cached in self._folder_names Parameters: ----------- force_resync: boolean Return the cached mapping or return a refreshed mapping (after refetching from the remote). """ if force_resync or self._folder_names is None: self._folder_names = defaultdict(list) raw_folders = self.folders() for f in raw_folders: self._folder_names[f.role].append(f.display_name) return self._folder_names def folders(self): """ Fetch the list of folders for the account from the remote, return as a list of RawFolder objects. NOTE: Always fetches the list of folders from the remote. """ raw_folders = [] folders = self._fetch_folder_list() for flags, delimiter, name in folders: if u'\\Noselect' in flags or u'\\NoSelect' in flags \ or u'\\NonExistent' in flags: # Special folders that can't contain messages, usually # just '[Gmail]' continue raw_folder = self._process_folder(name, flags) raw_folders.append(raw_folder) return raw_folders def _process_folder(self, display_name, flags): """ Determine the canonical_name for the remote folder from its `name` and `flags`. Returns ------- RawFolder representing the folder """ flag_map = {'\\Drafts': 'drafts', '\\Important': 'important', '\\Sent': 'sent', '\\Junk': 'spam', '\\Flagged': 'starred', '\\Trash': 'trash'} role = None if '\\All' in flags: role = 'all' elif display_name.lower() == 'inbox': # Special-case the display name here. In Gmail, the inbox # folder shows up in the folder list as 'INBOX', and in sync as # the label '\\Inbox'. We're just always going to give it the # display name 'Inbox'. role = 'inbox' display_name = 'Inbox' else: for flag in flags: if flag in flag_map: role = flag_map[flag] return RawFolder(display_name=display_name, role=role) def uids(self, uids): raw_messages = self.conn.fetch(uids, ['BODY.PEEK[]', 'INTERNALDATE', 'FLAGS', 'X-GM-THRID', 'X-GM-MSGID', 'X-GM-LABELS']) messages = [] uid_set = set(uids) for uid in sorted(raw_messages.iterkeys(), key=long): # Skip handling unsolicited FETCH responses if uid not in uid_set: continue msg = raw_messages[uid] messages.append(RawMessage(uid=long(uid), internaldate=msg['INTERNALDATE'], flags=msg['FLAGS'], body=msg['BODY[]'], g_thrid=long(msg['X-GM-THRID']), g_msgid=long(msg['X-GM-MSGID']), g_labels=msg['X-GM-LABELS'])) return messages def g_metadata(self, uids): """ Download Gmail MSGIDs, THRIDs, and message sizes for the given uids. Parameters ---------- uids : list UIDs to fetch data for. Must be from the selected folder. Returns ------- dict uid: GMetadata(msgid, thrid, size) """ # Super long sets of uids may fail with BAD ['Could not parse command'] # In that case, just fetch metadata for /all/ uids. seqset = uids if len(uids) < 1e6 else '1:*' data = self.conn.fetch(seqset, ['X-GM-MSGID', 'X-GM-THRID', 'RFC822.SIZE']) uid_set = set(uids) return {uid: GMetadata(ret['X-GM-MSGID'], ret['X-GM-THRID'], ret['RFC822.SIZE']) for uid, ret in data.items() if uid in uid_set} def expand_thread(self, g_thrid): """ Find all message UIDs in the selected folder with X-GM-THRID equal to g_thrid. Returns ------- list """ uids = [long(uid) for uid in self.conn.search('X-GM-THRID {}'.format(g_thrid))] # UIDs ascend over time; return in order most-recent first return sorted(uids, reverse=True) def find_by_header(self, header_name, header_value): criteria = ['HEADER {} {}'.format(header_name, header_value)] return self.conn.search(criteria)
gale320/sync-engine
inbox/crispin.py
Python
agpl-3.0
34,132
class TripPurpose < ApplicationRecord acts_as_paranoid # soft delete has_paper_trail validates :name, presence: true, uniqueness: { :case_sensitive => false, conditions: -> { where(deleted_at: nil) } } def self.by_provider(provider) hidden_ids = HiddenLookupTableValue.hidden_ids self.table_name, provider.try(:id) where.not(id: hidden_ids) end def as_api_json { name: name, code: id } end end
camsys/ridepilot
app/models/trip_purpose.rb
Ruby
agpl-3.0
441
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // 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-2022 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 AccessControlContextTypeHolder : ContextTypeHolder { #region Constants #endregion #region Private Fields #endregion #region Properties #endregion #region CTor public AccessControlContextTypeHolder() { } public AccessControlContextTypeHolder(JToken node) : base(node) { } #endregion #region Methods public override Params ToParams(bool includeObjectType = true) { Params kparams = base.ToParams(includeObjectType); if (includeObjectType) kparams.AddReplace("objectType", "KalturaAccessControlContextTypeHolder"); return kparams; } protected override string getPropertyName(string apiName) { switch(apiName) { default: return base.getPropertyName(apiName); } } #endregion } }
kaltura/KalturaGeneratedAPIClientsCsharp
KalturaClient/Types/AccessControlContextTypeHolder.cs
C#
agpl-3.0
2,292
define(function (require) { 'use strict'; var Vector2 = require('vector2-node'); /** * Returns a new unit vector in the direction specified by the angle */ Vector2.fromAngle = function(angle) { return new Vector2(1, 0).rotate(angle); }; Vector2.prototype.toString = function(precision) { if (precision === undefined) precision = 4; return '(' + this.x.toFixed(precision) + ', ' + this.y.toFixed(precision) + ')'; }; /** * Rounds each component to the nearest integer. */ Vector2.prototype.round = function() { this.x = Math.round(this.x); this.y = Math.round(this.y); return this; }; return Vector2; });
Connexions/simulations
common/math/vector2.js
JavaScript
agpl-3.0
731
<?php // require('../config.php'); require('../db_lib.php'); $db = new db(); // If the user clicked one of the buttons if ((isset($_GET['submit'])) || (isset($_GET['prev'])) || (isset($_GET['next']))) { $where = ''; $start_date = htmlspecialchars($_GET['start_date'], ENT_QUOTES); if ($start_date != '0000-00-00') { $where .= ' AND dms.created_at >= "' . $db->date($start_date) . '"'; } $end_date = htmlspecialchars($_GET['end_date'], ENT_QUOTES); if ($end_date != '0000-00-00') { $where .= ' AND dms.created_at <= "' . $db->date($end_date) . '"'; } $query = htmlspecialchars($_GET['query'], ENT_QUOTES); if ($query != '') { $query_words = explode(' ',$query); foreach($query_words as $word) { $word = trim($word); $where .= " AND dms.dm_text LIKE '%$word%' "; } } if(isset($_GET['prev'])) { $page = intval($_GET['page']) - 1; if($page<0) { $page=0; } } elseif ($_GET['next']) { $page = intval($_GET['page']) + 1; } else { $page = 0; } } else { $start_date = '0000-00-00'; $end_date = '0000-00-00'; $query = ''; $page = 0; } require('page_top.html'); print '<h2>Search DMs</h2>'; // Display the form with empty fields // or the values entered before Run button was clicked print "<form action='search_dms.php' method='get'>"; print "Start Date: <input type='text' name='start_date' value='$start_date'>"; print "End Date: <input type='text' name='end_date' value='$end_date'><br/>"; print "Search Terms: <input type='text' name='query' value='$query' size='50'>"; print "<input type='hidden' name='page' value=$page>"; print '<button type="submit" name="submit" value=1>Search</button>'; print '<button type="submit" name="prev" value=1>< Prev</button>'; print '<button type="submit" name="next" value=1>Next ></button>'; print '</form>'; if (!empty($where)) { require('../get_all_dms.php'); $dms = get_all_dms($where,$page*$results_per_page, $results_per_page); require('display_dms.php'); } require('page_bottom.html'); ?>
rolencea/org.civicrm.civisocial2
twitterAPI/civisocialtwitter/report/search_dms.php
PHP
agpl-3.0
2,051
const ERR = require('async-stacktrace'); const _ = require('lodash'); const async = require('async'); const sqldb = require('../prairielib/lib/sql-db'); module.exports = { pages(chosenPage, count, pageSize) { let lastPage = Math.ceil(count / pageSize); if (lastPage === 0) lastPage = 1; let currPage = Number(chosenPage); if (!_.isInteger(currPage)) currPage = 1; let prevPage = currPage - 1; let nextPage = currPage + 1; currPage = Math.max(1, Math.min(lastPage, currPage)); prevPage = Math.max(1, Math.min(lastPage, prevPage)); nextPage = Math.max(1, Math.min(lastPage, nextPage)); return { currPage, prevPage, nextPage, lastPage }; }, /** * Utility function to facilitate extremely large queries whose results * cannot fit in memory all at once. The given query must accept an "offset" * param that will be used to paginate the query. The "receiveRow" callback * will be called once for each row in the result set. The "done" callback * is called either if an error has occurred or when all rows have been * delivered. */ paginateQuery(sql, params, receiveRow, done) { const _params = Object.assign({}, params); let offset = 0; async.doWhilst( (callback) => { _params.offset = offset; sqldb.query(sql, _params, (err, result) => { if (ERR(err, callback)) return; async.eachSeries(result.rows, receiveRow, (err) => { if (ERR(err, callback)) return; offset += result.rows.length; callback(null, result.rows.length); }); }); }, (count, callback) => { callback(null, count > 0); }, (err) => { if (ERR(err, done)) return; done(null); } ); }, };
PrairieLearn/PrairieLearn
lib/paginate.js
JavaScript
agpl-3.0
1,786