code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class worldTrafficLightListenerComponent : entIComponent { [Ordinal(3)] [RED("intersectionRef")] public NodeRef IntersectionRef { get; set; } [Ordinal(4)] [RED("groupIdx")] public CUInt32 GroupIdx { get; set; } public worldTrafficLightListenerComponent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/worldTrafficLightListenerComponent.cs
C#
gpl-3.0
473
/* * A Command & Conquer: Renegade SSGM Plugin, containing all the single player mission scripts * Copyright(C) 2017 Neijwiert * * This program is free software : you can redistribute it and / or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program.If not, see <http://www.gnu.org/licenses/>. */ #include "General.h" #include "M01_Shed_Datadisc_JDG.h" /* M01 -> 123646 */ void M01_Shed_Datadisc_JDG::Custom(GameObject *obj, int type, int param, GameObject *sender) { if (type == CUSTOM_EVENT_POWERUP_GRANTED) { Commands->Set_HUD_Help_Text(7587, Vector3(0.196f, 0.882f, 0.196f)); // Data Link Updated - Satellite Image Enhanced\n GameObject *M01DataDiscTextControllerJDGObj = Commands->Find_Object(117188); if (M01DataDiscTextControllerJDGObj) { Commands->Send_Custom_Event(obj, M01DataDiscTextControllerJDGObj, 0, 10, 2.0f); } Commands->Clear_Map_Cell(9, 9); Commands->Clear_Map_Cell(9, 10); Commands->Clear_Map_Cell(10, 9); Commands->Clear_Map_Cell(10, 10); Commands->Clear_Map_Cell(10, 11); Commands->Clear_Map_Cell(11, 9); Commands->Clear_Map_Cell(11, 10); Commands->Clear_Map_Cell(11, 11); Commands->Clear_Map_Cell(11, 12); Commands->Clear_Map_Cell(12, 9); Commands->Clear_Map_Cell(12, 10); Commands->Clear_Map_Cell(12, 11); Commands->Clear_Map_Cell(12, 12); Commands->Clear_Map_Cell(13, 9); Commands->Clear_Map_Cell(13, 10); Commands->Clear_Map_Cell(13, 11); Commands->Clear_Map_Cell(13, 12); Commands->Clear_Map_Cell(14, 10); Commands->Clear_Map_Cell(14, 11); Commands->Clear_Map_Cell(14, 12); } } ScriptRegistrant<M01_Shed_Datadisc_JDG> M01_Shed_Datadisc_JDGRegistrant("M01_Shed_Datadisc_JDG", "");
Neijwiert/C-C-Renegade-Mission-Scripts
Source/Single Player Scripts/M01_Shed_Datadisc_JDG.cpp
C++
gpl-3.0
2,138
<?php /** * @copyright Ilch 2 * @package ilch */ return [ 'menuStatistic' => 'Statistik', 'menuOnline' => 'Online', 'menuOnlineStatistic' => 'Online Statistik', 'user' => 'Benutzer', 'lastHere' => 'Letzte Aktivität', 'ipAdress' => 'IP-Adresse', 'osBrowser' => 'OS-System / Browser', 'findOnSite' => 'Befindet sich gerade auf', 'onlineGuests' => 'Gäste', 'onlineGuest' => 'Gast', 'onlineUser' => 'User', 'author' => 'Autor', 'totalUsers' => 'Mitglieder', 'lastUser' => 'Neuestes Mitglied', 'siteOnlineSince' => 'Seite online seit', 'IlchCMSVersion' => 'Ilch CMS Version', 'totalArticles' => 'Artikel', 'totalComments' => 'Kommentare', 'installedModules' => 'Installierte Module', 'statOnline' => 'Online', 'statToday' => 'Heute', 'statYesterday' => 'Gestern', 'statMonth' => 'Monat', 'statYear' => 'Jahr', 'statUserRegist' => 'Registriert', 'statTotal' => 'Gesamt', 'visitsStatistic' => 'Besucherstatistik', 'siteStatistic' => 'Seitenstatistik', 'ilchVersionStatistic' => 'Version von Ilch', 'modulesStatistic' => 'Installierte Module', 'browserStatistic' => 'Browser-Statistik', 'unknownOrUnseenBrowser' => 'Unbekannter oder bisher nie gesehener Browser.', 'osStatistic' => 'OS-Statistik', 'unknownOrUnseenOS' => 'Unbekanntes oder bisher nie gesehenes Betriebssystem.', 'invalidDate' => 'Ungültiges Datum.', 'hour' => 'Stunde', 'clock' => 'Uhr', 'day' => 'Tag', 'yearMonthDay' => 'Jahr - Monat - Tag', 'yearMonth' => 'Jahr - Monat', 'year' => 'Jahr', 'browser' => 'Browser', 'os' => 'OS-System', 'language' => 'Sprache', 'unknown' => 'Unbekannt', 'numberVisits' => 'Besucher', 'noStatistic' => 'Keine Statistik vorhanden', 'everythingDisabled' => 'Der Administrator hat alle Statistiken ausgeblendet.', ];
IlchCMS/Ilch-2.0
application/modules/statistic/translations/de.php
PHP
gpl-3.0
1,908
import express from 'express'; import mongoose from 'mongoose'; import { Text } from '../../data/model'; const router = express.Router(); router.get('/', (req, res) => { function getAnnotationTypeForTrainingset() { if (req.query.annotationType) { const annotationTypeId = mongoose.Types.ObjectId(req.query.annotationType); return req.set.getAnnotationTypeById(annotationTypeId); } return req.set.getFirstAnnotationType(); } const page = parseInt(req.query.page) || 1; const amount = parseInt(req.query.amount) || 200; const annotationType = getAnnotationTypeForTrainingset(); Text.find({ setId: req.set._id }) .skip((page - 1) * amount) .limit(amount) .cursor() .map(text => text.mapAnnotationStatusWithOptionName(req.set, annotationType)) .on('cursor', () => { res.write('['); }) .on('data', (() => { let index = 0; res.setHeader('Content-Type', 'application/json'); return text => res.write((!(index++) ? '' : ',') + JSON.stringify(text)); })()) .on('end', () => { res.write(']\n'); res.end(); }); }); export default router;
annomania/annomania-api
src/controller/route/trainingset.js
JavaScript
gpl-3.0
1,118
package at.bbm.core.objects.fields.field; import at.bbm.core.events.EventType; import at.bbm.core.objects.fields.Field; import at.bbm.core.objects.fields.FieldType; import at.bbm.core.objects.players.Player; import at.bbm.core.map.Location; public class Ice extends Field { public static final int ID = 6; public static final String TEXTURE = "textures/ice.png"; public static final boolean LOCKED = false; public static final int DURABILITY = 1; public static final boolean ACCEPT_PLAYER = true; public static final boolean ACCEPT_FIRE = true; public static final double SPEED = 2.0; public Ice(final Location paramLocation) { super(FieldType.ICE, paramLocation, TEXTURE, LOCKED, DURABILITY, ACCEPT_PLAYER, ACCEPT_FIRE, SPEED); } public final void updatePlayer(final Player paramPlayer) { } public final void handleEvent(final EventType paramEventType) { } }
MichaelJ2/big-buum-man
source/big-buum-man-core/src/main/java/at/bbm/core/objects/fields/field/Ice.java
Java
gpl-3.0
928
<?php $L['Account_Title'] = 'Корисници и групе'; $L['Account_Description'] = 'Управљај корисницима и групама, подеси доменски идентитет и добављаче аутентификације'; $L['Account_Tags'] = 'сссд корисник група царство домен налог креберос лдап'; $L['AccountProvider_Error_1'] = 'Account provider generic error: SSSD exit code 1'; $L['AccountProvider_Error_22'] = 'Грешка пружаоца налога: неисправан ДН. Провери Базни ДН и Корисници ДН у подешавањима пружаоца услуга'; $L['AccountProvider_Error_32'] = 'Грешка пружаоца налога: нема уноса. Провери ЛДАП бинд креденцијале и Базни ДН у подешавањима пружаоца Налога'; $L['AccountProvider_Error_34'] = 'Грешка пружаоца услуга: нисправна лозинка уређаја. Проверите да ли је сервер исправно придружен у домен'; $L['AccountProvider_Error_49'] = 'Грешка пружаоца налога: погрешни креденцијали (${0})'; $L['AccountProvider_Error_49_710'] = 'Недовољна права приступа (49/710): наведите алтернативне ЛДАП бинд креденцијале у подешавањима пружаоца Налога'; $L['AccountProvider_Error_4'] = 'Упозорење пружаоца налога: достигнуто ограничење величине (${0})'; $L['AccountProvider_Error_104'] = 'Конекција пружаоца услуга је ресетована са супротне стране: проверите да ли сервер подржава ССЛ/ТЛС конекције'; $L['AccountProvider_Error_110'] = 'Конекција пружаоца налога је истекла'; $L['AccountProvider_Error_111'] = 'Конекција пружаоца налога је одбијена'; $L['AccountProvider_Error_82'] = 'LDAP client internal error (AccountProvider_Error_82)';
NethServer/nethserver-lang
locale/sr/server-manager/NethServer_Module_Account.php
PHP
gpl-3.0
2,216
from brainforge.learner import Backpropagation from brainforge.layers import Dense from brainforge.optimizers import Momentum from brainforge.util import etalon class DNI: def __init__(self, bpropnet, synth): self.bpropnet = bpropnet self.synth = synth self._predictor = None def predictor_coro(self): prediction = None delta_backwards = None while 1: inputs = yield prediction, delta_backwards prediction = self.bpropnet.predict(inputs) synthesized_delta = self.synth.predict(prediction) self.bpropnet.update(len(inputs)) delta_backwards = self.bpropnet.backpropagate(synthesized_delta) def predict(self, X): if self._predictor is None: self._predictor = self.predictor_coro() next(self._predictor) return self._predictor.send(X) def udpate(self, true_delta): synthesizer_delta = self.synth.cost.derivative( self.synth.output, true_delta ) self.synth.backpropagate(synthesizer_delta) self.synth.update(len(true_delta)) def build_net(inshape, outshape): net = Backpropagation(input_shape=inshape, layerstack=[ Dense(30, activation="tanh"), Dense(outshape, activation="softmax") ], cost="cxent", optimizer=Momentum(0.01)) return net def build_synth(inshape, outshape): synth = Backpropagation(input_shape=inshape, layerstack=[ Dense(outshape) ], cost="mse", optimizer=Momentum(0.01)) return synth X, Y = etalon predictor = build_net(X.shape[1:], Y.shape[1:]) pred_os = predictor.layers[-1].outshape synthesizer = build_synth(pred_os, pred_os) dni = DNI(predictor, synthesizer) pred, delta = dni.predict(X)
csxeba/brainforge
xperiments/xp_decoupled.py
Python
gpl-3.0
1,775
class ChangeContractNumberToVtContractNumberOnContracts < ActiveRecord::Migration[6.0] def change rename_column :contracts, :contract_number, :vt_contract_number end end
CodeforAustralia/dtf-genesis
db/migrate/20161027005904_change_contract_number_to_vt_contract_number_on_contracts.rb
Ruby
gpl-3.0
178
// CANAPE Network Testing Tool // Copyright (C) 2014 Context Information Security // // 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/>. using System; using System.ComponentModel; using CANAPE.NodeFactories; using CANAPE.Utils; namespace CANAPE.Documents.Net.NodeConfigs { /// <summary> /// Config for an edit node /// </summary> [Serializable] public class EditPacketNodeConfig : BaseNodeConfig { string _tag; ColorValue _color; /// <summary> /// The name of the node /// </summary> public const string NodeName = "editnode"; /// <summary> /// Get or set the colour to show in the edit window /// </summary> [LocalizedDescription("EditPacketNodeConfig_ColorDescription", typeof(Properties.Resources)), Category("Behavior")] public ColorValue Color { get { return _color; } set { if (_color != value) { _color = value; SetDirty(); } } } /// <summary> /// Get or set the textual tag to show in edit window /// </summary> [LocalizedDescription("EditPacketNodeConfig_TagDescription", typeof(Properties.Resources)), Category("Behavior")] public string Tag { get { return _tag; } set { if (_tag != value) { _tag = value; SetDirty(); } } } /// <summary> /// Get node name /// </summary> /// <returns>The node name</returns> public override string GetNodeName() { return NodeName; } /// <summary> /// Method called to create the factory /// </summary> /// <returns>The BaseNodeFactory</returns> protected override BaseNodeFactory OnCreateFactory() { return new EditPacketNodeFactory(_label, _id, _color, _tag); } /// <summary> /// Constructor /// </summary> public EditPacketNodeConfig() { Color = new ColorValue(255, 255, 255, 255); } } }
ctxis/canape
CANAPE.Documents/Net/NodeConfigs/EditPacketNodeConfig.cs
C#
gpl-3.0
3,021
@extends("layouts.app") @section("content") <div class="panel panel-default"> <div class="panel-heading">Editar rol</div> <div class="panel-body"> @include('roles.form',['rol'=>$rol, 'url' => '/roles/'.$rol->id,'method' => 'PUT']) </div> </div> @endsection
DanielIsaza/cidba
resources/views/roles/edit.blade.php
PHP
gpl-3.0
265
//===--- RewriteMacros.cpp - Rewrite macros into their expansions ---------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This code rewrites macro invocations into their expansions. This gives you // a macro expanded file that retains comments and #includes. // //===----------------------------------------------------------------------===// #include "clang/Rewrite/Rewriters.h" #include "clang/Rewrite/Rewriter.h" #include "clang/Lex/Preprocessor.h" #include "clang/Basic/SourceManager.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Path.h" #include "llvm/ADT/OwningPtr.h" #include <cstdio> using namespace clang; /// isSameToken - Return true if the two specified tokens start have the same /// content. static bool isSameToken(Token &RawTok, Token &PPTok) { // If two tokens have the same kind and the same identifier info, they are // obviously the same. if (PPTok.getKind() == RawTok.getKind() && PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo()) return true; // Otherwise, if they are different but have the same identifier info, they // are also considered to be the same. This allows keywords and raw lexed // identifiers with the same name to be treated the same. if (PPTok.getIdentifierInfo() && PPTok.getIdentifierInfo() == RawTok.getIdentifierInfo()) return true; return false; } /// GetNextRawTok - Return the next raw token in the stream, skipping over /// comments if ReturnComment is false. static const Token &GetNextRawTok(const std::vector<Token> &RawTokens, unsigned &CurTok, bool ReturnComment) { assert(CurTok < RawTokens.size() && "Overran eof!"); // If the client doesn't want comments and we have one, skip it. if (!ReturnComment && RawTokens[CurTok].is(tok::comment)) ++CurTok; return RawTokens[CurTok++]; } /// LexRawTokensFromMainFile - Lets all the raw tokens from the main file into /// the specified vector. static void LexRawTokensFromMainFile(Preprocessor &PP, std::vector<Token> &RawTokens) { SourceManager &SM = PP.getSourceManager(); // Create a lexer to lex all the tokens of the main file in raw mode. Even // though it is in raw mode, it will not return comments. const llvm::MemoryBuffer *FromFile = SM.getBuffer(SM.getMainFileID()); Lexer RawLex(SM.getMainFileID(), FromFile, SM, PP.getLangOptions()); // Switch on comment lexing because we really do want them. RawLex.SetCommentRetentionState(true); Token RawTok; do { RawLex.LexFromRawLexer(RawTok); // If we have an identifier with no identifier info for our raw token, look // up the indentifier info. This is important for equality comparison of // identifier tokens. if (RawTok.is(tok::raw_identifier)) PP.LookUpIdentifierInfo(RawTok); RawTokens.push_back(RawTok); } while (RawTok.isNot(tok::eof)); } /// RewriteMacrosInInput - Implement -rewrite-macros mode. void clang::RewriteMacrosInInput(Preprocessor &PP, raw_ostream *OS) { SourceManager &SM = PP.getSourceManager(); Rewriter Rewrite; Rewrite.setSourceMgr(SM, PP.getLangOptions()); RewriteBuffer &RB = Rewrite.getEditBuffer(SM.getMainFileID()); std::vector<Token> RawTokens; LexRawTokensFromMainFile(PP, RawTokens); unsigned CurRawTok = 0; Token RawTok = GetNextRawTok(RawTokens, CurRawTok, false); // Get the first preprocessing token. PP.EnterMainSourceFile(); Token PPTok; PP.Lex(PPTok); // Preprocess the input file in parallel with raw lexing the main file. Ignore // all tokens that are preprocessed from a file other than the main file (e.g. // a header). If we see tokens that are in the preprocessed file but not the // lexed file, we have a macro expansion. If we see tokens in the lexed file // that aren't in the preprocessed view, we have macros that expand to no // tokens, or macro arguments etc. while (RawTok.isNot(tok::eof) || PPTok.isNot(tok::eof)) { SourceLocation PPLoc = SM.getExpansionLoc(PPTok.getLocation()); // If PPTok is from a different source file, ignore it. if (!SM.isFromMainFile(PPLoc)) { PP.Lex(PPTok); continue; } // If the raw file hits a preprocessor directive, they will be extra tokens // in the raw file that don't exist in the preprocsesed file. However, we // choose to preserve them in the output file and otherwise handle them // specially. if (RawTok.is(tok::hash) && RawTok.isAtStartOfLine()) { // If this is a #warning directive or #pragma mark (GNU extensions), // comment the line out. if (RawTokens[CurRawTok].is(tok::identifier)) { const IdentifierInfo *II = RawTokens[CurRawTok].getIdentifierInfo(); if (II->getName() == "warning") { // Comment out #warning. RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//"); } else if (II->getName() == "pragma" && RawTokens[CurRawTok+1].is(tok::identifier) && (RawTokens[CurRawTok+1].getIdentifierInfo()->getName() == "mark")) { // Comment out #pragma mark. RB.InsertTextAfter(SM.getFileOffset(RawTok.getLocation()), "//"); } } // Otherwise, if this is a #include or some other directive, just leave it // in the file by skipping over the line. RawTok = GetNextRawTok(RawTokens, CurRawTok, false); while (!RawTok.isAtStartOfLine() && RawTok.isNot(tok::eof)) RawTok = GetNextRawTok(RawTokens, CurRawTok, false); continue; } // Okay, both tokens are from the same file. Get their offsets from the // start of the file. unsigned PPOffs = SM.getFileOffset(PPLoc); unsigned RawOffs = SM.getFileOffset(RawTok.getLocation()); // If the offsets are the same and the token kind is the same, ignore them. if (PPOffs == RawOffs && isSameToken(RawTok, PPTok)) { RawTok = GetNextRawTok(RawTokens, CurRawTok, false); PP.Lex(PPTok); continue; } // If the PP token is farther along than the raw token, something was // deleted. Comment out the raw token. if (RawOffs <= PPOffs) { // Comment out a whole run of tokens instead of bracketing each one with // comments. Add a leading space if RawTok didn't have one. bool HasSpace = RawTok.hasLeadingSpace(); RB.InsertTextAfter(RawOffs, " /*"+HasSpace); unsigned EndPos; do { EndPos = RawOffs+RawTok.getLength(); RawTok = GetNextRawTok(RawTokens, CurRawTok, true); RawOffs = SM.getFileOffset(RawTok.getLocation()); if (RawTok.is(tok::comment)) { // Skip past the comment. RawTok = GetNextRawTok(RawTokens, CurRawTok, false); break; } } while (RawOffs <= PPOffs && !RawTok.isAtStartOfLine() && (PPOffs != RawOffs || !isSameToken(RawTok, PPTok))); RB.InsertTextBefore(EndPos, "*/"); continue; } // Otherwise, there was a replacement an expansion. Insert the new token // in the output buffer. Insert the whole run of new tokens at once to get // them in the right order. unsigned InsertPos = PPOffs; std::string Expansion; while (PPOffs < RawOffs) { Expansion += ' ' + PP.getSpelling(PPTok); PP.Lex(PPTok); PPLoc = SM.getExpansionLoc(PPTok.getLocation()); PPOffs = SM.getFileOffset(PPLoc); } Expansion += ' '; RB.InsertTextBefore(InsertPos, Expansion); } // Get the buffer corresponding to MainFileID. If we haven't changed it, then // we are done. if (const RewriteBuffer *RewriteBuf = Rewrite.getRewriteBufferFor(SM.getMainFileID())) { //printf("Changed:\n"); *OS << std::string(RewriteBuf->begin(), RewriteBuf->end()); } else { fprintf(stderr, "No changes\n"); } OS->flush(); }
Bootz/multicore-opimization
llvm/tools/clang/lib/Rewrite/RewriteMacros.cpp
C++
gpl-3.0
8,109
/** * PLEASE DO NOT MODIFY THIS FILE. WORK ON THE ES6 VERSION. * OTHERWISE YOUR CHANGES WILL BE REPLACED ON THE NEXT BUILD. **/ /** * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ ((document, submitForm) => { 'use strict'; // Selectors used by this script const buttonDataSelector = 'data-submit-task'; const formId = 'adminForm'; /** * Submit the task * @param task */ const submitTask = task => { const form = document.getElementById(formId); if (form && task === 'subscriber.batch') { submitForm(task, form); } }; // Register events document.addEventListener('DOMContentLoaded', () => { const button = document.getElementById('batch-submit-button-id'); if (button) { button.addEventListener('click', e => { const task = e.target.getAttribute(buttonDataSelector); submitTask(task); }); } }); })(document, Joomla.submitform);
RomanaBW/BwPostman
src/media/com_bwpostman/js/admin-subscribers-default-batch-footer.es6.js
JavaScript
gpl-3.0
1,041
angular.module('sofa.scrollingShadow', []) .directive('sofaScrollingShadow', function() { 'use strict'; return { restrict: 'A', link: function(scope, $element){ var $topShadow = angular.element('<div class="sofa-scrolling-shadow-top"></div>'), $bottomShadow = angular.element('<div class="sofa-scrolling-shadow-bottom"></div>'), $parent = $element.parent(); $parent .append($topShadow) .append($bottomShadow); var topShadowHeight = $topShadow[0].clientHeight, bottomShadowHeight = $bottomShadow[0].clientHeight; //IE uses scrollTop instead of scrollY var getScrollTop = function(element){ return ('scrollTop' in element) ? element.scrollTop : element.scrollY; }; var updateShadows = function(){ var element = $element[0], scrollTop = getScrollTop(element), clientHeight = element.clientHeight, scrollHeight = element.scrollHeight, scrollBottom = scrollHeight - scrollTop - clientHeight, rollingShadowOffsetTop = 0, rollingShadowOffsetBottom = 0; if (scrollTop < topShadowHeight){ rollingShadowOffsetTop = (topShadowHeight - scrollTop) * -1; } if (scrollBottom < bottomShadowHeight){ rollingShadowOffsetBottom = (bottomShadowHeight - scrollBottom) * -1; } $topShadow.css('top', rollingShadowOffsetTop + 'px'); $bottomShadow.css('bottom', rollingShadowOffsetBottom + 'px'); }; setTimeout(updateShadows, 1); $element.bind('scroll', updateShadows); } }; });
sofa/angular-sofa-scrolling-shadow
src/sofaScrollingShadow.js
JavaScript
gpl-3.0
2,175
__author__ = 'Davide' import win32api import win32con import socket # stop not defined VK_MEDIA_STOP = 0xB2 class RemoteController: def play_pause(self): win32api.keybd_event(win32con.VK_MEDIA_PLAY_PAUSE, 34) def stop(self): win32api.keybd_event(VK_MEDIA_STOP, 34) def next(self): win32api.keybd_event(win32con.VK_MEDIA_NEXT_TRACK, 34) def prev(self): win32api.keybd_event(win32con.VK_MEDIA_PREV_TRACK, 34) def vol_up(self): win32api.keybd_event(win32con.VK_VOLUME_UP, 34) def vol_down(self): win32api.keybd_event(win32con.VK_VOLUME_DOWN, 34) def vol_mute(self): win32api.keybd_event(win32con.VK_VOLUME_MUTE, 34) class Handler: def __init__(self): self.controller = RemoteController() def dispatch(self, msg): if msg == b"p": self.controller.play_pause() elif msg == b"n": self.controller.next() elif msg == b"s": self.controller.stop() elif msg == b"v": self.controller.prev() elif msg == b"+": self.controller.vol_up() elif msg == b"-": self.controller.vol_down() elif msg == b"m": self.controller.vol_mute() if __name__ == "__main__": HOST, PORT = "localhost", 9999 handler = Handler() server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) server.bind((HOST, PORT)) while True: data, addr = server.recvfrom(256) print(data, addr) handler.dispatch(data)
DavideCanton/Python3
wmp_remote/server.py
Python
gpl-3.0
1,561
package gate.server; import com.sun.net.httpserver.Headers; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import gate.Document; import gate.Factory; import gate.FeatureMap; import gate.Gate; import gate.ProcessingResource; import gate.TextualDocument; import gate.corpora.DocumentXmlUtils; import gate.util.SimpleFeatureMapImpl; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.HashMap; import java.util.Map; import java.util.Properties; public class RequestHandler implements HttpHandler{ protected static class Module { String classname; FeatureMap config; public Module(String classname, FeatureMap config) { this.classname = classname; this.config = config; } } protected Map<String,Module> mModules; public RequestHandler(Properties config) throws Exception { Gate.init(); File jarFile = new File(RequestHandler.class.getProtectionDomain().getCodeSource().getLocation().toURI()); for (int n=1; ; ++n) { String plugin = config.getProperty("plugin"+n); if (plugin == null) break; Gate.getCreoleRegister().registerDirectories(new File(jarFile.getParentFile(),plugin).toURI().toURL()); System.out.println("Loaded plugin: "+plugin); } mModules = new HashMap<>(); for (int n=1; ; ++n) { String name = config.getProperty("module"+n+".name"); if (name == null) break; Map<String,String> p = getParameters(config.getProperty("module"+n+".params")); SimpleFeatureMapImpl fm = new SimpleFeatureMapImpl(); for (Map.Entry<String,String> p1 : p.entrySet()) { String v = p1.getValue(); if ("true".equals(v)) { fm.put(p1.getKey(), true); } else if ("false".equals(v)) { fm.put(p1.getKey(), false); } else if (v.matches("^[+-]?[0-9]+$")) { fm.put(p1.getKey(), Integer.parseInt(v)); } else if (v.matches("^[+-]?[0-9]+.[0-9]?$")) { fm.put(p1.getKey(), Float.parseFloat(v)); } else { fm.put(p1.getKey(), v); } } Module m = new Module(config.getProperty("module"+n+".class"), fm); if (m.classname == null) break; mModules.put(name, m); System.out.println("Loaded module: "+name+" - "+m.classname); } } @Override public void handle(HttpExchange request) throws IOException { String path = request.getRequestURI().getPath().replaceAll("\\\\", "/").replaceAll("\\.\\./", ""); try { if (process(path, request)) return; } catch (Exception e) { e.printStackTrace(System.err); sendError(request, 500, "500 Internal Server Error"); } // Return 404 sendError(request, 404, "404 '"+path+"' Not Found"); } protected boolean process(String path, HttpExchange request) throws Exception { // Shutdown handling if (path.equals("/exit")) { sendError(request, 200, "200 OK"); System.exit(0); return true; } if (path.equals("/process")) { Map<String,String> params = getParameters(request.getRequestURI().getRawQuery()); String run = params.getOrDefault("run",""); String text = params.getOrDefault("text",""); if (text.isEmpty()) { sendError(request, 400, "400 Missing parameter 'text'"); return true; } if (run.isEmpty()) { sendError(request, 400, "400 Missing parameter 'run'"); return true; } Document doc = Factory.newDocument(text); for (String r : run.split(",")) { Module m = mModules.get(r); if (m == null) { sendError(request, 400, "400 Invalid module name: "+r); return true; } ProcessingResource res = (ProcessingResource) Factory.createResource( m.classname ); res.setParameterValues(m.config); res.setParameterValue("document", doc); res.execute(); Factory.deleteResource(res); } // By default doc.toXml() is this, but this takes twice as long initially // and increases gradually, so not usable now (8.4.1) -> falling back to previous behaviour // String xml = DocumentStaxUtils.toXml(doc); String xml = DocumentXmlUtils.toXml((TextualDocument)doc); sendXML(request, xml); doc.cleanup(); return true; } return false; } protected void sendError(HttpExchange request, int errorCode, String text) { Headers h = request.getResponseHeaders(); h.add("Content-Type", "text/plain;charset=utf-8"); try { request.sendResponseHeaders(errorCode, text.length()); try (OutputStream os = request.getResponseBody()) { os.write(text.getBytes()); } } catch (IOException e) { System.err.println("Connection closed before finished"); } } protected void sendXML(HttpExchange request, String text) { Headers h = request.getResponseHeaders(); h.add("Content-Type", "text/xml;charset=utf-8"); try { request.sendResponseHeaders(200, 0); try (OutputStream os = request.getResponseBody()) { os.write(text.getBytes("UTF-8")); } } catch (IOException e) { System.err.println("Connection closed before finished"); } } protected static Map<String,String> getParameters(String query) { Map<String, String> result = new HashMap<>(); if (query == null) return result; try { for (String param : query.split("&")) { String pair[] = param.split("="); result.put(URLDecoder.decode(pair[0],"UTF-8"), pair.length>1 ? URLDecoder.decode(pair[1],"UTF-8") : ""); } } catch (UnsupportedEncodingException e) { e.printStackTrace(System.err); } return result; } }
dlt-rilmta/hunlp-GATE
gate-server/src/gate/server/RequestHandler.java
Java
gpl-3.0
5,482
<div class="row"> <div class="col-md-8 text-left"> <h2 class="red font-roboto"><?php the_title(); ?></h2> <p><?php the_date('d \d\e F \d\e Y'); ?> <span class="divider-left"><?php $categories = get_the_category(get_the_ID()); $separator = ' | '; $output = ''; if($categories){ foreach($categories as $category) { $output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "Veja todas as notícias em %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator; } echo trim($output, $separator); } ?></span> </p> <?php the_content(); ?> </div> <?php get_sidebar(); ?> </div>
Gabriel-Pereira-MJ/intercambio-tema
content-single.php
PHP
gpl-3.0
838
/** * Copyright (c) 2000-present Liferay, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. */ package org.kisti.edison.bestsimulation.service; import com.liferay.portal.service.InvokableService; /** * @author EDISON * @generated */ public class SimulationServiceClp implements SimulationService { public SimulationServiceClp(InvokableService invokableService) { _invokableService = invokableService; _methodName0 = "getBeanIdentifier"; _methodParameterTypes0 = new String[] { }; _methodName1 = "setBeanIdentifier"; _methodParameterTypes1 = new String[] { "java.lang.String" }; } @Override public java.lang.String getBeanIdentifier() { Object returnObj = null; try { returnObj = _invokableService.invokeMethod(_methodName0, _methodParameterTypes0, new Object[] { }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } return (java.lang.String)ClpSerializer.translateOutput(returnObj); } @Override public void setBeanIdentifier(java.lang.String beanIdentifier) { try { _invokableService.invokeMethod(_methodName1, _methodParameterTypes1, new Object[] { ClpSerializer.translateInput(beanIdentifier) }); } catch (Throwable t) { t = ClpSerializer.translateThrowable(t); if (t instanceof RuntimeException) { throw (RuntimeException)t; } else { throw new RuntimeException(t.getClass().getName() + " is not a valid exception"); } } } @Override public java.lang.Object invokeMethod(java.lang.String name, java.lang.String[] parameterTypes, java.lang.Object[] arguments) throws java.lang.Throwable { throw new UnsupportedOperationException(); } private InvokableService _invokableService; private String _methodName0; private String[] _methodParameterTypes0; private String _methodName1; private String[] _methodParameterTypes1; }
queza85/edison
edison-portal-framework/edison-simulation-portlet/docroot/WEB-INF/service/org/kisti/edison/bestsimulation/service/SimulationServiceClp.java
Java
gpl-3.0
2,538
import theano import theano.tensor as T import numpy as np class RNN: """ Base class containing the RNN weights used by both the encoder and decoder """ def __init__(self, K, embedding_size, hidden_layer=8, use_context_vector=False, E=None): """ K : dimensionality of the word embeddings embedding_size : dimensionality of the word embeddings hidden_layer : size of hidden layer use_context_vector : whether or not to use a context vector E : a word embedding to use (optional) """ # state of the hidden layer self.h = theano.shared(np.zeros(hidden_layer), name='h') # input weights to the hidden layer self.W = theano.shared(np.random.uniform( size=(hidden_layer, embedding_size), low=-0.1, high=0.1), name='W') # recurrent weights for the hidden layer self.U = theano.shared(np.random.uniform( size=(hidden_layer, hidden_layer), low=-0.1, high=0.1), name='U') # the extra transformation between the encoder and decoder self.V = theano.shared(np.eye(hidden_layer)) # word embedding matrix if E is None: self.E = theano.shared(np.random.uniform( size=(embedding_size, K), low=-0.1, high=0.1), name='E') else: self.E = E self.params = [self.W, self.U, self.V, self.E] # additional weights for the context vector if use_context_vector: self.C = theano.shared(np.random.uniform( size=(hidden_layer, hidden_layer), low=-0.1, high=0.1), name='C') self.params.extend([self.C]) def compute(self, x_t, h_tm1, c=None): """ Input x_t : the current word (a K-dimensional vector) h_tm1 : the state of the hidden layer before the current step Output h_t : the state of the hidden layer after the current step """ if c is None: return T.tanh(self.W.dot(self.E.dot(x_t)) + self.U.dot(h_tm1)) else: return T.tanh(self.W.dot(self.E.dot(x_t)) + self.U.dot(h_tm1) + self.C.dot(c))
pepijnkokke/ull2
code/rnn.py
Python
gpl-3.0
2,367
#!/usr/bin/python # This file is part of Ansible # # Ansible 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. # # Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>. ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: elb_application_lb short_description: Manage an Application load balancer description: - Manage an AWS Application Elastic Load Balancer. See U(https://aws.amazon.com/blogs/aws/new-aws-application-load-balancer/) for details. version_added: "2.4" requirements: [ boto3 ] author: "Rob White (@wimnat)" options: access_logs_enabled: description: - "Whether or not to enable access logs. When true, I(access_logs_s3_bucket) must be set." required: false type: bool access_logs_s3_bucket: description: - The name of the S3 bucket for the access logs. This attribute is required if access logs in Amazon S3 are enabled. The bucket must exist in the same region as the load balancer and have a bucket policy that grants Elastic Load Balancing permission to write to the bucket. required: false access_logs_s3_prefix: description: - The prefix for the location in the S3 bucket. If you don't specify a prefix, the access logs are stored in the root of the bucket. required: false deletion_protection: description: - Indicates whether deletion protection for the ELB is enabled. required: false default: no type: bool http2: description: - Indicates whether to enable HTTP2 routing. required: false default: no type: bool version_added: 2.6 idle_timeout: description: - The number of seconds to wait before an idle connection is closed. required: false default: 60 listeners: description: - A list of dicts containing listeners to attach to the ELB. See examples for detail of the dict required. Note that listener keys are CamelCased. required: false name: description: - The name of the load balancer. This name must be unique within your AWS account, can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens, and must not begin or end with a hyphen. required: true purge_listeners: description: - If yes, existing listeners will be purged from the ELB to match exactly what is defined by I(listeners) parameter. If the I(listeners) parameter is not set then listeners will not be modified default: yes type: bool purge_tags: description: - If yes, existing tags will be purged from the resource to match exactly what is defined by I(tags) parameter. If the I(tags) parameter is not set then tags will not be modified. required: false default: yes type: bool subnets: description: - A list of the IDs of the subnets to attach to the load balancer. You can specify only one subnet per Availability Zone. You must specify subnets from at least two Availability Zones. Required if state=present. required: false security_groups: description: - A list of the names or IDs of the security groups to assign to the load balancer. Required if state=present. required: false default: [] scheme: description: - Internet-facing or internal load balancer. An ELB scheme can not be modified after creation. required: false default: internet-facing choices: [ 'internet-facing', 'internal' ] state: description: - Create or destroy the load balancer. required: true choices: [ 'present', 'absent' ] tags: description: - A dictionary of one or more tags to assign to the load balancer. required: false wait: description: - Wait for the load balancer to have a state of 'active' before completing. A status check is performed every 15 seconds until a successful state is reached. An error is returned after 40 failed checks. default: no type: bool version_added: 2.6 wait_timeout: description: - The time in seconds to use in conjunction with I(wait). version_added: 2.6 purge_rules: description: - When set to no, keep the existing load balancer rules in place. Will modify and add, but will not delete. default: yes type: bool version_added: 2.7 extends_documentation_fragment: - aws - ec2 notes: - Listeners are matched based on port. If a listener's port is changed then a new listener will be created. - Listener rules are matched based on priority. If a rule's priority is changed then a new rule will be created. ''' EXAMPLES = ''' # Note: These examples do not set authentication details, see the AWS Guide for details. # Create an ELB and attach a listener - elb_application_lb: name: myelb security_groups: - sg-12345678 - my-sec-group subnets: - subnet-012345678 - subnet-abcdef000 listeners: - Protocol: HTTP # Required. The protocol for connections from clients to the load balancer (HTTP or HTTPS) (case-sensitive). Port: 80 # Required. The port on which the load balancer is listening. # The security policy that defines which ciphers and protocols are supported. The default is the current predefined security policy. SslPolicy: ELBSecurityPolicy-2015-05 Certificates: # The ARN of the certificate (only one certficate ARN should be provided) - CertificateArn: arn:aws:iam::12345678987:server-certificate/test.domain.com DefaultActions: - Type: forward # Required. Only 'forward' is accepted at this time TargetGroupName: # Required. The name of the target group state: present # Create an ELB and attach a listener with logging enabled - elb_application_lb: access_logs_enabled: yes access_logs_s3_bucket: mybucket access_logs_s3_prefix: "/logs" name: myelb security_groups: - sg-12345678 - my-sec-group subnets: - subnet-012345678 - subnet-abcdef000 listeners: - Protocol: HTTP # Required. The protocol for connections from clients to the load balancer (HTTP or HTTPS) (case-sensitive). Port: 80 # Required. The port on which the load balancer is listening. # The security policy that defines which ciphers and protocols are supported. The default is the current predefined security policy. SslPolicy: ELBSecurityPolicy-2015-05 Certificates: # The ARN of the certificate (only one certficate ARN should be provided) - CertificateArn: arn:aws:iam::12345678987:server-certificate/test.domain.com DefaultActions: - Type: forward # Required. Only 'forward' is accepted at this time TargetGroupName: # Required. The name of the target group state: present # Create an ALB with listeners and rules - elb_application_lb: name: test-alb subnets: - subnet-12345678 - subnet-87654321 security_groups: - sg-12345678 scheme: internal listeners: - Protocol: HTTPS Port: 443 DefaultActions: - Type: forward TargetGroupName: test-target-group Certificates: - CertificateArn: arn:aws:iam::12345678987:server-certificate/test.domain.com SslPolicy: ELBSecurityPolicy-2015-05 Rules: - Conditions: - Field: path-pattern Values: - '/test' Priority: '1' Actions: - TargetGroupName: test-target-group Type: forward state: present # Remove an ELB - elb_application_lb: name: myelb state: absent ''' RETURN = ''' access_logs_s3_bucket: description: The name of the S3 bucket for the access logs. returned: when state is present type: string sample: mys3bucket access_logs_s3_enabled: description: Indicates whether access logs stored in Amazon S3 are enabled. returned: when state is present type: string sample: true access_logs_s3_prefix: description: The prefix for the location in the S3 bucket. returned: when state is present type: string sample: /my/logs availability_zones: description: The Availability Zones for the load balancer. returned: when state is present type: list sample: "[{'subnet_id': 'subnet-aabbccddff', 'zone_name': 'ap-southeast-2a'}]" canonical_hosted_zone_id: description: The ID of the Amazon Route 53 hosted zone associated with the load balancer. returned: when state is present type: string sample: ABCDEF12345678 created_time: description: The date and time the load balancer was created. returned: when state is present type: string sample: "2015-02-12T02:14:02+00:00" deletion_protection_enabled: description: Indicates whether deletion protection is enabled. returned: when state is present type: string sample: true dns_name: description: The public DNS name of the load balancer. returned: when state is present type: string sample: internal-my-elb-123456789.ap-southeast-2.elb.amazonaws.com idle_timeout_timeout_seconds: description: The idle timeout value, in seconds. returned: when state is present type: string sample: 60 ip_address_type: description: The type of IP addresses used by the subnets for the load balancer. returned: when state is present type: string sample: ipv4 listeners: description: Information about the listeners. returned: when state is present type: complex contains: listener_arn: description: The Amazon Resource Name (ARN) of the listener. returned: when state is present type: string sample: "" load_balancer_arn: description: The Amazon Resource Name (ARN) of the load balancer. returned: when state is present type: string sample: "" port: description: The port on which the load balancer is listening. returned: when state is present type: int sample: 80 protocol: description: The protocol for connections from clients to the load balancer. returned: when state is present type: string sample: HTTPS certificates: description: The SSL server certificate. returned: when state is present type: complex contains: certificate_arn: description: The Amazon Resource Name (ARN) of the certificate. returned: when state is present type: string sample: "" ssl_policy: description: The security policy that defines which ciphers and protocols are supported. returned: when state is present type: string sample: "" default_actions: description: The default actions for the listener. returned: when state is present type: string contains: type: description: The type of action. returned: when state is present type: string sample: "" target_group_arn: description: The Amazon Resource Name (ARN) of the target group. returned: when state is present type: string sample: "" load_balancer_arn: description: The Amazon Resource Name (ARN) of the load balancer. returned: when state is present type: string sample: arn:aws:elasticloadbalancing:ap-southeast-2:0123456789:loadbalancer/app/my-elb/001122334455 load_balancer_name: description: The name of the load balancer. returned: when state is present type: string sample: my-elb routing_http2_enabled: description: Indicates whether HTTP/2 is enabled. returned: when state is present type: string sample: true scheme: description: Internet-facing or internal load balancer. returned: when state is present type: string sample: internal security_groups: description: The IDs of the security groups for the load balancer. returned: when state is present type: list sample: ['sg-0011223344'] state: description: The state of the load balancer. returned: when state is present type: dict sample: "{'code': 'active'}" tags: description: The tags attached to the load balancer. returned: when state is present type: dict sample: "{ 'Tag': 'Example' }" type: description: The type of load balancer. returned: when state is present type: string sample: application vpc_id: description: The ID of the VPC for the load balancer. returned: when state is present type: string sample: vpc-0011223344 ''' from ansible.module_utils.aws.core import AnsibleAWSModule from ansible.module_utils.ec2 import boto3_conn, get_aws_connection_info, camel_dict_to_snake_dict, ec2_argument_spec, \ boto3_tag_list_to_ansible_dict, compare_aws_tags, HAS_BOTO3 from ansible.module_utils.aws.elbv2 import ApplicationLoadBalancer, ELBListeners, ELBListener, ELBListenerRules, ELBListenerRule from ansible.module_utils.aws.elb_utils import get_elb_listener_rules def create_or_update_elb(elb_obj): """Create ELB or modify main attributes. json_exit here""" if elb_obj.elb: # ELB exists so check subnets, security groups and tags match what has been passed # Subnets if not elb_obj.compare_subnets(): elb_obj.modify_subnets() # Security Groups if not elb_obj.compare_security_groups(): elb_obj.modify_security_groups() # Tags - only need to play with tags if tags parameter has been set to something if elb_obj.tags is not None: # Delete necessary tags tags_need_modify, tags_to_delete = compare_aws_tags(boto3_tag_list_to_ansible_dict(elb_obj.elb['tags']), boto3_tag_list_to_ansible_dict(elb_obj.tags), elb_obj.purge_tags) if tags_to_delete: elb_obj.delete_tags(tags_to_delete) # Add/update tags if tags_need_modify: elb_obj.modify_tags() else: # Create load balancer elb_obj.create_elb() # ELB attributes elb_obj.update_elb_attributes() elb_obj.modify_elb_attributes() # Listeners listeners_obj = ELBListeners(elb_obj.connection, elb_obj.module, elb_obj.elb['LoadBalancerArn']) listeners_to_add, listeners_to_modify, listeners_to_delete = listeners_obj.compare_listeners() # Delete listeners for listener_to_delete in listeners_to_delete: listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_delete, elb_obj.elb['LoadBalancerArn']) listener_obj.delete() listeners_obj.changed = True # Add listeners for listener_to_add in listeners_to_add: listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_add, elb_obj.elb['LoadBalancerArn']) listener_obj.add() listeners_obj.changed = True # Modify listeners for listener_to_modify in listeners_to_modify: listener_obj = ELBListener(elb_obj.connection, elb_obj.module, listener_to_modify, elb_obj.elb['LoadBalancerArn']) listener_obj.modify() listeners_obj.changed = True # If listeners changed, mark ELB as changed if listeners_obj.changed: elb_obj.changed = True # Rules of each listener for listener in listeners_obj.listeners: if 'Rules' in listener: rules_obj = ELBListenerRules(elb_obj.connection, elb_obj.module, elb_obj.elb['LoadBalancerArn'], listener['Rules'], listener['Port']) rules_to_add, rules_to_modify, rules_to_delete = rules_obj.compare_rules() # Delete rules if elb_obj.module.params['purge_rules']: for rule in rules_to_delete: rule_obj = ELBListenerRule(elb_obj.connection, elb_obj.module, {'RuleArn': rule}, rules_obj.listener_arn) rule_obj.delete() elb_obj.changed = True # Add rules for rule in rules_to_add: rule_obj = ELBListenerRule(elb_obj.connection, elb_obj.module, rule, rules_obj.listener_arn) rule_obj.create() elb_obj.changed = True # Modify rules for rule in rules_to_modify: rule_obj = ELBListenerRule(elb_obj.connection, elb_obj.module, rule, rules_obj.listener_arn) rule_obj.modify() elb_obj.changed = True # Get the ELB again elb_obj.update() # Get the ELB listeners again listeners_obj.update() # Update the ELB attributes elb_obj.update_elb_attributes() # Convert to snake_case and merge in everything we want to return to the user snaked_elb = camel_dict_to_snake_dict(elb_obj.elb) snaked_elb.update(camel_dict_to_snake_dict(elb_obj.elb_attributes)) snaked_elb['listeners'] = [] for listener in listeners_obj.current_listeners: # For each listener, get listener rules listener['rules'] = get_elb_listener_rules(elb_obj.connection, elb_obj.module, listener['ListenerArn']) snaked_elb['listeners'].append(camel_dict_to_snake_dict(listener)) # Change tags to ansible friendly dict snaked_elb['tags'] = boto3_tag_list_to_ansible_dict(snaked_elb['tags']) elb_obj.module.exit_json(changed=elb_obj.changed, **snaked_elb) def delete_elb(elb_obj): if elb_obj.elb: elb_obj.delete() elb_obj.module.exit_json(changed=elb_obj.changed) def main(): argument_spec = ec2_argument_spec() argument_spec.update( dict( access_logs_enabled=dict(type='bool'), access_logs_s3_bucket=dict(type='str'), access_logs_s3_prefix=dict(type='str'), deletion_protection=dict(type='bool'), http2=dict(type='bool'), idle_timeout=dict(type='int'), listeners=dict(type='list', elements='dict', options=dict( Protocol=dict(type='str', required=True), Port=dict(type='int', required=True), SslPolicy=dict(type='str'), Certificates=dict(type='list'), DefaultActions=dict(type='list', required=True), Rules=dict(type='list') ) ), name=dict(required=True, type='str'), purge_listeners=dict(default=True, type='bool'), purge_tags=dict(default=True, type='bool'), subnets=dict(type='list'), security_groups=dict(type='list'), scheme=dict(default='internet-facing', choices=['internet-facing', 'internal']), state=dict(choices=['present', 'absent'], type='str'), tags=dict(type='dict'), wait_timeout=dict(type='int'), wait=dict(default=False, type='bool'), purge_rules=dict(default=True, type='bool') ) ) module = AnsibleAWSModule(argument_spec=argument_spec, required_if=[ ('state', 'present', ['subnets', 'security_groups']) ], required_together=( ['access_logs_enabled', 'access_logs_s3_bucket', 'access_logs_s3_prefix'] ) ) # Quick check of listeners parameters listeners = module.params.get("listeners") if listeners is not None: for listener in listeners: for key in listener.keys(): if key == 'Protocol' and listener[key] == 'HTTPS': if listener.get('SslPolicy') is None: module.fail_json(msg="'SslPolicy' is a required listener dict key when Protocol = HTTPS") if listener.get('Certificates') is None: module.fail_json(msg="'Certificates' is a required listener dict key when Protocol = HTTPS") connection = module.client('elbv2') connection_ec2 = module.client('ec2') state = module.params.get("state") elb = ApplicationLoadBalancer(connection, connection_ec2, module) if state == 'present': create_or_update_elb(elb) else: delete_elb(elb) if __name__ == '__main__': main()
hryamzik/ansible
lib/ansible/modules/cloud/amazon/elb_application_lb.py
Python
gpl-3.0
21,506
/* * Dover Framework - OpenSource Development framework for SAP Business One * Copyright (C) 2014 Eduardo Piva * * 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/>. * * Contact me at <efpiva@gmail.com> * */ using System.Xml.Serialization; using Dover.Framework.Monad; namespace Dover.Framework.Model.SAP { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] [System.Xml.Serialization.XmlRootAttribute(ElementName = "BOM", Namespace = "", IsNullable = false)] public partial class FormattedSearchBOM : IBOM { private IBO[] boField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("BO", Type=typeof(FormattedSearchBOMBO))] public IBO[] BO { get { return this.boField; } set { this.boField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class FormattedSearchBOMBO: IBO { private BOMBOAdmInfo admInfoField; private BOMBOQueryParams queryParamsField; private FormattedSearchField[] formattedSearchesField; private FormattedSearchValidValues[] userValidValuesField; internal override string[] GetKey() { return new string[]{"Index"}; } internal override SAPbobsCOM.BoObjectTypes GetBOType() { return SAPbobsCOM.BoObjectTypes.oFormattedSearches; } internal override string GetName() { return Messages.FormattedSearch; } internal override System.Type GetBOClassType() { return typeof(SAPbobsCOM.IFormattedSearches); } internal override string GetFormattedKey() { return "[" + FormattedSearches .With(x => x[0]) .Return(x => x.FormID, string.Empty) + "].[" + FormattedSearches .With(x => x[0]) .Return(x => x.ItemID, string.Empty); } internal override string GetFormattedDescription() { return "[" + FormattedSearches .With(x => x[0]) .Return(x => x.FormID, string.Empty) + "].[" + FormattedSearches .With(x => x[0]) .Return(x => x.ItemID, string.Empty); } /// <remarks/> public BOMBOAdmInfo AdmInfo { get { return this.admInfoField; } set { this.admInfoField = value; } } /// <remarks/> public BOMBOQueryParams QueryParams { get { return this.queryParamsField; } set { this.queryParamsField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("row", IsNullable = false)] public FormattedSearchField[] FormattedSearches { get { return this.formattedSearchesField; } set { this.formattedSearchesField = value; } } /// <remarks/> [System.Xml.Serialization.XmlArrayItemAttribute("row", IsNullable = false)] public FormattedSearchValidValues[] UserValidValues { get { return this.userValidValuesField; } set { this.userValidValuesField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class FormattedSearchField { private string formIDField; private string itemIDField; private string columnIDField; private string actionField; private long queryIDField; private bool queryIDFieldSpecified; private string refreshField; private string fieldIDField; private string forceRefreshField; private string byFieldField; /// <remarks/> public string FormID { get { return this.formIDField; } set { this.formIDField = value; } } /// <remarks/> public string ItemID { get { return this.itemIDField; } set { this.itemIDField = value; } } /// <remarks/> public string ColumnID { get { return this.columnIDField; } set { this.columnIDField = value; } } /// <remarks/> public string Action { get { return this.actionField; } set { this.actionField = value; } } /// <remarks/> public long QueryID { get { return this.queryIDField; } set { this.queryIDField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool QueryIDSpecified { get { return this.queryIDFieldSpecified; } set { this.queryIDFieldSpecified = value; } } /// <remarks/> public string Refresh { get { return this.refreshField; } set { this.refreshField = value; } } /// <remarks/> public string FieldID { get { return this.fieldIDField; } set { this.fieldIDField = value; } } /// <remarks/> public string ForceRefresh { get { return this.forceRefreshField; } set { this.forceRefreshField = value; } } /// <remarks/> public string ByField { get { return this.byFieldField; } set { this.byFieldField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.42")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)] public partial class FormattedSearchValidValues { private string fieldValueField; /// <remarks/> public string FieldValue { get { return this.fieldValueField; } set { this.fieldValueField = value; } } } }
efpiva/dover
Model/SAP/FormattedSearch.cs
C#
gpl-3.0
8,935
/******************************************************************************* * file : windowsmessagesink.cpp * created : 05.08.2018 * author : Slyshyk Oleksiy (alexslyshyk@gmail.com) *******************************************************************************/ #include "windowsmessagesink.hpp" namespace ldlog { void WindowsMessageSink::write(const LogMessage& message) { static std::string msg; msg = format(message); SendMessageA(hwnd_, msg_, wparam_, (LPARAM)msg.c_str()); } std::shared_ptr<Sink> newWindowsMessageSink(HWND hwnd, UINT msg, WPARAM wparam) { std::shared_ptr<Sink> res; res.reset(new WindowsMessageSink(hwnd, msg, wparam)); return res; } } // namespace ldlog
LDmicro/LDmicro
ldmicro/ldlog/src/sinks/windowsmessagesink.cpp
C++
gpl-3.0
744
require_relative 'boot' require 'rails/all' # Require the gems listed in Gemfile, including any gems # you've limited to :test, :development, or :production. Bundler.require(*Rails.groups) module FirstProject class Application < Rails::Application # Settings in config/environments/* take precedence over those specified here. # Application configuration should go into files in config/initializers # -- all .rb files in that directory are automatically loaded. end end
lilianglaoding/codeprimer
RubyLab/RailsProjects/firstProject/config/application.rb
Ruby
gpl-3.0
489
#-*-:coding:utf-8-*- from blindtex.latex2ast import converter #from latex2ast import ast from blindtex.interpreter import dictionary to_read = {'simple_superscript' : 'super %s ', 'comp_superscript' : 'super %s endSuper ', 'simple_subscript' : 'sub %s ', 'comp_subscript' : 'sub %s endSub ', 'simple_frac' : '%s over %s ', 'comp_frac' : 'fraction %s over %s endFraction ', 'simple_sqrt' : 'squareRootOf %s ', 'comp_sqrt' : 'squareRootOf %s endRoot ', 'simple_root' : 'root %s of %s ', 'comp_root' : 'root %s of %s endRoot ', 'simple_choose' : 'from %s choose %s ', 'comp_choose' : 'from %s choose %s endChoose ', 'simple_modulo' : 'modulo %s ', 'comp_modulo' : 'modulo %s endModulo ', 'simple_text' : 'text %s ', 'comp_text' : 'text %s endText ', 'from_to' : 'from %s to %s of ', 'over' : 'over %s of ', 'to' : 'to %s of ', 'end' : 'end%s ', 'linebreak' : 'linebreak', 'array' : 'array %s endArray ', 'array_element' : 'element',} '''dict: A dictionary with the strings to read some mathematical structures, like: Fractions, roots, large operators, etc.''' #Function to convert a math_object in a string. def lineal_read(Node): '''Function to convert a mathObject into a string. Args: Node(mathObject): A mathObject created by parser. Returns: String: A string with the lineal read of the mathObject.''' #Dictionary with the possible nodes with children and the functions each case call. with_children = {'block' : lineal_read_block, 'fraction' : lineal_read_fraction, 'root' : lineal_read_root, 'choose' : lineal_read_choose_binom, 'binom' : lineal_read_choose_binom, 'pmod' : lineal_read_pmod, 'text' : lineal_read_text, 'label' : lineal_read_label, 'array' : lineal_read_array} str_lineal_read = '' #The attributes will be readed in this order: # accent -> content-> children* -> style -> superscript -> subscript #TODO: Add the option for the user to change this. #TODO: Add the option to ommit style or whatever. #TODO: Add the translation by dictionary. #I'll go for the easiest and less elegant way: A chain of ifs. if(Node.content in with_children): #If the node has children. #Identify the type of children the node has and act accordingly str_lineal_read = str_lineal_read + with_children[Node.content](Node.children) else: str_lineal_read = str_lineal_read + lineal_read_content(Node) if(Node.style != None):#Add the style of the node. str_lineal_read = lineal_read_style(Node, str_lineal_read) if(Node.accent != None): #The accent str_lineal_read = lineal_read_accent(Node, str_lineal_read) #This part is to read the limits of large Operators like integral or sum. if(Node.kind == 'LargeOperators'): if(Node.subscript != None and Node.superscript != None): str_lineal_read = str_lineal_read + to_read['from_to']%(lineal_read(Node.subscript[0]), lineal_read(Node.superscript[0])) elif(Node.subscript != None and Node.superscript == None): str_lineal_read = str_lineal_read + to_read['over']%lineal_read(Node.subscript[0]) elif(Node.subscript == None and Node.superscript != None): str_lineal_read = str_lineal_read + to_read['to']%lineal_read(Node.superscript[0]) else:#If the math_object is not a LargeOperator but has scripts. if(Node.superscript != None): str_lineal_read = str_lineal_read + lineal_read_superscript(Node.superscript[0]) if(Node.subscript != None): str_lineal_read = str_lineal_read + lineal_read_subscript(Node.subscript[0]) return str_lineal_read #EndOfFunction #Function to read the content of the math_object def lineal_read_content(node): '''A function to returns as a string the content of a mathObject. Args: node(mathObject) Returns: string: A string with the content of the mathObject. ''' if(node.kind != None): return '%s '%node.content elif(node.content == r'\\'): return to_read['linebreak'] else: return '%s '%node.content #EOF #To read the accent def lineal_read_accent(node, str_read): ''' Args: node(mathObject) str_read(string): String with the reading so far. Returns: string: The string with the proper accent of the mathObject in the linear read. ''' if(is_simple(node)): return str_read + '%s '%node.accent else: return '%s '%node.accent + str_read + to_read['end']%node.accent #EOF #To read the style. def lineal_read_style(node, str_read): ''' Args: node(mathObject) str_read(string): String with the reading so far. Returns: string: The string with the proper stylr of the mathObject in the linear read. ''' if(is_simple(node)): return str_read + '%s '%node.style else: return '%s '%node.style + str_read + to_read['end']%node.style #EOF def lineal_read_superscript(node_script): ''' Args: node_script(mathObject): the mathObject that is a super script of another mathObject. Returns: string: The reading of this object that changes wether it is simple or not. ''' #Here if the script is a block it will be considered as a compound script. #This to avoid the following ambiguity: a^{b_c} and a^b_c #That, otherwise, would be read the same. if(is_simple(node_script) and node_script.content != 'block'): return to_read['simple_superscript']%lineal_read(node_script) else: return to_read['comp_superscript']%lineal_read(node_script) #EndOfFunction def lineal_read_subscript(node_script): ''' Args: node_script(mathObject): the mathObject that is a sub script of another mathObject. Returns: string: The reading of this object that changes wether it is simple or not. ''' #See lineal_read_superscript. if(is_simple(node_script) and node_script.content != 'block'): return to_read['simple_subscript']%lineal_read(node_script) else: return to_read['comp_subscript']%lineal_read(node_script) #EndOfFunction def is_simple(Node): '''A node is simple if it is just a character e.g. "a", "2", "\alpha" or if it is a block with just one character in it e.g. "{a}", "{2}", "{\alpha}" Args: node(mathObject) Returns: bool: True if the node is simple. ''' if(Node.get_children() == None): return True elif(Node.content == 'block' and len(Node.get_children()) == 1 ): return(is_simple(Node.get_children()[0]))#This is for cases like {{a+b}} (not simple) or {{{\alpha}}}(simple). else: return False #EndOfFunction def lineal_read_block(list_children): '''A Block has from one to several children, thus functions reads those. Args: list_childre(list of mathObject): The list of a block children, they al are mathObject. Returns: string:The linear read of such children. ''' # The child of a block is a formula, a formula is a list of nodes. str_result = '' for node in list_children: str_result = str_result + lineal_read(node) return str_result #EndOfFunction def lineal_read_fraction(list_children): '''A fraction is simple if both of its parts are simple, otherwise the function will tell where it begins and where it ends. Args: list_children(list of mathObjects): A list of lenght 2, the first is the numeratos the second the denominator. Returns: string: The reading of the fraction depending wether it is simple or not.''' #The list received here must be of lenght 2. The numerator and denominator. if(is_simple(list_children[0]) and is_simple(list_children[1])): return to_read['simple_frac']%(lineal_read(list_children[0]), lineal_read(list_children[1])) else: return to_read['comp_frac']%(lineal_read(list_children[0]), lineal_read(list_children[1])) #EndOfFunction def lineal_read_root(list_children): '''Here we have four cases: Square root simple or not, other root simple or not. In the not simple roots it tells where it begins and where it ends. Args: list_children(list of mathObjects): The arguments of a root, could be one if the root is square, of two if the root has other index, in this case the first mathObject is the index and the second the object of the root. Returns: string: The reading of the root depending wether it is simple or not. ''' #There are two cases here: Either the root has an index \sqrt[i]{k} or not. if(len(list_children) == 1):#It has not index if(is_simple(list_children[0])): return to_read['simple_sqrt']%(lineal_read(list_children[0])) else: return to_read['comp_sqrt']%(lineal_read(list_children[0])) else: if(is_simple(list_children[1])): return to_read['simple_root']%(lineal_read(list_children[0]), lineal_read(list_children[1])) else: return to_read['comp_root']%(lineal_read(list_children[0]), lineal_read(list_children[1])) #EndOfFunction def lineal_read_choose_binom(list_children): '''A binomial coefficient is simple if both of its parts are simple, otherwise the function will tell where it begins and where it ends. Args: list_childre(list of mathObjects): There are two arguments of a binomial coeffiecient. Returns: string: The reading of the binomial coefficient. ''' if(is_simple(list_children[0]) and is_simple(list_children[1])): return to_read['simple_choose']%(lineal_read(list_children[0]), lineal_read(list_children[1])) else: return to_read['comp_choose']%(lineal_read(list_children[0]), lineal_read(list_children[1])) #EndOfFunction def lineal_read_pmod(list_children): '''If the argument of the module is not simple the function will tell where the module begins and where it ends. Args: list_children(list of mathObjects): A single mathObject. Returns: string: The reading of the module depending wether is simple or not. ''' if(is_simple(list_children[0])): return to_read['simple_modulo']%(lineal_read(list_children[0])) else: return to_read['comp_modulo']%(lineal_read(list_children[0])) #EndOfFunction def lineal_read_text(list_children): ''' Args: list_children(list of mathObjects): The mathObject with the internal text. Returns: string: The reading of the text. It indicates where it begins and where it ends. ''' return 'text %s endtext'%(list_children)#Here the child is a string #EndOfFunction def lineal_read_label(list_children): '''As labels are important of LaTeX self reference every label is left the same. Args: list_children(list of mathObjects): The mathObject with the label. Returns: string: The same label. ''' return r'\%s'%(list_children)#The labels must be inaltered. #EndOFFunction def lineal_read_formula(list_formula): '''The parser of blindtex takes a formula in LaTeX and divide it into the different mathObjects present in the formula, this list of mathObjects is passed to this function. Args: list_formula(list of mathObjects): The list of all the mathObjects that shape the whole formula. Returns: string: The total lineal read of the formula, shaped by the lineal reads of every mathObject. ''' str_result = '' for node in list_formula: str_result = str_result + lineal_read(node) return str_result #EndOfFunction def lineal_read_array(list_array): ''' Args: list_array(list of mathObjects): The elemenst of the array and the delimitators of such array (strings like '&' and '\\') Returns: string: the lineal read of the array, distinguishing each element by a title that indicates its position (first its row and then its column) e.g. "element 1_2 a", indicates that the element is in the first row and second column. Also the result indicates where the array beings and where it ends. ''' nrow = 1 ncol = 1 str_result = '%s%d_%d '%(to_read['array_element'],nrow, ncol) array = list_array for element in array: str_element_reading = lineal_read(element) if(str_element_reading == '& '): ncol += 1 str_result += '%s%d_%d '%(to_read['array_element'],nrow, ncol) continue elif(str_element_reading == to_read['linebreak']): nrow += 1 ncol = 1 str_result += '%s%d_%d '%(to_read['array_element'],nrow, ncol) continue str_result += '%s '%str_element_reading return to_read['array']%str_result #EndOfFunction def lineal_read_formula_list(list_formula): str_result = '' for node in list_formula: str_result = str_result + lineal_read(node) return str_result.split() #EndOfFunction if __name__ == "__main__": while True: try: try: s = raw_input() except NameError: # Python3 s = input('spi> ') cv_s = converter.latex2list(s) print(lineal_read_formula(cv_s)) except EOFError: break
blindtex/blindtex
blindtex/interpreter/reader.py
Python
gpl-3.0
14,005
<?php /* * LibreNMS Network Management and Monitoring System * Copyright (C) 2006-2011, Observium Developers - http://www.observium.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * See COPYING for more details. */ use Illuminate\Support\Str; use LibreNMS\Config; use LibreNMS\Exceptions\HostExistsException; use LibreNMS\Exceptions\InvalidIpException; use LibreNMS\OS; use LibreNMS\Util\IP; use LibreNMS\Util\IPv6; use LibreNMS\Device\YamlDiscovery; function discover_new_device($hostname, $device = '', $method = '', $interface = '') { d_echo("discovering $hostname\n"); if (IP::isValid($hostname)) { $ip = $hostname; if (!Config::get('discovery_by_ip', false)) { d_echo('Discovery by IP disabled, skipping ' . $hostname); log_event("$method discovery of " . $hostname . " failed - Discovery by IP disabled", $device['device_id'], 'discovery', 4); return false; } } elseif (is_valid_hostname($hostname)) { if ($mydomain = Config::get('mydomain')) { $full_host = rtrim($hostname, '.') . '.' . $mydomain; if (isDomainResolves($full_host)) { $hostname = $full_host; } } $ip = gethostbyname($hostname); if ($ip == $hostname) { d_echo("name lookup of $hostname failed\n"); log_event("$method discovery of " . $hostname . " failed - Check name lookup", $device['device_id'], 'discovery', 5); return false; } } else { d_echo("Discovery failed: '$hostname' is not a valid ip or dns name\n"); return false; } d_echo("ip lookup result: $ip\n"); $hostname = rtrim($hostname, '.'); // remove trailing dot $ip = IP::parse($ip, true); if ($ip->inNetworks(Config::get('autodiscovery.nets-exclude'))) { d_echo("$ip in an excluded network - skipping\n"); return false; } if (!$ip->inNetworks(Config::get('nets'))) { d_echo("$ip not in a matched network - skipping\n"); return false; } try { $remote_device_id = addHost($hostname, '', '161', 'udp', Config::get('distributed_poller_group')); $remote_device = device_by_id_cache($remote_device_id, 1); echo '+[' . $remote_device['hostname'] . '(' . $remote_device['device_id'] . ')]'; discover_device($remote_device); device_by_id_cache($remote_device_id, 1); if ($remote_device_id && is_array($device) && !empty($method)) { $extra_log = ''; $int = cleanPort($interface); if (is_array($int)) { $extra_log = ' (port ' . $int['label'] . ') '; } log_event('Device ' . $remote_device['hostname'] . " ($ip) $extra_log autodiscovered through $method on " . $device['hostname'], $remote_device_id, 'discovery', 1); } else { log_event("$method discovery of " . $remote_device['hostname'] . " ($ip) failed - Check ping and SNMP access", $device['device_id'], 'discovery', 5); } return $remote_device_id; } catch (HostExistsException $e) { // already have this device } catch (Exception $e) { log_event("$method discovery of " . $hostname . " ($ip) failed - " . $e->getMessage(), $device['device_id'], 'discovery', 5); } return false; } //end discover_new_device() /** * @param $device */ function load_discovery(&$device) { $yaml_discovery = Config::get('install_dir') . '/includes/definitions/discovery/' . $device['os'] . '.yaml'; if (file_exists($yaml_discovery)) { $device['dynamic_discovery'] = Symfony\Component\Yaml\Yaml::parse( file_get_contents($yaml_discovery) ); } else { unset($device['dynamic_discovery']); } } /** * @param array $device The device to poll * @param bool $force_module Ignore device module overrides * @return bool if the device was discovered or skipped */ function discover_device(&$device, $force_module = false) { if ($device['snmp_disable'] == '1') { return false; } global $valid; $valid = array(); // Reset $valid array $attribs = DeviceCache::getPrimary()->getAttribs(); $device['attribs'] = $attribs; $device_start = microtime(true); // Start counting device poll time echo $device['hostname'] . ' ' . $device['device_id'] . ' ' . $device['os'] . ' '; $response = device_is_up($device, true); if ($response['status'] !== '1') { return false; } if ($device['os'] == 'generic') { // verify if OS has changed from generic $device['os'] = getHostOS($device); if ($device['os'] != 'generic') { echo "\nDevice os was updated to " . $device['os'] . '!'; dbUpdate(array('os' => $device['os']), 'devices', '`device_id` = ?', array($device['device_id'])); } } load_os($device); load_discovery($device); register_mibs($device, Config::getOsSetting($device['os'], 'register_mibs', array()), 'includes/discovery/os/' . $device['os'] . '.inc.php'); $os = OS::make($device); echo "\n"; $discovery_devices = Config::get('discovery_modules', array()); $discovery_devices = array('core' => true) + $discovery_devices; foreach ($discovery_devices as $module => $module_status) { $os_module_status = Config::getOsSetting($device['os'], "discovery_modules.$module"); d_echo("Modules status: Global" . (isset($module_status) ? ($module_status ? '+ ' : '- ') : ' ')); d_echo("OS" . (isset($os_module_status) ? ($os_module_status ? '+ ' : '- ') : ' ')); d_echo("Device" . (isset($attribs['discover_' . $module]) ? ($attribs['discover_' . $module] ? '+ ' : '- ') : ' ')); if ($force_module === true || $attribs['discover_' . $module] || ($os_module_status && !isset($attribs['discover_' . $module])) || ($module_status && !isset($os_module_status) && !isset($attribs['discover_' . $module])) ) { $module_start = microtime(true); $start_memory = memory_get_usage(); echo "\n#### Load disco module $module ####\n"; try { include "includes/discovery/$module.inc.php"; } catch (Exception $e) { // isolate module exceptions so they don't disrupt the polling process echo $e->getTraceAsString() .PHP_EOL; c_echo("%rError in $module module.%n " . $e->getMessage() . PHP_EOL); logfile("Error in $module module. " . $e->getMessage() . PHP_EOL . $e->getTraceAsString() . PHP_EOL); } $module_time = microtime(true) - $module_start; $module_time = substr($module_time, 0, 5); $module_mem = (memory_get_usage() - $start_memory); printf("\n>> Runtime for discovery module '%s': %.4f seconds with %s bytes\n", $module, $module_time, $module_mem); printChangedStats(); echo "#### Unload disco module $module ####\n\n"; } elseif (isset($attribs['discover_' . $module]) && $attribs['discover_' . $module] == '0') { echo "Module [ $module ] disabled on host.\n\n"; } elseif (isset($os_module_status) && $os_module_status == '0') { echo "Module [ $module ] disabled on os.\n\n"; } else { echo "Module [ $module ] disabled globally.\n\n"; } } if (is_mib_poller_enabled($device)) { $devicemib = array($device['sysObjectID'] => 'all'); register_mibs($device, $devicemib, "includes/discovery/functions.inc.php"); } $device_time = round(microtime(true) - $device_start, 3); dbUpdate(array('last_discovered' => array('NOW()'), 'last_discovered_timetaken' => $device_time), 'devices', '`device_id` = ?', array($device['device_id'])); echo "Discovered in $device_time seconds\n"; echo PHP_EOL; return true; } //end discover_device() // Discover sensors function discover_sensor(&$valid, $class, $device, $oid, $index, $type, $descr, $divisor = 1, $multiplier = 1, $low_limit = null, $low_warn_limit = null, $warn_limit = null, $high_limit = null, $current = null, $poller_type = 'snmp', $entPhysicalIndex = null, $entPhysicalIndex_measured = null, $user_func = null, $group = null) { $guess_limits = Config::get('sensors.guess_limits', true); $low_limit = set_null($low_limit); $low_warn_limit = set_null($low_warn_limit); $warn_limit = set_null($warn_limit); $high_limit = set_null($high_limit); if (!is_numeric($divisor)) { $divisor = 1; } if (can_skip_sensor($device, $type, $descr)) { return false; } d_echo("Discover sensor: $oid, $index, $type, $descr, $poller_type, $divisor, $multiplier, $entPhysicalIndex, $current, (limits: LL: $low_limit, LW: $low_warn_limit, W: $warn_limit, H: $high_limit)\n"); if (isset($warn_limit, $low_warn_limit) && $low_warn_limit > $warn_limit) { // Fix high/low thresholds (i.e. on negative numbers) list($warn_limit, $low_warn_limit) = [$low_warn_limit, $warn_limit]; } if (dbFetchCell('SELECT COUNT(sensor_id) FROM `sensors` WHERE `poller_type`= ? AND `sensor_class` = ? AND `device_id` = ? AND sensor_type = ? AND `sensor_index` = ?', array($poller_type, $class, $device['device_id'], $type, (string)$index)) == '0') { if ($guess_limits && is_null($high_limit)) { $high_limit = sensor_limit($class, $current); } if ($guess_limits && is_null($low_limit)) { $low_limit = sensor_low_limit($class, $current); } if (!is_null($high_limit) && $low_limit > $high_limit) { // Fix high/low thresholds (i.e. on negative numbers) list($high_limit, $low_limit) = array($low_limit, $high_limit); } $insert = array( 'poller_type' => $poller_type, 'sensor_class' => $class, 'device_id' => $device['device_id'], 'sensor_oid' => $oid, 'sensor_index' => $index, 'sensor_type' => $type, 'sensor_descr' => $descr, 'sensor_divisor' => $divisor, 'sensor_multiplier' => $multiplier, 'sensor_limit' => $high_limit, 'sensor_limit_warn' => $warn_limit, 'sensor_limit_low' => $low_limit, 'sensor_limit_low_warn' => $low_warn_limit, 'sensor_current' => $current, 'entPhysicalIndex' => $entPhysicalIndex, 'entPhysicalIndex_measured' => $entPhysicalIndex_measured, 'user_func' => $user_func, 'group' => $group, ); foreach ($insert as $key => $val_check) { if (!isset($val_check)) { unset($insert[$key]); } } $inserted = dbInsert($insert, 'sensors'); d_echo("( $inserted inserted )\n"); echo '+'; log_event('Sensor Added: ' . $class . ' ' . $type . ' ' . $index . ' ' . $descr, $device, 'sensor', 3, $inserted); } else { $sensor_entry = dbFetchRow('SELECT * FROM `sensors` WHERE `sensor_class` = ? AND `device_id` = ? AND `sensor_type` = ? AND `sensor_index` = ?', array($class, $device['device_id'], $type, (string)$index)); if (!isset($high_limit)) { if ($guess_limits && !$sensor_entry['sensor_limit']) { // Calculate a reasonable limit $high_limit = sensor_limit($class, $current); } else { // Use existing limit $high_limit = $sensor_entry['sensor_limit']; } } if (!isset($low_limit)) { if ($guess_limits && !$sensor_entry['sensor_limit_low']) { // Calculate a reasonable limit $low_limit = sensor_low_limit($class, $current); } else { // Use existing limit $low_limit = $sensor_entry['sensor_limit_low']; } } // Fix high/low thresholds (i.e. on negative numbers) if ($low_limit > $high_limit) { list($high_limit, $low_limit) = array($low_limit, $high_limit); } if ($high_limit != $sensor_entry['sensor_limit'] && $sensor_entry['sensor_custom'] == 'No') { $update = array('sensor_limit' => ($high_limit == null ? array('NULL') : $high_limit)); $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); d_echo("( $updated updated )\n"); echo 'H'; log_event('Sensor High Limit Updated: ' . $class . ' ' . $type . ' ' . $index . ' ' . $descr . ' (' . $high_limit . ')', $device, 'sensor', 3, $sensor_id); } if ($sensor_entry['sensor_limit_low'] != $low_limit && $sensor_entry['sensor_custom'] == 'No') { $update = array('sensor_limit_low' => ($low_limit == null ? array('NULL') : $low_limit)); $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); d_echo("( $updated updated )\n"); echo 'L'; log_event('Sensor Low Limit Updated: ' . $class . ' ' . $type . ' ' . $index . ' ' . $descr . ' (' . $low_limit . ')', $device, 'sensor', 3, $sensor_id); } if ($warn_limit != $sensor_entry['sensor_limit_warn'] && $sensor_entry['sensor_custom'] == 'No') { $update = array('sensor_limit_warn' => ($warn_limit == null ? array('NULL') : $warn_limit)); $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); d_echo("( $updated updated )\n"); echo 'WH'; log_event('Sensor Warn High Limit Updated: ' . $class . ' ' . $type . ' ' . $index . ' ' . $descr . ' (' . $warn_limit . ')', $device, 'sensor', 3, $sensor_id); } if ($sensor_entry['sensor_limit_low_warn'] != $low_warn_limit && $sensor_entry['sensor_custom'] == 'No') { $update = array('sensor_limit_low_warn' => ($low_warn_limit == null ? array('NULL') : $low_warn_limit)); $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); d_echo("( $updated updated )\n"); echo 'WL'; log_event('Sensor Warn Low Limit Updated: ' . $class . ' ' . $type . ' ' . $index . ' ' . $descr . ' (' . $low_warn_limit . ')', $device, 'sensor', 3, $sensor_id); } if ($oid == $sensor_entry['sensor_oid'] && $descr == $sensor_entry['sensor_descr'] && $multiplier == $sensor_entry['sensor_multiplier'] && $divisor == $sensor_entry['sensor_divisor'] && $entPhysicalIndex_measured == $sensor_entry['entPhysicalIndex_measured'] && $entPhysicalIndex == $sensor_entry['entPhysicalIndex'] && $user_func == $sensor_entry['user_func'] && $group == $sensor_entry['group'] ) { echo '.'; } else { $update = array( 'sensor_oid' => $oid, 'sensor_descr' => $descr, 'sensor_multiplier' => $multiplier, 'sensor_divisor' => $divisor, 'entPhysicalIndex' => $entPhysicalIndex, 'entPhysicalIndex_measured' => $entPhysicalIndex_measured, 'user_func' => $user_func, 'group' => $group, ); $updated = dbUpdate($update, 'sensors', '`sensor_id` = ?', array($sensor_entry['sensor_id'])); echo 'U'; log_event('Sensor Updated: ' . $class . ' ' . $type . ' ' . $index . ' ' . $descr, $device, 'sensor', 3, $sensor_id); d_echo("( $updated updated )\n"); } }//end if $valid[$class][$type][$index] = 1; } //end discover_sensor() function sensor_low_limit($class, $current) { // matching an empty case executes code until a break is reached switch ($class) { case 'temperature': $limit = $current - 10; break; case 'voltage': $limit = $current * 0.85; break; case 'humidity': $limit = 30; break; case 'fanspeed': $limit = $current * 0.80; break; case 'power_factor': $limit = -1; break; case 'signal': $limit = -80; break; case 'airflow': case 'snr': case 'frequency': case 'pressure': case 'cooling': $limit = $current * 0.95; break; default: return null; }//end switch return round($limit, 11); } //end sensor_low_limit() function sensor_limit($class, $current) { // matching an empty case executes code until a break is reached switch ($class) { case 'temperature': $limit = $current + 20; break; case 'voltage': $limit = $current * 1.15; break; case 'humidity': $limit = 70; break; case 'fanspeed': $limit = $current * 1.80; break; case 'power_factor': $limit = 1; break; case 'signal': $limit = -30; break; case 'load': $limit = 80; break; case 'airflow': case 'snr': case 'frequency': case 'pressure': case 'cooling': $limit = $current * 1.05; break; default: return null; }//end switch return round($limit, 11); } //end sensor_limit() function check_valid_sensors($device, $class, $valid, $poller_type = 'snmp') { $entries = dbFetchRows('SELECT * FROM sensors AS S, devices AS D WHERE S.sensor_class=? AND S.device_id = D.device_id AND D.device_id = ? AND S.poller_type = ?', array($class, $device['device_id'], $poller_type)); if (count($entries)) { foreach ($entries as $entry) { $index = $entry['sensor_index']; $type = $entry['sensor_type']; $class = $entry['sensor_class']; d_echo($index . ' -> ' . $type . "\n"); if (!$valid[$class][$type][$index]) { echo '-'; if ($class == 'state') { dbDelete('sensors_to_state_indexes', '`sensor_id` = ?', array($entry['sensor_id'])); } dbDelete('sensors', '`sensor_id` = ?', array($entry['sensor_id'])); log_event('Sensor Deleted: ' . $entry['sensor_class'] . ' ' . $entry['sensor_type'] . ' ' . $entry['sensor_index'] . ' ' . $entry['sensor_descr'], $device, 'sensor', 3, $sensor_id); } unset($oid); unset($type); } } } //end check_valid_sensors() function discover_juniAtmVp(&$valid, $device, $port_id, $vp_id, $vp_descr) { d_echo("Discover Juniper ATM VP: $port_id, $vp_id, $vp_descr\n"); if (dbFetchCell('SELECT COUNT(*) FROM `juniAtmVp` WHERE `port_id` = ? AND `vp_id` = ?', array($port_id, $vp_id)) == '0') { $inserted = dbInsert(array('port_id' => $port_id, 'vp_id' => $vp_id, 'vp_descr' => $vp_descr), 'juniAtmVp'); d_echo("( $inserted inserted )\n"); // FIXME vv no $device! log_event('Juniper ATM VP Added: port ' . $port_id . ' vp ' . $vp_id . ' descr' . $vp_descr, $device, 'juniAtmVp', 3, $inserted); } else { echo '.'; } $valid[$port_id][$vp_id] = 1; } //end discover_juniAtmVp() function discover_link($local_port_id, $protocol, $remote_port_id, $remote_hostname, $remote_port, $remote_platform, $remote_version, $local_device_id, $remote_device_id) { global $link_exists; d_echo("Discover link: $local_port_id, $protocol, $remote_port_id, $remote_hostname, $remote_port, $remote_platform, $remote_version, $remote_device_id\n"); if (dbFetchCell( 'SELECT COUNT(*) FROM `links` WHERE `remote_hostname` = ? AND `local_port_id` = ? AND `protocol` = ? AND `remote_port` = ?', array( $remote_hostname, $local_port_id, $protocol, $remote_port, ) ) == '0') { $insert_data = array( 'local_port_id' => $local_port_id, 'local_device_id' => $local_device_id, 'protocol' => $protocol, 'remote_hostname' => $remote_hostname, 'remote_device_id' => (int)$remote_device_id, 'remote_port' => $remote_port, 'remote_platform' => $remote_platform, 'remote_version' => $remote_version, ); if (!empty($remote_port_id)) { $insert_data['remote_port_id'] = (int)$remote_port_id; } $inserted = dbInsert($insert_data, 'links'); echo '+'; d_echo("( $inserted inserted )"); } else { $sql = 'SELECT `id`,`local_device_id`,`remote_platform`,`remote_version`,`remote_device_id`,`remote_port_id` FROM `links`'; $sql .= ' WHERE `remote_hostname` = ? AND `local_port_id` = ? AND `protocol` = ? AND `remote_port` = ?'; $data = dbFetchRow($sql, array($remote_hostname, $local_port_id, $protocol, $remote_port)); $update_data = array( 'local_device_id' => $local_device_id, 'remote_platform' => $remote_platform, 'remote_version' => $remote_version, 'remote_device_id' => (int)$remote_device_id, 'remote_port_id' => (int)$remote_port_id ); $id = $data['id']; unset($data['id']); if ($data == $update_data) { echo '.'; } else { $updated = dbUpdate($update_data, 'links', '`id` = ?', array($id)); echo 'U'; d_echo("( $updated updated )"); }//end if }//end if $link_exists[$local_port_id][$remote_hostname][$remote_port] = 1; } //end discover_link() function discover_storage(&$valid, $device, $index, $type, $mib, $descr, $size, $units, $used = null) { if (ignore_storage($device['os'], $descr)) { return; } d_echo("Discover Storage: $index, $type, $mib, $descr, $size, $units, $used\n"); if ($descr && $size > '0') { $storage = dbFetchRow('SELECT * FROM `storage` WHERE `storage_index` = ? AND `device_id` = ? AND `storage_mib` = ?', array($index, $device['device_id'], $mib)); if ($storage === false || !count($storage)) { if (Config::getOsSetting($device['os'], 'storage_perc_warn')) { $perc_warn = Config::getOsSetting($device['os'], 'storage_perc_warn'); } else { $perc_warn = Config::get('storage_perc_warn', 60); } $insert = dbInsert( array( 'device_id' => $device['device_id'], 'storage_descr' => $descr, 'storage_index' => $index, 'storage_mib' => $mib, 'storage_type' => $type, 'storage_units' => $units, 'storage_size' => $size, 'storage_used' => $used, 'storage_perc_warn' => $perc_warn, ), 'storage' ); echo '+'; } else { $updated = dbUpdate(array('storage_descr' => $descr, 'storage_type' => $type, 'storage_units' => $units, 'storage_size' => $size), 'storage', '`device_id` = ? AND `storage_index` = ? AND `storage_mib` = ?', array($device['device_id'], $index, $mib)); if ($updated) { echo 'U'; } else { echo '.'; } }//end if $valid[$mib][$index] = 1; }//end if } //end discover_storage() function discover_processor(&$valid, $device, $oid, $index, $type, $descr, $precision = '1', $current = null, $entPhysicalIndex = null, $hrDeviceIndex = null) { d_echo("Discover Processor: $oid, $index, $type, $descr, $precision, $current, $entPhysicalIndex, $hrDeviceIndex\n"); if ($descr) { $descr = trim(str_replace('"', '', $descr)); if (dbFetchCell('SELECT COUNT(processor_id) FROM `processors` WHERE `processor_index` = ? AND `device_id` = ? AND `processor_type` = ?', array($index, $device['device_id'], $type)) == '0') { $insert_data = array( 'device_id' => $device['device_id'], 'processor_descr' => $descr, 'processor_index' => $index, 'processor_oid' => $oid, 'processor_usage' => $current, 'processor_type' => $type, 'processor_precision' => $precision, ); $insert_data['hrDeviceIndex'] = (int)$hrDeviceIndex; $insert_data['entPhysicalIndex'] = (int)$entPhysicalIndex; $inserted = dbInsert($insert_data, 'processors'); echo '+'; log_event('Processor added: type ' . $type . ' index ' . $index . ' descr ' . $descr, $device, 'processor', 3, $inserted); } else { echo '.'; $update_data = array( 'processor_descr' => $descr, 'processor_oid' => $oid, 'processor_usage' => $current, 'processor_precision' => $precision, ); dbUpdate($update_data, 'processors', '`device_id`=? AND `processor_index`=? AND `processor_type`=?', array($device['device_id'], $index, $type)); }//end if $valid[$type][$index] = 1; }//end if } //end discover_processor() function discover_mempool(&$valid, $device, $index, $type, $descr, $precision = '1', $entPhysicalIndex = null, $hrDeviceIndex = null, $perc_warn = '90') { $descr = substr($descr, 0, 64); d_echo("Discover Mempool: $index, $type, $descr, $precision, $entPhysicalIndex, $hrDeviceIndex, $perc_warn\n"); // FIXME implement the mempool_perc, mempool_used, etc. if ($descr) { if (dbFetchCell('SELECT COUNT(mempool_id) FROM `mempools` WHERE `mempool_index` = ? AND `device_id` = ? AND `mempool_type` = ?', array($index, $device['device_id'], $type)) == '0') { $insert_data = array( 'device_id' => $device['device_id'], 'mempool_descr' => $descr, 'mempool_index' => $index, 'mempool_type' => $type, 'mempool_precision' => $precision, 'mempool_perc' => 0, 'mempool_used' => 0, 'mempool_free' => 0, 'mempool_total' => 0, 'mempool_perc_warn' => $perc_warn, ); if (is_numeric($entPhysicalIndex)) { $insert_data['entPhysicalIndex'] = $entPhysicalIndex; } if (is_numeric($hrDeviceIndex)) { $insert_data['hrDeviceIndex'] = $hrDeviceIndex; } $inserted = dbInsert($insert_data, 'mempools'); echo '+'; log_event('Memory pool added: type ' . $type . ' index ' . $index . ' descr ' . $descr, $device, 'mempool', 3, $inserted); } else { echo '.'; $update_data = array( 'mempool_descr' => $descr, ); if (is_numeric($entPhysicalIndex)) { $update_data['entPhysicalIndex'] = $entPhysicalIndex; } if (is_numeric($hrDeviceIndex)) { $update_data['hrDeviceIndex'] = $hrDeviceIndex; } dbUpdate($update_data, 'mempools', 'device_id=? AND mempool_index=? AND mempool_type=?', array($device['device_id'], $index, $type)); }//end if $valid[$type][$index] = 1; }//end if } //end discover_mempool() function discover_toner(&$valid, $device, $oid, $index, $type, $descr, $capacity_oid = null, $capacity = null, $current = null) { d_echo("Discover Toner: $oid, $index, $type, $descr, $capacity_oid, $capacity, $current\n"); if (dbFetchCell('SELECT COUNT(toner_id) FROM `toner` WHERE device_id = ? AND toner_type = ? AND `toner_index` = ? AND `toner_oid` =?', array($device['device_id'], $type, $index, $oid)) == '0') { $inserted = dbInsert(array('device_id' => $device['device_id'], 'toner_oid' => $oid, 'toner_capacity_oid' => $capacity_oid, 'toner_index' => $index, 'toner_type' => $type, 'toner_descr' => $descr, 'toner_capacity' => $capacity, 'toner_current' => $current), 'toner'); echo '+'; log_event('Toner added: type ' . $type . ' index ' . $index . ' descr ' . $descr, $device, 'toner', 3, $inserted); } else { $toner_entry = dbFetchRow('SELECT * FROM `toner` WHERE `device_id` = ? AND `toner_type` = ? AND `toner_index` =?', array($device['device_id'], $type, $index)); if ($oid == $toner_entry['toner_oid'] && $descr == $toner_entry['toner_descr'] && $capacity == $toner_entry['toner_capacity'] && $capacity_oid == $toner_entry['toner_capacity_oid']) { echo '.'; } else { dbUpdate(array('toner_descr' => $descr, 'toner_oid' => $oid, 'toner_capacity_oid' => $capacity_oid, 'toner_capacity' => $capacity), 'toner', 'device_id=? AND toner_type=? AND `toner_index`=?', array($device['device_id'], $type, $index)); echo 'U'; } } $valid[$type][$oid] = 1; } //end discover_toner() function discover_entity_physical(&$valid, $device, $entPhysicalIndex, $entPhysicalDescr, $entPhysicalClass, $entPhysicalName, $entPhysicalModelName, $entPhysicalSerialNum, $entPhysicalContainedIn, $entPhysicalMfgName, $entPhysicalParentRelPos, $entPhysicalVendorType, $entPhysicalHardwareRev, $entPhysicalFirmwareRev, $entPhysicalSoftwareRev, $entPhysicalIsFRU, $entPhysicalAlias, $entPhysicalAssetID, $ifIndex) { d_echo("Discover Inventory Item: $entPhysicalIndex, $entPhysicalDescr, $entPhysicalClass, $entPhysicalName, $entPhysicalModelName, $entPhysicalSerialNum, $entPhysicalContainedIn, $entPhysicalMfgName, $entPhysicalParentRelPos, $entPhysicalVendorType, $entPhysicalHardwareRev, $entPhysicalFirmwareRev, $entPhysicalSoftwareRev, $entPhysicalIsFRU, $entPhysicalAlias, $entPhysicalAssetID, $ifIndex\n"); if ($entPhysicalDescr || $entPhysicalName) { if (dbFetchCell('SELECT COUNT(entPhysical_id) FROM `entPhysical` WHERE `device_id` = ? AND `entPhysicalIndex` = ?', array($device['device_id'], $entPhysicalIndex)) == '0') { $insert_data = array( 'device_id' => $device['device_id'], 'entPhysicalIndex' => $entPhysicalIndex, 'entPhysicalDescr' => $entPhysicalDescr, 'entPhysicalClass' => $entPhysicalClass, 'entPhysicalName' => $entPhysicalName, 'entPhysicalModelName' => $entPhysicalModelName, 'entPhysicalSerialNum' => $entPhysicalSerialNum, 'entPhysicalContainedIn' => $entPhysicalContainedIn, 'entPhysicalMfgName' => $entPhysicalMfgName, 'entPhysicalParentRelPos' => $entPhysicalParentRelPos, 'entPhysicalVendorType' => $entPhysicalVendorType, 'entPhysicalHardwareRev' => $entPhysicalHardwareRev, 'entPhysicalFirmwareRev' => $entPhysicalFirmwareRev, 'entPhysicalSoftwareRev' => $entPhysicalSoftwareRev, 'entPhysicalIsFRU' => $entPhysicalIsFRU, 'entPhysicalAlias' => $entPhysicalAlias, 'entPhysicalAssetID' => $entPhysicalAssetID, ); if (!empty($ifIndex)) { $insert_data['ifIndex'] = $ifIndex; } $inserted = dbInsert($insert_data, 'entPhysical'); echo '+'; log_event('Inventory Item added: index ' . $entPhysicalIndex . ' descr ' . $entPhysicalDescr, $device, 'entity-physical', 3, $inserted); } else { echo '.'; $update_data = array( 'entPhysicalIndex' => $entPhysicalIndex, 'entPhysicalDescr' => $entPhysicalDescr, 'entPhysicalClass' => $entPhysicalClass, 'entPhysicalName' => $entPhysicalName, 'entPhysicalModelName' => $entPhysicalModelName, 'entPhysicalSerialNum' => $entPhysicalSerialNum, 'entPhysicalContainedIn' => $entPhysicalContainedIn, 'entPhysicalMfgName' => $entPhysicalMfgName, 'entPhysicalParentRelPos' => $entPhysicalParentRelPos, 'entPhysicalVendorType' => $entPhysicalVendorType, 'entPhysicalHardwareRev' => $entPhysicalHardwareRev, 'entPhysicalFirmwareRev' => $entPhysicalFirmwareRev, 'entPhysicalSoftwareRev' => $entPhysicalSoftwareRev, 'entPhysicalIsFRU' => $entPhysicalIsFRU, 'entPhysicalAlias' => $entPhysicalAlias, 'entPhysicalAssetID' => $entPhysicalAssetID, 'ifIndex' => $ifIndex, ); dbUpdate($update_data, 'entPhysical', '`device_id`=? AND `entPhysicalIndex`=?', array($device['device_id'], $entPhysicalIndex)); }//end if $valid[$entPhysicalIndex] = 1; }//end if } //end discover_entity_physical() function discover_process_ipv6(&$valid, $ifIndex, $ipv6_address, $ipv6_prefixlen, $ipv6_origin, $context_name = '') { global $device; if (!IPv6::isValid($ipv6_address, true)) { // ignore link-locals (coming from IPV6-MIB) return; } $ipv6 = new IPv6($ipv6_address); $ipv6_network = $ipv6->getNetwork($ipv6_prefixlen); $ipv6_compressed = $ipv6->compressed(); if (dbFetchCell('SELECT COUNT(*) FROM `ports` WHERE device_id = ? AND `ifIndex` = ?', array($device['device_id'], $ifIndex)) != '0' && $ipv6_prefixlen > '0' && $ipv6_prefixlen < '129' && $ipv6_compressed != '::1') { $port_id = dbFetchCell('SELECT port_id FROM `ports` WHERE device_id = ? AND ifIndex = ?', array($device['device_id'], $ifIndex)); if (is_numeric($port_id)) { if (dbFetchCell('SELECT COUNT(*) FROM `ipv6_networks` WHERE `ipv6_network` = ?', array($ipv6_network)) < '1') { dbInsert(array('ipv6_network' => $ipv6_network, 'context_name' => $context_name), 'ipv6_networks'); echo 'N'; } else { //Update Context dbUpdate(array('context_name' => $device['context_name']), 'ipv6_networks', '`ipv6_network` = ?', array($ipv6_network)); echo 'n'; } if ($context_name == null) { $ipv6_network_id = dbFetchCell('SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ? AND `context_name` IS NULL', array($ipv6_network)); } else { $ipv6_network_id = dbFetchCell('SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ? AND `context_name` = ?', array($ipv6_network, $context_name)); } if (dbFetchCell('SELECT COUNT(*) FROM `ipv6_addresses` WHERE `ipv6_address` = ? AND `ipv6_prefixlen` = ? AND `port_id` = ?', array($ipv6_address, $ipv6_prefixlen, $port_id)) == '0') { dbInsert(array( 'ipv6_address' => $ipv6_address, 'ipv6_compressed' => $ipv6_compressed, 'ipv6_prefixlen' => $ipv6_prefixlen, 'ipv6_origin' => $ipv6_origin, 'ipv6_network_id' => $ipv6_network_id, 'port_id' => $port_id, 'context_name' => $context_name ), 'ipv6_addresses'); echo '+'; } else if (dbFetchCell('SELECT COUNT(*) FROM `ipv6_addresses` WHERE `ipv6_address` = ? AND `ipv6_prefixlen` = ? AND `port_id` = ? AND `ipv6_network_id` = ""', [$ipv6_address, $ipv6_prefixlen, $port_id]) == '1') { // Update IPv6 network ID if not set if ($context_name == null) { $ipv6_network_id = dbFetchCell('SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ? AND `context_name` IS NULL', [$ipv6_network]); } else { $ipv6_network_id = dbFetchCell('SELECT `ipv6_network_id` FROM `ipv6_networks` WHERE `ipv6_network` = ? AND `context_name` = ?', [$ipv6_network, $context_name]); } dbUpdate(['ipv6_network_id' => $ipv6_network_id], 'ipv6_addresses', '`ipv6_address` = ? AND `ipv6_prefixlen` = ? AND `port_id` = ?', [$ipv6_address, $ipv6_prefixlen, $port_id]); echo 'u'; } else { //Update Context dbUpdate(array('context_name' => $device['context_name']), 'ipv6_addresses', '`ipv6_address` = ? AND `ipv6_prefixlen` = ? AND `port_id` = ?', array($ipv6_address, $ipv6_prefixlen, $port_id)); echo '.'; } $full_address = "$ipv6_address/$ipv6_prefixlen"; $valid_address = $full_address . '-' . $port_id; $valid['ipv6'][$valid_address] = 1; } }//end if }//end discover_process_ipv6() /* * Check entity sensors to be excluded * * @param string value to check * @param array device * * @return bool true if sensor is valid * false if sensor is invalid */ function check_entity_sensor($string, $device) { $fringe = array_merge(Config::get('bad_entity_sensor_regex', array()), Config::getOsSetting($device['os'], 'bad_entity_sensor_regex', array())); foreach ($fringe as $bad) { if (preg_match($bad . "i", $string)) { d_echo("Ignored entity sensor: $bad : $string"); return false; } } return true; } /** * Get the device divisor, account for device specific quirks * The default divisor is 10 * * @param array $device device array * @param string $os_version firmware version poweralert quirks * @param string $sensor_type the type of this sensor * @param string $oid the OID of this sensor * @return int */ function get_device_divisor($device, $os_version, $sensor_type, $oid) { if ($device['os'] == 'poweralert') { if ($sensor_type == 'current' || $sensor_type == 'frequency') { if (version_compare($os_version, '12.06.0068', '>=')) { return 10; } elseif (version_compare($os_version, '12.04.0055', '=')) { return 10; } elseif (version_compare($os_version, '12.04.0056', '>=')) { return 1; } } elseif ($sensor_type == 'load') { if (version_compare($os_version, '12.06.0064', '=')) { return 10; } else { return 1; } } } elseif ($device['os'] == 'huaweiups') { if ($sensor_type == 'frequency') { if (Str::startsWith($device['hardware'], "UPS2000")) { return 10; } return 100; } } elseif ($device['os'] == 'hpe-rtups') { if ($sensor_type == 'voltage' && !Str::startsWith($oid, '.1.3.6.1.2.1.33.1.2.5.') && !Str::startsWith($oid, '.1.3.6.1.2.1.33.1.3.3.1.3')) { return 1; } } elseif ($device['os'] == 'apc-mgeups') { if ($sensor_type == 'voltage') { return 10; } } // UPS-MIB Defaults if ($sensor_type == 'load') { return 1; } if ($sensor_type == 'voltage' && !Str::startsWith($oid, '.1.3.6.1.2.1.33.1.2.5.')) { return 1; } if ($sensor_type == 'runtime') { if (Str::startsWith($oid, '.1.3.6.1.2.1.33.1.2.2.')) { return 60; } if (Str::startsWith($oid, '.1.3.6.1.2.1.33.1.2.3.')) { if ($device['os'] == 'routeros') { return 60; } else { return 1; } } } return 10; } /** * @param int $raw_capacity The value return from snmp * @return int normalized capacity value */ function get_toner_capacity($raw_capacity) { // unknown or unrestricted capacity, assume 100 if (empty($raw_capacity) || $raw_capacity < 0) { return 100; } return $raw_capacity; } /** * Should we ignore this storage device based on teh description? (usually the mount path or drive) * * @param string $os The OS of the device * @param string $descr The description of the storage * @return boolean */ function ignore_storage($os, $descr) { foreach (Config::getOsSetting($os, 'ignore_mount') as $im) { if ($im == $descr) { d_echo("ignored $descr (matched: $im)\n"); return true; } } foreach (Config::getOsSetting($os, 'ignore_mount_string') as $ims) { if (Str::contains($descr, $ims)) { d_echo("ignored $descr (matched: $ims)\n"); return true; } } foreach (Config::getOsSetting($os, 'ignore_mount_regexp') as $imr) { if (preg_match($imr, $descr)) { d_echo("ignored $descr (matched: $imr)\n"); return true; } } return false; } /** * @param $valid * @param $device * @param $sensor_type * @param $pre_cache */ function discovery_process(&$valid, $device, $sensor_type, $pre_cache) { if ($device['dynamic_discovery']['modules']['sensors'][$sensor_type] && ! can_skip_sensor($device, $sensor_type, '')) { $sensor_options = array(); if (isset($device['dynamic_discovery']['modules']['sensors'][$sensor_type]['options'])) { $sensor_options = $device['dynamic_discovery']['modules']['sensors'][$sensor_type]['options']; } d_echo("Dynamic Discovery ($sensor_type): "); d_echo($device['dynamic_discovery']['modules']['sensors'][$sensor_type]); foreach ($device['dynamic_discovery']['modules']['sensors'][$sensor_type]['data'] as $data) { $tmp_name = $data['oid']; $raw_data = (array)$pre_cache[$tmp_name]; d_echo("Data $tmp_name: "); d_echo($raw_data); foreach ($raw_data as $index => $snmp_data) { $user_function = null; if (isset($data['user_func'])) { $user_function = $data['user_func']; } // get the value for this sensor, check 'value' and 'oid', if state string, translate to a number $data_name = isset($data['value']) ? $data['value'] : $data['oid']; // fallback to oid if value is not set $snmp_value = $snmp_data[$data_name]; if (!is_numeric($snmp_value)) { if ($sensor_type === 'temperature') { // For temp sensors, try and detect fahrenheit values if (Str::endsWith($snmp_value, array('f', 'F'))) { $user_function = 'fahrenheit_to_celsius'; } } preg_match('/-?\d*\.?\d+/', $snmp_value, $temp_response); if (!empty($temp_response[0])) { $snmp_value = $temp_response[0]; } } if (is_numeric($snmp_value)) { $value = $snmp_value; } elseif ($sensor_type === 'state') { // translate string states to values (poller does this as well) $states = array_column($data['states'], 'value', 'descr'); $value = isset($states[$snmp_value]) ? $states[$snmp_value] : false; } else { $value = false; } d_echo("Final sensor value: $value\n"); $skippedFromYaml = YamlDiscovery::canSkipItem($value, $index, $data, $sensor_options, $pre_cache); if ($skippedFromYaml === false && is_numeric($value)) { $oid = str_replace('{{ $index }}', $index, $data['num_oid']); // if index is a string, we need to convert it to OID // strlen($index) as first number, and each letter converted to a number, separated by dots $oid = str_replace('{{ $index_string }}', strlen($index) . '.' . implode(".", unpack("c*", $index)), $oid); // process the description $descr = YamlDiscovery::replaceValues('descr', $index, null, $data, $pre_cache); // process the group $group = YamlDiscovery::replaceValues('group', $index, null, $data, $pre_cache) ?: null; $divisor = $data['divisor'] ?: ($sensor_options['divisor'] ?: 1); $multiplier = $data['multiplier'] ?: ($sensor_options['multiplier'] ?: 1); $limits = ['low_limit', 'low_warn_limit', 'warn_limit', 'high_limit']; foreach ($limits as $limit) { if (is_numeric($data[$limit])) { $$limit = $data[$limit]; } else { $$limit = YamlDiscovery::getValueFromData($limit, $index, $data, $pre_cache, 'null'); if (is_numeric($$limit)) { $$limit = ($$limit / $divisor) * $multiplier; } } } echo "Cur $value, Low: $low_limit, Low Warn: $low_warn_limit, Warn: $warn_limit, High: $high_limit".PHP_EOL; $entPhysicalIndex = YamlDiscovery::replaceValues('entPhysicalIndex', $index, null, $data, $pre_cache) ?: null; $entPhysicalIndex_measured = isset($data['entPhysicalIndex_measured']) ? $data['entPhysicalIndex_measured'] : null; $sensor_name = $device['os']; if ($sensor_type === 'state') { $sensor_name = $data['state_name'] ?: $data['oid']; create_state_index($sensor_name, $data['states']); } else { // We default to 1 for both divisors / multipliers so it should be safe to do the calculation using both. $value = ($value / $divisor) * $multiplier; } //user_func must be applied after divisor/multiplier if (isset($user_function) && is_callable($user_function)) { $value = $user_function($value); } $uindex = str_replace('{{ $index }}', $index, isset($data['index']) ? $data['index'] : $index); discover_sensor($valid['sensor'], $sensor_type, $device, $oid, $uindex, $sensor_name, $descr, $divisor, $multiplier, $low_limit, $low_warn_limit, $warn_limit, $high_limit, $value, 'snmp', $entPhysicalIndex, $entPhysicalIndex_measured, $user_function, $group); if ($sensor_type === 'state') { create_sensor_to_state_index($device, $sensor_name, $uindex); } } } } } } /** * @param $types * @param $device * @param array $pre_cache */ function sensors($types, $device, $valid, $pre_cache = array()) { foreach ((array)$types as $sensor_class) { echo ucfirst($sensor_class) . ': '; $dir = Config::get('install_dir') . '/includes/discovery/sensors/' . $sensor_class .'/'; if (is_file($dir . $device['os_group'] . '.inc.php')) { include $dir . $device['os_group'] . '.inc.php'; } if (is_file($dir . $device['os'] . '.inc.php')) { include $dir . $device['os'] . '.inc.php'; } if (Config::getOsSetting($device['os'], 'rfc1628_compat', false)) { if (is_file($dir . '/rfc1628.inc.php')) { include $dir . '/rfc1628.inc.php'; } } discovery_process($valid, $device, $sensor_class, $pre_cache); d_echo($valid['sensor'][$sensor_class]); check_valid_sensors($device, $sensor_class, $valid['sensor']); echo "\n"; } } function build_bgp_peers($device, $data, $peer2) { d_echo("Peers : $data\n"); $remove = array( 'ARISTA-BGP4V2-MIB::aristaBgp4V2PeerRemoteAs.1.', 'CISCO-BGP4-MIB::cbgpPeer2RemoteAs.', 'BGP4-MIB::bgpPeerRemoteAs.', 'HUAWEI-BGP-VPN-MIB::hwBgpPeerRemoteAs.', '.1.3.6.1.4.1.2636.5.1.1.2.1.1.1.13.', ); $peers = trim(str_replace($remove, '', $data)); $peerlist = array(); $ver = ''; foreach (explode("\n", $peers) as $peer) { $local_ip = null; if ($peer2 === true) { list($ver, $peer) = explode('.', $peer, 2); } list($peer_ip, $peer_as) = explode(' ', $peer); if ($device['os'] === 'junos') { $ver = ''; $octets = count(explode(".", $peer_ip)); if ($octets > 11) { // ipv6 $peer_ip = (string)IP::parse(snmp2ipv6($peer_ip), true); } else { // ipv4 $peer_ip = implode('.', array_slice(explode('.', $peer_ip), -4)); } } else { if (strstr($peer_ip, ':')) { $peer_ip_snmp = preg_replace('/:/', ' ', $peer_ip); $peer_ip = preg_replace('/(\S+\s+\S+)\s/', '$1:', $peer_ip_snmp); $peer_ip = str_replace('"', '', str_replace(' ', '', $peer_ip)); } } if ($peer && $peer_ip != '0.0.0.0') { d_echo("Found peer $peer_ip (AS$peer_as)\n"); $peerlist[] = array( 'ip' => $peer_ip, 'as' => $peer_as, 'localip' => $local_ip ?: '0.0.0.0', 'ver' => $ver, ); } } return $peerlist; } function build_cbgp_peers($device, $peer, $af_data, $peer2) { d_echo('afi data :: '); d_echo($af_data); $af_list = array(); foreach ($af_data as $k => $v) { if ($peer2 === true) { list(,$k) = explode('.', $k, 2); } d_echo("AFISAFI = $k\n"); $afisafi_tmp = explode('.', $k); if ($device['os_group'] === 'vrp') { $vpninst_id = array_shift($afisafi_tmp); $afi = array_shift($afisafi_tmp); $safi = array_shift($afisafi_tmp); $peertype = array_shift($afisafi_tmp); $bgp_ip = implode('.', $afisafi_tmp); } else { $safi = array_pop($afisafi_tmp); $afi = array_pop($afisafi_tmp); $bgp_ip = str_replace(".$afi.$safi", '', $k); if ($device['os_group'] === 'arista') { $bgp_ip = str_replace("$afi.", '', $bgp_ip); } } $bgp_ip = preg_replace('/:/', ' ', $bgp_ip); $bgp_ip = preg_replace('/(\S+\s+\S+)\s/', '$1:', $bgp_ip); $bgp_ip = str_replace('"', '', str_replace(' ', '', $bgp_ip)); if ($afi && $safi && $bgp_ip == $peer['ip']) { $af_list[$bgp_ip][$afi][$safi] = 1; add_cbgp_peer($device, $peer, $afi, $safi); } } return $af_list; } function add_bgp_peer($device, $peer) { if (dbFetchCell('SELECT COUNT(*) from `bgpPeers` WHERE device_id = ? AND bgpPeerIdentifier = ?', array($device['device_id'], $peer['ip'])) < '1') { $bgpPeers = array( 'device_id' => $device['device_id'], 'bgpPeerIdentifier' => $peer['ip'], 'bgpPeerRemoteAs' => $peer['as'], 'context_name' => $device['context_name'], 'astext' => $peer['astext'], 'bgpPeerState' => 'idle', 'bgpPeerAdminStatus' => 'stop', 'bgpLocalAddr' => $peer['localip'] ?: '0.0.0.0', 'bgpPeerRemoteAddr' => '0.0.0.0', 'bgpPeerInUpdates' => 0, 'bgpPeerOutUpdates' => 0, 'bgpPeerInTotalMessages' => 0, 'bgpPeerOutTotalMessages' => 0, 'bgpPeerFsmEstablishedTime' => 0, 'bgpPeerInUpdateElapsedTime' => 0, ); dbInsert($bgpPeers, 'bgpPeers'); if (Config::get('autodiscovery.bgp')) { $name = gethostbyaddr($peer['ip']); discover_new_device($name, $device, 'BGP'); } echo '+'; } else { dbUpdate(array('bgpPeerRemoteAs' => $peer['as'], 'astext' => $peer['astext']), 'bgpPeers', 'device_id=? AND bgpPeerIdentifier=?', array($device['device_id'], $peer['ip'])); echo '.'; } } function add_cbgp_peer($device, $peer, $afi, $safi) { if (dbFetchCell('SELECT COUNT(*) from `bgpPeers_cbgp` WHERE device_id = ? AND bgpPeerIdentifier = ? AND afi=? AND safi=?', array($device['device_id'], $peer['ip'], $afi, $safi)) == 0) { $cbgp = array( 'device_id' => $device['device_id'], 'bgpPeerIdentifier' => $peer['ip'], 'afi' => $afi, 'safi' => $safi, 'context_name' => $device['context_name'], 'AcceptedPrefixes' => 0, 'DeniedPrefixes' => 0, 'PrefixAdminLimit' => 0, 'PrefixThreshold' => 0, 'PrefixClearThreshold' => 0, 'AdvertisedPrefixes' => 0, 'SuppressedPrefixes' => 0, 'WithdrawnPrefixes' => 0, 'AcceptedPrefixes_delta' => 0, 'AcceptedPrefixes_prev' => 0, 'DeniedPrefixes_delta' => 0, 'DeniedPrefixes_prev' => 0, 'AdvertisedPrefixes_delta' => 0, 'AdvertisedPrefixes_prev' => 0, 'SuppressedPrefixes_delta' => 0, 'SuppressedPrefixes_prev' => 0, 'WithdrawnPrefixes_delta' => 0, 'WithdrawnPrefixes_prev' => 0, ); dbInsert($cbgp, 'bgpPeers_cbgp'); } } /** * check if we should skip this sensor from discovery * @param $device * @param string $sensor_type * @param string $sensor_descr * @return bool */ function can_skip_sensor($device, $sensor_type = '', $sensor_descr = '') { if (! empty($sensor_type) && Config::getCombined($device['os'], "disabled_sensors.$sensor_type", false)) { return true; } foreach (Config::getCombined($device['os'], "disabled_sensors_regex", []) as $skipRegex) { if (! empty($sensor_descr) && preg_match($skipRegex, $sensor_descr)) { return true; } } return false; } /** * check if we should skip this device from discovery * @param string $sysName * @param string $sysDescr * @param string $platform * @return bool */ function can_skip_discovery($sysName, $sysDescr = '', $platform = '') { if ($sysName) { foreach ((array)Config::get('autodiscovery.xdp_exclude.sysname_regexp') as $needle) { if (preg_match($needle .'i', $sysName)) { d_echo("$sysName - regexp '$needle' matches '$sysName' - skipping device discovery \n"); return true; } } } if ($sysDescr) { foreach ((array)Config::get('autodiscovery.xdp_exclude.sysdesc_regexp') as $needle) { if (preg_match($needle .'i', $sysDescr)) { d_echo("$sysName - regexp '$needle' matches '$sysDescr' - skipping device discovery \n"); return true; } } } if ($platform) { foreach ((array)Config::get('autodiscovery.cdp_exclude.platform_regexp') as $needle) { if (preg_match($needle .'i', $platform)) { d_echo("$sysName - regexp '$needle' matches '$platform' - skipping device discovery \n"); return true; } } } return false; } /** * Try to find a device by sysName, hostname, ip, or mac_address * If a device cannot be found, returns 0 * * @param string $name sysName or hostname * @param string $ip May be an IP or hex string * @param string $mac_address * @return int the device_id or 0 */ function find_device_id($name = '', $ip = '', $mac_address = '') { $where = array(); $params = array(); if ($name && is_valid_hostname($name)) { $where[] = '`sysName`=?'; $params[] = $name; $where[] = '`hostname`=?'; $params[] = $name; if ($mydomain = Config::get('mydomain')) { $where[] = '`hostname`=?'; $params[] = "$name.$mydomain"; } } if ($ip) { $where[] = '`hostname`=?'; $params[] = $ip; try { $params[] = IP::fromHexString($ip)->packed(); $where[] = '`ip`=?'; } catch (InvalidIpException $e) { // } } if (!empty($where)) { $sql = 'SELECT `device_id` FROM `devices` WHERE ' . implode(' OR ', $where); if ($device_id = dbFetchCell($sql, $params)) { return (int)$device_id; } } if ($mac_address && $mac_address != '000000000000') { if ($device_id = dbFetchCell('SELECT `device_id` FROM `ports` WHERE `ifPhysAddress`=?', array($mac_address))) { return (int)$device_id; } } return 0; } /** * Try to find a port by ifDescr, ifName, ifAlias, or MAC * * @param string $description matched against ifDescr, ifName, and ifAlias * @param string $identifier matched against ifDescr, ifName, and ifAlias * @param int $device_id restrict search to ports on a specific device * @param string $mac_address check against ifPhysAddress (should be in lowercase hexadecimal) * @return int */ function find_port_id($description, $identifier = '', $device_id = 0, $mac_address = null) { if (!($device_id || $mac_address)) { return 0; } $statements = array(); $params = array(); if ($device_id) { if ($description) { // order is important here, the standard says this is ifDescr, which some mfg confuse with ifName $statements[] = "SELECT `port_id` FROM `ports` WHERE `device_id`=? AND (`ifDescr`=? OR `ifName`=?)"; $params[] = $device_id; $params[] = $description; $params[] = $description; // we check ifAlias last because this is a user editable field, but some bad LLDP implementations use it $statements[] = "SELECT `port_id` FROM `ports` WHERE `device_id`=? AND `ifAlias`=?"; $params[] = $device_id; $params[] = $description; } if ($identifier) { if (is_numeric($identifier)) { $statements[] = 'SELECT `port_id` FROM `ports` WHERE `device_id`=? AND (`ifIndex`=? OR `ifAlias`=?)'; } else { $statements[] = 'SELECT `port_id` FROM `ports` WHERE `device_id`=? AND (`ifDescr`=? OR `ifName`=?)'; } $params[] = $device_id; $params[] = $identifier; $params[] = $identifier; } } if ($mac_address) { $mac_statement = 'SELECT `port_id` FROM `ports` WHERE '; if ($device_id) { $mac_statement .= '`device_id`=? AND '; $params[] = $device_id; } $mac_statement .= '`ifPhysAddress`=?'; $statements[] = $mac_statement; $params[] = $mac_address; } if (empty($statements)) { return 0; } $queries = implode(' UNION ', $statements); $sql = "SELECT * FROM ($queries LIMIT 1) p"; return (int)dbFetchCell($sql, $params); }
arjitc/librenms
includes/discovery/functions.inc.php
PHP
gpl-3.0
59,929
package sensorServer; import java.util.Collection; import java.util.Collections; import java.util.concurrent.TimeUnit; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.scheduling.TaskScheduler; import sensorServer.configuration.SensorConfiguration; import sensorServer.configuration.SensorUpdateInterval; @Configuration public class SensorServiceTestContext { @Bean public TimeService timeService() { return () -> 1l; } @Bean String sensorName() { return "e2a"; } @Bean public Collection<SensorConfiguration> sensorConfiguration(String sensorName) { return Collections.singleton(SensorConfiguration.builder().name(sensorName).sensorFile("") .sensorUpdateInterval(new SensorUpdateInterval(TimeUnit.HOURS, 1l)).build()); } }
nemecp4/termoserver
sensorServer/src/test/java/sensorServer/SensorServiceTestContext.java
Java
gpl-3.0
927
package processing.visualcube1e3.simulator; import processing.core.PApplet; /** * General vector math useful for calculations in 2D space. * A vector defines a point in 3D space. * * @author Andreas Rentschler * @date 2008-07-21 * @version 1.0 */ class Vector2D { public final float x, y; /** * Create a new Vector. * @param x Vector's x value * @param y Vector's y value */ public Vector2D(float x, float y) { this.x = x; this.y = y; } /** * Show string representation. * @return This Vector's string representation */ public String toString() { return "(" + x + ", " + y + ")"; } /** * Get Vector's norm. * @return A number containing this Vector's norm */ public float norm() { return PApplet.sqrt(x*x + y*y); } /** * Normalize Vector. * @return A new Vector containing the result */ public Vector2D normalize() { float d = this.norm(); return new Vector2D(x/d, y/d); } /** * Create Vector conjugate. * @return A new Vector containing the result */ public Vector2D conjugate() { return new Vector2D(-x, -y); } /** * Add Vector to another Vector. * @param b Vector to be added * @return A new Vector containing the result */ public Vector2D plus(Vector2D b) { Vector2D a = this; return new Vector2D(a.x+b.x, a.y+b.y); } /** * Subtract another Vector from Vector. * @param b Vector to be subtracted * @return A new Vector containing the result */ public Vector2D minus(Vector2D b) { Vector2D a = this; return new Vector2D(a.x-b.x, a.y-b.y); } /** * Calculate distance to another Vector. * @param b Another Vector * @return Distance */ public float distance(Vector2D b) { Vector2D a = this; return a.minus(b).norm(); } /** * Multiply Vector by another Vector (cross product). * @param b Right-sided multiplication Vector * @return A new Vector containing the result */ public Vector2D cross(Vector2D b) { Vector2D a = this; return new Vector2D( + a.y*b.x - b.x*a.x, - a.x*b.y + b.x*a.y); } /** * Multiply Vector by another Vector (dot product). * @param b Right-sided multiplication Vector * @return A scalar containing the result */ public float dot(Vector2D b) { Vector2D a = this; return a.x*b.x + a.y*b.y; } /** * Multiply Vector by another Vector (scalar product). * @param b Multiplication scalar * @return A new Vector containing the result */ public Vector2D times(float f) { return new Vector2D(x*f, y*f); } /** Invert Vector. * @return A new Vector containing the result */ public Vector2D inverse() { float d = x*x + y*y ; return new Vector2D(x/d, y/d); } /** * Divide Vector a by another Vector b. * @param b Divisor Vector * @return A new Vector containing the result */ public Vector2D divides(Vector2D b) { Vector2D a = this; return a.inverse().cross(b); } /** * Divide Vector by a number. * @param b Divisor number * @return A new Vector containing the result */ public Vector2D divides(float b) { return new Vector2D(x/b, y/b); } /** * Ensure Vector stays in range. * @param a minimum value * @param b maximum value * @return A new Vector containing the result */ public Vector2D constrain(float a, float b) { return new Vector2D( PApplet.constrain(x, a, b), PApplet.constrain(y, a, b)); } }
qvt/vc
VisualCube1e3/src/processing/visualcube1e3/simulator/Vector2D.java
Java
gpl-3.0
3,370
/* * Copyright (c) 2006-2009 Marvisan Pty. Ltd. All rights reserved. * Use is subject to license terms. */ /* * QuoteCancelMsg50SP2Test.java * * $Id: QuoteCancelMsg50SP2Test.java,v 1.3 2010-03-21 11:25:16 vrotaru Exp $ */ package net.hades.fix.message.impl.v50sp2; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import net.hades.fix.TestUtils; import net.hades.fix.message.MsgTest; import net.hades.fix.message.QuoteCancelMsg; import net.hades.fix.message.builder.FIXMsgBuilder; import net.hades.fix.message.impl.v50sp2.data.QuoteCancelMsg50SP2TestData; import net.hades.fix.message.type.ApplVerID; import net.hades.fix.message.type.BeginString; import net.hades.fix.message.type.MsgType; import net.hades.fix.message.type.QuoteCancelType; /** * Test suite for FIX 5.0SP2 QuoteCancelMsg class. * * @author <a href="mailto:support@marvisan.com">Support Team</a> * @version $Revision: 1.3 $ * @created 01/05/2009, 12:18:17 PM */ public class QuoteCancelMsg50SP2Test extends MsgTest { public QuoteCancelMsg50SP2Test() { } @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() { TestUtils.enableValidation(); } @After public void tearDown() { } /** * Test of encode method, of class QuoteCancelMsg for required fields only. * @throws Exception */ @Test public void a1_testEncodeReq() throws Exception { System.out.println("-->testEncodeReq"); QuoteCancelMsg msg = (QuoteCancelMsg) FIXMsgBuilder.build(MsgType.QuoteCancel.getValue(), BeginString.FIXT_1_1, ApplVerID.FIX50SP2); TestUtils.populateFIXT11HeaderAll(msg); msg.getHeader().setApplVerID(ApplVerID.FIX50SP2); msg.setQuoteID("X162773883"); msg.setQuoteCancelType(QuoteCancelType.CancelAllQuotes.getValue()); String encoded = new String(msg.encode(), DEFAULT_CHARACTER_SET); System.out.println("encoded-->" + encoded); QuoteCancelMsg dmsg = (QuoteCancelMsg) FIXMsgBuilder.build(encoded.getBytes(DEFAULT_CHARACTER_SET)); dmsg.decode(); assertEquals(msg.getQuoteID(), dmsg.getQuoteID()); assertEquals(msg.getQuoteCancelType().intValue(), dmsg.getQuoteCancelType().intValue()); } /** * Test of encode/decode method, of class QuoteCancelMsg for all fields. * @throws Exception */ @Test public void b2_testEncodeDecodeAll() throws Exception { System.out.println("-->testEncodeDecodeAll"); QuoteCancelMsg msg = (QuoteCancelMsg) FIXMsgBuilder.build(MsgType.QuoteCancel.getValue(), BeginString.FIXT_1_1, ApplVerID.FIX50SP2); QuoteCancelMsg50SP2TestData.getInstance().populate(msg); String encoded = new String(msg.encode(), DEFAULT_CHARACTER_SET); System.out.println("encoded-->" + encoded); QuoteCancelMsg dmsg = (QuoteCancelMsg) FIXMsgBuilder.build(encoded.getBytes(DEFAULT_CHARACTER_SET)); dmsg.decode(); QuoteCancelMsg50SP2TestData.getInstance().check(msg, dmsg); } // NEGATIVE TEST CASES ///////////////////////////////////////// /** * Test of encode method, of class QuoteCancelMsg with missing QuoteID data. */ @Test public void testEncodeMissingQuoteID() { System.out.println("-->testEncodeMissingQuoteID"); try { QuoteCancelMsg msg = (QuoteCancelMsg) FIXMsgBuilder.build(MsgType.QuoteCancel.getValue(), BeginString.FIXT_1_1, ApplVerID.FIX50SP2); TestUtils.populateFIXT11HeaderAll(msg); msg.getHeader().setApplVerID(ApplVerID.FIX50SP2); msg.setQuoteCancelType(QuoteCancelType.CancelSpecifiedQuote.getValue()); msg.encode(); fail("Expect exception thrown."); } catch (Exception ex) { assertEquals( "Tag value(s) for [QuoteID] is missing.", ex.getMessage()); } } /** * Test of encode method, of class QuoteCancelMsg with missing QuoteCancelType data. */ @Test public void testEncodeMissingQuoteCancelType() { System.out.println("-->testEncodeMissingQuoteCancelType"); try { QuoteCancelMsg msg = (QuoteCancelMsg) FIXMsgBuilder.build(MsgType.QuoteCancel.getValue(), BeginString.FIXT_1_1, ApplVerID.FIX50SP2); TestUtils.populateFIXT11HeaderAll(msg); msg.getHeader().setApplVerID(ApplVerID.FIX50SP2); msg.setQuoteID("43423534534"); msg.encode(); fail("Expect exception thrown."); } catch (Exception ex) { assertEquals( "Tag value(s) for [QuoteCancelType] is missing.", ex.getMessage()); } } /** * Test of encode method, of class QuoteCancelMsg with missing all required data. */ @Test public void testEncodeMissingAllReq() { System.out.println("-->testEncodeMissingAllReq"); try { QuoteCancelMsg msg = (QuoteCancelMsg) FIXMsgBuilder.build(MsgType.QuoteCancel.getValue(), BeginString.FIXT_1_1, ApplVerID.FIX50SP2); TestUtils.populateFIXT11HeaderAll(msg); msg.getHeader().setApplVerID(ApplVerID.FIX50SP2); msg.encode(); fail("Expect exception thrown."); } catch (Exception ex) { assertEquals( "Tag value(s) for [QuoteCancelType] is missing.", ex.getMessage()); } } // UTILITY MESSAGES ///////////////////////////////////////// private void checkUnsupportedException(Exception ex) { assertEquals("This tag is not supported in [QuoteCancelMsg] message version [5.0SP2].", ex.getMessage()); } }
marvisan/HadesFIX
Model/src/test/java/net/hades/fix/message/impl/v50sp2/QuoteCancelMsg50SP2Test.java
Java
gpl-3.0
5,843
<?php /* CAT:Step chart */ /* pChart library inclusions */ require_once("bootstrap.php"); use pChart\pColor; use pChart\pDraw; use pChart\pCharts; /* Create the pChart object */ $myPicture = new pDraw(700,230); /* Populate the pData object */ $myPicture->myData->addPoints([-4,VOID,VOID,12,8,3],"Probe 1"); $myPicture->myData->addPoints([3,12,15,8,5,-5],"Probe 2"); $myPicture->myData->addPoints([2,7,5,18,19,22],"Probe 3"); $myPicture->myData->setSerieTicks("Probe 2",4); $myPicture->myData->setAxisName(0,"Temperatures"); $myPicture->myData->addPoints(["Jan","Feb","Mar","Apr","May","Jun"],"Labels"); $myPicture->myData->setSerieDescription("Labels","Months"); $myPicture->myData->setAbscissa("Labels"); /* Draw the background */ $myPicture->drawFilledRectangle(0,0,700,230,["Color"=>new pColor(170,183,87), "Dash"=>TRUE, "DashColor"=>new pColor(190,203,107)]); /* Overlay with a gradient */ $myPicture->drawGradientArea(0,0,700,230,DIRECTION_VERTICAL, ["StartColor"=>new pColor(219,231,139,50),"EndColor"=>new pColor(1,138,68,50)]); $myPicture->drawGradientArea(0,0,700,20, DIRECTION_VERTICAL, ["StartColor"=>new pColor(0,0,0,80),"EndColor"=>new pColor(50,50,50,80)]); /* Add a border to the picture */ $myPicture->drawRectangle(0,0,699,229,["Color"=>new pColor(0)]); /* Write the picture title */ $myPicture->setFontProperties(array("FontName"=>"pChart/fonts/Silkscreen.ttf","FontSize"=>6)); $myPicture->drawText(10,13,"drawStepChart() - draw a step chart",["Color"=>new pColor(255)]); /* Write the chart title */ $myPicture->setFontProperties(array("FontName"=>"pChart/fonts/Forgotte.ttf","FontSize"=>11)); $myPicture->drawText(250,55,"Average temperature",["FontSize"=>20,"Align"=>TEXT_ALIGN_BOTTOMMIDDLE]); /* Create the pCharts object */ $pCharts = new pCharts($myPicture); /* Draw the scale and the 1st chart */ $myPicture->setGraphArea(60,60,450,190); $myPicture->drawFilledRectangle(60,60,450,190,["Color"=>new pColor(255,255,255,10),"Surrounding"=>-200]); $myPicture->drawScale(["DrawSubTicks"=>TRUE]); $myPicture->setShadow(TRUE,["X"=>1,"Y"=>1,"Color"=>new pColor(255,255,255,10)]); $myPicture->setFontProperties(["FontName"=>"pChart/fonts/pf_arma_five.ttf","FontSize"=>6]); $pCharts->drawStepChart(["DisplayValues"=>TRUE,"DisplayType"=>DISPLAY_AUTO]); $myPicture->setShadow(FALSE); /* Draw the scale and the 2nd chart */ $myPicture->setGraphArea(500,60,670,190); $myPicture->drawFilledRectangle(500,60,670,190,["Color"=>new pColor(255,255,255,10),"Surrounding"=>-200]); $myPicture->drawScale(["Pos"=>SCALE_POS_TOPBOTTOM,"DrawSubTicks"=>TRUE]); $myPicture->setShadow(TRUE,["X"=>-1,"Y"=>1,"Color"=>new pColor(0,0,0,10)]); $pCharts->drawStepChart(); $myPicture->setShadow(FALSE); /* Write the chart legend */ $myPicture->drawLegend(510,205,["Style"=>LEGEND_NOBORDER,"Mode"=>LEGEND_HORIZONTAL]); /* Render the picture (choose the best way) */ $myPicture->autoOutput("temp/example.drawStepChart.png"); ?>
selleron/pointageWebCEGID
pChart2.0-for-PHP7-master/examples/example.drawStepChart.php
PHP
gpl-3.0
2,933
package de.voidnode.trading4j.functionality.expertadvisor; import static java.util.Arrays.asList; import de.voidnode.trading4j.api.ExpertAdvisor; import de.voidnode.trading4j.domain.marketdata.MarketData; import de.voidnode.trading4j.domain.marketdata.impl.BasicMarketData; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import static org.mockito.Mockito.inOrder; /** * Checks if {@link MarketDataDistributor} works as expected. * * @author Raik Bieniek */ @RunWith(MockitoJUnitRunner.class) public class MarketDataDistributorTest { private final MarketData candle1 = new BasicMarketData(1.0); private final MarketData candle2 = new BasicMarketData(2.0); @Mock private ExpertAdvisor<MarketData> input1; @Mock private ExpertAdvisor<MarketData> input2; private MarketDataDistributor<MarketData> cut; /** * Sets up the class under test. */ @Before public void setUpCutAndTests() { cut = new MarketDataDistributor<>(asList(input1, input2)); } /** * The cut passes received {@link MarketData}s to all {@link ExpertAdvisor}s passed in the constructor in the order * they where passed in the constructor. */ @Test public void distributesCandleSticksToTheExpertAdvisorsInTheOrderPassedInTheConstructor() { cut.newData(candle1); cut.newData(candle2); final InOrder inOrder = inOrder(input1, input2); inOrder.verify(input1).newData(candle1); inOrder.verify(input2).newData(candle1); inOrder.verify(input1).newData(candle2); inOrder.verify(input2).newData(candle2); inOrder.verifyNoMoreInteractions(); } }
rbi/trading4j
core/src/test/java/de/voidnode/trading4j/functionality/expertadvisor/MarketDataDistributorTest.java
Java
gpl-3.0
1,802
class TournamentController < ApplicationController include TournamentHelper include BracketHelper include ParticipantHelper load_and_authorize_resource def show @tournament = Tournament.find_by(id: params[:id]) if @tournament.nil? redirect_to tournament_index_path, alert: "Tournament #{params[:id].to_s} doesn't exist" else @participants = participantHelper_list_participants_from_event_id(@tournament.id) @brackets = bracketHelper_list_brackets_from_tournament_id(@tournament.id) end end def participant_register participant = Participant.find_by(id: params[:participant_id]) tournament = Tournament.find_by(id: params[:id]) if tournament.nil? || participant.nil? redirect_to request.headers["HTTP_REFERER"], alert: "Tournament #{params[:id].to_s} or \ Participant #{params[:participant_id].to_s} doesn't exist" else participant.tournament_ids << tournament.id if !participant.tournament_ids.include?(tournament.id) participant.save tournament.participant_ids << participant.id if !tournament.participant_ids.include?(participant.id) tournament.save redirect_to request.headers["HTTP_REFERER"], notice: "Register Tournament success" end end def participant_unregister participant = Participant.find_by(id: params[:participant_id]) tournament = Tournament.find_by(id: params[:id]) if tournament.nil? || participant.nil? redirect_to request.headers["HTTP_REFERER"], alert: "Tournament #{params[:id].to_s} or \ Participant #{params[:participant_id].to_s} doesn't exist" else participant.tournament_ids.delete(tournament.id) if participant.tournament_ids.include?(tournament.id) participant.save tournament.participant_ids.delete(participant.id) if tournament.participant_ids.include?(participant.id) tournament.save redirect_to request.headers["HTTP_REFERER"], notice: "Unregister Tournament success" end end end
noxsnono/esport42_RoR
app/controllers/tournament_controller.rb
Ruby
gpl-3.0
2,089
/* Aversive++ Copyright (C) 2014 Eirbot 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/>. */ #ifndef STM32_DEVICE_HPP #define STM32_DEVICE_HPP #include "../../common/device/device.hpp" #endif//STM32_DEVICE_HPP
astralien3000/aversive--
include/stm32/device/device.hpp
C++
gpl-3.0
1,238
import logging from agent import run logger = logging.getLogger(__name__) def example_experiment(): repeat = 5 avg_rew = 0.0 episodes = 100000 sleep = 0.00 params = run.getparams(episodes) reward_list = [] for i in range(repeat): reward, allparams, totrewlist, totrewavglist, greedyrewlist, reward_threshold = run.main(params.copy(),numavg=100,sleep=sleep) reward_list.append(reward) avg_rew+=reward avg_rew/=repeat print(allparams) print("avg_rew",avg_rew) print("rew list",reward_list) if __name__ == '__main__': run.main(None)
davidenitti/ML
RL/run_agent.py
Python
gpl-3.0
604
// synchronizationWithFetchAddRelaxed.cpp #include <atomic> #include <chrono> #include <iostream> #include <random> #include <thread> #include <utility> #include <vector> constexpr long long size= 100000000; constexpr long long firBound= 25000000; constexpr long long secBound= 50000000; constexpr long long thiBound= 75000000; constexpr long long fouBound= 100000000; void sumUp(std::atomic<unsigned long long>& sum, const std::vector<int>& val, unsigned long long beg, unsigned long long end){ for (auto it= beg; it < end; ++it){ sum.fetch_add(val[it],std::memory_order_relaxed); } } int main(){ std::cout << std::endl; std::vector<int> randValues; randValues.reserve(size); std::mt19937 engine; std::uniform_int_distribution<> uniformDist(1,10); for ( long long i=0 ; i< size ; ++i) randValues.push_back(uniformDist(engine)); std::atomic<unsigned long long> sum(0); auto start = std::chrono::system_clock::now(); std::thread t1(sumUp,std::ref(sum),std::ref(randValues),0,firBound); std::thread t2(sumUp,std::ref(sum),std::ref(randValues),firBound,secBound); std::thread t3(sumUp,std::ref(sum),std::ref(randValues),secBound,thiBound); std::thread t4(sumUp,std::ref(sum),std::ref(randValues),thiBound,fouBound); t1.join(); t2.join(); t3.join(); t4.join(); std::chrono::duration<double> dur= std::chrono::system_clock::now() - start; std::cout << "Time for addition " << dur.count() << " seconds" << std::endl; std::cout << "Result: " << sum << std::endl; std::cout << std::endl; }
RainerGrimm/ModernesCppSource
source/synchronizationWithFetchAddRelaxed.cpp
C++
gpl-3.0
1,560
<?php // Heading $_['heading_title'] = 'Districts'; // Text $_['text_success'] = 'Success: You have modified zones!'; // Column $_['column_name'] = 'Dzongkhag'; $_['column_code'] = 'State Code'; $_['column_country'] = 'Country'; $_['column_action'] = 'Action'; // Entry $_['entry_status'] = 'State Status:'; $_['entry_name'] = 'State Name:'; $_['entry_code'] = 'State Code:'; $_['entry_country'] = 'Country:'; // Error $_['error_permission'] = 'Warning: You do not have permission to modify States!'; $_['error_name'] = 'State Name must be between 3 and 128 characters!'; $_['error_country'] = 'Please select country'; $_['error_same'] = 'State already exist!'; $_['error_default'] = 'Warning: This State cannot be deleted as it is currently assigned as the default store State!'; $_['error_store'] = 'Warning: This State cannot be deleted as it is currently assigned to %s stores!'; $_['error_address'] = 'Warning: This State cannot be deleted as it is currently assigned to %s address book entries!'; $_['error_affiliate'] = 'Warning: This State cannot be deleted as it is currently assigned to %s affiliates!'; $_['error_zone_to_geo_zone'] = 'Warning: This State cannot be deleted as it is currently assigned to %s States to cities!'; ?>
drupsta/villagebazaar
admin/language/english/localisation/zone.php
PHP
gpl-3.0
1,424
module Rooftop # The Rooftop API returns content for basic and advanced custom fields together. This module # cleans up the response, and creates a collection of ContentField objects, with which we can do # things like parse links. module Content def self.included(base) base.include Rooftop::HookCalls base.send(:add_to_hook, :after_find, ->(r) { # basic content is the stuff which comes from WP by default. if r.respond_to?(:content) && r.content.is_a?(Hash) basic_fields = r.content[:basic].collect {|k,v| {name: k, value: v, fieldset: "Basic"}} # advanced fields from from ACF, and are exposed in the api in this form: # [ # { # "title"=>"The fieldset title", # "fields"=>[ # {"name"=>"field name", "label"=>"display name", "class"=>"type of field", "value"=>"The value of the field"}, # {"name"=>"field name", "label"=>"display name", "class"=>"type of field", # "value"=>"The value of the field"}, # etc. # ] # } # ] # Given that's a bit convoluted, we get both the content types into the same output format, like this: # {"field name", "label"=>"display name", "class"=>"type of field", "value"=>"value of the field", "fieldset"=>"fieldset if there is one, or Basic for the builtin ones"} advanced_fields = r.content[:advanced].collect do |fieldset| fieldset[:fields].each do |field| field.merge!(fieldset: fieldset[:title]) if field[:class].present? field[:type] = field[:class] end field.delete(:class) end fieldset[:fields] end advanced_fields.flatten! schema = (Rooftop.configuration.advanced_options[:use_advanced_fields_schema] && r.respond_to?(:advanced_fields)) ? r.advanced_fields : nil r.fields = Rooftop::Content::Collection.new((basic_fields + advanced_fields), r, schema) end }) base.send(:add_to_hook, :after_initialize, ->(r) { r.stub_fields! unless r.persisted? if r.class.respond_to?(:write_advanced_fields?) && r.class.write_advanced_fields? && Rooftop.configuration.advanced_options[:use_advanced_fields_schema] r.fields = Rooftop::Content::Collection.new({}, r, r.advanced_fields) unless r.persisted? end }) base.send(:before_save, ->(r) { # if this object is allowed to write back to ACF, we need to build up the appropriate structure if r.respond_to?(:write_advanced_fields) && r.write_advanced_fields? r.content[:advanced] = r.fields.to_params end r.status_will_change!# unless r.persisted? r.slug_will_change!# unless r.persisted? r.content_will_change! r.restore_fields! if r.respond_to?(:fields) # in any case, remove the fields attribute to nothing; we don't want to send this back. }) end # test whether an instance has a field by name. Accepts a second argument if you want to test either the string value or the class. def has_field?(name, comparison=nil) has_field = fields.respond_to?(name.to_sym) if comparison.present? && comparison.is_a?(String) has_field && (fields.send(name.to_sym) == comparison) elsif comparison.present? has_field && fields.send(name.to_sym).is_a?(comparison) else has_field end end def stub_fields! unless respond_to?(:content) && content.is_a?(Hash) self.class.send(:attr_accessor, :content) self.class.send(:define_attribute_method, :content) self.content = {"basic"=>{"content"=>"", "excerpt"=>""}, "advanced"=>[]}.with_indifferent_access end unless respond_to?(:status) self.class.send(:attr_accessor, :status) self.class.send(:define_attribute_method, :status) self.status = 'draft' end unless respond_to?(:slug) self.class.send(:attr_accessor, :slug) self.class.send(:define_attribute_method, :slug) end unless respond_to?(:title) self.class.send(:attr_accessor, :slug) self.class.send(:define_attribute_method, :slug) end end end end
rooftopcms/rooftop-ruby
lib/rooftop/content/content_fields.rb
Ruby
gpl-3.0
4,354
timer = 500 # delay in milliseconds def toggle(): pass
librallu/RICM4Projet
tests/led/led.py
Python
gpl-3.0
57
/* * This file is part of Log4Jdbc. * * Log4Jdbc 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. * * Log4Jdbc 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 Log4Jdbc. If not, see <http://www.gnu.org/licenses/>. * */ package fr.ms.log4jdbc.proxy.jdbc.operation; import java.lang.reflect.Method; import java.sql.CallableStatement; import java.sql.PreparedStatement; import java.sql.Statement; import fr.ms.log4jdbc.lang.reflect.TimeInvocation; import fr.ms.log4jdbc.SqlOperation; import fr.ms.log4jdbc.SqlOperationContext; import fr.ms.log4jdbc.context.jdbc.ConnectionContextJDBC; import fr.ms.log4jdbc.context.jdbc.TransactionContextJDBC; import fr.ms.log4jdbc.proxy.Log4JdbcProxy; import fr.ms.log4jdbc.proxy.handler.Log4JdbcOperation; import fr.ms.log4jdbc.proxy.jdbc.operation.factory.ConnectionOperationFactory; import fr.ms.log4jdbc.sql.QueryImpl; import fr.ms.log4jdbc.util.logging.Logger; import fr.ms.log4jdbc.util.logging.LoggerManager; /** * * @see <a href="http://marcosemiao4j.wordpress.com">Marco4J</a> * * * @author Marco Semiao * */ public class ConnectionOperation implements Log4JdbcOperation { private final static Logger LOG = LoggerManager.getLogger(ConnectionOperation.class); private final ConnectionContextJDBC connectionContext; private final TimeInvocation timeInvocation; private final Method method; private final Object[] args; private final ConnectionOperationFactory connectionOperationFactory; private QueryImpl query; public ConnectionOperation(final ConnectionOperationFactory connectionOperationFactory, final ConnectionContextJDBC connectionContext, final TimeInvocation timeInvocation, final Method method, final Object[] args, QueryImpl query) { this.connectionContext = connectionContext; this.timeInvocation = timeInvocation; this.method = method; this.args = args; this.connectionOperationFactory = connectionOperationFactory; this.query = query; } public SqlOperation getOperation() { final String nameMethod = method.getName(); if (nameMethod.equals("setAutoCommit")) { setAutoCommit(args); } else if (nameMethod.equals("commit")) { commit(); } else if (nameMethod.equals("rollback")) { rollback(args); } else if (nameMethod.equals("setSavepoint")) { setSavepoint(timeInvocation.getWrapInvocation().getInvoke()); } else if (nameMethod.equals("close")) { close(); } else if (nameMethod.equals("setTransactionIsolation")) { setTransactionIsolation(args); } final SqlOperationContext sqlOperationContext = new SqlOperationContext(timeInvocation, connectionContext, query); return sqlOperationContext; } private void setTransactionIsolation(final Object[] args) { final int transactionIsolation = ((Integer) args[0]).intValue(); connectionContext.setTransactionIsolation(transactionIsolation); } private void setAutoCommit(final Object[] args) { final boolean autoCommit = ((Boolean) args[0]).booleanValue(); final boolean commit = connectionOperationFactory.executeAutoCommit(autoCommit); connectionContext.setTransactionEnabled(!autoCommit); if (commit) { commit(); } if (LOG.isDebugEnabled()) { LOG.debug("Set Auto Commit : " + autoCommit); } } private void commit() { connectionContext.commit(); if (LOG.isDebugEnabled()) { LOG.debug("Commit Transaction"); } } private void setSavepoint(final Object savePoint) { final TransactionContextJDBC transactionContext = connectionContext.getTransactionContext(); if (transactionContext != null) { transactionContext.setSavePoint(savePoint); } if (LOG.isDebugEnabled()) { LOG.debug("savepoint : " + savePoint); } } private void rollback(final Object[] args) { Object savePoint = null; if (args != null && args[0] != null) { savePoint = args[0]; } rollback(savePoint); if (LOG.isDebugEnabled()) { LOG.debug("rollback : " + args); } } private void rollback(final Object savePoint) { connectionContext.rollback(savePoint); } private void close() { connectionContext.close(); } public Object getInvoke() { final Object invoke = timeInvocation.getWrapInvocation().getInvoke(); if (invoke != null) { if (invoke instanceof CallableStatement) { final CallableStatement callableStatement = (CallableStatement) invoke; return Log4JdbcProxy.proxyCallableStatement(callableStatement, connectionContext, query); } else if (invoke instanceof PreparedStatement) { final PreparedStatement preparedStatement = (PreparedStatement) invoke; return Log4JdbcProxy.proxyPreparedStatement(preparedStatement, connectionContext, query); } else if (invoke instanceof Statement) { final Statement statement = (Statement) invoke; return Log4JdbcProxy.proxyStatement(statement, connectionContext); } } return invoke; } }
marcosemiao/log4jdbc
core/log4jdbc-driver/src/main/java/fr/ms/log4jdbc/proxy/jdbc/operation/ConnectionOperation.java
Java
gpl-3.0
5,276
# -*- coding: utf-8 -*- # # Copyright (C) Translate House and contributors. # # This file is a part of the PyLIFF project. It is distributed under the GPL3 # or later license. See the LICENSE file for a copy of the license and the # AUTHORS file for copyright and authorship information. import pytest @pytest.mark.test def test_pyliff_target(file_units_xliff): f1 = file_units_xliff.files.next() units = f1.units segments = units.next().segments s1 = segments.next() assert s1.target.text == 'Unit 1 target' s2 = segments.next() assert s2.target.text == 'Unit 1 target - part 2' s3 = segments.next() assert s3.target is None
translate/pyliff
tests/target.py
Python
gpl-3.0
668
/* Copyright 2011 OCAD University Copyright 2010-2011 Lucendo Development Ltd. Licensed under the Educational Community License (ECL), Version 2.0 or the New BSD license. You may not use this file except in compliance with one these Licenses. You may obtain a copy of the ECL 2.0 License and BSD License at https://github.com/fluid-project/infusion/raw/master/Infusion-LICENSE.txt */ // Declare dependencies /*global fluid_1_4:true, jQuery*/ // JSLint options /*jslint white: true, funcinvoke: true, continue: true, elsecatch: true, operator: true, jslintok:true, undef: true, newcap: true, regexp: true, bitwise: true, browser: true, forin: true, maxerr: 100, indent: 4 */ var fluid_1_4 = fluid_1_4 || {}; (function ($, fluid) { /** The Fluid "IoC System proper" - resolution of references and * completely automated instantiation of declaratively defined * component trees */ var inCreationMarker = "__CURRENTLY_IN_CREATION__"; // unsupported, non-API function fluid.isFireBreak = function(component) { return component.options && component.options["fluid.visitComponents.fireBreak"]; }; // unsupported, non-API function fluid.visitComponentChildren = function(that, visitor, options, up, down) { options = options || {}; for (var name in that) { var component = that[name]; //Every component *should* have an id, but some clients may not yet be compliant //if (component && component.typeName && !component.id) { // fluid.fail("No id"); //} if (!component || !component.typeName || (component.id && options.visited && options.visited[component.id])) {continue; } if (options.visited) { options.visited[component.id] = true; } if (visitor(component, name, options, up, down)) { return true; } if (!fluid.isFireBreak(component) && !options.flat) { fluid.visitComponentChildren(component, visitor, options, up, down + 1); } } }; // thatStack contains an increasing list of MORE SPECIFIC thats. var visitComponents = function(thatStack, visitor, options) { options = options || { visited: {}, flat: true }; var up = 0; for (var i = thatStack.length - 1; i >= 0; --i) { var that = thatStack[i]; if (fluid.isFireBreak(that)) { return; } if (that.typeName) { options.visited[that.id] = true; if (visitor(that, "", options, 0, 0)) { return; } } if (fluid.visitComponentChildren(that, visitor, options, up, 1)) { return; } ++up; } }; // An EL segment resolver strategy that will attempt to trigger creation of // components that it discovers along the EL path, if they have been defined but not yet // constructed. Spring, eat your heart out! Wot no SPR-2048? function makeGingerStrategy(instantiator, that, thatStack) { return function(component, thisSeg) { var atval = component[thisSeg]; if (atval === undefined) { var parentPath = instantiator.idToPath[component.id]; atval = instantiator.pathToComponent[fluid.composePath(parentPath, thisSeg)]; // if it was not attached to the component, but it is in the instantiator, it MUST be in creation - prepare to fail if (atval) { atval[inCreationMarker] = true; } } if (atval !== undefined) { if (atval[inCreationMarker]) { fluid.fail("Component " + fluid.dumpThat(atval) + " at path \"" + thisSeg + "\" of parent " + fluid.dumpThat(component) + " cannot be used for lookup" + " since it is still in creation. Please reorganise your dependencies so that they no longer contain circular references"); } } else { if (fluid.get(component, fluid.path("options", "components", thisSeg, "type"))) { fluid.initDependent(component, thisSeg); atval = component[thisSeg]; } } return atval; }; } // unsupported, non-API function fluid.dumpThat = function(that, instantiator) { return "{ typeName: \"" + that.typeName + "\" id: " + that.id + "}"; }; // unsupported, non-API function fluid.dumpThatStack = function(thatStack, instantiator) { var togo = fluid.transform(thatStack, function(that) { var path = instantiator.idToPath[that.id]; return fluid.dumpThat(that) + (path? (" - path: " + path) : ""); }); return togo.join("\n"); }; // Return an array of objects describing the current activity // unsupported, non-API function fluid.describeActivity = function() { return fluid.threadLocal().activityStack || []; }; // Execute the supplied function with the specified activity description pushed onto the stack // unsupported, non-API function fluid.pushActivity = function(func, message) { if (!message) { return func(); } var root = fluid.threadLocal(); if (!root.activityStack) { root.activityStack = []; } var frames = fluid.makeArray(message); frames.push("\n"); frames.unshift("\n"); root.activityStack = frames.concat(root.activityStack); return fluid.tryCatch(func, null, function() { root.activityStack = root.activityStack.slice(frames.length); }); }; // Return a function wrapped by the activity of describing its activity // unsupported, non-API function fluid.wrapActivity = function(func, messageSpec) { return function() { var args = fluid.makeArray(arguments); var message = fluid.transform(fluid.makeArray(messageSpec), function(specEl) { if (specEl.indexOf("arguments.") === 0) { var el = specEl.substring("arguments.".length); return fluid.get(args, el); } else { return specEl; } }); return fluid.pushActivity(function() { return func.apply(null, args); }, message); }; }; var localRecordExpected = /arguments|options|container/; function makeStackFetcher(instantiator, parentThat, localRecord, expandOptions) { expandOptions = expandOptions || {}; var thatStack = instantiator.getFullStack(parentThat); var fetchStrategies = [fluid.model.funcResolverStrategy, makeGingerStrategy(instantiator, parentThat, thatStack)]; var fetcher = function(parsed) { var context = parsed.context; if (localRecord && localRecordExpected.test(context)) { var fetched = fluid.get(localRecord[context], parsed.path); return (context === "arguments" || expandOptions.direct)? fetched : { marker: context === "options"? fluid.EXPAND : fluid.EXPAND_NOW, value: fetched }; } var foundComponent; visitComponents(thatStack, function(component, name, options, up, down) { if (context === name || context === component.typeName || context === component.nickName) { foundComponent = component; if (down > 1) { fluid.log("***WARNING: value resolution for context " + context + " found at depth " + down + ": this may not be supported in future"); } return true; // YOUR VISIT IS AT AN END!! } if (fluid.get(component, fluid.path("options", "components", context, "type")) && !component[context]) { foundComponent = fluid.get(component, context, {strategies: fetchStrategies}); return true; } }); if (!foundComponent && parsed.path !== "") { var ref = fluid.renderContextReference(parsed); fluid.log("Failed to resolve reference " + ref + ": thatStack contains\n" + fluid.dumpThatStack(thatStack, instantiator)); fluid.fail("Failed to resolve reference " + ref + " - could not match context with name " + context + " from component root of type " + thatStack[0].typeName, "\ninstantiator contents: ", instantiator); } return fluid.get(foundComponent, parsed.path, fetchStrategies); }; return fetcher; } function makeStackResolverOptions(instantiator, parentThat, localRecord, expandOptions) { return $.extend({}, fluid.defaults("fluid.resolveEnvironment"), { fetcher: makeStackFetcher(instantiator, parentThat, localRecord, expandOptions) }); } // unsupported, non-API function fluid.instantiator = function(freeInstantiator) { // NB: We may not use the options merging framework itself here, since "withInstantiator" below // will blow up, as it tries to resolve the instantiator which we are instantiating *NOW* var preThat = { options: { "fluid.visitComponents.fireBreak": true }, idToPath: {}, pathToComponent: {}, stackCount: 0, nickName: "instantiator" }; var that = fluid.typeTag("fluid.instantiator"); that = $.extend(that, preThat); that.stack = function(count) { return that.stackCount += count; }; that.getThatStack = function(component) { var path = that.idToPath[component.id] || ""; var parsed = fluid.model.parseEL(path); var togo = fluid.transform(parsed, function(value, i) { var parentPath = fluid.model.composeSegments.apply(null, parsed.slice(0, i + 1)); return that.pathToComponent[parentPath]; }); var root = that.pathToComponent[""]; if (root) { togo.unshift(root); } return togo; }; that.getEnvironmentalStack = function() { var togo = [fluid.staticEnvironment]; if (!freeInstantiator) { togo.push(fluid.threadLocal()); } return togo; }; that.getFullStack = function(component) { var thatStack = component? that.getThatStack(component) : []; return that.getEnvironmentalStack().concat(thatStack); }; function recordComponent(component, path) { that.idToPath[component.id] = path; if (that.pathToComponent[path]) { fluid.fail("Error during instantiation - path " + path + " which has just created component " + fluid.dumpThat(component) + " has already been used for component " + fluid.dumpThat(that.pathToComponent[path]) + " - this is a circular instantiation or other oversight." + " Please clear the component using instantiator.clearComponent() before reusing the path."); } that.pathToComponent[path] = component; } that.recordRoot = function(component) { if (component && component.id && !that.pathToComponent[""]) { recordComponent(component, ""); } }; that.pushUpcomingInstantiation = function(parent, name) { that.expectedParent = parent; that.expectedName = name; }; that.recordComponent = function(component) { if (that.expectedName) { that.recordKnownComponent(that.expectedParent, component, that.expectedName); delete that.expectedName; delete that.expectedParent; } else { that.recordRoot(component); } }; that.clearComponent = function(component, name, child, options, noModTree) { options = options || {visited: {}, flat: true}; child = child || component[name]; fluid.visitComponentChildren(child, function(gchild, gchildname) { that.clearComponent(child, gchildname, null, options, noModTree); }, options); var path = that.idToPath[child.id]; delete that.idToPath[child.id]; delete that.pathToComponent[path]; if (!noModTree) { delete component[name]; } }; that.recordKnownComponent = function(parent, component, name) { var parentPath = that.idToPath[parent.id] || ""; var path = fluid.model.composePath(parentPath, name); recordComponent(component, path); }; return that; }; fluid.freeInstantiator = fluid.instantiator(true); // unsupported, non-API function fluid.argMapToDemands = function(argMap) { var togo = []; fluid.each(argMap, function(value, key) { togo[value] = "{" + key + "}"; }); return togo; }; // unsupported, non-API function fluid.makePassArgsSpec = function(initArgs) { return fluid.transform(initArgs, function(arg, index) { return "{arguments}." + index; }); }; function mergeToMergeAll(options) { if (options && options.mergeOptions) { options.mergeAllOptions = ["{options}"].concat(fluid.makeArray(options.mergeOptions)); } } function upgradeMergeOptions(demandspec) { mergeToMergeAll(demandspec); if (demandspec.mergeAllOptions) { if (demandspec.options) { fluid.fail("demandspec ", demandspec, " is invalid - cannot specify literal options together with mergeOptions or mergeAllOptions"); } demandspec.options = { mergeAllOptions: demandspec.mergeAllOptions }; } if (demandspec.options) { delete demandspec.options.mergeOptions; } } /** Given a concrete argument list and/or options, determine the final concrete * "invocation specification" which is coded by the supplied demandspec in the * environment "thatStack" - the return is a package of concrete global function name * and argument list which is suitable to be executed directly by fluid.invokeGlobalFunction. */ // unsupported, non-API function fluid.embodyDemands = function(instantiator, parentThat, demandspec, initArgs, options) { options = options || {}; upgradeMergeOptions(demandspec); var oldOptions = fluid.get(options, "componentRecord.options"); options.componentRecord = $.extend(true, {}, options.componentRecord, fluid.censorKeys(demandspec, ["args", "funcName", "registeredFrom"])); var mergeAllZero = fluid.get(options, "componentRecord.options.mergeAllOptions.0"); if (mergeAllZero === "{options}") { fluid.set(options, "componentRecord.options.mergeAllOptions.0", oldOptions); } var demands = $.makeArray(demandspec.args); var upDefaults = fluid.defaults(demandspec.funcName); // I can SEE into TIME!! var argMap = upDefaults? upDefaults.argumentMap : null; var inferMap = false; if (!argMap && (upDefaults || (options && options.componentRecord)) && !options.passArgs) { inferMap = true; // infer that it must be a little component if we have any reason to believe it is a component if (demands.length < 2) { argMap = fluid.rawDefaults("fluid.littleComponent").argumentMap; } else { argMap = {options: demands.length - 1}; // wild guess in the old style } } options = options || {}; if (demands.length === 0) { if (options.componentRecord && argMap) { demands = fluid.argMapToDemands(argMap); } else if (options.passArgs) { demands = fluid.makePassArgsSpec(initArgs); } } var localRecord = $.extend({"arguments": initArgs}, fluid.censorKeys(options.componentRecord, ["type"])); fluid.each(argMap, function(index, name) { if (initArgs.length > 0) { localRecord[name] = localRecord["arguments"][index]; } if (demandspec[name] !== undefined && localRecord[name] === undefined) { localRecord[name] = demandspec[name]; } }); mergeToMergeAll(localRecord.options); mergeToMergeAll(argMap && demands[argMap.options]); var upstreamLocalRecord = $.extend({}, localRecord); if (options.componentRecord.options !== undefined) { upstreamLocalRecord.options = options.componentRecord.options; } var expandOptions = makeStackResolverOptions(instantiator, parentThat, localRecord); var args = []; if (demands) { for (var i = 0; i < demands.length; ++i) { var arg = demands[i]; // Weak detection since we cannot guarantee this material has not been copied if (fluid.isMarker(arg) && arg.value === fluid.COMPONENT_OPTIONS.value) { arg = "{options}"; // Backwards compatibility for non-users of GRADES - last-ditch chance to correct the inference if (inferMap) { argMap = {options: i}; } } if (typeof(arg) === "string") { if (arg.charAt(0) === "@") { var argpos = arg.substring(1); arg = "{arguments}." + argpos; } } if (!argMap || argMap.options !== i) { // defer expansion required if it is non-pseudoarguments demands and this argument *is* the options args[i] = fluid.expander.expandLight(arg, expandOptions); } else { // It is the component options if (arg && typeof(arg) === "object" && !arg.targetTypeName) { arg.targetTypeName = demandspec.funcName; } // ensure to copy the arg since it is an alias of the demand block material (FLUID-4223) // and will be destructively expanded args[i] = {marker: fluid.EXPAND, value: fluid.copy(arg), localRecord: upstreamLocalRecord}; } if (args[i] && fluid.isMarker(args[i].marker, fluid.EXPAND_NOW)) { args[i] = fluid.expander.expandLight(args[i].value, expandOptions); } } } else { args = initArgs? initArgs : []; } var togo = { args: args, funcName: demandspec.funcName }; return togo; }; var aliasTable = {}; fluid.alias = function(demandingName, aliasName) { if (aliasName) { aliasTable[demandingName] = aliasName; } else { return aliasTable[demandingName]; } }; var dependentStore = {}; function searchDemands(demandingName, contextNames) { var exist = dependentStore[demandingName] || []; outer: for (var i = 0; i < exist.length; ++i) { var rec = exist[i]; for (var j = 0; j < contextNames.length; ++j) { if (rec.contexts[j] !== contextNames[j]) { continue outer; } } return rec.spec; // jslint:ok } } fluid.demands = function(demandingName, contextName, spec) { var contextNames = $.makeArray(contextName).sort(); if (!spec) { return searchDemands(demandingName, contextNames); } else if (spec.length) { spec = {args: spec}; } if (fluid.getCallerInfo) { var callerInfo = fluid.getCallerInfo(5); if (callerInfo) { spec.registeredFrom = callerInfo; } } var exist = dependentStore[demandingName]; if (!exist) { exist = []; dependentStore[demandingName] = exist; } exist.push({contexts: contextNames, spec: spec}); }; // unsupported, non-API function fluid.compareDemands = function(speca, specb) { var p1 = speca.uncess - specb.uncess; return p1 === 0? specb.intersect - speca.intersect : p1; }; // unsupported, non-API function fluid.isDemandLogging = function(demandingNames) { return fluid.isLogging() && demandingNames[0] !== "fluid.threadLocal"; }; // unsupported, non-API function fluid.locateAllDemands = function(instantiator, parentThat, demandingNames) { var demandLogging = fluid.isDemandLogging(demandingNames); if (demandLogging) { fluid.log("Resolving demands for function names ", demandingNames, " in context of " + (parentThat? "component " + parentThat.typeName : "no component")); } var contextNames = {}; var visited = []; var thatStack = instantiator.getFullStack(parentThat); visitComponents(thatStack, function(component, xname, options, up, down) { contextNames[component.typeName] = true; visited.push(component); }); if (demandLogging) { fluid.log("Components in scope for resolution:\n" + fluid.dumpThatStack(visited, instantiator)); } var matches = []; for (var i = 0; i < demandingNames.length; ++i) { var rec = dependentStore[demandingNames[i]] || []; for (var j = 0; j < rec.length; ++j) { var spec = rec[j]; var record = {spec: spec, intersect: 0, uncess: 0}; for (var k = 0; k < spec.contexts.length; ++k) { record[contextNames[spec.contexts[k]]? "intersect" : "uncess"] += 2; } if (spec.contexts.length === 0) { // allow weak priority for contextless matches record.intersect++; } // TODO: Potentially more subtle algorithm here - also ambiguity reports matches.push(record); } } matches.sort(fluid.compareDemands); return matches; }; // unsupported, non-API function fluid.locateDemands = function(instantiator, parentThat, demandingNames) { var matches = fluid.locateAllDemands(instantiator, parentThat, demandingNames); var demandspec = matches.length === 0 || matches[0].intersect === 0? null : matches[0].spec.spec; if (fluid.isDemandLogging(demandingNames)) { if (demandspec) { fluid.log("Located " + matches.length + " potential match" + (matches.length === 1? "" : "es") + ", selected best match with " + matches[0].intersect + " matched context names: ", demandspec); } else { fluid.log("No matches found for demands, using direct implementation"); } } return demandspec; }; /** Determine the appropriate demand specification held in the fluid.demands environment * relative to "thatStack" for the function name(s) funcNames. */ // unsupported, non-API function fluid.determineDemands = function (instantiator, parentThat, funcNames) { funcNames = $.makeArray(funcNames); var newFuncName = funcNames[0]; var demandspec = fluid.locateDemands(instantiator, parentThat, funcNames) || {}; if (demandspec.funcName) { newFuncName = demandspec.funcName; } var aliasTo = fluid.alias(newFuncName); if (aliasTo) { newFuncName = aliasTo; fluid.log("Following redirect from function name " + newFuncName + " to " + aliasTo); var demandspec2 = fluid.locateDemands(instantiator, parentThat, [aliasTo]); if (demandspec2) { fluid.each(demandspec2, function(value, key) { if (localRecordExpected.test(key)) { fluid.fail("Error in demands block ", demandspec2, " - content with key \"" + key + "\" is not supported since this demands block was resolved via an alias from \"" + newFuncName + "\""); } }); if (demandspec2.funcName) { newFuncName = demandspec2.funcName; fluid.log("Followed final inner demands to function name \"" + newFuncName + "\""); } } } return fluid.merge(null, {funcName: newFuncName, args: fluid.makeArray(demandspec.args)}, fluid.censorKeys(demandspec, ["funcName", "args"])); }; // unsupported, non-API function fluid.resolveDemands = function(instantiator, parentThat, funcNames, initArgs, options) { var demandspec = fluid.determineDemands(instantiator, parentThat, funcNames); return fluid.embodyDemands(instantiator, parentThat, demandspec, initArgs, options); }; // TODO: make a *slightly* more performant version of fluid.invoke that perhaps caches the demands // after the first successful invocation fluid.invoke = function(functionName, args, that, environment) { args = fluid.makeArray(args); return fluid.withInstantiator(that, function(instantiator) { var invokeSpec = fluid.resolveDemands(instantiator, that, functionName, args, {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }); }; fluid.invoke = fluid.wrapActivity(fluid.invoke, [" while invoking function with name \"", "arguments.0", "\" from component", "arguments.2"]); /** Make a function which performs only "static redispatch" of the supplied function name - * that is, taking only account of the contents of the "static environment". Since the static * environment is assumed to be constant, the dispatch of the call will be evaluated at the * time this call is made, as an optimisation. */ fluid.makeFreeInvoker = function(functionName, environment) { var demandSpec = fluid.determineDemands(fluid.freeInstantiator, null, functionName); return function() { var invokeSpec = fluid.embodyDemands(fluid.freeInstantiator, null, demandSpec, arguments, {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }; }; fluid.makeInvoker = function(instantiator, that, demandspec, functionName, environment) { demandspec = demandspec || fluid.determineDemands(instantiator, that, functionName); return function() { var args = arguments; return fluid.pushActivity(function() { var invokeSpec = fluid.embodyDemands(instantiator, that, demandspec, args, {passArgs: true}); return fluid.invokeGlobalFunction(invokeSpec.funcName, invokeSpec.args, environment); }, [" while invoking invoker with name " + functionName + " on component", that]); }; }; // unsupported, non-API function fluid.event.dispatchListener = function(instantiator, that, listener, eventName, eventSpec) { return function() { var demandspec = fluid.determineDemands(instantiator, that, eventName); if (demandspec.args.length === 0 && eventSpec.args) { demandspec.args = eventSpec.args; } var resolved = fluid.embodyDemands(instantiator, that, demandspec, arguments, {passArgs: true, componentOptions: eventSpec}); listener.apply(null, resolved.args); }; }; // unsupported, non-API function fluid.event.resolveEvent = function(that, eventName, eventSpec) { return fluid.withInstantiator(that, function(instantiator) { if (typeof(eventSpec) === "string") { var firer = fluid.expandOptions(eventSpec, that); if (!firer) { fluid.fail("Error in fluid.event.resolveEvent - context path " + eventSpec + " could not be looked up to a valid event firer"); } return firer; } else { var event = eventSpec.event; var origin; if (!event) { fluid.fail("Event specification for event with name " + eventName + " does not include a base event specification"); } if (event.charAt(0) === "{") { origin = fluid.expandOptions(event, that); } else { origin = that.events[event]; } if (!origin) { fluid.fail("Error in event specification - could not resolve base event reference " + event + " to an event firer"); } var firer = {}; // jslint:ok - already defined fluid.each(["fire", "removeListener"], function(method) { firer[method] = function() {origin[method].apply(null, arguments);}; }); firer.addListener = function(listener, namespace, predicate, priority) { origin.addListener(fluid.event.dispatchListener(instantiator, that, listener, eventName, eventSpec), namespace, predicate, priority); }; return firer; } }); }; fluid.registerNamespace("fluid.expander"); /** rescue that part of a component's options which should not be subject to * options expansion via IoC - this initially consists of "components" and "mergePolicy" * but will be expanded by the set of paths specified as "noexpand" within "mergePolicy" */ // unsupported, non-API function fluid.expander.preserveFromExpansion = function(options) { var preserve = {}; var preserveList = fluid.arrayToHash(["mergePolicy", "mergeAllOptions", "components", "invokers", "events", "listeners", "transformOptions"]); fluid.each(options.mergePolicy, function(value, key) { if (fluid.mergePolicyIs(value, "noexpand")) { preserveList[key] = true; } }); fluid.each(preserveList, function(xvalue, path) { var pen = fluid.model.getPenultimate(options, path); var value = pen.root[pen.last]; delete pen.root[pen.last]; fluid.set(preserve, path, value); }); return { restore: function(target) { fluid.each(preserveList, function(xvalue, path) { var preserved = fluid.get(preserve, path); if (preserved !== undefined) { fluid.set(target, path, preserved); } }); } }; }; /** Expand a set of component options with respect to a set of "expanders" (essentially only * deferredCall) - This substitution is destructive since it is assumed that the options are already "live" as the * result of environmental substitutions. Note that options contained inside "components" will not be expanded * by this call directly to avoid linearly increasing expansion depth if this call is occuring as a result of * "initDependents" */ // TODO: This needs to be integrated with "embodyDemands" above which makes a call to "resolveEnvironment" directly // but with very similarly derived options (makeStackResolverOptions) fluid.expandOptions = function(args, that, localRecord, outerExpandOptions) { if (!args) { return args; } return fluid.withInstantiator(that, function(instantiator) { //fluid.log("expandOptions for " + that.typeName + " executing with instantiator " + instantiator.id); var expandOptions = makeStackResolverOptions(instantiator, that, localRecord, outerExpandOptions); expandOptions.noCopy = true; // It is still possible a model may be fetched even though it is preserved var pres; if (!fluid.isArrayable(args) && !fluid.isPrimitive(args)) { pres = fluid.expander.preserveFromExpansion(args); } var expanded = fluid.expander.expandLight(args, expandOptions); if (pres) { pres.restore(expanded); } return expanded; }); }; // unsupported, non-API function fluid.locateTransformationRecord = function(that) { return fluid.withInstantiator(that, function(instantiator) { var matches = fluid.locateAllDemands(instantiator, that, ["fluid.transformOptions"]); return fluid.find(matches, function(match) { return match.uncess === 0 && fluid.contains(match.spec.contexts, that.typeName)? match.spec.spec : undefined; }); }); }; // fluid.hashToArray = function(hash) { var togo = []; fluid.each(hash, function(value, key) { togo.push(key); }); return togo; }; // unsupported, non-API function fluid.localRecordExpected = ["type", "options", "arguments", "mergeOptions", "mergeAllOptions", "createOnEvent", "priority"]; // unsupported, non-API function fluid.checkComponentRecord = function(defaults, localRecord) { var expected = fluid.arrayToHash(fluid.localRecordExpected); fluid.each(defaults.argumentMap, function(value, key) { expected[key] = true; }); fluid.each(localRecord, function(value, key) { if (!expected[key]) { fluid.fail("Probable error in subcomponent record - key \"" + key + "\" found, where the only legal options are " + fluid.hashToArray(expected).join(", ")); } }); }; // unsupported, non-API function fluid.expandComponentOptions = function(defaults, userOptions, that) { if (userOptions && userOptions.localRecord) { fluid.checkComponentRecord(defaults, userOptions.localRecord); } defaults = fluid.expandOptions(fluid.copy(defaults), that); var localRecord = {}; if (userOptions && userOptions.marker === fluid.EXPAND) { // TODO: Somewhat perplexing... the local record itself, by any route we could get here, consists of unexpanded // material taken from "componentOptions" var localOptions = fluid.get(userOptions, "localRecord.options"); if (localOptions) { if (defaults && defaults.mergePolicy) { localOptions.mergePolicy = defaults.mergePolicy; } localRecord.options = fluid.expandOptions(localOptions, that); } localRecord["arguments"] = fluid.get(userOptions, "localRecord.arguments"); var toExpand = userOptions.value; userOptions = fluid.expandOptions(toExpand, that, localRecord, {direct: true}); } localRecord.directOptions = userOptions; if (!localRecord.options) { // Catch the case where there is no demands block and everything is in the subcomponent record - // in this case, embodyDemands will not construct a localRecord and what the user refers to by "options" // is really what we properly call "directOptions". localRecord.options = userOptions; } var mergeOptions = (userOptions && userOptions.mergeAllOptions) || ["{directOptions}"]; var togo = fluid.transform(mergeOptions, function(path) { // Avoid use of expandOptions in simple case to avoid infinite recursion when constructing instantiator return path === "{directOptions}"? localRecord.directOptions : fluid.expandOptions(path, that, localRecord, {direct: true}); }); var transRec = fluid.locateTransformationRecord(that); if (transRec) { togo[0].transformOptions = transRec.options; } return [defaults].concat(togo); }; fluid.expandComponentOptions = fluid.wrapActivity(fluid.expandComponentOptions, [" while expanding component options ", "arguments.1.value", " with record ", "arguments.1", " for component ", "arguments.2"]); // The case without the instantiator is from the ginger strategy - this logic is still a little ragged fluid.initDependent = function(that, name, userInstantiator, directArgs) { if (!that || that[name]) { return; } fluid.log("Beginning instantiation of component with name \"" + name + "\" as child of " + fluid.dumpThat(that)); directArgs = directArgs || []; var root = fluid.threadLocal(); if (userInstantiator) { var existing = root["fluid.instantiator"]; if (existing && existing !== userInstantiator) { fluid.fail("Error in initDependent: user instantiator supplied with id " + userInstantiator.id + " which differs from that for currently active instantiation with id " + existing.id); } else { root["fluid.instantiator"] = userInstantiator; // fluid.log("*** initDependent for " + that.typeName + " member " + name + " was supplied USER instantiator with id " + userInstantiator.id + " - STORED"); } } var component = that.options.components[name]; fluid.withInstantiator(that, function(instantiator) { if (typeof(component) === "string") { that[name] = fluid.expandOptions([component], that)[0]; // TODO: expose more sensible semantic for expandOptions } else if (component.type) { var invokeSpec = fluid.resolveDemands(instantiator, that, [component.type, name], directArgs, {componentRecord: component}); instantiator.pushUpcomingInstantiation(that, name); fluid.tryCatch(function() { that[inCreationMarker] = true; var instance = fluid.initSubcomponentImpl(that, {type: invokeSpec.funcName}, invokeSpec.args); // The existing instantiator record will be provisional, adjust it to take account of the true return // TODO: Instantiator contents are generally extremely incomplete var path = fluid.composePath(instantiator.idToPath[that.id] || "", name); var existing = instantiator.pathToComponent[path]; if (existing && existing !== instance) { instantiator.clearComponent(that, name, existing, null, true); } if (instance && instance.typeName && instance.id && instance !== existing) { instantiator.recordKnownComponent(that, instance, name); } that[name] = instance; }, null, function() { delete that[inCreationMarker]; instantiator.pushUpcomingInstantiation(); }); } else { that[name] = component; } }, [" while instantiating dependent component with name \"" + name + "\" with record ", component, " as child of ", that]); fluid.log("Finished instantiation of component with name \"" + name + "\" as child of " + fluid.dumpThat(that)); }; // NON-API function // This function is stateful and MUST NOT be called by client code fluid.withInstantiator = function(that, func, message) { var root = fluid.threadLocal(); var instantiator = root["fluid.instantiator"]; if (!instantiator) { instantiator = root["fluid.instantiator"] = fluid.instantiator(); //fluid.log("Created new instantiator with id " + instantiator.id + " in order to operate on component " + typeName); } return fluid.pushActivity(function() { return fluid.tryCatch(function() { if (that) { instantiator.recordComponent(that); } instantiator.stack(1); //fluid.log("Instantiator stack +1 to " + instantiator.stackCount + " for " + typeName); return func(instantiator); }, null, function() { var count = instantiator.stack(-1); //fluid.log("Instantiator stack -1 to " + instantiator.stackCount + " for " + typeName); if (count === 0) { //fluid.log("Clearing instantiator with id " + instantiator.id + " from threadLocal for end of " + typeName); delete root["fluid.instantiator"]; } }); }, message); }; // unsupported, non-API function fluid.bindDeferredComponent = function(that, componentName, component, instantiator) { var events = fluid.makeArray(component.createOnEvent); fluid.each(events, function(eventName) { that.events[eventName].addListener(function() { if (that[componentName]) { instantiator.clearComponent(that, componentName); } fluid.initDependent(that, componentName, instantiator); }, null, null, component.priority); }); }; // unsupported, non-API function fluid.priorityForComponent = function(component) { return component.priority? component.priority : (component.type === "fluid.typeFount" || fluid.hasGrade(fluid.defaults(component.type), "fluid.typeFount"))? "first" : undefined; }; fluid.initDependents = function(that) { var options = that.options; var components = options.components || {}; var componentSort = {}; fluid.withInstantiator(that, function(instantiator) { fluid.each(components, function(component, name) { if (!component.createOnEvent) { var priority = fluid.priorityForComponent(component); componentSort[name] = {key: name, priority: fluid.event.mapPriority(priority, 0)}; } else { fluid.bindDeferredComponent(that, name, component, instantiator); } }); var componentList = fluid.event.sortListeners(componentSort); fluid.each(componentList, function(entry) { fluid.initDependent(that, entry.key); }); var invokers = options.invokers || {}; for (var name in invokers) { var invokerec = invokers[name]; var funcName = typeof(invokerec) === "string"? invokerec : null; that[name] = fluid.withInstantiator(that, function(instantiator) { fluid.log("Beginning instantiation of invoker with name \"" + name + "\" as child of " + fluid.dumpThat(that)); return fluid.makeInvoker(instantiator, that, funcName? null : invokerec, funcName); }, [" while instantiating invoker with name \"" + name + "\" with record ", invokerec, " as child of ", that]); // jslint:ok fluid.log("Finished instantiation of invoker with name \"" + name + "\" as child of " + fluid.dumpThat(that)); } }); }; fluid.staticEnvironment = fluid.typeTag("fluid.staticEnvironment"); fluid.staticEnvironment.environmentClass = fluid.typeTag("fluid.browser"); // fluid.environmentalRoot.environmentClass = fluid.typeTag("fluid.rhino"); fluid.demands("fluid.threadLocal", "fluid.browser", {funcName: "fluid.singleThreadLocal"}); var singleThreadLocal = fluid.typeTag("fluid.dynamicEnvironment"); fluid.singleThreadLocal = function() { return singleThreadLocal; }; fluid.threadLocal = function() { // quick implementation since this is not very dynamic, a hazard to debugging, and used frequently within IoC itself var demands = fluid.locateDemands(fluid.freeInstantiator, null, ["fluid.threadLocal"]); return fluid.invokeGlobalFunction(demands.funcName, arguments); }; function applyLocalChange(applier, type, path, value) { var change = { type: type, path: path, value: value }; applier.fireChangeRequest(change); } // unsupported, non-API function fluid.withEnvironment = function(envAdd, func, prefix) { prefix = prefix || ""; var root = fluid.threadLocal(); var applier = fluid.makeChangeApplier(root, {thin: true}); return fluid.tryCatch(function() { for (var key in envAdd) { applyLocalChange(applier, "ADD", fluid.model.composePath(prefix, key), envAdd[key]); } $.extend(root, envAdd); return func(); }, null, function() { for (var key in envAdd) { // jslint:ok duplicate "value" // TODO: This could be much better through i) refactoring the ChangeApplier so we could naturally use "rollback" semantics // and/or implementing this material using some form of "prototype chain" applyLocalChange(applier, "DELETE", fluid.model.composePath(prefix, key)); } }); }; // unsupported, non-API function fluid.makeEnvironmentFetcher = function(prefix, directModel) { return function(parsed) { var env = fluid.get(fluid.threadLocal(), prefix); return fluid.fetchContextReference(parsed, directModel, env); }; }; // unsupported, non-API function fluid.extractEL = function(string, options) { if (options.ELstyle === "ALL") { return string; } else if (options.ELstyle.length === 1) { if (string.charAt(0) === options.ELstyle) { return string.substring(1); } } else if (options.ELstyle === "${}") { var i1 = string.indexOf("${"); var i2 = string.lastIndexOf("}"); if (i1 === 0 && i2 !== -1) { return string.substring(2, i2); } } }; // unsupported, non-API function fluid.extractELWithContext = function(string, options) { var EL = fluid.extractEL(string, options); if (EL && EL.charAt(0) === "{") { return fluid.parseContextReference(EL, 0); } return EL? {path: EL} : EL; }; fluid.parseContextReference = function(reference, index, delimiter) { var endcpos = reference.indexOf("}", index + 1); if (endcpos === -1) { fluid.fail("Cannot parse context reference \"" + reference + "\": Malformed context reference without }"); } var context = reference.substring(index + 1, endcpos); var endpos = delimiter? reference.indexOf(delimiter, endcpos + 1) : reference.length; var path = reference.substring(endcpos + 1, endpos); if (path.charAt(0) === ".") { path = path.substring(1); } return {context: context, path: path, endpos: endpos}; }; fluid.renderContextReference = function(parsed) { return "{" + parsed.context + "}" + parsed.path; }; fluid.fetchContextReference = function(parsed, directModel, env) { var base = parsed.context? env[parsed.context] : directModel; if (!base) { return base; } return fluid.get(base, parsed.path); }; // unsupported, non-API function fluid.resolveContextValue = function(string, options) { if (options.bareContextRefs && string.charAt(0) === "{") { var parsed = fluid.parseContextReference(string, 0); return options.fetcher(parsed); } else if (options.ELstyle && options.ELstyle !== "${}") { var parsed = fluid.extractELWithContext(string, options); // jslint:ok if (parsed) { return options.fetcher(parsed); } } while (typeof(string) === "string") { var i1 = string.indexOf("${"); var i2 = string.indexOf("}", i1 + 2); if (i1 !== -1 && i2 !== -1) { var parsed; // jslint:ok if (string.charAt(i1 + 2) === "{") { parsed = fluid.parseContextReference(string, i1 + 2, "}"); i2 = parsed.endpos; } else { parsed = {path: string.substring(i1 + 2, i2)}; } var subs = options.fetcher(parsed); var all = (i1 === 0 && i2 === string.length - 1); // TODO: test case for all undefined substitution if (subs === undefined || subs === null) { return subs; } string = all? subs : string.substring(0, i1) + subs + string.substring(i2 + 1); } else { break; } } return string; }; fluid.resolveContextValue = fluid.wrapActivity(fluid.resolveContextValue, [" while resolving context value ", "arguments.0"]); function resolveEnvironmentImpl(obj, options) { fluid.guardCircularity(options.seenIds, obj, "expansion", " - please ensure options are not circularly connected, or protect from expansion using the \"noexpand\" policy or expander"); function recurse(arg) { return resolveEnvironmentImpl(arg, options); } if (typeof(obj) === "string" && !options.noValue) { return fluid.resolveContextValue(obj, options); } else if (fluid.isPrimitive(obj) || obj.nodeType !== undefined || obj.jquery) { return obj; } else if (options.filter) { return options.filter(obj, recurse, options); } else { return (options.noCopy? fluid.each : fluid.transform)(obj, function(value, key) { return resolveEnvironmentImpl(value, options); }); } } fluid.defaults("fluid.resolveEnvironment", { ELstyle: "${}", seenIds: {}, bareContextRefs: true }); fluid.resolveEnvironment = function(obj, options) { // Don't create a component here since this function is itself used in the // component expansion pathway - avoid all expansion in any case to head off FLUID-4301 options = $.extend(true, {}, fluid.rawDefaults("fluid.resolveEnvironment"), options); return resolveEnvironmentImpl(obj, options); }; /** "light" expanders, starting with support functions for the "deferredFetcher" expander **/ fluid.expander.deferredCall = function(target, source, recurse) { var expander = source.expander; var args = (!expander.args || fluid.isArrayable(expander.args))? expander.args : $.makeArray(expander.args); args = recurse(args); return fluid.invokeGlobalFunction(expander.func, args); }; fluid.deferredCall = fluid.expander.deferredCall; // put in top namespace for convenience fluid.deferredInvokeCall = function(target, source, recurse) { var expander = source.expander; var args = (!expander.args || fluid.isArrayable(expander.args))? expander.args : $.makeArray(expander.args); args = recurse(args); return fluid.invoke(expander.func, args); }; // The "noexpand" expander which simply unwraps one level of expansion and ceases. fluid.expander.noexpand = function(target, source) { return $.extend(target, source.expander.tree); }; fluid.noexpand = fluid.expander.noexpand; // TODO: check naming and namespacing // unsupported, non-API function fluid.expander.lightFilter = function (obj, recurse, options) { var togo; if (fluid.isArrayable(obj)) { togo = options.noCopy? obj : []; fluid.each(obj, function(value, key) {togo[key] = recurse(value);}); } else { togo = options.noCopy? obj : {}; for (var key in obj) { var value = obj[key]; var expander; if (key === "expander" && !(options.expandOnly && options.expandOnly[value.type])) { expander = fluid.getGlobalValue(value.type); if (expander) { return expander.call(null, togo, obj, recurse, options); } } if (key !== "expander" || !expander) { togo[key] = recurse(value); } } } return options.noCopy? obj : togo; }; // unsupported, non-API function fluid.expander.expandLight = function (source, expandOptions) { var options = $.extend({}, expandOptions); options.filter = fluid.expander.lightFilter; return fluid.resolveEnvironment(source, options); }; })(jQuery, fluid_1_4);
gregrgay/booking
Web/scripts/infusion/framework/core/js/FluidIoC.js
JavaScript
gpl-3.0
54,696
<?php namespace calavera\customerBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Bugs * * @ORM\Table(name="bugs") * @ORM\Entity */ class Bugs { /** * @var string * * @ORM\Column(name="id", type="string", length=36, nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=true) */ private $name; /** * @var \DateTime * * @ORM\Column(name="date_entered", type="datetime", nullable=true) */ private $dateEntered; /** * @var \DateTime * * @ORM\Column(name="date_modified", type="datetime", nullable=true) */ private $dateModified; /** * @var string * * @ORM\Column(name="modified_user_id", type="string", length=36, nullable=true) */ private $modifiedUserId; /** * @var string * * @ORM\Column(name="created_by", type="string", length=36, nullable=true) */ private $createdBy; /** * @var string * * @ORM\Column(name="description", type="text", nullable=true) */ private $description; /** * @var boolean * * @ORM\Column(name="deleted", type="boolean", nullable=true) */ private $deleted; /** * @var string * * @ORM\Column(name="assigned_user_id", type="string", length=36, nullable=true) */ private $assignedUserId; /** * @var integer * * @ORM\Column(name="bug_number", type="integer", nullable=false) */ private $bugNumber; /** * @var string * * @ORM\Column(name="type", type="string", length=255, nullable=true) */ private $type; /** * @var string * * @ORM\Column(name="status", type="string", length=100, nullable=true) */ private $status; /** * @var string * * @ORM\Column(name="priority", type="string", length=100, nullable=true) */ private $priority; /** * @var string * * @ORM\Column(name="resolution", type="string", length=255, nullable=true) */ private $resolution; /** * @var string * * @ORM\Column(name="work_log", type="text", nullable=true) */ private $workLog; /** * @var string * * @ORM\Column(name="found_in_release", type="string", length=255, nullable=true) */ private $foundInRelease; /** * @var string * * @ORM\Column(name="fixed_in_release", type="string", length=255, nullable=true) */ private $fixedInRelease; /** * @var string * * @ORM\Column(name="source", type="string", length=255, nullable=true) */ private $source; /** * @var string * * @ORM\Column(name="product_category", type="string", length=255, nullable=true) */ private $productCategory; /** * Set name * * @param string $name * @return Bugs */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } /** * Set dateEntered * * @param \DateTime $dateEntered * @return Bugs */ public function setDateEntered($dateEntered) { $this->dateEntered = $dateEntered; return $this; } /** * Get dateEntered * * @return \DateTime */ public function getDateEntered() { return $this->dateEntered; } /** * Set dateModified * * @param \DateTime $dateModified * @return Bugs */ public function setDateModified($dateModified) { $this->dateModified = $dateModified; return $this; } /** * Get dateModified * * @return \DateTime */ public function getDateModified() { return $this->dateModified; } /** * Set modifiedUserId * * @param string $modifiedUserId * @return Bugs */ public function setModifiedUserId($modifiedUserId) { $this->modifiedUserId = $modifiedUserId; return $this; } /** * Get modifiedUserId * * @return string */ public function getModifiedUserId() { return $this->modifiedUserId; } /** * Set createdBy * * @param string $createdBy * @return Bugs */ public function setCreatedBy($createdBy) { $this->createdBy = $createdBy; return $this; } /** * Get createdBy * * @return string */ public function getCreatedBy() { return $this->createdBy; } /** * Set description * * @param string $description * @return Bugs */ public function setDescription($description) { $this->description = $description; return $this; } /** * Get description * * @return string */ public function getDescription() { return $this->description; } /** * Set deleted * * @param boolean $deleted * @return Bugs */ public function setDeleted($deleted) { $this->deleted = $deleted; return $this; } /** * Get deleted * * @return boolean */ public function getDeleted() { return $this->deleted; } /** * Set assignedUserId * * @param string $assignedUserId * @return Bugs */ public function setAssignedUserId($assignedUserId) { $this->assignedUserId = $assignedUserId; return $this; } /** * Get assignedUserId * * @return string */ public function getAssignedUserId() { return $this->assignedUserId; } /** * Set bugNumber * * @param integer $bugNumber * @return Bugs */ public function setBugNumber($bugNumber) { $this->bugNumber = $bugNumber; return $this; } /** * Get bugNumber * * @return integer */ public function getBugNumber() { return $this->bugNumber; } /** * Set type * * @param string $type * @return Bugs */ public function setType($type) { $this->type = $type; return $this; } /** * Get type * * @return string */ public function getType() { return $this->type; } /** * Set status * * @param string $status * @return Bugs */ public function setStatus($status) { $this->status = $status; return $this; } /** * Get status * * @return string */ public function getStatus() { return $this->status; } /** * Set priority * * @param string $priority * @return Bugs */ public function setPriority($priority) { $this->priority = $priority; return $this; } /** * Get priority * * @return string */ public function getPriority() { return $this->priority; } /** * Set resolution * * @param string $resolution * @return Bugs */ public function setResolution($resolution) { $this->resolution = $resolution; return $this; } /** * Get resolution * * @return string */ public function getResolution() { return $this->resolution; } /** * Set workLog * * @param string $workLog * @return Bugs */ public function setWorkLog($workLog) { $this->workLog = $workLog; return $this; } /** * Get workLog * * @return string */ public function getWorkLog() { return $this->workLog; } /** * Set foundInRelease * * @param string $foundInRelease * @return Bugs */ public function setFoundInRelease($foundInRelease) { $this->foundInRelease = $foundInRelease; return $this; } /** * Get foundInRelease * * @return string */ public function getFoundInRelease() { return $this->foundInRelease; } /** * Set fixedInRelease * * @param string $fixedInRelease * @return Bugs */ public function setFixedInRelease($fixedInRelease) { $this->fixedInRelease = $fixedInRelease; return $this; } /** * Get fixedInRelease * * @return string */ public function getFixedInRelease() { return $this->fixedInRelease; } /** * Set source * * @param string $source * @return Bugs */ public function setSource($source) { $this->source = $source; return $this; } /** * Get source * * @return string */ public function getSource() { return $this->source; } /** * Set productCategory * * @param string $productCategory * @return Bugs */ public function setProductCategory($productCategory) { $this->productCategory = $productCategory; return $this; } /** * Get productCategory * * @return string */ public function getProductCategory() { return $this->productCategory; } /** * Get id * * @return string */ public function getId() { return $this->id; } }
uetiko/calaveraportal
src/calavera/customerBundle/Entity/Bugs.php
PHP
gpl-3.0
9,843
/* * This file is part of AlesharikWebServer. * * AlesharikWebServer 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. * * AlesharikWebServer 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 AlesharikWebServer. If not, see <http://www.gnu.org/licenses/>. * */ package com.alesharik.webserver.api.qt; import javax.annotation.Nonnull; import java.util.concurrent.atomic.AtomicInteger; public class QSize implements QSerializable { private final AtomicInteger width; private final AtomicInteger height; public QSize(int w, int h) { width = new AtomicInteger(w); height = new AtomicInteger(h); } public QSize() { width = new AtomicInteger(); height = new AtomicInteger(); } public void setWidth(int w) { width.set(w); } public void setHeight(int h) { height.set(h); } public int getWidth() { return width.get(); } public int getHeight() { return height.get(); } @Override public void write(@Nonnull QDataStream stream) { stream.writeInt(width.get()); stream.writeInt(height.get()); } @Override public void read(@Nonnull QDataStream stream) { width.set(stream.readInt()); height.set(stream.readInt()); } }
alesharik/AlesharikWebServer
api/src/com/alesharik/webserver/api/qt/QSize.java
Java
gpl-3.0
1,790
// HashCalculator // Tool for calculating and comparing file hash sums, e.g. sha1 // Copyright(C) 2016 Anthony Fung // 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/>. using System; using HashCalculator.Interface; namespace HashCalculatorTests.TestingInfrastructure { /// <summary> /// Synchronously invokes the method argument. Used in unit tests, where /// Application.Current.Dispatcher.BeginInvoke(method) would not be suitable /// </summary> internal class TestingDispatcherService : IDispatcherService { public void BeginInvoke(Action method) { method(); } } }
Ant-f/HashCalculator
HashCalculatorTests/TestingInfrastructure/TestingDispatcherService.cs
C#
gpl-3.0
1,224
package com.jzctb.mis.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import org.apache.log4j.Logger; // 编码过滤器 public class EncodingFilter implements Filter { private String charset = null; private boolean ignore = false; public void init(FilterConfig filterConfig) throws ServletException { String charset = filterConfig.getInitParameter("charset"); String ignore = filterConfig.getInitParameter("ignore"); if (this.charset == null) this.charset = charset; if ("true".equals(ignore)) { this.ignore = true; } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (!ignore) { request.setCharacterEncoding(charset); response.setCharacterEncoding(charset); // response.setContentType("text/html; charset="+charset); } chain.doFilter(request, response); } public void destroy() { charset = null; ignore = false; } public static Logger logger = Logger.getLogger(EncodingFilter.class); }
yanxiaosheng/mis
src/com/jzctb/mis/filter/EncodingFilter.java
Java
gpl-3.0
1,276
/* -*- tab-width: 4 -*- * * Electric(tm) VLSI Design System * * File: Nand2LT_sy.java * * Copyright (c) 2003 Sun Microsystems and Static Free Software * * Electric(tm) 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. * * Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to * the Free Software Foundation, Inc., 59 Temple Place, Suite 330, * Boston, Mass 02111-1307, USA. */ package com.sun.electric.tool.generator.layout.gates; import com.sun.electric.database.hierarchy.Cell; import com.sun.electric.database.prototype.PortCharacteristic; import com.sun.electric.tool.generator.layout.FoldedMos; import com.sun.electric.tool.generator.layout.FoldedNmos; import com.sun.electric.tool.generator.layout.FoldedPmos; import com.sun.electric.tool.generator.layout.FoldsAndWidth; import com.sun.electric.tool.generator.layout.LayoutLib; import com.sun.electric.tool.generator.layout.StdCellParams; import com.sun.electric.tool.generator.layout.TechType; import com.sun.electric.tool.generator.layout.TrackRouter; import com.sun.electric.tool.generator.layout.TrackRouterH; import com.sun.electric.tool.Job; public class Nand2LT_sy { private static final double nmosTop = -9.0; private static final double pmosBot = 9.0; private static final double wellOverhangDiff = 6; private static final double inbY = -4.0; private static final double inaY = 4.0; private static final double outHiY = 11.0; private static final double outLoY = -11.0; private static void error(boolean pred, String msg) { Job.error(pred, msg); } public static Cell makePart(double sz, StdCellParams stdCell) { TechType tech = stdCell.getTechType(); sz = stdCell.roundSize(sz); String nm = "nand2LT_sy"; sz = stdCell.checkMinStrength(sz, 1, nm); // Compute number of folds and width for PMOS double spaceAvail = stdCell.getCellTop() - wellOverhangDiff - pmosBot; double totWid = sz * 3 * 2; // 2 independent pullups FoldsAndWidth fwP = stdCell.calcFoldsAndWidth(spaceAvail, totWid, 2); error(fwP==null, "can't make nand2LT_sy this small: "+sz); // Compute number of folds and width for NMOS int nbStacked = 2; spaceAvail = nmosTop - (stdCell.getCellBot()+wellOverhangDiff); totWid = sz * 3 * nbStacked; FoldsAndWidth fwN = stdCell.calcFoldsAndWidth(spaceAvail, totWid, 2); error(fwN==null, "can't make nand2LT_sy this small: "+sz); // create NAND Part Cell nand = stdCell.findPart(nm, sz); if (nand!=null) return nand; nand = stdCell.newPart(nm, sz); // leave vertical m1 track for inB double inbX = 1.5 + 2; // m1_m1_sp/2 + m1_wid/2 double mosX = inbX + 2 + 3 + 2; // m1_wid/2 + m1_m1_sp + diffCont_wid/2 // NMOS double nmosY = nmosTop - fwN.physWid/2; FoldedMos nmos = new FoldedNmos(mosX, nmosY, fwN.nbFolds, nbStacked, fwN.gateWid, nand, tech); // PMOS Create multiple PMOS ORs. Align source of each OR with // every other source of NMOS double pmosY = pmosBot + fwP.physWid/2; FoldedMos[] pmoss = new FoldedMos[fwP.nbFolds/2]; for (int i=0; i<pmoss.length; i++) { double pmosPitch = 26; double pmosX = mosX + pmosPitch * i; pmoss[i] = new FoldedPmos(pmosX, pmosY, 2, 1, fwP.gateWid, nand, tech); } stdCell.fillDiffAndSelectNotches(pmoss, true); // create vdd and gnd exports and connect to MOS source/drains stdCell.wireVddGnd(nmos, StdCellParams.EVEN, nand); stdCell.wireVddGnd(pmoss, StdCellParams.EVEN, nand); // Nand input B LayoutLib.newExport(nand, "inb", PortCharacteristic.IN, tech.m1(), 4, inbX, inbY); TrackRouter inB = new TrackRouterH(tech.m1(), 3, inbY, tech, nand); inB.connect(nand.findExport("inb")); for (int i=0; i<nmos.nbGates(); i+=2) { inB.connect(nmos.getGate(i, 'T'), -1.5); } for (int i=0; i<pmoss.length; i++) { inB.connect(pmoss[i].getGate(0, 'B'), -1.5); } // Nand input A // NAND input in1 // m1_wid + m1_space + m1_wid/2 double inaX = StdCellParams.getRightDiffX(pmoss, nmos) + 2 + 3 + 2; LayoutLib.newExport(nand, "ina", PortCharacteristic.IN, tech.m1(), 4, inaX, inaY); TrackRouter ina = new TrackRouterH(tech.m1(), 3, inaY, tech, nand); ina.connect(nand.findExport("ina")); for (int i=1; i<nmos.nbGates(); i+=2) { ina.connect(nmos.getGate(i, 'T'), 1.5); } for (int i=0; i<pmoss.length; i++) { ina.connect(pmoss[i].getGate(1, 'B'), -1.5); } // Nand output double outX = inaX + 2 + 3 + 2; // m1_wid/2 + m1_sp + m1_wid/2 LayoutLib.newExport(nand, "out", PortCharacteristic.OUT, tech.m1(), 4, outX, outHiY); TrackRouter outHi = new TrackRouterH(tech.m2(), 4, outHiY, tech, nand); outHi.connect(nand.findExport("out")); for (int i=0; i<pmoss.length; i++) { outHi.connect(pmoss[i].getSrcDrn(1)); } TrackRouter outLo = new TrackRouterH(tech.m2(), 4, outLoY, tech, nand); outLo.connect(nand.findExport("out")); for (int i=1; i<nmos.nbSrcDrns(); i+=2) { outLo.connect(nmos.getSrcDrn(i)); } // add wells double wellMinX = 0; double wellMaxX = outX + 2 + 1.5; // m1_wid/2 + m1m1_space/2 stdCell.addNmosWell(wellMinX, wellMaxX, nand); stdCell.addPmosWell(wellMinX, wellMaxX, nand); // add essential bounds stdCell.addEssentialBounds(wellMinX, wellMaxX, nand); // perform Network Consistency Check stdCell.doNCC(nand, nm+"{sch}"); return nand; } }
imr/Electric8
com/sun/electric/tool/generator/layout/gates/Nand2LT_sy.java
Java
gpl-3.0
5,838
<?php // Heading $_['heading_title'] = 'Avez-vous oublié votre mot de passe ?'; // Text $_['text_account'] = 'Compte'; $_['text_forgotten'] = 'Mot de passe oublié'; $_['text_your_email'] = 'Votre adresse électronique'; $_['text_email'] = 'Saisissez l\'adresse électronique associée à votre compte. Cliquez sur soumettre pour que votre mot de passe vous soit envoyé par courrier électronique.'; $_['text_success'] = 'Succès: un nouveau mot de passe a été envoyé à votre adresse électronique.'; // Entry $_['entry_email'] = 'Adresse électronique'; // Error $_['error_email'] = 'Attention : cette adresse électronique n\'a pas été trouvée dans nos fichiers, veuillez essayer à nouveau !';
pedrocones/store
upload/catalog/language/fr-CA/account/forgotten.php
PHP
gpl-3.0
746
var searchData= [ ['emails_2ephp',['emails.php',['../emails_8php.html',1,'']]], ['emails_5flinks_2ephp',['emails_links.php',['../emails__links_8php.html',1,'']]] ];
labscoop/xortify
releases/XOOPS 2.6/4.14/docs/html/search/files_65.js
JavaScript
gpl-3.0
169
<?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateAnalyticsForumTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('analytics_forum', function(Blueprint $table) { $table->increments('id'); $table->integer('all_post'); $table->integer('cat1_post'); $table->integer('cat2_post'); $table->integer('cat3_post'); $table->integer('daily_post'); $table->integer('cat1_daily_post'); $table->integer('cat2_daily_post'); $table->integer('cat3_daily_post'); $table->integer('daily_male_post'); $table->integer('daily_female_post'); $table->timestamp('deleted_at')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('analytics_forum'); } }
Luxurioust/wizard
app/database/migrations/2014_12_16_194340_create_analytics_forum_table.php
PHP
gpl-3.0
1,086
/* * Copyright (c) 2019 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.magma; import java.lang.ref.WeakReference; import java.util.Collection; import java.util.LinkedHashSet; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import org.obiba.magma.concurrent.LockManager; import org.obiba.magma.support.Disposables; import org.obiba.magma.support.Initialisables; import org.obiba.magma.support.ValueTableReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; @SuppressWarnings( { "AssignmentToStaticFieldFromInstanceMethod", "UnusedDeclaration", "StaticMethodOnlyUsedInOneClass" }) public class MagmaEngine implements DatasourceRegistry { private final static Logger log = LoggerFactory.getLogger(MagmaEngine.class); /** * Keeps a reference on all singletons */ @SuppressWarnings("StaticNonFinalField") private static Set<Object> singletons; @Nullable @SuppressWarnings("StaticNonFinalField") private static MagmaEngine instance; private final ValueTypeFactory valueTypeFactory; private DatasourceRegistry datasourceRegistry = new DefaultDatasourceRegistry(); private final Set<MagmaEngineExtension> extensions = Sets.newHashSet(); private final LockManager lockManager = new LockManager(); public MagmaEngine() { if(instance != null) { throw new IllegalStateException( "MagmaEngine already instantiated. Only one instance of MagmaEngine should be instantiated."); } instance = this; singletons = new LinkedHashSet<>(); valueTypeFactory = new ValueTypeFactory(); } @NotNull public static MagmaEngine get() { if(instance == null) { log.debug("Instantiating a new MagmaEngine without any extensions."); new MagmaEngine(); } return instance; } public static boolean isInstantiated() { return instance != null; } public MagmaEngine extend(@NotNull MagmaEngineExtension extension) { //noinspection ConstantConditions if(extension == null) throw new IllegalArgumentException("extension cannot be null"); if(!hasExtension(extension.getClass())) { Initialisables.initialise(extension); extensions.add(extension); } return this; } public boolean hasExtension(Class<? extends MagmaEngineExtension> extensionType) { try { Iterables.getOnlyElement(Iterables.filter(extensions, extensionType)); return true; } catch(NoSuchElementException e) { return false; } } /** * Returns true if the {@code MagmaEngine} has a instance of {@code MagmaEngineExtension} whose name equals the name * provided. * * @param name * @return */ public boolean hasExtension(String name) { for(MagmaEngineExtension e : extensions) { if(e.getName().equals(name)) return true; } return false; } public <T extends MagmaEngineExtension> T getExtension(Class<T> extensionType) { try { return Iterables.getOnlyElement(Iterables.filter(extensions, extensionType)); } catch(NoSuchElementException e) { throw new MagmaRuntimeException("No extension of type '" + extensionType + "' was registered."); } } public DatasourceRegistry getDatasourceRegistry() { return datasourceRegistry; } public void decorate(Decorator<DatasourceRegistry> registryDecorator) { datasourceRegistry = registryDecorator.decorate(datasourceRegistry); } @Override public ValueTableReference createReference(String reference) { return getDatasourceRegistry().createReference(reference); } @Override public Datasource getDatasource(String name) { return getDatasourceRegistry().getDatasource(name); } @Override public Datasource addDatasource(Datasource datasource) { return getDatasourceRegistry().addDatasource(datasource); } @Override public Datasource addDatasource(DatasourceFactory factory) { return getDatasourceRegistry().addDatasource(factory); } @Override public void addDecorator(Decorator<Datasource> decorator) { getDatasourceRegistry().addDecorator(decorator); } @Override public String addTransientDatasource(DatasourceFactory factory) { return getDatasourceRegistry().addTransientDatasource(factory); } @Override public Set<Datasource> getDatasources() { return getDatasourceRegistry().getDatasources(); } @Override public Datasource getTransientDatasourceInstance(String uid) { return getDatasourceRegistry().getTransientDatasourceInstance(uid); } @Override public boolean hasDatasource(String name) { return getDatasourceRegistry().hasDatasource(name); } @Override public boolean hasTransientDatasource(String uid) { return getDatasourceRegistry().hasTransientDatasource(uid); } @Override public void removeDatasource(Datasource datasource) { getDatasourceRegistry().removeDatasource(datasource); } @Override public void removeTransientDatasource(@Nullable String uid) { getDatasourceRegistry().removeTransientDatasource(uid); } ValueTypeFactory getValueTypeFactory() { return valueTypeFactory; } public void lock(Collection<String> lockNames) throws InterruptedException { lockManager.lock(lockNames); } public void unlock(Iterable<String> lockNames) { lockManager.unlock(lockNames, true); } public <T> WeakReference<T> registerInstance(T singleton) { singletons.add(singleton); return new WeakReference<>(singleton); } public void shutdown() { for(Disposable d : Iterables.filter(extensions, Disposable.class)) { Disposables.silentlyDispose(d); } Disposables.silentlyDispose(datasourceRegistry); singletons = null; instance = null; } }
obiba/magma
magma-api/src/main/java/org/obiba/magma/MagmaEngine.java
Java
gpl-3.0
6,132
<?php namespace Fox\Core\Utils\Database; use Fox\Core\Utils\Util, Fox\ORM\Entity; class Converter { private $metadata; private $fileManager; private $schemaConverter; private $schemaFromMetadata = null; public function __construct(\Fox\Core\Utils\Metadata $metadata, \Fox\Core\Utils\File\Manager $fileManager) { $this->metadata = $metadata; $this->fileManager = $fileManager; $this->ormConverter = new Orm\Converter($this->metadata, $this->fileManager); $this->schemaConverter = new Schema\Converter($this->fileManager); } protected function getMetadata() { return $this->metadata; } protected function getOrmConverter() { return $this->ormConverter; } protected function getSchemaConverter() { return $this->schemaConverter; } public function getSchemaFromMetadata($entityList = null) { $ormMeta = $this->getMetadata()->getOrmMetadata(); $this->schemaFromMetadata = $this->getSchemaConverter()->process($ormMeta, $entityList); return $this->schemaFromMetadata; } /** * Main method of convertation from metadata to orm metadata and database schema * * @return bool */ public function process() { $GLOBALS['log']->debug('Orm\Converter - Start: orm convertation'); $ormMeta = $this->getOrmConverter()->process(); //save database meta to a file espoMetadata.php $result = $this->getMetadata()->setOrmMetadata($ormMeta); $GLOBALS['log']->debug('Orm\Converter - End: orm convertation, result=['.$result.']'); return $result; } }
ilovefox8/zhcrm
application/Fox/Core/Utils/Database/Converter.php
PHP
gpl-3.0
1,682
//////////////////////////////////////////////////////////////////////////////// // // This file is part of Strata. // // Strata 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. // // Strata 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 // Strata. If not, see <http://www.gnu.org/licenses/>. // // Copyright 2010-2018 Albert Kottke // //////////////////////////////////////////////////////////////////////////////// #include "StressRatioProfileOutput.h" #include "AbstractCalculator.h" #include "AbstractMotion.h" #include "SoilProfile.h" #include "SubLayer.h" #include <QChar> StressRatioProfileOutput::StressRatioProfileOutput(OutputCatalog* catalog) : AbstractProfileOutput(catalog) { _offset_bot = 1; _offset_top = 1; } auto StressRatioProfileOutput::name() const -> QString { return tr("Stress Ratio Profile"); } auto StressRatioProfileOutput::shortName() const -> QString { return tr("stressRatio"); } auto StressRatioProfileOutput::xLabel() const -> const QString { return tr("Stress Ratio, %1_max / %2_v").arg(QChar(0x03C4)).arg(QChar(0x03C3)); } void StressRatioProfileOutput::extract(AbstractCalculator* const calculator, QVector<double> & ref, QVector<double> & data) const { const QList<SubLayer> & subLayers = calculator->site()->subLayers(); // Uses depth from the center of the layer ref.clear(); ref << 0; for (const SubLayer &sl : subLayers) ref << sl.depthToMid(); ref << subLayers.last().depthToBase(); data = calculator->site()->stressRatioProfile(); data.prepend(0); extrap(ref, data, subLayers.last().thickness()); }
arkottke/strata
source/StressRatioProfileOutput.cpp
C++
gpl-3.0
2,100
from django.contrib import admin from comun.models import Departamento, Partido admin.site.register(Departamento) admin.site.register(Partido)
mmanto/sstuv
comun/admin.py
Python
gpl-3.0
144
/* Developed with the contribution of the European Commission - Directorate General for Maritime Affairs and Fisheries © European Union, 2015-2016. This file is part of the Integrated Fisheries Data Management (IFDM) Suite. The IFDM Suite is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. The IFDM Suite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the IFDM Suite. If not, see <http://www.gnu.org/licenses/>. */ describe('AuditconfigurationCtrl', function() { var scope, createController, createSetting; beforeEach(module('unionvmsWeb')); beforeEach(inject(function($rootScope, $controller) { scope = $rootScope.$new(); createController = function() { return $controller('AuditconfigurationCtrl', { '$scope': scope, '$resource': function(url) { if (url === "config/rest/settings/:id") { return singleSettingResource; } else if (url === "config/rest/catalog") { return settingCatalogResource; } } }); }; createSetting = function() { return { id: 123, key: "test.key", value: "some_value", global: false, description: "A setting for testing.", module: "movement", lastModified: 0 }; }; })); it('should only show tabs with at least one non-global setting', function() { var controller = createController(); expect(scope.tabs).toEqual(["systemMonitor", "globalSettings", "reporting","activity", "mobileTerminal"]); }); it('should provide the right partial URLs', function() { var controller = createController(); scope.activeTab = "systemMonitor"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationModule/systemMonitor.html"); scope.activeTab = "globalSettings"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationGeneral/configurationGeneral.html"); scope.activeTab = "reporting"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationReporting/configurationReporting.html"); scope.activeTab = "activity"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationActivity/configurationActivity.html"); scope.activeTab = "any other value"; expect(scope.configurationPageUrl()).toBe("partial/admin/adminConfiguration/configurationModule/configurationModule.html"); }); it('should begin editing a setting by backing up setting value and description', function() { var controller = createController(); var setting = createSetting(); scope.setEditing(setting, true); expect(setting.previousValue).toBe("some_value"); expect(setting.previousDescription).toBe("A setting for testing."); expect(setting.editing).toBe(true); }); it('should stop editing by deleting setting value and description backups', function() { var controller = createController(); var setting = createSetting(); setting.previousValue = "previousValue"; setting.previousDescription = "previousDescription"; scope.setEditing(setting, false); expect(setting.previousValue).not.toBeDefined(); expect(setting.previousDescription).not.toBeDefined(); expect(setting.editing).toBe(false); }); it('should cancel editing by restoring setting value and description from backup', function() { var setting = createSetting(); setting.previousValue = "previousValue"; setting.previousDescription = "previousDescription"; var controller = createController(); spyOn(scope, "setEditing"); scope.cancelEditing(setting); expect(setting.value).toBe("previousValue"); expect(setting.description).toBe("previousDescription"); expect(scope.setEditing).toHaveBeenCalledWith(jasmine.any(Object), false); }); it('should set lastModified when updating a setting, and set editing to false', function() { var controller = createController(); var setting = createSetting(); spyOn(scope, "setEditing"); scope.updateSetting(setting); expect(setting.lastModified).toBe(123); expect(scope.setEditing).toHaveBeenCalledWith(jasmine.any(Object), false); }); it('should filter by replacing periods with underscores', inject(function($filter) { expect($filter('replace')('apa.bepa.cepa')).toBe('apa_bepa_cepa'); expect($filter('replace')('')).toBe(''); })); var catalog = { data: { "vessel": [ { key: "key.1", value: "value.1", description: "A global vessel setting", global: true } ], "mobileTerminal": [ { key: "key.2", value: "value.2", description: "A module-specific setting for mobile terminals", global: false }, { key: "key.3", value: "value.3", description: "A global mobile terminal setting", global: true } ] } }; var response = { data: { id: 123, key: "test.key", value: "some_value", global: false, description: "A setting for testing.", module: "movement", lastModified: 123 } }; var singleSettingResource = { update: function(params, data, callback) { callback(response); } }; var settingCatalogResource = { get: function(callback) { callback(catalog); } }; });
UnionVMS/UVMS-Frontend
app/partial/admin/adminConfiguration/adminConfiguration-spec.js
JavaScript
gpl-3.0
5,549
# coding: utf-8 """ Copyright (c) 2013 João Bernardo Vianna Oliveira This file is part of Discoder. Discoder 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. Discoder 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 Discoder. If not, see <http://www.gnu.org/licenses/>. """ from __future__ import print_function import multiprocessing import multiprocessing.dummy import socket import threading from discoder.distributed import send_data, get_data from discoder.lib.helper import star __author__ = 'jb' QUEUE_LOCK = threading.Lock() KEEP_BALANCE_ORDER = False def load_client(client, cmd): """ Open socket and write command to be executed remotely """ s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(client) send_data(s, cmd) out = get_data(s) s.close() return out class CommandInfo(object): """ Keep track of position of command after its execution """ def __init__(self, pos, data): self.pos = pos self.data = data class LoadBalancer(object): def __init__(self, queue): self.queue = queue def run(self, client, num): done = [] lock = threading.Lock() def queue_run(n): with lock: done_thread = [] done.append(done_thread) while True: try: with QUEUE_LOCK: cmd = self.queue.get_nowait() except Exception: break res = load_client(client, [cmd.data])[0] done_thread.append([cmd.pos, res]) ths = [] for x in range(num): th = threading.Thread(target=queue_run, args=(x,)) th.daemon = True th.start() ths.append(th) for th in ths: th.join() return done def list_numeric_order(data): """ Convert a list of balance outputs and put then in numerical segment order. [ [ [ [1, X1], [3, X3] ], [ [0, X0], [5, X5] ], ], [ [ [2, X2], [7, X7] ], [ [4, X4], [6, X6] ], ], ] Output: [X0, X1, X2, X3, X4, X5, X6, X7] :param data: 4-Dimensional list :return: list """ dic = {} for d in data: d = [x for sub in d for x in sub] dic.update(d) return [val for key, val in sorted(dic.items())] def run(nodes, args, balance=False): """ Connect to clients using multiple processes. """ #import pprint #print('Connecting to nodes:') #print(*('\t{0}:{1}'.format(*i) for i in nodes), sep='\n') #pprint.pprint(args, width=200) #print('Command:', len(args)) nnodes = len(nodes) pool = multiprocessing.dummy.Pool(nnodes) if balance: args = [CommandInfo(i, x) for i, x in enumerate(args)] queue = multiprocessing.Queue(maxsize=len(args)) for el in args: queue.put(el, block=True) parts = [balance for _ in range(nnodes)] out = pool.map(star(LoadBalancer(queue).run), zip(nodes, parts)) if not KEEP_BALANCE_ORDER: out = list_numeric_order(out) else: n = len(args) // nnodes # noinspection PyArgumentList parts = [args[i:i+n] for i in range(0, n * nnodes, n)] out = pool.map(star(load_client), zip(nodes, parts)) #pool.close() return out
jbvsmo/discoder
discoder/distributed/server.py
Python
gpl-3.0
3,939
package NJU.HouseWang.nju_eas_server.systemMessage; public enum UserType { Admin("管理员"), SchoolDean("学校教务老师"), DeptAD("院系教务老师"), Teacher("任课老师"), Student("学生"); private String chName; private UserType(String chName) { this.chName = chName; } public String getChName() { return chName; } }
NJU-HouseWang/nju-eas-server
src/main/java/NJU/HouseWang/nju_eas_server/systemMessage/UserType.java
Java
gpl-3.0
353
Bitrix 16.5 Business Demo = 15835c954707d2e6d70c9aaff892ca49
gohdan/DFC
known_files/hashes/bitrix/modules/forum/install/components/bitrix/forum/templates/.default/help.php
PHP
gpl-3.0
61
Bitrix 16.5 Business Demo = b804541b55ffbf377df97c657f7b27db
gohdan/DFC
known_files/hashes/bitrix/modules/bitrixcloud/install/admin/bitrixcloud_backup.php
PHP
gpl-3.0
61
#include "NotNamespaceProperty.h" using namespace Com::Ecosoftware::Engines::Xsd; NotNamespaceProperty::NotNamespaceProperty ( bool value ) { this->value = value; } NotNamespaceProperty::NotNamespaceProperty ( const NotNamespaceProperty & ) : PropertyAbs () {} NotNamespaceProperty::~NotNamespaceProperty () {} bool NotNamespaceProperty::getValue () const { return this->value; } void NotNamespaceProperty::setValue ( bool value ) { this->value = value; }
remizero/qtrcp
com/ecosoftware/engines/xsd/core/properties/NotNamespaceProperty.cpp
C++
gpl-3.0
471
/* * 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. */ /** * * @author Arles Cerrato */ public class FileBinary { }
Arles96/LibraryPassword
PasswordLibrary/src/FileBinary.java
Java
gpl-3.0
255
# -*- coding: utf-8 -*- """ env.testsuite.blueprints ~~~~~~~~~~~~~~~~~~~~~~~~~~ Blueprints (and currently mod_auth) :copyright: (c) 2011 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import flask import unittest import warnings from flask.testsuite import FlaskTestCase, emits_module_deprecation_warning from flask._compat import text_type from werkzeug.exceptions import NotFound from werkzeug.http import parse_cache_control_header from jinja2 import TemplateNotFound # import moduleapp here because it uses deprecated features and we don't # want to see the warnings warnings.simplefilter('ignore', DeprecationWarning) from moduleapp import app as moduleapp warnings.simplefilter('default', DeprecationWarning) class ModuleTestCase(FlaskTestCase): @emits_module_deprecation_warning def test_basic_module(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin', url_prefix='/admin') @admin.route('/') def admin_index(): return 'admin index' @admin.route('/login') def admin_login(): return 'admin login' @admin.route('/logout') def admin_logout(): return 'admin logout' @app.route('/') def index(): return 'the index' app.register_module(admin) c = app.test_client() self.assert_equal(c.get('/').data, b'the index') self.assert_equal(c.get('/admin/').data, b'admin index') self.assert_equal(c.get('/admin/login').data, b'admin login') self.assert_equal(c.get('/admin/logout').data, b'admin logout') @emits_module_deprecation_warning def test_default_endpoint_name(self): app = flask.Flask(__name__) mod = flask.Module(__name__, 'frontend') def index(): return 'Awesome' mod.add_url_rule('/', view_func=index) app.register_module(mod) rv = app.test_client().get('/') self.assert_equal(rv.data, b'Awesome') with app.test_request_context(): self.assert_equal(flask.url_for('frontend.index'), '/') @emits_module_deprecation_warning def test_request_processing(self): catched = [] app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin', url_prefix='/admin') @admin.before_request def before_admin_request(): catched.append('before-admin') @admin.after_request def after_admin_request(response): catched.append('after-admin') return response @admin.route('/') def admin_index(): return 'the admin' @app.before_request def before_request(): catched.append('before-app') @app.after_request def after_request(response): catched.append('after-app') return response @app.route('/') def index(): return 'the index' app.register_module(admin) c = app.test_client() self.assert_equal(c.get('/').data, b'the index') self.assert_equal(catched, ['before-app', 'after-app']) del catched[:] self.assert_equal(c.get('/admin/').data, b'the admin') self.assert_equal(catched, ['before-app', 'before-admin', 'after-admin', 'after-app']) @emits_module_deprecation_warning def test_context_processors(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin', url_prefix='/admin') @app.context_processor def inject_all_regular(): return {'a': 1} @admin.context_processor def inject_admin(): return {'b': 2} @admin.app_context_processor def inject_all_module(): return {'c': 3} @app.route('/') def index(): return flask.render_template_string('{{ a }}{{ b }}{{ c }}') @admin.route('/') def admin_index(): return flask.render_template_string('{{ a }}{{ b }}{{ c }}') app.register_module(admin) c = app.test_client() self.assert_equal(c.get('/').data, b'13') self.assert_equal(c.get('/admin/').data, b'123') @emits_module_deprecation_warning def test_late_binding(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin') @admin.route('/') def index(): return '42' app.register_module(admin, url_prefix='/admin') self.assert_equal(app.test_client().get('/admin/').data, b'42') @emits_module_deprecation_warning def test_error_handling(self): app = flask.Flask(__name__) admin = flask.Module(__name__, 'admin') @admin.app_errorhandler(404) def not_found(e): return 'not found', 404 @admin.app_errorhandler(500) def internal_server_error(e): return 'internal server error', 500 @admin.route('/') def index(): flask.abort(404) @admin.route('/error') def error(): 1 // 0 app.register_module(admin) c = app.test_client() rv = c.get('/') self.assert_equal(rv.status_code, 404) self.assert_equal(rv.data, b'not found') rv = c.get('/error') self.assert_equal(rv.status_code, 500) self.assert_equal(b'internal server error', rv.data) def test_templates_and_static(self): app = moduleapp app.testing = True c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'Hello from the Frontend') rv = c.get('/admin/') self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/index2') self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') self.assert_equal(rv.data.strip(), b'Admin File') rv.close() rv = c.get('/admin/static/css/test.css') self.assert_equal(rv.data.strip(), b'/* nested file */') rv.close() with app.test_request_context(): self.assert_equal(flask.url_for('admin.static', filename='test.txt'), '/admin/static/test.txt') with app.test_request_context(): try: flask.render_template('missing.html') except TemplateNotFound as e: self.assert_equal(e.name, 'missing.html') else: self.assert_true(0, 'expected exception') with flask.Flask(__name__).test_request_context(): self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested') def test_safe_access(self): app = moduleapp with app.test_request_context(): f = app.view_functions['admin.static'] try: f('/etc/passwd') except NotFound: pass else: self.assert_true(0, 'expected exception') try: f('../__init__.py') except NotFound: pass else: self.assert_true(0, 'expected exception') # testcase for a security issue that may exist on windows systems import os import ntpath old_path = os.path os.path = ntpath try: try: f('..\\__init__.py') except NotFound: pass else: self.assert_true(0, 'expected exception') finally: os.path = old_path @emits_module_deprecation_warning def test_endpoint_decorator(self): from werkzeug.routing import Submount, Rule from flask import Module app = flask.Flask(__name__) app.testing = True app.url_map.add(Submount('/foo', [ Rule('/bar', endpoint='bar'), Rule('/', endpoint='index') ])) module = Module(__name__, __name__) @module.endpoint('bar') def bar(): return 'bar' @module.endpoint('index') def index(): return 'index' app.register_module(module) c = app.test_client() self.assert_equal(c.get('/foo/').data, b'index') self.assert_equal(c.get('/foo/bar').data, b'bar') class BlueprintTestCase(FlaskTestCase): def test_blueprint_specific_error_handling(self): frontend = flask.Blueprint('frontend', __name__) backend = flask.Blueprint('backend', __name__) sideend = flask.Blueprint('sideend', __name__) @frontend.errorhandler(403) def frontend_forbidden(e): return 'frontend says no', 403 @frontend.route('/frontend-no') def frontend_no(): flask.abort(403) @backend.errorhandler(403) def backend_forbidden(e): return 'backend says no', 403 @backend.route('/backend-no') def backend_no(): flask.abort(403) @sideend.route('/what-is-a-sideend') def sideend_no(): flask.abort(403) app = flask.Flask(__name__) app.register_blueprint(frontend) app.register_blueprint(backend) app.register_blueprint(sideend) @app.errorhandler(403) def app_forbidden(e): return 'application itself says no', 403 c = app.test_client() self.assert_equal(c.get('/frontend-no').data, b'frontend says no') self.assert_equal(c.get('/backend-no').data, b'backend says no') self.assert_equal(c.get('/what-is-a-sideend').data, b'application itself says no') def test_blueprint_url_definitions(self): bp = flask.Blueprint('test', __name__) @bp.route('/foo', defaults={'baz': 42}) def foo(bar, baz): return '%s/%d' % (bar, baz) @bp.route('/bar') def bar(bar): return text_type(bar) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/1', url_defaults={'bar': 23}) app.register_blueprint(bp, url_prefix='/2', url_defaults={'bar': 19}) c = app.test_client() self.assert_equal(c.get('/1/foo').data, b'23/42') self.assert_equal(c.get('/2/foo').data, b'19/42') self.assert_equal(c.get('/1/bar').data, b'23') self.assert_equal(c.get('/2/bar').data, b'19') def test_blueprint_url_processors(self): bp = flask.Blueprint('frontend', __name__, url_prefix='/<lang_code>') @bp.url_defaults def add_language_code(endpoint, values): values.setdefault('lang_code', flask.g.lang_code) @bp.url_value_preprocessor def pull_lang_code(endpoint, values): flask.g.lang_code = values.pop('lang_code') @bp.route('/') def index(): return flask.url_for('.about') @bp.route('/about') def about(): return flask.url_for('.index') app = flask.Flask(__name__) app.register_blueprint(bp) c = app.test_client() self.assert_equal(c.get('/de/').data, b'/de/about') self.assert_equal(c.get('/de/about').data, b'/de/') def test_templates_and_static(self): from blueprintapp import app c = app.test_client() rv = c.get('/') self.assert_equal(rv.data, b'Hello from the Frontend') rv = c.get('/admin/') self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/index2') self.assert_equal(rv.data, b'Hello from the Admin') rv = c.get('/admin/static/test.txt') self.assert_equal(rv.data.strip(), b'Admin File') rv.close() rv = c.get('/admin/static/css/test.css') self.assert_equal(rv.data.strip(), b'/* nested file */') rv.close() # try/finally, in case other tests use this app for Blueprint tests. max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] try: expected_max_age = 3600 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == expected_max_age: expected_max_age = 7200 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = expected_max_age rv = c.get('/admin/static/css/test.css') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, expected_max_age) rv.close() finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default with app.test_request_context(): self.assert_equal(flask.url_for('admin.static', filename='test.txt'), '/admin/static/test.txt') with app.test_request_context(): try: flask.render_template('missing.html') except TemplateNotFound as e: self.assert_equal(e.name, 'missing.html') else: self.assert_true(0, 'expected exception') with flask.Flask(__name__).test_request_context(): self.assert_equal(flask.render_template('nested/nested.txt'), 'I\'m nested') def test_default_static_cache_timeout(self): app = flask.Flask(__name__) class MyBlueprint(flask.Blueprint): def get_send_file_max_age(self, filename): return 100 blueprint = MyBlueprint('blueprint', __name__, static_folder='static') app.register_blueprint(blueprint) # try/finally, in case other tests use this app for Blueprint tests. max_age_default = app.config['SEND_FILE_MAX_AGE_DEFAULT'] try: with app.test_request_context(): unexpected_max_age = 3600 if app.config['SEND_FILE_MAX_AGE_DEFAULT'] == unexpected_max_age: unexpected_max_age = 7200 app.config['SEND_FILE_MAX_AGE_DEFAULT'] = unexpected_max_age rv = blueprint.send_static_file('index.html') cc = parse_cache_control_header(rv.headers['Cache-Control']) self.assert_equal(cc.max_age, 100) rv.close() finally: app.config['SEND_FILE_MAX_AGE_DEFAULT'] = max_age_default def test_templates_list(self): from blueprintapp import app templates = sorted(app.jinja_env.list_templates()) self.assert_equal(templates, ['admin/index.html', 'frontend/index.html']) def test_dotted_names(self): frontend = flask.Blueprint('myapp.frontend', __name__) backend = flask.Blueprint('myapp.backend', __name__) @frontend.route('/fe') def frontend_index(): return flask.url_for('myapp.backend.backend_index') @frontend.route('/fe2') def frontend_page2(): return flask.url_for('.frontend_index') @backend.route('/be') def backend_index(): return flask.url_for('myapp.frontend.frontend_index') app = flask.Flask(__name__) app.register_blueprint(frontend) app.register_blueprint(backend) c = app.test_client() self.assert_equal(c.get('/fe').data.strip(), b'/be') self.assert_equal(c.get('/fe2').data.strip(), b'/fe') self.assert_equal(c.get('/be').data.strip(), b'/fe') def test_dotted_names_from_app(self): app = flask.Flask(__name__) app.testing = True test = flask.Blueprint('test', __name__) @app.route('/') def app_index(): return flask.url_for('test.index') @test.route('/test/') def index(): return flask.url_for('app_index') app.register_blueprint(test) with app.test_client() as c: rv = c.get('/') self.assert_equal(rv.data, b'/test/') def test_empty_url_defaults(self): bp = flask.Blueprint('bp', __name__) @bp.route('/', defaults={'page': 1}) @bp.route('/page/<int:page>') def something(page): return str(page) app = flask.Flask(__name__) app.register_blueprint(bp) c = app.test_client() self.assert_equal(c.get('/').data, b'1') self.assert_equal(c.get('/page/2').data, b'2') def test_route_decorator_custom_endpoint(self): bp = flask.Blueprint('bp', __name__) @bp.route('/foo') def foo(): return flask.request.endpoint @bp.route('/bar', endpoint='bar') def foo_bar(): return flask.request.endpoint @bp.route('/bar/123', endpoint='123') def foo_bar_foo(): return flask.request.endpoint @bp.route('/bar/foo') def bar_foo(): return flask.request.endpoint app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.request.endpoint c = app.test_client() self.assertEqual(c.get('/').data, b'index') self.assertEqual(c.get('/py/foo').data, b'bp.foo') self.assertEqual(c.get('/py/bar').data, b'bp.bar') self.assertEqual(c.get('/py/bar/123').data, b'bp.123') self.assertEqual(c.get('/py/bar/foo').data, b'bp.bar_foo') def test_route_decorator_custom_endpoint_with_dots(self): bp = flask.Blueprint('bp', __name__) @bp.route('/foo') def foo(): return flask.request.endpoint try: @bp.route('/bar', endpoint='bar.bar') def foo_bar(): return flask.request.endpoint except AssertionError: pass else: raise AssertionError('expected AssertionError not raised') try: @bp.route('/bar/123', endpoint='bar.123') def foo_bar_foo(): return flask.request.endpoint except AssertionError: pass else: raise AssertionError('expected AssertionError not raised') def foo_foo_foo(): pass self.assertRaises( AssertionError, lambda: bp.add_url_rule( '/bar/123', endpoint='bar.123', view_func=foo_foo_foo ) ) self.assertRaises( AssertionError, bp.route('/bar/123', endpoint='bar.123'), lambda: None ) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') c = app.test_client() self.assertEqual(c.get('/py/foo').data, b'bp.foo') # The rule's didn't actually made it through rv = c.get('/py/bar') assert rv.status_code == 404 rv = c.get('/py/bar/123') assert rv.status_code == 404 def test_template_filter(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_filter() def my_reverse(s): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') def test_add_template_filter(self): bp = flask.Blueprint('bp', __name__) def my_reverse(s): return s[::-1] bp.add_app_template_filter(my_reverse) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('my_reverse', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse) self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba') def test_template_filter_with_name(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_filter('strrev') def my_reverse(s): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') def test_add_template_filter_with_name(self): bp = flask.Blueprint('bp', __name__) def my_reverse(s): return s[::-1] bp.add_app_template_filter(my_reverse, 'strrev') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('strrev', app.jinja_env.filters.keys()) self.assert_equal(app.jinja_env.filters['strrev'], my_reverse) self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba') def test_template_filter_with_template(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_filter() def super_reverse(s): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_filter_after_route_with_template(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') bp = flask.Blueprint('bp', __name__) @bp.app_template_filter() def super_reverse(s): return s[::-1] app.register_blueprint(bp, url_prefix='/py') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_template(self): bp = flask.Blueprint('bp', __name__) def super_reverse(s): return s[::-1] bp.add_app_template_filter(super_reverse) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_filter_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_filter('super_reverse') def my_reverse(s): return s[::-1] app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_add_template_filter_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) def my_reverse(s): return s[::-1] bp.add_app_template_filter(my_reverse, 'super_reverse') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_filter.html', value='abcd') rv = app.test_client().get('/') self.assert_equal(rv.data, b'dcba') def test_template_test(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_test() def is_boolean(value): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('is_boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) self.assert_true(app.jinja_env.tests['is_boolean'](False)) def test_add_template_test(self): bp = flask.Blueprint('bp', __name__) def is_boolean(value): return isinstance(value, bool) bp.add_app_template_test(is_boolean) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('is_boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['is_boolean'], is_boolean) self.assert_true(app.jinja_env.tests['is_boolean'](False)) def test_template_test_with_name(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_test('boolean') def is_boolean(value): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_add_template_test_with_name(self): bp = flask.Blueprint('bp', __name__) def is_boolean(value): return isinstance(value, bool) bp.add_app_template_test(is_boolean, 'boolean') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') self.assert_in('boolean', app.jinja_env.tests.keys()) self.assert_equal(app.jinja_env.tests['boolean'], is_boolean) self.assert_true(app.jinja_env.tests['boolean'](False)) def test_template_test_with_template(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_test() def boolean(value): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_template_test_after_route_with_template(self): app = flask.Flask(__name__) @app.route('/') def index(): return flask.render_template('template_test.html', value=False) bp = flask.Blueprint('bp', __name__) @bp.app_template_test() def boolean(value): return isinstance(value, bool) app.register_blueprint(bp, url_prefix='/py') rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_test_with_template(self): bp = flask.Blueprint('bp', __name__) def boolean(value): return isinstance(value, bool) bp.add_app_template_test(boolean) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) @bp.app_template_test('boolean') def is_boolean(value): return isinstance(value, bool) app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def test_add_template_test_with_name_and_template(self): bp = flask.Blueprint('bp', __name__) def is_boolean(value): return isinstance(value, bool) bp.add_app_template_test(is_boolean, 'boolean') app = flask.Flask(__name__) app.register_blueprint(bp, url_prefix='/py') @app.route('/') def index(): return flask.render_template('template_test.html', value=False) rv = app.test_client().get('/') self.assert_in(b'Success!', rv.data) def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(BlueprintTestCase)) suite.addTest(unittest.makeSuite(ModuleTestCase)) return suite
ncdesouza/bookworm
env/lib/python2.7/site-packages/flask/testsuite/blueprints.py
Python
gpl-3.0
28,088
package pers.hai.sample.dp.visitor; import java.util.Collection; /** * TODO * <p> * Create Time: 2019-06-14 11:17 * Last Modify: 2019-06-14 * * @author Q-WHai * @see <a href="https://github.com/qwhai">https://github.com/qwhai</a> */ public interface Visitor { void visitString(StringElement stringE); void visitFloat(FloatElement floatE); void visitCollection(Collection collection); }
William-Hai/DesignPatternCollections
src/main/java/pers/hai/sample/dp/visitor/Visitor.java
Java
gpl-3.0
407
class CreateSocialLinks < ActiveRecord::Migration def change create_table :social_links do |t| t.string :provider t.string :link t.string :icon_class t.text :description t.references :cycle, index: true, foreign_key: true t.timestamps null: false end end end
itsriodejaneiro/mudamos-web
db/migrate/20151007193639_create_social_links.rb
Ruby
gpl-3.0
308
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * Strings for component 'message', language 'en', branch 'MOODLE_20_STABLE' * * @package message * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ $string['addcontact'] = 'Add contact'; $string['addsomecontacts'] = 'To send a message to someone, or to add a shortcut for them on this page, use the <a href="{$a}">search tab</a> above.'; $string['addsomecontactsincoming'] = 'These messages are from people who are not in your contact list. To add them to your contacts, click the "Add contact" icon next to their name.'; $string['ago'] = '{$a} ago'; $string['ajax_gui'] = 'Ajax chat room'; $string['allmine'] = 'All messages to me or from me'; $string['allstudents'] = 'All messages between students in course'; $string['allusers'] = 'All messages from all users'; $string['backupmessageshelp'] = 'If enabled, then instant messages will be included in SITE automated backups'; $string['beepnewmessage'] = 'Beep on new message'; $string['blockcontact'] = 'Block contact'; $string['blockedmessages'] = '{$a} message(s) to/from blocked users'; $string['blockedusers'] = 'Blocked users ({$a})'; $string['blocknoncontacts'] = 'Block unknown users'; $string['cannotsavemessageprefs'] = 'Could not save user messaging preferences'; $string['contactlistempty'] = 'Your contact list is empty'; $string['contacts'] = 'Contacts'; $string['context'] = 'context'; $string['deletemessagesdays'] = 'Number of days before old messages are automatically deleted'; $string['disabled'] = 'Messaging is disabled on this site'; $string['discussion'] = 'Discussion'; $string['editmymessage'] = 'Messaging'; $string['emailmessages'] = 'Email messages when I am offline'; $string['emailtagline'] = 'This is a copy of a message sent to you at "{$a->sitename}". Go to {$a->url} to reply.'; $string['emptysearchstring'] = 'You must search for something'; $string['errorcallingprocessor'] = 'Error calling defined processor'; $string['formorethan'] = 'For more than'; $string['guestnoeditmessage'] = 'Guest user can not edit messaging options'; $string['guestnoeditmessageother'] = 'Guest user can not edit other user messaging options'; $string['gotomessages'] = 'Go to messages'; $string['includeblockedusers'] = 'Include blocked users'; $string['incomingcontacts'] = 'Incoming contacts ({$a})'; $string['keywords'] = 'Keywords'; $string['keywordssearchresults'] = 'Search results: {$a} messages found'; $string['keywordssearchresultstoomany'] = 'Search results: More than {$a} messages found. Refine your search.'; $string['loggedin'] = 'Online'; $string['loggedindescription'] = 'When I\'m online'; $string['loggedoff'] = 'Not online'; $string['loggedoffdescription'] = 'When I\'m not online'; $string['managecontacts'] = 'Manage my contacts'; $string['mostrecent'] = 'Recent messages'; $string['mailsent'] = 'Your message was sent via email.'; $string['maxmessages'] = 'Maximum number of messages to show in the discussion history'; $string['message'] = 'Message'; $string['messagehistory'] = 'Message history'; $string['messagehistoryfull'] = 'All messages'; $string['messages'] = 'Messages'; $string['messaging'] = 'Messaging'; $string['messagingdisabled'] = 'Messaging is disabled on this site, emails will be sent instead'; $string['mycontacts'] = 'My contacts'; $string['newonlymsg'] = 'Show only new'; $string['newsearch'] = 'New search'; $string['noframesjs'] = 'Use more accessible interface'; $string['nomessages'] = 'No messages waiting'; $string['nomessagesfound'] = 'No messages were found'; $string['nosearchresults'] = 'There were no results from your search'; $string['offline'] = 'Offline'; $string['offlinecontacts'] = 'Offline contacts ({$a})'; $string['online'] = 'Online'; $string['onlinecontacts'] = 'Online contacts ({$a})'; $string['onlyfromme'] = 'Only messages from me'; $string['onlymycourses'] = 'Only in my courses'; $string['onlytome'] = 'Only messages to me'; $string['pagerefreshes'] = 'This page refreshes automatically every {$a} seconds'; $string['private_config'] = 'Popup message window'; $string['processortag'] = 'Destination'; $string['providers_config'] = 'Configure notification methods for incoming messages'; $string['providerstag'] = 'Source'; $string['readmessages'] = '{$a} read messages'; $string['removecontact'] = 'Remove contact'; $string['savemysettings'] = 'Save my settings'; $string['search'] = 'Search'; $string['searchforperson'] = 'Search for a person'; $string['searchmessages'] = 'Search messages'; $string['searchcombined'] = 'Search people and messages'; $string['sendmessage'] = 'Send message'; $string['sendmessageto'] = 'Send message to {$a}'; $string['sendmessagetopopup'] = 'Send message to {$a} - new window'; $string['settings'] = 'Settings'; $string['settingssaved'] = 'Your settings have been saved'; $string['showmessagewindow'] = 'Popup window on new message'; $string['strftimedaydatetime'] = '%A, %d %B %Y, %I:%M %p'; $string['timenosee'] = 'Minutes since I was last seen online'; $string['timesent'] = 'Time Sent'; $string['unblockcontact'] = 'Unblock contact'; $string['unreadmessages'] = '{$a} unread messages'; $string['unreadnewmessages'] = '{$a} new messages'; $string['unreadnewmessage'] = 'New message from {$a}'; $string['userisblockingyou'] = 'This user has blocked you from sending messages to them'; $string['userisblockingyounoncontact'] = 'This user is only accepting messages from people listed as contacts, and you are not currently on the list.'; $string['userssearchresults'] = 'Search results: {$a} users found';
dpogue/thss-moodle
lang/en/message.php
PHP
gpl-3.0
6,279
/******************************************************************************* * This file is part of Minebot. * * Minebot 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. * * Minebot 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 Minebot. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package net.famzangl.minecraft.minebot.ai.task.place; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.MarkerManager; import net.famzangl.minecraft.minebot.ai.AIHelper; import net.famzangl.minecraft.minebot.ai.ItemFilter; import net.famzangl.minecraft.minebot.ai.path.world.BlockSets; import net.famzangl.minecraft.minebot.ai.task.BlockHalf; import net.famzangl.minecraft.minebot.ai.task.TaskOperations; import net.famzangl.minecraft.minebot.ai.task.error.StringTaskError; import net.minecraft.util.EnumFacing; import net.minecraft.util.math.BlockPos; /** * Place a block at the given upper/lower side of its adjacent blocks by * standing at the place where the block should go, then jumping up and placing * the block while being in the air. * * @author michael * */ public class JumpingPlaceAtHalfTask extends JumpingPlaceBlockAtFloorTask { private static final Marker MARKER_JUMPING_PLACE_HALF = MarkerManager.getMarker("jumping_place_half"); public final static EnumFacing[] TRY_FOR_LOWER = new EnumFacing[] { EnumFacing.DOWN, EnumFacing.EAST, EnumFacing.NORTH, EnumFacing.WEST, EnumFacing.SOUTH }; public final static EnumFacing[] TRY_FOR_UPPER = new EnumFacing[] { EnumFacing.EAST, EnumFacing.NORTH, EnumFacing.WEST, EnumFacing.SOUTH }; protected BlockHalf side; protected EnumFacing lookingDirection = null; private int attempts; public JumpingPlaceAtHalfTask(BlockPos pos, ItemFilter filter, BlockHalf side) { super(pos, filter); this.side = side; } @Override protected void faceBlock(AIHelper aiHelper, TaskOperations taskOperations) { final EnumFacing[] dirs = getBuildDirs(); for (int i = 0; i < dirs.length; i++) { if (faceSideBlock(aiHelper, dirs[attempts++ % dirs.length])) { return; } } taskOperations.desync(new StringTaskError("Could not face anywhere to place.")); } protected EnumFacing[] getBuildDirs() { return side == BlockHalf.UPPER_HALF ? TRY_FOR_UPPER : TRY_FOR_LOWER; } protected boolean faceSideBlock(AIHelper aiHelper, EnumFacing dir) { LOGGER.trace(MARKER_JUMPING_PLACE_HALF, "Facing side " + dir); BlockPos facingBlock = getPlaceAtPos().offset(dir); if (BlockSets.AIR.isAt(aiHelper.getWorld(), facingBlock)) { return false; } else { aiHelper.faceSideOf(facingBlock, dir.getOpposite(), getSide(dir) == BlockHalf.UPPER_HALF ? 0.5 : 0, getSide(dir) == BlockHalf.LOWER_HALF ? 0.5 : 1, aiHelper.getMinecraft().player.posX - pos.getX(), aiHelper.getMinecraft().player.posZ - pos.getZ(), lookingDirection); return true; } } protected BlockHalf getSide(EnumFacing dir) { return dir == EnumFacing.DOWN ? BlockHalf.UPPER_HALF : BlockHalf.LOWER_HALF; } @Override protected boolean isFacingRightBlock(AIHelper aiHelper) { for (final EnumFacing d : getBuildDirs()) { if (isFacing(aiHelper, d)) { return true; } } return false; } }
michaelzangl/minebot
Minebot/src/net/famzangl/minecraft/minebot/ai/task/place/JumpingPlaceAtHalfTask.java
Java
gpl-3.0
3,747
<?php /** * @file * Contains \Drupal\Tests\Core\Cache\Context\CacheContextsManagerTest. */ namespace Drupal\Tests\Core\Cache\Context; use Drupal\Core\Cache\CacheableMetadata; use Drupal\Core\Cache\Context\CacheContextsManager; use Drupal\Core\Cache\Context\CacheContextInterface; use Drupal\Core\Cache\Context\CalculatedCacheContextInterface; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Tests\UnitTestCase; use Symfony\Component\DependencyInjection\Container; /** * @coversDefaultClass \Drupal\Core\Cache\Context\CacheContextsManager * @group Cache */ class CacheContextsManagerTest extends UnitTestCase { /** * @covers ::optimizeTokens * * @dataProvider providerTestOptimizeTokens */ public function testOptimizeTokens(array $context_tokens, array $optimized_context_tokens) { $container = $this->getMockBuilder('Drupal\Core\DependencyInjection\Container') ->disableOriginalConstructor() ->getMock(); $container->expects($this->any()) ->method('get') ->will($this->returnValueMap([ ['cache_context.a', Container::EXCEPTION_ON_INVALID_REFERENCE, new FooCacheContext()], ['cache_context.a.b', Container::EXCEPTION_ON_INVALID_REFERENCE, new FooCacheContext()], ['cache_context.a.b.c', Container::EXCEPTION_ON_INVALID_REFERENCE, new BazCacheContext()], ['cache_context.x', Container::EXCEPTION_ON_INVALID_REFERENCE, new BazCacheContext()], ['cache_context.a.b.no-optimize', Container::EXCEPTION_ON_INVALID_REFERENCE, new NoOptimizeCacheContext()], ])); $cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture()); $this->assertSame($optimized_context_tokens, $cache_contexts_manager->optimizeTokens($context_tokens)); } /** * Provides a list of context token sets. */ public function providerTestOptimizeTokens() { return [ [['a', 'x'], ['a', 'x']], [['a.b', 'x'], ['a.b', 'x']], // Direct ancestor, single-level hierarchy. [['a', 'a.b'], ['a']], [['a.b', 'a'], ['a']], // Direct ancestor, multi-level hierarchy. [['a.b', 'a.b.c'], ['a.b']], [['a.b.c', 'a.b'], ['a.b']], // Indirect ancestor. [['a', 'a.b.c'], ['a']], [['a.b.c', 'a'], ['a']], // Direct & indirect ancestors. [['a', 'a.b', 'a.b.c'], ['a']], [['a', 'a.b.c', 'a.b'], ['a']], [['a.b', 'a', 'a.b.c'], ['a']], [['a.b', 'a.b.c', 'a'], ['a']], [['a.b.c', 'a.b', 'a'], ['a']], [['a.b.c', 'a', 'a.b'], ['a']], // Using parameters. [['a', 'a.b.c:foo'], ['a']], [['a.b.c:foo', 'a'], ['a']], [['a.b.c:foo', 'a.b.c'], ['a.b.c']], // max-age 0 is treated as non-optimizable. [['a.b.no-optimize', 'a.b', 'a'], ['a.b.no-optimize', 'a']], ]; } /** * @covers ::convertTokensToKeys */ public function testConvertTokensToKeys() { $container = $this->getMockContainer(); $cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture()); $new_keys = $cache_contexts_manager->convertTokensToKeys([ 'foo', 'baz:parameterA', 'baz:parameterB', ]); $expected = [ 'baz.cnenzrgreN', 'baz.cnenzrgreO', 'bar', ]; $this->assertEquals($expected, $new_keys->getKeys()); } /** * @covers ::convertTokensToKeys * * @expectedException \LogicException * @expectedExceptionMessage "non-cache-context" is not a valid cache context ID. */ public function testInvalidContext() { $container = $this->getMockContainer(); $cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture()); $cache_contexts_manager->convertTokensToKeys(["non-cache-context"]); } /** * @covers ::convertTokensToKeys * * @expectedException \Exception * * @dataProvider providerTestInvalidCalculatedContext */ public function testInvalidCalculatedContext($context_token) { $container = $this->getMockContainer(); $cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture()); $cache_contexts_manager->convertTokensToKeys([$context_token]); } /** * Provides a list of invalid 'baz' cache contexts: the parameter is missing. */ public function providerTestInvalidCalculatedContext() { return [ ['baz'], ['baz:'], ]; } public function testAvailableContextStrings() { $cache_contexts_manager = new CacheContextsManager($this->getMockContainer(), $this->getContextsFixture()); $contexts = $cache_contexts_manager->getAll(); $this->assertEquals(array("foo", "baz"), $contexts); } public function testAvailableContextLabels() { $container = $this->getMockContainer(); $cache_contexts_manager = new CacheContextsManager($container, $this->getContextsFixture()); $labels = $cache_contexts_manager->getLabels(); $expected = array("foo" => "Foo"); $this->assertEquals($expected, $labels); } protected function getContextsFixture() { return array('foo', 'baz'); } protected function getMockContainer() { $container = $this->getMockBuilder('Drupal\Core\DependencyInjection\Container') ->disableOriginalConstructor() ->getMock(); $container->expects($this->any()) ->method('get') ->will($this->returnValueMap([ ['cache_context.foo', Container::EXCEPTION_ON_INVALID_REFERENCE, new FooCacheContext()], ['cache_context.baz', Container::EXCEPTION_ON_INVALID_REFERENCE, new BazCacheContext()], ])); return $container; } /** * Provides a list of cache context token arrays. * * @return array */ public function validateTokensProvider() { return [ [[], FALSE], [['foo'], FALSE], [['foo', 'foo.bar'], FALSE], [['foo', 'baz:llama'], FALSE], // Invalid. [[FALSE], 'Cache contexts must be strings, boolean given.'], [[TRUE], 'Cache contexts must be strings, boolean given.'], [['foo', FALSE], 'Cache contexts must be strings, boolean given.'], [[NULL], 'Cache contexts must be strings, NULL given.'], [['foo', NULL], 'Cache contexts must be strings, NULL given.'], [[1337], 'Cache contexts must be strings, integer given.'], [['foo', 1337], 'Cache contexts must be strings, integer given.'], [[3.14], 'Cache contexts must be strings, double given.'], [['foo', 3.14], 'Cache contexts must be strings, double given.'], [[[]], 'Cache contexts must be strings, array given.'], [['foo', []], 'Cache contexts must be strings, array given.'], [['foo', ['bar']], 'Cache contexts must be strings, array given.'], [[new \stdClass()], 'Cache contexts must be strings, object given.'], [['foo', new \stdClass()], 'Cache contexts must be strings, object given.'], // Non-existing. [['foo.bar', 'qux'], '"qux" is not a valid cache context ID.'], [['qux', 'baz'], '"qux" is not a valid cache context ID.'], ]; } /** * @covers ::validateTokens * * @dataProvider validateTokensProvider */ public function testValidateContexts(array $contexts, $expected_exception_message) { $container = new ContainerBuilder(); $cache_contexts_manager = new CacheContextsManager($container, ['foo', 'foo.bar', 'baz']); if ($expected_exception_message !== FALSE) { $this->setExpectedException('LogicException', $expected_exception_message); } // If it doesn't throw an exception, validateTokens() returns NULL. $this->assertNull($cache_contexts_manager->validateTokens($contexts)); } } /** * Fake cache context class. */ class FooCacheContext implements CacheContextInterface { /** * {@inheritdoc} */ public static function getLabel() { return 'Foo'; } /** * {@inheritdoc} */ public function getContext() { return 'bar'; } /** * {@inheritdoc} */ public function getCacheableMetadata() { return new CacheableMetadata(); } } /** * Fake calculated cache context class. */ class BazCacheContext implements CalculatedCacheContextInterface { /** * {@inheritdoc} */ public static function getLabel() { return 'Baz'; } /** * {@inheritdoc} */ public function getContext($parameter = NULL) { if (!is_string($parameter) || strlen($parameter) === 0) { throw new \Exception(); } return 'baz.' . str_rot13($parameter); } /** * {@inheritdoc} */ public function getCacheableMetadata($parameter = NULL) { return new CacheableMetadata(); } } /** * Non-optimizable context class. */ class NoOptimizeCacheContext implements CacheContextInterface { /** * {@inheritdoc} */ public static function getLabel() { return 'Foo'; } /** * {@inheritdoc} */ public function getContext() { return 'bar'; } /** * {@inheritdoc} */ public function getCacheableMetadata() { $cacheable_metadata = new CacheableMetadata(); return $cacheable_metadata->setCacheMaxAge(0); } }
mbarcia/drupsible-org
core/tests/Drupal/Tests/Core/Cache/Context/CacheContextsManagerTest.php
PHP
gpl-3.0
9,085
namespace Maticsoft.Model.Pay { using System; [Serializable] public class RechargeRequest { private string _paymentgateway; private int _paymenttypeid; private decimal _rechargeblance; private long _rechargeid; private int? _sellerid; private int _status; private DateTime _tradedate; private int? _tradetype; private int _userid; public string PaymentGateway { get { return this._paymentgateway; } set { this._paymentgateway = value; } } public int PaymentTypeId { get { return this._paymenttypeid; } set { this._paymenttypeid = value; } } public decimal RechargeBlance { get { return this._rechargeblance; } set { this._rechargeblance = value; } } public long RechargeId { get { return this._rechargeid; } set { this._rechargeid = value; } } public int? SellerId { get { return this._sellerid; } set { this._sellerid = value; } } public int Status { get { return this._status; } set { this._status = value; } } public DateTime TradeDate { get { return this._tradedate; } set { this._tradedate = value; } } public int? Tradetype { get { return this._tradetype; } set { this._tradetype = value; } } public int UserId { get { return this._userid; } set { this._userid = value; } } } }
51zhaoshi/myyyyshop
Maticsoft.Model_Source/Maticsoft.Model.Pay/RechargeRequest.cs
C#
gpl-3.0
2,439
namespace Maticsoft.TaoBao.Request { using Maticsoft.TaoBao; using Maticsoft.TaoBao.Util; using System; using System.Collections.Generic; using System.Runtime.CompilerServices; public class TmallProductSpecGetRequest : ITopRequest<TmallProductSpecGetResponse> { private IDictionary<string, string> otherParameters; public void AddOtherParameter(string key, string value) { if (this.otherParameters == null) { this.otherParameters = new TopDictionary(); } this.otherParameters.Add(key, value); } public string GetApiName() { return "tmall.product.spec.get"; } public IDictionary<string, string> GetParameters() { TopDictionary dictionary = new TopDictionary(); dictionary.Add("spec_id", this.SpecId); dictionary.AddAll(this.otherParameters); return dictionary; } public void Validate() { RequestValidator.ValidateRequired("spec_id", this.SpecId); } public long? SpecId { get; set; } } }
51zhaoshi/myyyyshop
Maticsoft.TaoBao_Source/Maticsoft.TaoBao.Request/TmallProductSpecGetRequest.cs
C#
gpl-3.0
1,173
package com.mrdios.competencymatrix.springboot.example.rabbitmq.topic; import org.springframework.amqp.core.Binding; import org.springframework.amqp.core.BindingBuilder; import org.springframework.amqp.core.Queue; import org.springframework.amqp.core.TopicExchange; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * topic * * @author MrDios * @date 2017-08-08 */ @Configuration public class TopicRabbitConfig { static final String message = "topic.message"; static final String messages = "topic.messages"; @Bean public Queue queueMessage() { return new Queue(message); } @Bean public Queue queueMessages() { return new Queue(messages); } @Bean TopicExchange exchange() { return new TopicExchange("exchange"); } @Bean Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with(message); } @Bean Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) { return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#"); } }
balderdasher/competency-matrix
spring-boot/src/main/java/com/mrdios/competencymatrix/springboot/example/rabbitmq/topic/TopicRabbitConfig.java
Java
gpl-3.0
1,217
# ! /usr/bin/env python2.7 # _*_ coding:utf-8 _*_ """ @author = lucas.wang @create_time = 2018-01-12 """ import optparse import os import sys import getpass import json import hashlib import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header from datetime import date, time, datetime, timedelta # 配置文件路径 commendPath = "/Users/" + getpass.getuser() + "/" commendFinderName = ".ipa_build_py" commendFullPath = commendPath + commendFinderName configFileName = "ipaBuildPyConfigFile.json" commendFilePath = commendFullPath + "/" + configFileName # 工程名 targetName = None # 临时文件夹名称 tempFinder = None # git地址 gitPath = None # checkout后的本地路径 target_path = commendPath + "Documents" # 主路径 mainPath = None # 证书名 certificateName = None # 邮件参数 emailFromUser = None emailToUser = None emailPassword = None emailHost = None # 判断是否是workspace isWorkSpace = False # 版本 tag = "dev" # 钥匙链相关 keychainPath = "~/Library/Keychains/login.keychain" keychainPassword = "" # 显示已有的参数 def showParameter(): print "targetName :%s" % targetName print "gitPath :%s" % gitPath print "certificateName :%s" % certificateName print "emailFromUser :%s" % emailFromUser print "emailToUser :%s" % emailToUser print "emailPassword :%s" % emailPassword print "emailHost :%s" % emailHost print "keychainPassword(Optional) :%s" % keychainPassword # 设置参数 def setParameter(): global targetName global tempFinder global mainPath global gitPath global certificateName global emailFromUser global emailToUser global emailPassword global emailHost global keychainPassword targetName = raw_input("input targetName:") if not isNone(targetName): m = hashlib.md5() m.update('BossZP') tempFinder = m.hexdigest() mainPath = commendPath + 'Documents' + '/' + tempFinder gitPath = raw_input("input gitPath:") certificateName = raw_input("input certificateName:") emailFromUser = raw_input("input emailFromUser:") emailToUser = raw_input("input emailToUser:") emailPassword = raw_input("input emailPassword:") emailHost = raw_input("input emailHost:") keychainPassword = raw_input("input keychainPassword:") # 保存到本地 writeJsonFile() # 判断字符串是否为空 def isNone(para): if para == None or len(para) == 0: return True else: return False # 是否需要设置参数 def isNeedSetParameter(): if isNone(targetName) or isNone(gitPath) or isNone(certificateName) or isNone( emailFromUser) or isNone(emailToUser) or isNone(emailPassword) or isNone(emailHost): return True else: return False # 参数设置 def setOptparse(): p = optparse.OptionParser() # 参数配置指令 p.add_option("--config", "-c", action="store_true", default=None, help="config User's data") # 获取所有版本 p.add_option("--showTags", "-s", action="store_true", default=None, help="show all tags") # 设置版本指令 p.add_option('--tag', '-t', default="master", help="app's tag") options, arguments = p.parse_args() global tag tag = options.tag # 配置信息 if options.config == True and len(arguments) == 0: configMethod() # 获取所有版本 if options.showTags == True and len(arguments) == 0: gitShowTags() # 配置信息 def configMethod(): os.system("clear") readJsonFile() print "您的参数如下:" print "************************************" showParameter() print "************************************" setParameter() sys.exit() # 设置配置文件路径 def createFinder(): # 没有文件夹,创建文件夹 if not os.path.exists(commendPath + commendFinderName): os.system("cd %s;mkdir %s" % (commendPath, commendFinderName)) # 没有文件,创建文件 if not os.path.isfile(commendFilePath): os.system("cd %s;touch %s" % (commendFullPath, configFileName)) initJsonFile() return # 初始化json配置文件 def initJsonFile(): fout = open(commendFilePath, 'w') js = {} js["targetName"] = None js["gitPath"] = None js["certificateName"] = None js["emailFromUser"] = None js["emailToUser"] = None js["emailPassword"] = None js["emailHost"] = None js["tempFinder"] = None js["mainPath"] = None js["keychainPassword"] = None outStr = json.dumps(js, ensure_ascii=False) fout.write(outStr.strip().encode('utf-8') + '\n') fout.close() # 读取json文件 def readJsonFile(): fin = open(commendFilePath, 'r') for eachLine in fin: line = eachLine.strip().decode('utf-8') line = line.strip(',') js = None try: js = json.loads(line) global targetName global tempFinder global mainPath global gitPath global certificateName global emailFromUser global emailToUser global emailPassword global emailHost global keychainPassword targetName = js["targetName"] gitPath = js["gitPath"] certificateName = js["certificateName"] # firToken = js["firToken"] emailFromUser = js["emailFromUser"] emailToUser = js["emailToUser"] emailPassword = js["emailPassword"] emailHost = js["emailHost"] tempFinder = js["tempFinder"] mainPath = js["mainPath"] keychainPassword = js["keychainPassword"] except Exception, e: print Exception print e continue fin.close() # 写json文件 def writeJsonFile(): showParameter() try: fout = open(commendFilePath, 'w') js = {} js["targetName"] = targetName js["gitPath"] = gitPath js["certificateName"] = certificateName js["emailFromUser"] = emailFromUser js["emailToUser"] = emailToUser js["emailPassword"] = emailPassword js["emailHost"] = emailHost js["tempFinder"] = tempFinder js["mainPath"] = mainPath js["keychainPassword"] = keychainPassword outStr = json.dumps(js, ensure_ascii=False) fout.write(outStr.strip().encode('utf-8') + '\n') fout.close() except Exception, e: print Exception print e # 删除文件夹 def rmoveFinder(): os.system("rm -r -f %s" % mainPath) return # 创建文件夹 def createFileFinder(): os.system("mkdir %s" % mainPath) return # 对文件夹授权 def allowFinder(): os.system("chmod -R 777 %s" % mainPath) return # 查找文件 def scan_files(directory, postfix): files_list = [] for root, sub_dirs, files in os.walk(directory): for special_file in sub_dirs: if special_file.endswith(postfix): files_list.append(os.path.join(root, special_file)) return files_list # 判断文件夹是否存在 def isFinderExists(): return os.path.exists(mainPath) # clone工程 def gitClone(): os.system('git clone %s %s --depth 1' % (gitPath, mainPath)) return # 显示所有版本 def gitShowTags(): os.system("clear") readJsonFile() print "所有的版本" print mainPath print "************************************" os.system('cd %s;git tag' % mainPath) print "************************************" sys.exit() # pull工程 def gitPull(): os.system("cd %s;git reset --hard;git pull" % mainPath) return # 设置版本 def setGitVersion(version): if len(version) > 0: os.system("cd %s;git reset --hard;git checkout %s" % (mainPath, version)) return # 回到主版本 def setGitVersionMaster(): setGitVersion("master") return # clean工程 def cleanPro(): global isWorkSpace if isWorkSpace: os.system('cd %s;xcodebuild -workspace %s.xcworkspace -scheme %s clean' % (mainPath, targetName, targetName)) else: os.system('cd %s;xcodebuild -target %s clean' % (mainPath, targetName)) return # 清理pbxproj文件 def clearPbxproj(): global all_the_text path = "%s/%s.xcodeproj/project.pbxproj" % (mainPath, targetName) file_object = open(path) try: all_the_text = file_object.readlines() for text in all_the_text: if 'PROVISIONING_PROFILE' in text: all_the_text.remove(text) finally: file_object.close() file_object = open(path, 'w') try: for text in all_the_text: file_object.write(text) finally: file_object.close() return def allowKeychain(): # User interaction is not allowed os.system("security unlock-keychain -p '%s' %s" % (keychainPassword, keychainPath)) return # 编译获取.app文件和dsym def buildApp(): global isWorkSpace files_list = scan_files(mainPath, postfix=".xcodeproj") temp = -1 for k in range(len(files_list)): if files_list[k] == mainPath + "/" + targetName + ".xcodeproj": temp = k if temp >= 0: files_list.pop(temp) for target in files_list: target = target.replace(".xcodeproj", "") tmpList = target.split('/') name = tmpList[len(tmpList) - 1] path = target.replace(name, "") path = path[0:len(path) - 1] os.system("cd %s;xcodebuild -target %s CODE_SIGN_IDENTITY='%s'" % (path, name, certificateName)) if isWorkSpace: os.system( "cd %s;xcodebuild -workspace %s.xcworkspace -scheme %s CODE_SIGN_IDENTITY='%s' -derivedDataPath build/" % ( mainPath, targetName, targetName, certificateName)) else: os.system("cd %s;xcodebuild -target %s CODE_SIGN_IDENTITY='%s'" % (mainPath, targetName, certificateName)) return # 创建ipa def cerateIPA(): os.system("cd %s;rm -r -f %s.ipa" % (mainPath, targetName)) os.system( "cd %s;xcrun -sdk iphoneos PackageApplication -v %s/build/Build/Products/Debug-iphoneos/%s.app -o %s/%s.ipa CODE_SIGN_IDENTITY='%s'" % ( mainPath, mainPath, targetName, mainPath, targetName, certificateName)) return # 发邮件给测试不带附件 def sendEmail(text): if not os.path.exists("%s/%s.ipa" % (mainPath, targetName)): print "没有找到ipa文件" return msg = MIMEText('地址:%s' % text, 'plain', 'utf-8') msg['to'] = emailToUser msg['from'] = emailFromUser msg['subject'] = '新的测试包已经上传' try: server = smtplib.SMTP() server.connect(emailHost) server.login(emailFromUser, emailPassword) server.sendmail(msg['from'], msg['to'], msg.as_string()) server.quit() print '发送成功' except Exception, e: print str(e) return # 定时任务 def runTask(func, day=0, hour=0, min=0, second=0): # Init time now = datetime.now() strnow = now.strftime('%Y-%m-%d %H:%M:%S') print "now:", strnow # First next run time period = timedelta(days=day, hours=hour, minutes=min, seconds=second) next_time = now + period strnext_time = next_time.strftime('%Y-%m-%d %H:%M:%S') print "next run:", strnext_time while True: # Get system current time iter_now = datetime.now() iter_now_time = iter_now.strftime('%Y-%m-%d %H:%M:%S') if str(iter_now_time) == str(strnext_time): # Get every start work time print "start work: %s" % iter_now_time # Call task func func() print "task done." # Get next iteration time iter_time = iter_now + period strnext_time = iter_time.strftime('%Y-%m-%d %H:%M:%S') print "next_iter: %s" % strnext_time # Continue next iteration continue def setVersion(): global tag setGitVersion(tag) return # 判断是否是workspace def checkWorkSpace(): global isWorkSpace if os.path.exists("%s/%s.xcworkspace" % (mainPath, targetName)): isWorkSpace = True else: isWorkSpace = False return # 主函数 def main(): # 设置配置文件路径 createFinder() # 参数设置 setOptparse() # 读取json文件 readJsonFile() # 是否需要设置参数 if isNeedSetParameter(): print "您需要设置参数,您的参数如下(使用 --config 或者 -c):" showParameter() sys.exit() # 获取最新代码 if not isFinderExists(): createFileFinder() gitClone() else: gitPull() # 判断是否是workspace checkWorkSpace() # 设置版本 setVersion() # 设置文件夹权限 allowFinder() allowKeychain() # clear pbxproj文件 clearPbxproj() # clean工程 cleanPro() # 编译 buildApp() # 生成ipa文件 cerateIPA() # 发邮件给测试 sendEmail("Test address") return main()
Lucas-Wong/ToolsProject
IOS/ipa.py
Python
gpl-3.0
13,459
package org.workcraft.plugins.son.tools; import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import org.workcraft.Tool; import org.workcraft.dom.Node; import org.workcraft.exceptions.InvalidConnectionException; import org.workcraft.gui.graph.tools.AbstractTool; import org.workcraft.gui.graph.tools.Decorator; import org.workcraft.gui.graph.tools.GraphEditor; import org.workcraft.plugins.son.ONGroup; import org.workcraft.plugins.son.SON; import org.workcraft.plugins.son.VisualSON; import org.workcraft.plugins.son.algorithm.ASONAlg; import org.workcraft.plugins.son.algorithm.BSONAlg; import org.workcraft.plugins.son.algorithm.CSONCycleAlg; import org.workcraft.plugins.son.algorithm.Path; import org.workcraft.plugins.son.algorithm.PathAlgorithm; import org.workcraft.plugins.son.algorithm.RelationAlgorithm; import org.workcraft.plugins.son.connections.SONConnection; import org.workcraft.plugins.son.connections.VisualSONConnection; import org.workcraft.plugins.son.elements.Block; import org.workcraft.plugins.son.elements.ChannelPlace; import org.workcraft.plugins.son.elements.Condition; import org.workcraft.plugins.son.elements.TransitionNode; import org.workcraft.plugins.son.exception.UnboundedException; import org.workcraft.plugins.son.util.Marking; import org.workcraft.plugins.son.util.Phase; import org.workcraft.util.GUI; import org.workcraft.util.WorkspaceUtils; import org.workcraft.workspace.WorkspaceEntry; public class TestTool extends AbstractTool implements Tool { private String message = ""; public boolean isApplicableTo(WorkspaceEntry we) { return WorkspaceUtils.isApplicable(we, SON.class); } public String getSection() { return "test"; } public String getDisplayName() { return "Test"; } GraphEditor editor1; public void run(WorkspaceEntry we) { System.out.println("================================================================================"); SON net = (SON) we.getModelEntry().getMathModel(); // VisualSON vnet = (VisualSON) we.getModelEntry().getVisualModel(); // reachableMarkingsTest(net); esitmationTest(net); // timeTest(net); // bhvTimeTest(net); // getScenario(net); // dfsTest(net); // outputBefore(net); // phaseTest(net); // csonCycleTest(net); // abtreactConditionTest(net); // GUI.drawEditorMessage(editor, g, Color.red, "sfasdfadsfa"); // syncCycleTest(net); // blockMathLevelTest(net, vnet); // mathLevelTest(net, vnet); // connectionTypeTest(net, vnet); // this.convertBlockTest(net, vnet); // relation(net, vnet); // conditionOutputTest(vnet); } private void reachableMarkingsTest(SON net) { ASONAlg alg = new ASONAlg(net); for (ONGroup group : net.getGroups()) { try { Collection<Marking> markings = alg.getReachableMarkings(group); for (Marking marking : markings) { System.out.println(); for (Node node : marking) { System.out.print(net.getNodeReference(node) + ", "); } } } catch (UnboundedException e) { System.out.println(e.getMessage()); } } } private void esitmationTest(SON net) { // DFSEstimationAlg timeAlg = new DFSEstimationAlg(net, new Interval(0, // 0), Granularity.YEAR_YEAR, null); // BSONAlg bsonAlg = new BSONAlg(net); // try { // //timeAlg.entireEst(); // } catch (AlternativeStructureException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } System.out.println(net.getConditions().size() + " " + net.getSONConnections().size()); // try { // Interval result = // timeAlg.EstimateEndTime(bsonAlg.getInitial(net.getComponents()).iterator().next(), // null); // System.out.println("result" + result); // } catch (InconsistentTimeException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } catch (TimeOutOfBoundsException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } } /* * private void timeTest(SON net) { TimeAlg timeAlg = new TimeAlg(net); * * for (Node node : net.getComponents()) { * System.out.println(net.getNodeReference(node)); try { for (String str : * timeAlg.onConsistecy(node)) { System.out.println(str); } } catch * (InvalidStructureException e) { System.out.println("Structure error"); } * } } */ /* * private void bhvTimeTest(SON net) { BSONAlg bsonAlg = new BSONAlg(net); * * Collection<ONGroup> upperGroups = * bsonAlg.getUpperGroups(net.getGroups()); Collection<ONGroup> lowerGroups * = bsonAlg.getLowerGroups(net.getGroups()); Map<Condition, * Collection<Phase>> phases = bsonAlg.getAllPhases(); * * TimeAlg timeAlg = new TimeAlg(net); * * for (ONGroup group : upperGroups) { for (TransitionNode t : * group.getTransitionNodes()) { * System.out.println(net.getNodeReference(t)); for (String str : * timeAlg.bsonConsistency(t, phases)) { System.out.println(str); } } } * * for (ONGroup group : lowerGroups) { for (Condition c : * group.getConditions()) { if (net.getInputPNConnections(c).isEmpty()) { * System.out.println("ini: " + net.getNodeReference(c)); for (String str : * timeAlg.bsonConsistency2(c)) { System.out.println(str); } } * * if (net.getOutputPNConnections(c).isEmpty()) { System.out.println( * "fine: " + net.getNodeReference(c)); for (String str : * timeAlg.bsonConsistency3(c)) { System.out.println(str); } } * * } } } */ protected Collection<ChannelPlace> getSyncCPs(SON net) { Collection<ChannelPlace> result = new HashSet<>(); HashSet<Node> nodes = new HashSet<>(); nodes.addAll(net.getTransitionNodes()); nodes.addAll(net.getChannelPlaces()); CSONCycleAlg cycleAlg = new CSONCycleAlg(net); for (Path path : cycleAlg.syncCycleTask(nodes)) { for (Node node : path) { if (node instanceof ChannelPlace) { result.add((ChannelPlace) node); } } } return result; } private void getScenario(SON net) { new ScenarioGeneratorTool(); } private void dfsTest(SON net) { PathAlgorithm alg = new PathAlgorithm(net); RelationAlgorithm alg2 = new RelationAlgorithm(net); ONGroup g = net.getGroups().iterator().next(); Collection<Path> result = alg.getPaths(alg2.getONInitial(g).iterator().next(), alg2.getONFinal(g).iterator().next(), net.getGroups().iterator().next().getComponents()); for (Path path : result) { System.out.println(path.toString(net)); } } private void outputBefore(SON net) { BSONAlg bsonAlg = new BSONAlg(net); System.out.println("\nOutput before(e):"); Collection<TransitionNode[]> before = new ArrayList<>(); Collection<ONGroup> groups = bsonAlg.getUpperGroups(net.getGroups()); Collection<TransitionNode> set = new HashSet<>(); for (ONGroup group : groups) { set.addAll(group.getTransitionNodes()); } for (TransitionNode e : set) { // before = bsonAlg.before(e); if (!before.isEmpty()) { Collection<String> subResult = new ArrayList<>(); System.out.println("before(" + net.getComponentLabel(e) + "): "); for (TransitionNode[] t : before) { subResult.add("(" + net.getComponentLabel(t[0]) + " " + net.getComponentLabel(t[1]) + ")"); } System.out.println(subResult); } } } @Override public void drawInScreenSpace(final GraphEditor editor, Graphics2D g) { System.out.println("editor1111111"); int a = 0; if (a == 0) { GUI.drawEditorMessage(editor, g, Color.BLACK, "afdasfasd"); } } private void relation(SON net, VisualSON vnet) { for (Node node : net.getComponents()) { System.out.println("node name: " + net.getName(node) + " node pre size:" + net.getPreset(node).size() + " node post size:" + net.getPostset(node).size()); } } private void phaseTest(SON net) { BSONAlg alg = new BSONAlg(net); System.out.println("phase test"); for (Condition c : alg.getAllPhases().keySet()) { System.out.println("condition = " + net.getNodeReference(c)); for (Phase phase : alg.getAllPhases().get(c)) { System.out.println("phase = " + phase.toString(net)); } } } private void syncCycleTest(SON net) { CSONCycleAlg csonPath = new CSONCycleAlg(net); HashSet<Node> nodes = new HashSet<>(); nodes.addAll(net.getChannelPlaces()); nodes.addAll(net.getTransitionNodes()); for (Path path : csonPath.syncEventCycleTask(nodes)) { System.out.println(path.toString(net)); } } private void csonCycleTest(SON net) { CSONCycleAlg csonPath = new CSONCycleAlg(net); for (Path path : csonPath.cycleTask(net.getComponents())) { System.out.println(path.toString(net)); } } private void exceptionTest() throws InvalidConnectionException { boolean a = true; if (a) { message = "adfa"; throw new InvalidConnectionException(message); } } private void abtreactConditionTest(SON net) { BSONAlg alg = new BSONAlg(net); for (Node node : net.getComponents()) { for (Condition c : alg.getUpperConditions(node)) { System.out.println( "abstract condition of " + net.getNodeReference(node) + " is " + net.getNodeReference(c)); } } System.out.println("********************"); } /* * private void convertBlockTest(SONModel net, VisualSON vnet) { for (Node * node : net.getSONConnections()) { System.out.println("before " + * net.getName(node) + " parent " + node.getParent().toString() + " type = " * + ((SONConnection) node).getType()); } vnet.connectToBlocks(); * System.out.println("node size =" + net.getComponents().size()); for (Node * node : net.getSONConnections()) { System.out.println("after " + * net.getName(node) + " parent " + node.getParent().toString() + " type = " * + ((SONConnection) node).getType()); } } */ private void blockMathLevelTest(SON net, VisualSON vnet) { for (Block block : net.getBlocks()) { System.out.println("block name :" + net.getName(block)); System.out.println("connection size : " + block.getSONConnections().size()); } /* * for (VisualBlock block : vnet.getVisualBlocks()) { * System.out.println("visual block name :" + vnet.getName(block)); * System.out. println("visual connection size : " + * block.getVisualSONConnections().size()); } */ } private void mathLevelTest(SON net, VisualSON vnet) { for (ONGroup group : net.getGroups()) { System.out.println(group.toString()); System.out.println("Page size = " + group.getPageNodes().size()); System.out.println("block size = " + group.getBlocks().size()); System.out.println("Condition size = " + group.getConditions().size()); System.out.println("Event size = " + group.getEvents().size()); System.out.println("Connection size = " + group.getSONConnections().size()); System.out.println(); } /* * for (PageNode page : net.getPageNodes()) { System.out.println( * "page parent " + page.getParent().toString()); } */ /* * for (VisualONGroup vgroup: vnet.getVisualONGroups()) { * System.out.println(vgroup.toString()); System.out.println( * "Visual Page size = " + vgroup.getVisualPages().size()); * System.out.println("Visual Condition size = " + * vgroup.getVisualConditions().size()); System.out.println( * "Visual Connection size = " + * vgroup.getVisualSONConnections().size()); System.out.println( * "Visual block size = " + vgroup.getVisualBlocks().size()); * * } */ /* * for (VisualPage page : vnet.getVisualPages()) { System.out.println(); * System.out.println("visual page parent " + * page.getParent().toString()); } */ } private void connectionTypeTest(SON net, VisualSON vnet) { for (SONConnection con : net.getSONConnections()) { System.out.println("con type " + con.getSemantics()); System.out.println("con fisrt " + con.getFirst()); System.out.println("con fisrt " + con.getSecond()); } for (VisualSONConnection con : vnet.getVisualSONConnections()) { System.out.println("con type " + con.getSemantics()); System.out.println("con fisrt " + con.getFirst()); System.out.println("con fisrt " + con.getSecond()); } } @Override public Decorator getDecorator(GraphEditor editor) { // TODO Auto-generated method stub return null; } @Override public String getLabel() { // TODO Auto-generated method stub return null; } }
shelllbw/workcraft
SonPlugin/src/org/workcraft/plugins/son/tools/TestTool.java
Java
gpl-3.0
13,970
// ---------------------------------------------------------------------------- // Buzz, a Javascript HTML5 Audio library // v 1.0.x beta // Licensed under the MIT license. // http://buzz.jaysalvat.com/ // ---------------------------------------------------------------------------- // Copyright (C) 2011 Jay Salvat // http://jaysalvat.com/ // ---------------------------------------------------------------------------- // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files ( the "Software" ), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // ---------------------------------------------------------------------------- // // multi-channel support Addition by Alaa-eddine KADDOURI // // // Usage : // var mySound = new buzz.sound( // "music", { // formats: [ "ogg", "mp3" ], // channels : 4 // }); // // mySound.play(); //will use channel 0 // setTimeout(function() { // mySound.play(); //will use channel 1 if channel 0 still playing // }, 3000); // // var buzz = { defaults: { autoplay: false, duration: 5000, formats: [], loop: false, placeholder: '--', preload: 'metadata', volume: 80 }, types: { 'mp3': 'audio/mpeg', 'ogg': 'audio/ogg', 'wav': 'audio/wav', 'aac': 'audio/aac', 'm4a': 'audio/x-m4a' }, sounds: [], el: document.createElement( 'audio' ), sound: function( src, options ) { options = options || {}; var _pool = []; var _instance = this; var pid = 0, events = [], eventsOnce = {}, supported = buzz.isSupported(); // publics this.load = function() { if ( !supported || poolfn( 'load' )) { return this; } this.sound.load(); return this; }; this.play = function() { if ( !supported ) { return this; } //multi-channel support ---------------------// if (this.isPool) { var snd = getChannel(); if (!snd) return; this.sound = snd.sound; } //-------------------------------------------// this.sound.play(); return this; }; this.togglePlay = function() { if ( !supported || poolfn( 'togglePlay' )) { return this; } if ( this.sound.paused ) { this.sound.play(); } else { this.sound.pause(); } return this; }; this.pause = function() { if ( !supported || poolfn( 'pause' )) { return this; } this.sound.pause(); return this; }; this.isPaused = function() { if ( !supported ) { return null; } return this.sound.paused; }; this.stop = function() { if ( !supported || poolfn( 'stop' )) { return this; } this.setTime( 0 ); this.sound.pause(); return this; }; this.isEnded = function() { if ( !supported ) { return null; } return this.sound.ended; }; this.loop = function() { if ( !supported || poolfn( 'loop' )) { return this; } this.sound.loop = 'loop'; this.bind( 'ended.buzzloop', function() { this.currentTime = 0; this.play(); }); return this; }; this.unloop = function() { if ( !supported || poolfn( 'unloop' )) { return this; } this.sound.removeAttribute( 'loop' ); this.unbind( 'ended.buzzloop' ); return this; }; this.mute = function() { if ( !supported || poolfn( 'mute' )) { return this; } this.sound.muted = true; return this; }; this.unmute = function() { if ( !supported || poolfn( 'unmute' )) { return this; } this.sound.muted = false; return this; }; this.toggleMute = function() { if ( !supported || poolfn( 'toggleMute' )) { return this; } this.sound.muted = !this.sound.muted; return this; }; this.isMuted = function() { if ( !supported ) { return null; } return this.sound.muted; }; this.setVolume = function( volume ) { if ( !supported || poolfn( 'setVolume', volume)) { return this; } if ( volume < 0 ) { volume = 0; } if ( volume > 100 ) { volume = 100; } this.volume = volume; this.sound.volume = volume / 100; return this; }; this.getVolume = function() { if ( !supported ) { return this; } return this.volume; }; this.increaseVolume = function( value ) { return this.setVolume( this.volume + ( value || 1 ) ); }; this.decreaseVolume = function( value ) { return this.setVolume( this.volume - ( value || 1 ) ); }; this.setTime = function( time ) { if ( !supported || poolfn( 'setTime', time )) { return this; } this.whenReady( function() { this.sound.currentTime = time; }); return this; }; this.getTime = function(channelIdx) { if ( !supported) { return null; } if (channelIdx !== undefined && this.isPool) { var channel = getChannel(channelIdx); if (channel && channel.sound) { var time = Math.round( channel.sound.currentTime * 100 ) / 100; return isNaN( time ) ? buzz.defaults.placeholder : time; } } var time = Math.round( this.sound.currentTime * 100 ) / 100; return isNaN( time ) ? buzz.defaults.placeholder : time; }; this.setPercent = function( percent ) { if ( !supported ) { return this; } return this.setTime( buzz.fromPercent( percent, this.sound.duration ) ); }; this.getPercent = function() { if ( !supported ) { return null; } var percent = Math.round( buzz.toPercent( this.sound.currentTime, this.sound.duration ) ); return isNaN( percent ) ? buzz.defaults.placeholder : percent; }; this.setSpeed = function( duration ) { if ( !supported ) { return this; } this.sound.playbackRate = duration; }; this.getSpeed = function() { if ( !supported ) { return null; } return this.sound.playbackRate; }; this.getDuration = function() { if ( !supported ) { return null; } var duration = Math.round( this.sound.duration * 100 ) / 100; return isNaN( duration ) ? buzz.defaults.placeholder : duration; }; this.getPlayed = function() { if ( !supported ) { return null; } return timerangeToArray( this.sound.played ); }; this.getBuffered = function() { if ( !supported ) { return null; } return timerangeToArray( this.sound.buffered ); }; this.getSeekable = function() { if ( !supported ) { return null; } return timerangeToArray( this.sound.seekable ); }; this.getErrorCode = function() { if ( supported && this.sound.error ) { return this.sound.error.code; } return 0; }; this.getErrorMessage = function() { if ( !supported ) { return null; } switch( this.getErrorCode() ) { case 1: return 'MEDIA_ERR_ABORTED'; case 2: return 'MEDIA_ERR_NETWORK'; case 3: return 'MEDIA_ERR_DECODE'; case 4: return 'MEDIA_ERR_SRC_NOT_SUPPORTED'; default: return null; } }; this.getStateCode = function() { if ( !supported ) { return null; } return this.sound.readyState; }; this.getStateMessage = function() { if ( !supported ) { return null; } switch( this.getStateCode() ) { case 0: return 'HAVE_NOTHING'; case 1: return 'HAVE_METADATA'; case 2: return 'HAVE_CURRENT_DATA'; case 3: return 'HAVE_FUTURE_DATA'; case 4: return 'HAVE_ENOUGH_DATA'; default: return null; } }; this.getNetworkStateCode = function() { if ( !supported ) { return null; } return this.sound.networkState; }; this.getNetworkStateMessage = function() { if ( !supported ) { return null; } switch( this.getNetworkStateCode() ) { case 0: return 'NETWORK_EMPTY'; case 1: return 'NETWORK_IDLE'; case 2: return 'NETWORK_LOADING'; case 3: return 'NETWORK_NO_SOURCE'; default: return null; } }; this.set = function( key, value ) { if ( !supported || poolfn( 'set', key, value )) { return this; } this.sound[ key ] = value; return this; }; this.get = function( key ) { if ( !supported ) { return null; } return key ? this.sound[ key ] : this.sound; }; this.bind = function( types, func ) { if ( !supported || poolfn( 'bind', types, func )) { return this; } types = types.split( ' ' ); var that = this, efunc = function( e ) { func.call( that, e ); }; for( var t = 0; t < types.length; t++ ) { var type = types[ t ], idx = type; type = idx.split( '.' )[ 0 ]; events.push( { idx: idx, func: efunc } ); this.sound.addEventListener( type, efunc, true ); } return this; }; this.unbind = function( types ) { if ( !supported || poolfn( 'unbind', types )) { return this; } types = types.split( ' ' ); for( var t = 0; t < types.length; t++ ) { var idx = types[ t ], type = idx.split( '.' )[ 0 ]; for( var i = 0; i < events.length; i++ ) { var namespace = events[ i ].idx.split( '.' ); if ( events[ i ].idx == idx || ( namespace[ 1 ] && namespace[ 1 ] == idx.replace( '.', '' ) ) ) { this.sound.removeEventListener( type, events[ i ].func, true ); // remove event events.splice(i, 1); } } } return this; }; this.bindOnce = function( type, func ) { if ( !supported || poolfn( 'bindOnce', type, func )) { return this; } var that = this; eventsOnce[ pid++ ] = false; this.bind( type + '.' + pid, function() { if ( !eventsOnce[ pid ] ) { eventsOnce[ pid ] = true; func.call( that ); } that.unbind( type + '.' + pid ); }); }; this.trigger = function( types ) { if ( !supported || poolfn( 'trigger', types )) { return this; } types = types.split( ' ' ); for( var t = 0; t < types.length; t++ ) { var idx = types[ t ]; for( var i = 0; i < events.length; i++ ) { var eventType = events[ i ].idx.split( '.' ); if ( events[ i ].idx == idx || ( eventType[ 0 ] && eventType[ 0 ] == idx.replace( '.', '' ) ) ) { var evt = document.createEvent('HTMLEvents'); evt.initEvent( eventType[ 0 ], false, true ); this.sound.dispatchEvent( evt ); } } } return this; }; this.fadeTo = function( to, duration, callback ) { if ( !supported ) { return this; } if ( duration instanceof Function ) { callback = duration; duration = buzz.defaults.duration; } else { duration = duration || buzz.defaults.duration; } var from = this.volume, delay = duration / Math.abs( from - to ), that = this; this.play(); function doFade() { setTimeout( function() { if ( from < to && that.volume < to ) { that.setVolume( that.volume += 1 ); doFade(); } else if ( from > to && that.volume > to ) { that.setVolume( that.volume -= 1 ); doFade(); } else if ( callback instanceof Function ) { callback.apply( that ); } }, delay ); } this.whenReady( function() { doFade(); }); return this; }; this.fadeIn = function( duration, callback ) { if ( !supported || poolfn( 'fadeIn', duration, callback )) { return this; } return this.setVolume(0).fadeTo( 100, duration, callback ); }; this.fadeOut = function( duration, callback ) { if ( !supported || poolfn( 'fadeOut', duration, callback )) { return this; } return this.fadeTo( 0, duration, callback ); }; this.fadeWith = function( sound, duration ) { if ( !supported ) { return this; } this.fadeOut( duration, function() { this.stop(); }); sound.play().fadeIn( duration ); return this; }; this.whenReady = function( func ) { if ( !supported ) { return null; } var that = this; if ( this.sound.readyState === 0 ) { this.bind( 'canplay.buzzwhenready', function() { func.call( that ); }); } else { func.call( that ); } }; // privates function timerangeToArray( timeRange ) { var array = [], length = timeRange.length - 1; for( var i = 0; i <= length; i++ ) { array.push({ start: timeRange.start( length ), end: timeRange.end( length ) }); } return array; } function getExt( filename ) { return filename.split('.').pop(); } function addSource( sound, src ) { var source = document.createElement( 'source' ); source.src = src; if ( buzz.types[ getExt( src ) ] ) { source.type = buzz.types[ getExt( src ) ]; } sound.appendChild( source ); } //multi-channel support --------------------------// function poolfn() { if (!_instance.isPool) return false; var args = argsToArray( null, arguments ), func = args.shift(); for( var i = 0; i < _pool.length; i++ ) { _pool[ i ][ func ].apply( _pool[ i ], args ); } return true; } function argsToArray( array, args ) { return ( array instanceof Array ) ? array : Array.prototype.slice.call( args ); } //look for available channel function getChannel(channelIdx) { if (channelIdx !== undefined) return _pool[channelIdx]; for (var i =0; i<_pool.length; i++) { if (_pool[i].isEnded() || _pool[i].isPaused()) return _pool[i]; } return false; } //-----------------------------------------------------// // init if ( supported && src ) { for(var i in buzz.defaults ) { if(buzz.defaults.hasOwnProperty(i)) { options[ i ] = options[ i ] || buzz.defaults[ i ]; } } // multi-channel support -------------------// if (options.channels > 1) //pool or simple sound instance ? { this.isPool = true; var poolsCount = options.channels; for (var i=0; i<poolsCount; i++) { options.channels = 0; _pool.push(new buzz.sound(src, options)); //clone original sound but only initialize one channel per clone } //init first channel this.sound = _pool[0].sound; return; } //-----------------------------------------// this.sound = document.createElement( 'audio' ); if ( src instanceof Array ) { for( var j in src ) { if(src.hasOwnProperty(j)) { addSource( this.sound, src[ j ] ); } } } else if ( options.formats.length ) { for( var k in options.formats ) { if(options.formats.hasOwnProperty(k)) { addSource( this.sound, src + '.' + options.formats[ k ] ); } } } else { addSource( this.sound, src ); } if ( options.loop ) { this.loop(); } if ( options.autoplay ) { this.sound.autoplay = 'autoplay'; } if ( options.preload === true ) { this.sound.preload = 'auto'; } else if ( options.preload === false ) { this.sound.preload = 'none'; } else { this.sound.preload = options.preload; } this.setVolume( options.volume ); buzz.sounds.push( this ); } }, group: function( sounds ) { sounds = argsToArray( sounds, arguments ); // publics this.getSounds = function() { return sounds; }; this.add = function( soundArray ) { soundArray = argsToArray( soundArray, arguments ); for( var a = 0; a < soundArray.length; a++ ) { sounds.push( soundArray[ a ] ); } }; this.remove = function( soundArray ) { soundArray = argsToArray( soundArray, arguments ); for( var a = 0; a < soundArray.length; a++ ) { for( var i = 0; i < sounds.length; i++ ) { if ( sounds[ i ] == soundArray[ a ] ) { sounds.splice(i, 1); break; } } } }; this.load = function() { fn( 'load' ); return this; }; this.play = function() { fn( 'play' ); return this; }; this.togglePlay = function( ) { fn( 'togglePlay' ); return this; }; this.pause = function( time ) { fn( 'pause', time ); return this; }; this.stop = function() { fn( 'stop' ); return this; }; this.mute = function() { fn( 'mute' ); return this; }; this.unmute = function() { fn( 'unmute' ); return this; }; this.toggleMute = function() { fn( 'toggleMute' ); return this; }; this.setVolume = function( volume ) { fn( 'setVolume', volume ); return this; }; this.increaseVolume = function( value ) { fn( 'increaseVolume', value ); return this; }; this.decreaseVolume = function( value ) { fn( 'decreaseVolume', value ); return this; }; this.loop = function() { fn( 'loop' ); return this; }; this.unloop = function() { fn( 'unloop' ); return this; }; this.setTime = function( time ) { fn( 'setTime', time ); return this; }; this.set = function( key, value ) { fn( 'set', key, value ); return this; }; this.bind = function( type, func ) { fn( 'bind', type, func ); return this; }; this.unbind = function( type ) { fn( 'unbind', type ); return this; }; this.bindOnce = function( type, func ) { fn( 'bindOnce', type, func ); return this; }; this.trigger = function( type ) { fn( 'trigger', type ); return this; }; this.fade = function( from, to, duration, callback ) { fn( 'fade', from, to, duration, callback ); return this; }; this.fadeIn = function( duration, callback ) { fn( 'fadeIn', duration, callback ); return this; }; this.fadeOut = function( duration, callback ) { fn( 'fadeOut', duration, callback ); return this; }; // privates function fn() { var args = argsToArray( null, arguments ), func = args.shift(); for( var i = 0; i < sounds.length; i++ ) { sounds[ i ][ func ].apply( sounds[ i ], args ); } } function argsToArray( array, args ) { return ( array instanceof Array ) ? array : Array.prototype.slice.call( args ); } }, all: function() { return new buzz.group( buzz.sounds ); }, isSupported: function() { return !!buzz.el.canPlayType; }, isOGGSupported: function() { return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/ogg; codecs="vorbis"' ); }, isWAVSupported: function() { return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/wav; codecs="1"' ); }, isMP3Supported: function() { return !!buzz.el.canPlayType && buzz.el.canPlayType( 'audio/mpeg;' ); }, isAACSupported: function() { return !!buzz.el.canPlayType && ( buzz.el.canPlayType( 'audio/x-m4a;' ) || buzz.el.canPlayType( 'audio/aac;' ) ); }, toTimer: function( time, withHours ) { var h, m, s; h = Math.floor( time / 3600 ); h = isNaN( h ) ? '--' : ( h >= 10 ) ? h : '0' + h; m = withHours ? Math.floor( time / 60 % 60 ) : Math.floor( time / 60 ); m = isNaN( m ) ? '--' : ( m >= 10 ) ? m : '0' + m; s = Math.floor( time % 60 ); s = isNaN( s ) ? '--' : ( s >= 10 ) ? s : '0' + s; return withHours ? h + ':' + m + ':' + s : m + ':' + s; }, fromTimer: function( time ) { var splits = time.toString().split( ':' ); if ( splits && splits.length == 3 ) { time = ( parseInt( splits[ 0 ], 10 ) * 3600 ) + ( parseInt(splits[ 1 ], 10 ) * 60 ) + parseInt( splits[ 2 ], 10 ); } if ( splits && splits.length == 2 ) { time = ( parseInt( splits[ 0 ], 10 ) * 60 ) + parseInt( splits[ 1 ], 10 ); } return time; }, toPercent: function( value, total, decimal ) { var r = Math.pow( 10, decimal || 0 ); return Math.round( ( ( value * 100 ) / total ) * r ) / r; }, fromPercent: function( percent, total, decimal ) { var r = Math.pow( 10, decimal || 0 ); return Math.round( ( ( total / 100 ) * percent ) * r ) / r; } };
kushsolitary/Inkpen
public/assets/js/buzz.js
JavaScript
gpl-3.0
26,388
/* * A Command & Conquer: Renegade SSGM Plugin, containing all the single player mission scripts * Copyright(C) 2017 Neijwiert * * This program is free software : you can redistribute it and / or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program.If not, see <http://www.gnu.org/licenses/>. */ #include "General.h" #include "MX0_KillNotify.h" void MX0_KillNotify::Register_Auto_Save_Variables() { Auto_Save_Variable(&this->doTaunts, sizeof(this->doTaunts), 1); } // 1 Second later when the star is done with his animation in the intro cinematic. void MX0_KillNotify::Created(GameObject *obj) { this->doTaunts = false; } void MX0_KillNotify::Custom(GameObject *obj, int type, int param, GameObject *sender) { // Received from MX0_MissionStart_DME after MX0_NOD_TroopDrop sent custom to it if (type == 114) { Commands->Start_Timer(obj, this, 3.0f, 139); Commands->Start_Timer(obj, this, 7.0f, 140); } } void MX0_KillNotify::Timer_Expired(GameObject *obj, int number) { // Triggered 3 seconds after custom type 114 received from MX0_MissionStart_DME if (number == 139) { int conversationId = Commands->Create_Conversation("MX0CON020", 95, 2000.0f, false); //NOD control, I count 5 GDI targets. Commands->Join_Conversation(obj, conversationId, true, true, true); Commands->Start_Conversation(conversationId, 100020); Commands->Monitor_Conversation(obj, conversationId); } // Triggered 7 seconds after custom type 114 received from MX0_MissionStart_DME else if (number == 140) { int conversationId = Commands->Create_Conversation("MX0CON021", 99, 2000.0f, false); //Correction. Make that 4. Commands->Join_Conversation(obj, conversationId, true, true, true); Commands->Start_Conversation(conversationId, 100021); Commands->Monitor_Conversation(obj, conversationId); Commands->Start_Timer(obj, this, 5.0f, 141); } // Triggered 5 seconds after timer 140 triggered or 5 seconds after this triggered else if (number == 141) { if (this->doTaunts) { static const char * const CONVERSATIONS[] = { "Mx0_NODSNIPER_Alt01", //Tracking targets… "Mx0_NODSNIPER_Alt02", //Stay right there, infidel. "Mx0_NODSNIPER_Alt03", //Don’t move, infidel. "Mx0_NODSNIPER_Alt04", //Easy… "Mx0_NODSNIPER_Alt05", //Heh! "Mx0_NODSNIPER_Alt06" //Steady… }; int randomInt = Commands->Get_Random_Int(0, 6); int conversationId = Commands->Create_Conversation(CONVERSATIONS[randomInt], 95, 2000.0f, false); Commands->Join_Conversation(obj, conversationId, true, true, true); Commands->Start_Conversation(conversationId, 100021); Commands->Monitor_Conversation(obj, conversationId); Commands->Start_Timer(obj, this, 5.0f, 141); } } } void MX0_KillNotify::Killed(GameObject *obj, GameObject *killer) { Vector3 pos = Commands->Get_Position(obj); if (killer == Commands->Get_A_Star(pos)) { GameObject *MX0MissionStartDMEObj = Commands->Find_Object(1200001); Commands->Send_Custom_Event(obj, MX0MissionStartDMEObj, 138, 0, 0.0f); } } ScriptRegistrant<MX0_KillNotify> MX0_KillNotifyRegistrant("MX0_KillNotify", "");
Neijwiert/C-C-Renegade-Mission-Scripts
Source/Single Player Scripts/MX0_KillNotify.cpp
C++
gpl-3.0
3,584
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | foam-extend: Open Source CFD \\ / O peration | Version: 3.2 \\ / A nd | Web: http://www.foam-extend.org \\/ M anipulation | For copyright notice see file Copyright ------------------------------------------------------------------------------- License This file is part of foam-extend. foam-extend 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. foam-extend 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 foam-extend. If not, see <http://www.gnu.org/licenses/>. \*---------------------------------------------------------------------------*/ #include "polyMesh.H" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // // Update this with w2 if not yet set. inline bool Foam::wallNormalInfo::update(const wallNormalInfo& w2) { if (!w2.valid()) { FatalErrorIn ( "wallNormalInfo::update(const wallNormalInfo&)" ) << "Problem: w2 is not valid" << abort(FatalError); return false; } else if (valid()) { // our already set. Stop any transfer return false; } else { normal_ = w2.normal(); return true; } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Null constructor inline Foam::wallNormalInfo::wallNormalInfo() : normal_(greatVector) {} // Construct from normal inline Foam::wallNormalInfo::wallNormalInfo(const vector& normal) : normal_(normal) {} // Construct as copy inline Foam::wallNormalInfo::wallNormalInfo(const wallNormalInfo& wpt) : normal_(wpt.normal()) {} // * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * // inline const Foam::vector& Foam::wallNormalInfo::normal() const { return normal_; } inline bool Foam::wallNormalInfo::valid() const { return normal_ != greatVector; } // No geometric data so never any problem on cyclics inline bool Foam::wallNormalInfo::sameGeometry ( const polyMesh&, const wallNormalInfo& w2, const scalar tol ) const { return true; } // No geometric data. inline void Foam::wallNormalInfo::leaveDomain ( const polyMesh&, const polyPatch& patch, const label patchFaceI, const point& faceCentre ) {} // No geometric data. inline void Foam::wallNormalInfo::transform ( const polyMesh&, const tensor& rotTensor ) {} // No geometric data. inline void Foam::wallNormalInfo::enterDomain ( const polyMesh&, const polyPatch& patch, const label patchFaceI, const point& faceCentre ) {} // Update this with w2 if w2 nearer to pt. inline bool Foam::wallNormalInfo::updateCell ( const polyMesh&, const label thisCellI, const label neighbourFaceI, const wallNormalInfo& neighbourWallInfo, const scalar tol ) { return update(neighbourWallInfo); } // Update this with w2 if w2 nearer to pt. inline bool Foam::wallNormalInfo::updateFace ( const polyMesh&, const label thisFaceI, const label neighbourCellI, const wallNormalInfo& neighbourWallInfo, const scalar tol ) { return update(neighbourWallInfo); } // Update this with w2 if w2 nearer to pt. inline bool Foam::wallNormalInfo::updateFace ( const polyMesh&, const label thisFaceI, const wallNormalInfo& neighbourWallInfo, const scalar tol ) { return update(neighbourWallInfo); } // * * * * * * * * * * * * * * * Member Operators * * * * * * * * * * * * * // inline bool Foam::wallNormalInfo::operator==(const Foam::wallNormalInfo& rhs) const { return normal() == rhs.normal(); } inline bool Foam::wallNormalInfo::operator!=(const Foam::wallNormalInfo& rhs) const { return !(*this == rhs); } // ************************************************************************* //
Unofficial-Extend-Project-Mirror/foam-extend-foam-extend-3.2
src/dynamicMesh/dynamicMesh/directTopoChange/meshCut/wallLayerCells/wallNormalInfo/wallNormalInfoI.H
C++
gpl-3.0
4,412
// ActiveTime // Copyright (C) 2011-2017 Dust in the Wind // // 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/>. using System; using System.Diagnostics.CodeAnalysis; using DustInTheWind.ActiveTime.Persistence; using DustInTheWind.ActiveTime.Persistence.LiteDB.Module.Repositories; using DustInTheWind.ActiveTime.UnitTests.PersistenceModule.LiteDB.Helpers; using LiteDB; using NUnit.Framework; namespace DustInTheWind.ActiveTime.UnitTests.PersistenceModule.LiteDB.Repositories.DayCommentRepositoryTests { [TestFixture] [SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable", Justification = "The disposable objects are disposed in the TearDown method.")] public class AddTests { private DayCommentRepository dayCommentRepository; private LiteDatabase database; [SetUp] public void SetUp() { DbTestHelper.ClearDatabase(); database = new LiteDatabase(DbTestHelper.ConnectionString); dayCommentRepository = new DayCommentRepository(database); } [TearDown] public void TearDown() { database.Dispose(); } [Test] public void sets_the_id_of_the_DayComment_entity() { DayComment dayComment = CreateDayCommentEntity(); dayCommentRepository.Add(dayComment); Assert.That(dayComment.Id, Is.Not.EqualTo(0)); } [Test] public void saves_the_DayComment_in_the_database() { DayComment dayComment = CreateDayCommentEntity(); dayCommentRepository.Add(dayComment); DbAssert.AssertDayCommentCount(1, x => x.Id == dayComment.Id); } [Test] public void saves_two_DayComments_in_the_database() { DayComment dayComment1 = CreateDayCommentEntity(); dayComment1.Date = new DateTime(2014, 06, 13); DayComment dayComment2 = CreateDayCommentEntity(); dayComment2.Date = new DateTime(2014, 03, 05); dayCommentRepository.Add(dayComment1); dayCommentRepository.Add(dayComment2); DbAssert.AssertDayCommentCount(1, x => x.Id == dayComment1.Id); DbAssert.AssertDayCommentCount(1, x => x.Id == dayComment2.Id); } [Test] public void throws_if_two_identical_DayComments_are_saved() { Assert.Throws<PersistenceException>(() => { DayComment dayComment1 = CreateDayCommentEntity(); DayComment dayComment2 = CreateDayCommentEntity(); dayCommentRepository.Add(dayComment1); dayCommentRepository.Add(dayComment2); }); } [Test] public void correctly_adds_all_the_fields() { DayComment dayComment = CreateDayCommentEntity(); dayCommentRepository.Add(dayComment); DbAssert.AssertExistsDayCommentEqualTo(dayComment); } private static DayComment CreateDayCommentEntity() { return new DayComment { Id = 0, Date = new DateTime(2014, 04, 30), Comment = "This is a comment" }; } } }
emanueldejanu/ActiveTime
sources/ActiveTime.Tests/PersistenceModule.LiteDB/Repositories/DayCommentRepositoryTests/AddTests.cs
C#
gpl-3.0
4,022
# -*- coding: utf-8 -*- # Generated by Django 1.11.13 on 2018-08-26 08:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("accounts", "0001_squashed_0037_auto_20180416_1406")] operations = [ migrations.AddField( model_name="profile", name="uploaded", field=models.IntegerField(db_index=True, default=0), ) ]
dontnod/weblate
weblate/accounts/migrations/0002_profile_uploaded.py
Python
gpl-3.0
466
// Decompiled with JetBrains decompiler // Type: System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy // Assembly: System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 5ABD58FD-DF31-44FD-A492-63F2B47CC9AF // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.dll using System; using System.Collections; using System.ComponentModel; using System.Net; using System.Runtime; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Text; namespace System.Security.Authentication.ExtendedProtection { /// <summary> /// The <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> class represents the extended protection policy used by the server to validate incoming client connections. /// </summary> [TypeConverter(typeof (ExtendedProtectionPolicyTypeConverter))] [Serializable] public class ExtendedProtectionPolicy : ISerializable { private ServiceNameCollection customServiceNames; private PolicyEnforcement policyEnforcement; private ProtectionScenario protectionScenario; private ChannelBinding customChannelBinding; private const string policyEnforcementName = "policyEnforcement"; private const string protectionScenarioName = "protectionScenario"; private const string customServiceNamesName = "customServiceNames"; private const string customChannelBindingName = "customChannelBinding"; /// <summary> /// Gets the custom Service Provider Name (SPN) list used to match against a client's SPN. /// </summary> /// /// <returns> /// A <see cref="T:System.Security.Authentication.ExtendedProtection.ServiceNameCollection"/> that contains the custom SPN list that is used to match against a client's SPN. /// </returns> public ServiceNameCollection CustomServiceNames { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.customServiceNames; } } /// <summary> /// Gets when the extended protection policy should be enforced. /// </summary> /// /// <returns> /// A <see cref="T:System.Security.Authentication.ExtendedProtection.PolicyEnforcement"/> value that indicates when the extended protection policy should be enforced. /// </returns> public PolicyEnforcement PolicyEnforcement { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.policyEnforcement; } } /// <summary> /// Gets the kind of protection enforced by the extended protection policy. /// </summary> /// /// <returns> /// A <see cref="T:System.Security.Authentication.ExtendedProtection.ProtectionScenario"/> value that indicates the kind of protection enforced by the policy. /// </returns> public ProtectionScenario ProtectionScenario { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.protectionScenario; } } /// <summary> /// Gets a custom channel binding token (CBT) to use for validation. /// </summary> /// /// <returns> /// A <see cref="T:System.Security.Authentication.ExtendedProtection.ChannelBinding"/> that contains a custom channel binding to use for validation. /// </returns> public ChannelBinding CustomChannelBinding { [TargetedPatchingOptOut("Performance critical to inline this type of method across NGen image boundaries")] get { return this.customChannelBinding; } } /// <summary> /// Indicates whether the operating system supports integrated windows authentication with extended protection. /// </summary> /// /// <returns> /// true if the operating system supports integrated windows authentication with extended protection, otherwise false. /// </returns> public static bool OSSupportsExtendedProtection { get { return AuthenticationManager.OSSupportsExtendedProtection; } } /// <summary> /// Initializes a new instance of the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> class that specifies when the extended protection policy should be enforced, the kind of protection enforced by the policy, and a custom Service Provider Name (SPN) list that is used to match against a client's SPN. /// </summary> /// <param name="policyEnforcement">A <see cref="T:System.Security.Authentication.ExtendedProtection.PolicyEnforcement"/> value that indicates when the extended protection policy should be enforced.</param><param name="protectionScenario">A <see cref="T:System.Security.Authentication.ExtendedProtection.ProtectionScenario"/> value that indicates the kind of protection enforced by the policy.</param><param name="customServiceNames">A <see cref="T:System.Security.Authentication.ExtendedProtection.ServiceNameCollection"/> that contains the custom SPN list that is used to match against a client's SPN.</param><exception cref="T:System.ArgumentException"><paramref name="policyEnforcement"/> is specified as <see cref="F:System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never"/>.</exception><exception cref="T:System.ArgumentNullException"><paramref name="customServiceNames "/>is nullor an empty list. </exception> public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, ProtectionScenario protectionScenario, ServiceNameCollection customServiceNames) { if (policyEnforcement == PolicyEnforcement.Never) throw new ArgumentException(SR.GetString("security_ExtendedProtectionPolicy_UseDifferentConstructorForNever"), "policyEnforcement"); if (customServiceNames != null && customServiceNames.Count == 0) throw new ArgumentException(SR.GetString("security_ExtendedProtectionPolicy_NoEmptyServiceNameCollection"), "customServiceNames"); this.policyEnforcement = policyEnforcement; this.protectionScenario = protectionScenario; this.customServiceNames = customServiceNames; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> class that specifies when the extended protection policy should be enforced, the kind of protection enforced by the policy, and a custom Service Provider Name (SPN) list that is used to match against a client's SPN. /// </summary> /// <param name="policyEnforcement">A <see cref="T:System.Security.Authentication.ExtendedProtection.PolicyEnforcement"/> value that indicates when the extended protection policy should be enforced.</param><param name="protectionScenario">A <see cref="T:System.Security.Authentication.ExtendedProtection.ProtectionScenario"/> value that indicates the kind of protection enforced by the policy.</param><param name="customServiceNames">A <see cref="T:System.Collections.ICollection"/> that contains the custom SPN list that is used to match against a client's SPN.</param><exception cref="T:System.ArgumentException"><paramref name="policyEnforcement"/> is specified as <see cref="F:System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never"/>.</exception><exception cref="T:System.ArgumentNullException"><paramref name="customServiceNames "/>is nullor an empty list. </exception> public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, ProtectionScenario protectionScenario, ICollection customServiceNames) : this(policyEnforcement, protectionScenario, customServiceNames == null ? (ServiceNameCollection) null : new ServiceNameCollection(customServiceNames)) { } /// <summary> /// Initializes a new instance of the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> class that specifies when the extended protection policy should be enforced and the channel binding token (CBT) to be used. /// </summary> /// <param name="policyEnforcement">A <see cref="T:System.Security.Authentication.ExtendedProtection.PolicyEnforcement"/> value that indicates when the extended protection policy should be enforced.</param><param name="customChannelBinding">A <see cref="T:System.Security.Authentication.ExtendedProtection.ChannelBinding"/> that contains a custom channel binding to use for validation.</param><exception cref="T:System.ArgumentException"><paramref name="policyEnforcement"/> is specified as <see cref="F:System.Security.Authentication.ExtendedProtection.PolicyEnforcement.Never"/>.</exception><exception cref="T:System.ArgumentNullException"><paramref name="customChannelBinding "/>is null. </exception> public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement, ChannelBinding customChannelBinding) { if (policyEnforcement == PolicyEnforcement.Never) throw new ArgumentException(SR.GetString("security_ExtendedProtectionPolicy_UseDifferentConstructorForNever"), "policyEnforcement"); if (customChannelBinding == null) throw new ArgumentNullException("customChannelBinding"); this.policyEnforcement = policyEnforcement; this.protectionScenario = ProtectionScenario.TransportSelected; this.customChannelBinding = customChannelBinding; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> class that specifies when the extended protection policy should be enforced. /// </summary> /// <param name="policyEnforcement">A <see cref="T:System.Security.Authentication.ExtendedProtection.PolicyEnforcement"/> value that indicates when the extended protection policy should be enforced.</param> public ExtendedProtectionPolicy(PolicyEnforcement policyEnforcement) { this.policyEnforcement = policyEnforcement; this.protectionScenario = ProtectionScenario.TransportSelected; } /// <summary> /// Initializes a new instance of the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> class from a <see cref="T:System.Runtime.Serialization.SerializationInfo"/> object that contains the required data to populate the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/>. /// </summary> /// <param name="info">A <see cref="T:System.Runtime.Serialization.SerializationInfo"/> instance that contains the information that is required to serialize the new <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> instance.</param><param name="context">A <see cref="T:System.Runtime.Serialization.StreamingContext"/> that contains the source of the serialized stream that is associated with the new <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> instance.</param> protected ExtendedProtectionPolicy(SerializationInfo info, StreamingContext context) { this.policyEnforcement = (PolicyEnforcement) info.GetInt32("policyEnforcement"); this.protectionScenario = (ProtectionScenario) info.GetInt32("protectionScenario"); this.customServiceNames = (ServiceNameCollection) info.GetValue("customServiceNames", typeof (ServiceNameCollection)); byte[] source = (byte[]) info.GetValue("customChannelBinding", typeof (byte[])); if (source == null) return; this.customChannelBinding = (ChannelBinding) SafeLocalFreeChannelBinding.LocalAlloc(source.Length); Marshal.Copy(source, 0, this.customChannelBinding.DangerousGetHandle(), source.Length); } /// <summary> /// Gets a string representation for the extended protection policy instance. /// </summary> /// /// <returns> /// A <see cref="T:System.String"/> instance that contains the representation of the <see cref="T:System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy"/> instance. /// </returns> public override string ToString() { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("ProtectionScenario="); stringBuilder.Append(this.protectionScenario.ToString()); stringBuilder.Append("; PolicyEnforcement="); stringBuilder.Append(this.policyEnforcement.ToString()); stringBuilder.Append("; CustomChannelBinding="); if (this.customChannelBinding == null) stringBuilder.Append("<null>"); else stringBuilder.Append(this.customChannelBinding.ToString()); stringBuilder.Append("; ServiceNames="); if (this.customServiceNames == null) { stringBuilder.Append("<null>"); } else { bool flag = true; foreach (string str in (ReadOnlyCollectionBase) this.customServiceNames) { if (flag) flag = false; else stringBuilder.Append(", "); stringBuilder.Append(str); } } return stringBuilder.ToString(); } [SecurityPermission(SecurityAction.LinkDemand, SerializationFormatter = true)] void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("policyEnforcement", (int) this.policyEnforcement); info.AddValue("protectionScenario", (int) this.protectionScenario); info.AddValue("customServiceNames", (object) this.customServiceNames, typeof (ServiceNameCollection)); if (this.customChannelBinding == null) { info.AddValue("customChannelBinding", (object) null, typeof (byte[])); } else { byte[] destination = new byte[this.customChannelBinding.Size]; Marshal.Copy(this.customChannelBinding.DangerousGetHandle(), destination, 0, this.customChannelBinding.Size); info.AddValue("customChannelBinding", (object) destination, typeof (byte[])); } } } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System/System/Security/Authentication/ExtendedProtection/ExtendedProtectionPolicy.cs
C#
gpl-3.0
14,133
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GAME.Common.Core.Interfaces.Plugin; namespace GAME.Common.Core.Interfaces { public interface IPluginGroup : IGroup { int CountLaunched { get; set; } } }
madks13/G.A.M.E.
GAME.Common/Interfaces/IPluginGroup.cs
C#
gpl-3.0
300
<?php // This file is part of Moodle - http://moodle.org/ // // Moodle is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // Moodle is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Moodle. If not, see <http://www.gnu.org/licenses/>. /** * MOODLE VERSION INFORMATION * * This file defines the current version of the core Moodle code being used. * This is compared against the values stored in the database to determine * whether upgrades should be performed (see lib/db/*.php) * * @package core * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com) * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later */ defined('MOODLE_INTERNAL') || die(); $version = 2015091000.00; // YYYYMMDD = weekly release date of this DEV branch. // RR = release increments - 00 in DEV branches. // .XX = incremental changes. $release = '3.0dev (Build: 20150910)'; // Human-friendly version name $branch = '30'; // This version's branch. $maturity = MATURITY_ALPHA; // This version's maturity level.
davidluz/moodle
version.php
PHP
gpl-3.0
1,637
/* Copyright (c) Goran Sterjov This file is part of the Fuse Project. Fuse 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. Fuse 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 Fuse; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ using System; using System.IO; using Gtk; namespace Fuse.Plugin.Library { /// <summary> /// Adds specific playlist functionality to the ListStore class. /// </summary> public class PlaylistStore : ListStore { PlaylistDataManager data_manager = new PlaylistDataManager (); public PlaylistStore () : base (typeof (Playlist)) {} /// <summary> /// Checks to see if the playlist is already in the library. /// </summary> public bool PlaylistExists (string name) { bool exists = false; this.Foreach (delegate (TreeModel model, TreePath tree_path, TreeIter iter) { Playlist playlist = (Playlist) model.GetValue (iter, 0); if (playlist.Name == name) exists = true; return exists; }); return exists; } /// <summary> /// Create a new playlist and add it to the store. /// </summary> public void CreatePlaylist () { int i = 1; string new_playlist = "New Playlist"; string name = new_playlist; while (PlaylistExists (name)) name = new_playlist + " " + i++; Playlist playlist = new Playlist (name); this.AppendValues (playlist); data_manager.AddPlaylist (playlist); } /// <summary> /// Add files into the playlist. /// </summary> public void AddFiles (string[] files, Playlist playlist) { if (files == null || files.Length == 0) return; string path = Path.GetDirectoryName (files[0]); // load the files within the directory Progress progress = new Progress (Global.Core.Library.MediaBox); progress.Start ((double) files.Length); progress.Push ("Waiting in queue: " + Utils.GetFolderName (path)); // queue process Global.Core.Library.DelegateQueue.Enqueue (delegate { foreach (string file in files) { if (progress.Canceled) break; progress.Push ("Loading File: " + Path.GetFileName (file)); Global.Core.Library.MediaTree.MediaStore.AddMedia (file, playlist); progress.Step (); } progress.End (); }); } /// <summary> /// Add the folder into the playlist. /// </summary> public void AddFolder (string path, Playlist playlist) { // load the files within the directory Progress progress = new Progress (Global.Core.Library.MediaBox); progress.Start (Utils.FileCount (path)); progress.Push ("Waiting in queue: " + Utils.GetFolderName (path)); // queue process Global.Core.Library.DelegateQueue.Enqueue (delegate { addDirRecurse (path, progress, playlist); progress.End (); }); } /// <summary> /// The data manager for the store. /// </summary> public PlaylistDataManager DataManager { get{ return data_manager; } } // recursively add directories into the media library private void addDirRecurse (string path, Progress progress, Playlist playlist) { // add all files within the directory foreach (string file in Directory.GetFiles (path)) { if (progress.Canceled) return; progress.Push ("Loading File: " + Path.GetFileName (file)); Global.Core.Library.MediaTree.MediaStore.AddMedia (file, playlist); progress.Step (); } // recurse into directories, if any foreach (string dir in Directory.GetDirectories (path)) { if (progress.Canceled) return; addDirRecurse (dir, progress, playlist); } } } }
gsterjov/fusemc
Plugin.Library/Playlists/PlaylistStore.cs
C#
gpl-3.0
4,170
/** * Module dependencies */ var _ = require('@sailshq/lodash'); var getDisplayTypeLabel = require('./get-display-type-label'); /** * getNounPhrase() * * Given an RTTC "display type" string (and some options) * return an appropriate human-readable noun-phrase. * Useful for error messages, user interfaces, etc. * * @required {String} type * Recognizes any of the standard RTTC types: * • string * • number * • boolean * • lamda * • dictionary * • array * • json * • ref * * * @optional {Dictionary} options * * @property {Boolean} plural * If enabled, the returned noun phrase will be plural. * @default false * * @property {Boolean} completeSentence * If enabled, a complete sentence with a capital letter * & ending punctuation (a period) will be returned. * Otherwise (by default), the returned noun phrase will * be a fragment designed for use in an existing sentence. * @default false * * @property {String} determiner * One of: * • "the" (definite article) * • "a" (indefinite article) * • "any" (existential qualifier) * • "" (no determiner) * > Note that if "a" is specified, either "a" or "an" will be used, * > whichever is more appropriate. * > (for more background, see https://en.wikipedia.org/wiki/Article_(grammar) * > and/or https://en.wikipedia.org/wiki/English_determiners) * @default "a" (or "", if plural) * * * @return {String} [noun phrase] */ module.exports = function getNounPhrase(type, options){ if (typeof type !== 'string') { throw new Error('Usage error: rttc.getNounPhrase() expects a string display type such as '+ '`dictionary` or `ref`. If you are trying to get the noun phrase for an exemplar, do '+ '`rttc.getNounPhrase(rttc.inferDisplayType(exemplar))`. If you are trying to get a noun '+ 'phrase to represent voidness (i.e. null exemplar), then you should determine that on a '+ 'case-by-case basis-- there\'s no good sane default.'); } // Set up defaults options = options || {}; options = _.defaults(options, { plural: false, completeSentence: false, determiner: !options.plural ? 'a' : '' }); // Tolerate "an" for "a" if (options.determiner === 'an') { options.determiner = 'a'; } // Validate determiner if (!_.contains(['the', 'a', 'any', ''], options.determiner)) { throw new Error('Usage error: Unrecognized `determiner` option: `'+options.determiner+'`. '+ 'Should be either "the", "a", "any", or "". (defaults to "a", or "" if plural)'); } // Ensure we're not trying to use "a" in a plural noun phrase. if (options.plural && options.determiner === 'a') { throw new Error('Usage error: Cannot use that determiner ("a") to generate a plural noun phrase. '+ 'Trust me, it wouldn\'t sound right.'); } // Compute the display type label that will be used below. var displayTypeLabel = getDisplayTypeLabel(type, { capitalization: 'fragment', plural: options.plural }); // Determine the appropriate naked noun phrase. // (i.e. with determiner, but without ending punctuation or start-sentence capitalization) var nounPhrase; if (type === 'string') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'number') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'boolean') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'lamda') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'dictionary') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'array') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'an '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else if (type === 'json') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } // for future reference, this is where we could do: // > "might be a string, number, boolean, dictionary, array, or even null" } else if (type === 'ref') { switch (options.determiner) { case 'the': nounPhrase = 'the '+displayTypeLabel; break; case 'a': nounPhrase = 'a '+displayTypeLabel; break; case 'any': nounPhrase = 'any '+displayTypeLabel; break; case '': nounPhrase = displayTypeLabel; break; } } else { throw new Error('Unknown type: `'+type+'`'); } // Finally, deal with sentence capitalization and ending punctuation (if relevant). if (options.completeSentence) { nounPhrase = nounPhrase[0].toUpperCase() + nounPhrase.slice(1); nounPhrase += '.'; } // And return our noun phrase. return nounPhrase; };
deshbandhu-renovite/receipt-eCommerce
node_modules/rttc/lib/get-noun-phrase.js
JavaScript
gpl-3.0
6,514
/* Actiona Copyright (C) 2005 Jonathan Mercier-Ganady Actiona 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. Actiona 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/>. Contact: jmgr@jmgr.info */ #pragma once #include "actiontools/actioninstance.hpp" class QDialog; class QGridLayout; class QAbstractButton; class QComboBox; class QListWidget; class QButtonGroup; namespace Actions { class MultiDataInputInstance : public ActionTools::ActionInstance { Q_OBJECT public: enum Mode { ComboBoxMode, EditableComboBoxMode, ListMode, CheckboxMode, RadioButtonMode }; Q_ENUM(Mode) MultiDataInputInstance(const ActionTools::ActionDefinition *definition, QObject *parent = nullptr); static Tools::StringListPair modes; void startExecution() override; void stopExecution() override; private slots: void accepted(); void rejected(); void listItemSelectionChanged(); void checkboxChecked(QAbstractButton *checkbox); private: template<class T> QGridLayout *createRadioButtonsOrCheckboxes(const QString &defaultValue, bool exclusive); void saveSelectedRadioButtonOrCheckBox(); void closeDialog(); QDialog *mDialog; Mode mMode; QString mVariable; QStringList mItems; int mMinimumChoiceCount; int mMaximumChoiceCount; QComboBox *mComboBox; QListWidget *mListWidget; QButtonGroup *mButtonGroup; Q_DISABLE_COPY(MultiDataInputInstance) }; }
Jmgr/actiona
actions/windows/src/actions/multidatainputinstance.hpp
C++
gpl-3.0
1,924
/**************************************************************************** ** Meta object code from reading C++ file 'qscilexerpo.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.4.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../Qsci/qscilexerpo.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qscilexerpo.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.4.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE struct qt_meta_stringdata_QsciLexerPO_t { QByteArrayData data[5]; char stringdata[49]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_QsciLexerPO_t, stringdata) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_QsciLexerPO_t qt_meta_stringdata_QsciLexerPO = { { QT_MOC_LITERAL(0, 0, 11), // "QsciLexerPO" QT_MOC_LITERAL(1, 12, 15), // "setFoldComments" QT_MOC_LITERAL(2, 28, 0), // "" QT_MOC_LITERAL(3, 29, 4), // "fold" QT_MOC_LITERAL(4, 34, 14) // "setFoldCompact" }, "QsciLexerPO\0setFoldComments\0\0fold\0" "setFoldCompact" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_QsciLexerPO[] = { // content: 7, // revision 0, // classname 0, 0, // classinfo 2, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: name, argc, parameters, tag, flags 1, 1, 24, 2, 0x0a /* Public */, 4, 1, 27, 2, 0x0a /* Public */, // slots: parameters QMetaType::Void, QMetaType::Bool, 3, QMetaType::Void, QMetaType::Bool, 3, 0 // eod }; void QsciLexerPO::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { QsciLexerPO *_t = static_cast<QsciLexerPO *>(_o); switch (_id) { case 0: _t->setFoldComments((*reinterpret_cast< bool(*)>(_a[1]))); break; case 1: _t->setFoldCompact((*reinterpret_cast< bool(*)>(_a[1]))); break; default: ; } } } const QMetaObject QsciLexerPO::staticMetaObject = { { &QsciLexer::staticMetaObject, qt_meta_stringdata_QsciLexerPO.data, qt_meta_data_QsciLexerPO, qt_static_metacall, Q_NULLPTR, Q_NULLPTR} }; const QMetaObject *QsciLexerPO::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *QsciLexerPO::qt_metacast(const char *_clname) { if (!_clname) return Q_NULLPTR; if (!strcmp(_clname, qt_meta_stringdata_QsciLexerPO.stringdata)) return static_cast<void*>(const_cast< QsciLexerPO*>(this)); return QsciLexer::qt_metacast(_clname); } int QsciLexerPO::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QsciLexer::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 2) qt_static_metacall(this, _c, _id, _a); _id -= 2; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 2) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 2; } return _id; } QT_END_MOC_NAMESPACE
jgcoded/QScintilla
Qt4Qt5/release/moc_qscilexerpo.cpp
C++
gpl-3.0
3,656
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { public static PlayerController Shared; public float speedFowardPerSec = 5; // units per second public float speedBackwardPerSec = 2; // units per second public float jumpSpeed = 8; public float gravity = 9.8f; private float vSpeed = 0; // current vertical velocity // Use this for initialization void Awake () { Shared = this; } // Update is called once per frame void Update () { Vector3 vel; if (Input.GetAxis ("Vertical") > 0) vel = new Vector3 (Input.GetAxis ("Horizontal") * speedFowardPerSec / 2, 0, Input.GetAxis ("Vertical") * speedFowardPerSec); else vel = new Vector3 (Input.GetAxis ("Horizontal") * speedFowardPerSec / 2, 0, Input.GetAxis ("Vertical") * speedBackwardPerSec); var controller = GetComponent<CharacterController>(); if (controller.isGrounded){ vSpeed = 0; // grounded character has vSpeed = 0... if (Input.GetKeyDown("space")){ // unless it jumps: vSpeed = jumpSpeed; } } // apply gravity acceleration to vertical speed: vSpeed -= gravity * Time.deltaTime; vel.y = vSpeed; // include vertical speed in vel // convert vel to displacement and Move the character: controller.Move(vel * Time.deltaTime); } void OnCollision(string tag){ GameObject GC = GameObject.FindGameObjectWithTag("GameController"); if(tag == "Ghost"){ GC.SendMessage("GameOver"); } if(tag == "Temple"){ if(SoulController.Shared.SoulboxCount<7) Camera.main.SendMessage("feedback"); else GC.SendMessage("EndGame"); } } void OnCollisionEnter(Collision collision) { OnCollision (collision.collider.tag); } public void OnTriggerEnter(Collider coli){ OnCollision (coli.gameObject.tag); } void OnControllerColliderHit(ControllerColliderHit hit) { string tag = hit.collider.tag; OnCollision (tag); } }
obandox/el_movimiento_es_vida
Assets/App/Scripts/Controllers/PlayerController.cs
C#
gpl-3.0
1,915
#!/usr/bin/python # # original code from adafruit, see below copyrights # hacked version for bioreactor one # #-------------------------------------------------------------------------------------------- # -- 031616 -- converting temp to fahrenhight, and logging # -- 031816 -- adding in the led libraries to do a simple test, hopefully will add scrolling display # -- 031816 -- well, attempt at creating a font library for the 8x8 screen, # since they aint one. # -- 031916 -- (b) reverse the current characters # -- (g) open the log, and get the temp in f and humidity in h, with dec # -- then build the logic to display the right character. # -- (s) implement the rest of the characters # -- 032116 -- just received the max7219, branching to max2719_scroller, # -- attempting to intgrate the new display and add time # -- (s) add feature for weather, stocks, and headlines. # -- also removed the adafruit webIDE, checking it didn't catasrophically # -- fuck up anything else with it.. also upgrading and updating... fingers crossed... #--------------------------------------------------------------------------------------------------- # # .=-.-. _,.---._ ,---. # _..---. /==/_ /,-.' , - `. _.-. .--.' \ _..---. # .' .'.-. \|==|, |/==/_, , - \ .-,.'| \==\-/\ \ .' .'.-. \ # /==/- '=' /|==| |==| .=. |==|, | /==/-|_\ | /==/- '=' / # |==|-, ' |==|- |==|_ : ;=: - |==|- | \==\, - \ |==|-, ' # |==| .=. \|==| ,|==| , '=' |==|, | /==/ - ,| |==| .=. \ # /==/- '=' ,|==|- |\==\ - ,_ /|==|- `-._/==/- /\ - \ /==/- '=' ,| # |==| - //==/. / '.='. - .' /==/ - , ,|==\ _.\=\.-'|==| - / # `-._`.___,' `--`-` `--`--'' `--`-----' `--` `-._`.___,' # _,.---._ .-._ ,----. # ,-.' , - `. /==/ \ .-._ ,-.--` , \ # /==/_, , - \|==|, \/ /, /==|- _.-` # |==| .=. |==|- \| ||==| `.-. # |==|_ : ;=: - |==| , | -/==/_ , / # |==| , '=' |==| - _ |==| .-' # \==\ - ,_ /|==| /\ , |==|_ ,`-._ # '.='. - .' /==/, | |- /==/ , / # `--`--'' `--`./ `--`--`-----`` # # ,--.--------. ,--.--------. ,--.--------. # /==/, - , -\ /==/, - , -\ /==/, - , -\ # \==\.-. - ,-./ \==\.-. - ,-./ \==\.-. - ,-./ # `--`--------` `--`--------` `--`--------` # # ,----. ,---.--. ,-.--, ,---.--. # _.-. ,-.--` , \ _,..---._ / -_ \==\.--.-. /=/, .'/ -_ \==\ # .-,.'| |==|- _.-`/==/, - \ |` / \/==/\==\ -\/=/- / |` / \/==/ # |==|, | |==| `.-.|==| _ _\ \ \ /==/ \==\ `-' ,/ \ \ /==/ # |==|- | /==/_ , /|==| .=. | / \==/ |==|, - | / \==/ # |==|, | |==| .-' |==|,| | -| /. / \==\ /==/ , \ /. / \==\ # |==|- `-._|==|_ ,`-._|==| '=' / | _ \_/\==\/==/, .--, - \| _ \_/\==\ # /==/ - , ,/==/ , /|==|-, _`/ \ . - /==/\==\- \/=/ , /\ . - /==/ # `--`-----'`--`-----`` `-.`.____.' '----`--` `--`-' `--` '----`--` # #-------------------------------------------------------------------------------- # Copyleft (c) 2016 Alchemy Computing # Copyright (c) 2014 Adafruit Industries # Hacker: Justin Knox # legal shit--------------------------------------------------------------------- # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # end of legal shit--------------------------------------------------------------- #--------------------------------------------------- # .__ __ # |__| _____ ______ ____________/ |_ ______ # | |/ \\____ \ / _ \_ __ \ __\/ ___/ # | | Y Y \ |_> > <_> ) | \/| | \___ \ # |__|__|_| / __/ \____/|__| |__| /____ > # \/|__| \/ # #--------------------------------------------------- import time import datetime import max7219.led as led import time from max7219.font import proportional, SINCLAIR_FONT, TINY_FONT, CP437_FONT from random import randrange from collections import deque #---------------------------------------------------- # .__ # _____ _____ |__| ____ # / \\__ \ | |/ \ # | Y Y \/ __ \| | | \ # |__|_| (____ /__|___| / # \/ \/ \/ #---------------------------------------------------- # =========================================================================== # 8x8 Pixel Example # # =========================================================================== toggle = True sleepCount = 0 print "-----=-=-=-------=- bioreactor-one - montior-one -=---------=-=-=--------" print " .... testing .... pixels ... LEDS .................... " print "-------=---------=---------------------------------=-----------=----------" print "Press CTRL+Z to exit" print "--------------------------------------------------------------------------" device = led.matrix(cascaded=1) device.orientation(180) #device.show_message("-----=-=-=-------=- bioreactor-one - montior-one -=---------=-=-=--------\ # \ # .... testing .... pixels ... LEDS .................... \ # ", font=proportional(CP437_FONT)) # # open the log for reading values #---------------------------------------------------------------------------------- print "-----=-=-=-------=- bioreactor-one - montior-one -=---------=-=-=--------" tempValFlog = open("/home/pi/curr_F.log", "r"); print "Opening log... .", tempValFlog.name, " ...in..", tempValFlog.mode, "..access mode." tempValHlog = open("/home/pi/curr_H.log", "r"); print "Opening log... .", tempValHlog.name, " ...in..", tempValHlog.mode, "..access mode." print "-------=---------=---------------------------------=-----------=----------" print " press CTL-Z to exit " print "--------------------------------------------------------------------------" prevFloatFval = 0 prevFloatHval = 0 scrollon = True #device.show_message(" Welcome to BioLabOne - AlchemyComputing ") while(scrollon): print "-----=-=-=-------=- bioreactor-one - montior-one -=---------=-=-=--------" tempValFlog = open("/home/pi/curr_F.log", "r"); print "Opening log... .", tempValFlog.name, " ...in..", tempValFlog.mode, "..access mode." tempValHlog = open("/home/pi/curr_H.log", "r"); print "Opening log... .", tempValHlog.name, " ...in..", tempValHlog.mode, "..access mode." #---------------------------------------------------------------------------------- # 032116 -- new strategy is to open the log, check for a new value, # -- if there's no new value, close the log, and wait half a second # -- if there is a new value, display the new value, and close the log! #---------------------------------------------------------------------------------- currentF = tempValFlog.read(5) currentH = tempValHlog.read(5) print "Got values..." print "....current from log F: ", currentF print "....current fom log H: ", currentH print "--------------------" #-------------------------------------------------------- # closing the log just in case simple_logger.py needs it #-------------------------------------------------------- print "Closing log...", tempValFlog.name print "Closing log...", tempValHlog.name tempValFlog.close() tempValHlog.close() print " ", tempValFlog.closed print " ", tempValHlog.closed print "--------------------------=-=-=-=-=-=------------------------------------------" # 032216 -- converting back in the old code that grabbed the decimal values #first we have to isolate the 100's place, in this case 0 #if the 100's is 0, then we'll display a space #then lets grab the 10's, 1's and the decimal portion. #also, we gotta typecast the shit out of this cause of pythons implicit typing... hundyPlaceFval = int(float(currentF) / 100) tensPlaceFval = int(float(currentF) / 10) onesPlaceFval = int( float(currentF) - (hundyPlaceFval*100 + tensPlaceFval*10) ) decimalPlaceFval = int((float(currentF) - ( hundyPlaceFval + tensPlaceFval + onesPlaceFval )) * 10) decimalPlaceFval /= 100 #lets see what we got print 'F hundy', int(hundyPlaceFval) print 'F tens', int(tensPlaceFval) print 'F ones', int(onesPlaceFval) print 'F deci', int(decimalPlaceFval) #now lets do the Humidity's hundyPlaceHval = int(float(currentH) / 100) tensPlaceHval = int(float(currentH) / 10) onesPlaceHval = int( float(currentH) - (hundyPlaceHval*100 + tensPlaceHval*10) ) decimalPlaceHval = int((float(currentH) - ( hundyPlaceHval + tensPlaceHval + onesPlaceHval )) * 10) decimalPlaceHval /= 100 #lets see what we got print '\n' print 'H hundy', int(hundyPlaceHval) print 'H tens', int(tensPlaceHval) print 'H ones', int(onesPlaceHval) print 'H deci', int(decimalPlaceHval) floatFval = float(hundyPlaceFval*100 + tensPlaceFval*10 + onesPlaceFval + decimalPlaceFval/10) floatHval = float(hundyPlaceHval*100 + tensPlaceHval*10 + onesPlaceHval + decimalPlaceHval/10) #-------------- always display the values -------------------------------------------- device.show_message( " F: " ) device.show_message( str( floatFval ) ) device.letter(0, 248) device.show_message( " H: " ) device.show_message( str( floatHval ) ) device.show_message("%") device.show_message( time.strftime("%c")) #------------------------------------------code below only shows when temp changes #-----------------------------------------------------------------------show fahrenheit #device.show_message( "Fahrenheit = " ) if( floatFval > (0.1 + prevFloatFval ) ): #device.letter(0, 176);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 176);time.sleep(1) device.show_message( " +F: " ) device.show_message( str( floatFval ) ) device.letter(0, 248) sleepCount = 0 if( floatFval < (0.1 - prevFloatFval) ): #device.letter(0, 176);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 176);time.sleep(1) device.show_message( " -F: " ) device.show_message( str( floatFval ) ) device.letter(0, 248) sleepCount = 0 if( floatFval == ( prevFloatFval ) ): if(sleepCount<6): device.show_message( " - - - " ) sleepCount+=1 #-----------------------------------------------------------------------one by one display #if(hundyPlaceFval!=0): # device.show_message( str(hundyPlaceFval ) ) #device.show_message( str(tensPlaceFval ) ) #device.show_message( str(onesPlaceFval ) ) #device.show_message(".") #device.show_message( str(decimalPlaceFval ) ) #------------------------------------------------------------------------show humidity #device.show_message( "Humidity = " ) if( floatHval > (0.1 + prevFloatHval) ): #device.letter(0, 176);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 176);time.sleep(1) device.show_message( " +H: " ) device.show_message( str( floatHval ) ) device.show_message("%") sleepCount = 0 if( floatHval < (0.1 - prevFloatHval) ): #device.letter(0, 176);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 219);time.sleep(1) #device.letter(0, 177);time.sleep(1) #device.letter(0, 176);time.sleep(1) device.show_message( " -H: " ) device.show_message( str( floatHval ) ) device.show_message("%") sleepCount = 0 if( floatHval == ( prevFloatHval ) ): if(sleepCount<4): device.show_message( "- - - " ) sleepCount+=1 #------------------------------------------------------------------------go to sleep if(sleepCount > 3): sleepCount-=1 print "Sleeping ... ", sleepCount time.sleep(3) #------------------------------------------------------------------------single message method #-----------------------------------------------------------------------one by one display #if(hundyPlaceHval!=0): # device.show_message( str(hundyPlaceHval ) ) #device.show_message( str(tensPlaceHval ) ) #device.show_message( str(onesPlaceHval ) ) #device.show_message(".") #device.show_message( str(decimalPlaceHval ) ) prevFloatFval = floatFval prevFloatHval = floatHval #time.sleep(3) #device.show_message( "Current Time: ") #device.show_message( time.strftime("%c")) #tempRSSfeed = open("/home/pi/feeds/feeds.db", "r") #feedData = tempRSSfeed.read(end) #device.show_message( feedData)
alchemycomputing/raspberrypi-bioreactorproject
maxscroller.py
Python
gpl-3.0
13,796
######################################################################## # $HeadURL$ # File : InstallTools.py # Author : Ricardo Graciani ######################################################################## """ Collection of Tools for installation of DIRAC components: MySQL, DB's, Services's, Agents It only makes use of defaults in LocalInstallation Section in dirac.cfg The Following Options are used:: /DIRAC/Setup: Setup to be used for any operation /LocalInstallation/InstanceName: Name of the Instance for the current Setup (default /DIRAC/Setup) /LocalInstallation/LogLevel: LogLevel set in "run" script for all components installed /LocalInstallation/RootPath: Used instead of rootPath in "run" script if defined (if links are used to named versions) /LocalInstallation/InstancePath: Location where runit and startup directories are created (default rootPath) /LocalInstallation/UseVersionsDir: DIRAC is installed under versions/<Versioned Directory> with a link from pro (This option overwrites RootPath and InstancePath) /LocalInstallation/Host: Used when build the URL to be published for the installed service (default: socket.getfqdn()) /LocalInstallation/RunitDir: Location where runit directory is created (default InstancePath/runit) /LocalInstallation/StartupDir: Location where startup directory is created (default InstancePath/startup) /LocalInstallation/MySQLDir: Location where mysql databases are created (default InstancePath/mysql) /LocalInstallation/Database/User: (default Dirac) /LocalInstallation/Database/Password: (must be set for SystemAdministrator Service to work) /LocalInstallation/Database/RootPwd: (must be set for SystemAdministrator Service to work) /LocalInstallation/Database/Host: (must be set for SystemAdministrator Service to work) /LocalInstallation/Database/MySQLSmallMem: Configure a MySQL with small memory requirements for testing purposes innodb_buffer_pool_size=200MB /LocalInstallation/Database/MySQLLargeMem: Configure a MySQL with high memory requirements for production purposes innodb_buffer_pool_size=10000MB The setupSite method (used by the dirac-setup-site command) will use the following info:: /LocalInstallation/Systems: List of Systems to be defined for this instance in the CS (default: Configuration, Framework) /LocalInstallation/Databases: List of Databases to be installed and configured /LocalInstallation/Services: List of System/ServiceName to be setup /LocalInstallation/Agents: List of System/AgentName to be setup /LocalInstallation/WebPortal: Boolean to setup the Web Portal (default no) /LocalInstallation/ConfigurationMaster: Boolean, requires Configuration/Server to be given in the list of Services (default: no) /LocalInstallation/PrivateConfiguration: Boolean, requires Configuration/Server to be given in the list of Services (default: no) If a Master Configuration Server is being installed the following Options can be used:: /LocalInstallation/ConfigurationName: Name of the Configuration (default: Setup ) /LocalInstallation/AdminUserName: Name of the Admin user (default: None ) /LocalInstallation/AdminUserDN: DN of the Admin user certificate (default: None ) /LocalInstallation/AdminUserEmail: Email of the Admin user (default: None ) /LocalInstallation/AdminGroupName: Name of the Admin group (default: dirac_admin ) /LocalInstallation/HostDN: DN of the host certificate (default: None ) /LocalInstallation/VirtualOrganization: Name of the main Virtual Organization (default: None) """ __RCSID__ = "$Id$" # import os, re, glob, stat, time, shutil, socket gDefaultPerms = stat.S_IWUSR | stat.S_IRUSR | stat.S_IXUSR | stat.S_IRGRP | stat.S_IXGRP | stat.S_IROTH | stat.S_IXOTH import DIRAC from DIRAC import rootPath from DIRAC import gLogger from DIRAC import S_OK, S_ERROR from DIRAC.Core.Utilities.CFG import CFG from DIRAC.Core.Utilities.Version import getVersion from DIRAC.Core.Utilities.Subprocess import systemCall from DIRAC.ConfigurationSystem.Client.CSAPI import CSAPI from DIRAC.ConfigurationSystem.Client.Helpers import cfgPath, cfgPathToList, cfgInstallPath, \ cfgInstallSection, ResourcesDefaults, CSGlobals from DIRAC.Core.Security.Properties import ALARMS_MANAGEMENT, SERVICE_ADMINISTRATOR, \ CS_ADMINISTRATOR, JOB_ADMINISTRATOR, \ FULL_DELEGATION, PROXY_MANAGEMENT, OPERATOR, \ NORMAL_USER, TRUSTED_HOST from DIRAC.ConfigurationSystem.Client import PathFinder from DIRAC.Core.Base.private.ModuleLoader import ModuleLoader from DIRAC.Core.Base.AgentModule import AgentModule from DIRAC.Core.Base.ExecutorModule import ExecutorModule from DIRAC.Core.DISET.RequestHandler import RequestHandler from DIRAC.Core.Utilities.PrettyPrint import printTable from DIRAC.Core.Utilities.Platform import getPlatformString # On command line tools this can be set to True to abort after the first error. exitOnError = False # First some global defaults gLogger.debug( 'DIRAC Root Path =', rootPath ) def loadDiracCfg( verbose = False ): """ Read again defaults from dirac.cfg """ global localCfg, cfgFile, setup, instance, logLevel, linkedRootPath, host global basePath, instancePath, runitDir, startDir global db, mysqlDir, mysqlDbDir, mysqlLogDir, mysqlMyOrg, mysqlMyCnf, mysqlStartupScript global mysqlRootPwd, mysqlUser, mysqlPassword, mysqlHost, mysqlMode global mysqlSmallMem, mysqlLargeMem, mysqlPort, mysqlRootUser from DIRAC.Core.Utilities.Network import getFQDN localCfg = CFG() cfgFile = os.path.join( rootPath, 'etc', 'dirac.cfg' ) try: localCfg.loadFromFile( cfgFile ) except Exception: gLogger.always( "Can't load ", cfgFile ) gLogger.always( "Might be OK if setting up the site" ) setup = localCfg.getOption( cfgPath( 'DIRAC', 'Setup' ), '' ) instance = localCfg.getOption( cfgInstallPath( 'InstanceName' ), setup ) logLevel = localCfg.getOption( cfgInstallPath( 'LogLevel' ), 'INFO' ) linkedRootPath = localCfg.getOption( cfgInstallPath( 'RootPath' ), rootPath ) useVersionsDir = localCfg.getOption( cfgInstallPath( 'UseVersionsDir' ), False ) host = localCfg.getOption( cfgInstallPath( 'Host' ), getFQDN() ) basePath = os.path.dirname( rootPath ) instancePath = localCfg.getOption( cfgInstallPath( 'InstancePath' ), rootPath ) if useVersionsDir: # This option takes precedence instancePath = os.path.dirname( os.path.dirname( rootPath ) ) linkedRootPath = os.path.join( instancePath, 'pro' ) if verbose: gLogger.notice( 'Using Instance Base Dir at', instancePath ) runitDir = os.path.join( instancePath, 'runit' ) runitDir = localCfg.getOption( cfgInstallPath( 'RunitDir' ), runitDir ) if verbose: gLogger.notice( 'Using Runit Dir at', runitDir ) startDir = os.path.join( instancePath, 'startup' ) startDir = localCfg.getOption( cfgInstallPath( 'StartupDir' ), startDir ) if verbose: gLogger.notice( 'Using Startup Dir at', startDir ) # Now some MySQL default values db = {} mysqlDir = os.path.join( instancePath, 'mysql' ) mysqlDir = localCfg.getOption( cfgInstallPath( 'MySQLDir' ), mysqlDir ) if verbose: gLogger.notice( 'Using MySQL Dir at', mysqlDir ) mysqlDbDir = os.path.join( mysqlDir, 'db' ) mysqlLogDir = os.path.join( mysqlDir, 'log' ) mysqlMyOrg = os.path.join( rootPath, 'mysql', 'etc', 'my.cnf' ) mysqlMyCnf = os.path.join( mysqlDir, '.my.cnf' ) mysqlStartupScript = os.path.join( rootPath, 'mysql', 'share', 'mysql', 'mysql.server' ) mysqlRootPwd = localCfg.getOption( cfgInstallPath( 'Database', 'RootPwd' ), mysqlRootPwd ) if verbose and mysqlRootPwd: gLogger.notice( 'Reading Root MySQL Password from local configuration' ) mysqlUser = localCfg.getOption( cfgInstallPath( 'Database', 'User' ), '' ) if mysqlUser: if verbose: gLogger.notice( 'Reading MySQL User from local configuration' ) else: mysqlUser = 'Dirac' mysqlPassword = localCfg.getOption( cfgInstallPath( 'Database', 'Password' ), mysqlPassword ) if verbose and mysqlPassword: gLogger.notice( 'Reading %s MySQL Password from local configuration ' % mysqlUser ) mysqlHost = localCfg.getOption( cfgInstallPath( 'Database', 'Host' ), '' ) if mysqlHost: if verbose: gLogger.notice( 'Using MySQL Host from local configuration', mysqlHost ) else: # if it is not defined use the same as for dirac services mysqlHost = host mysqlPort = localCfg.getOption( cfgInstallPath( 'Database', 'Port' ), 0 ) if mysqlPort: if verbose: gLogger.notice( 'Using MySQL Port from local configuration ', mysqlPort ) else: # if it is not defined use the same as for dirac services mysqlPort = 3306 mysqlRootUser = localCfg.getOption( cfgInstallPath( 'Database', 'RootUser' ), '' ) if mysqlRootUser: if verbose: gLogger.notice( 'Using MySQL root user from local configuration ', mysqlRootUser ) else: # if it is not defined use root mysqlRootUser = 'root' mysqlMode = localCfg.getOption( cfgInstallPath( 'Database', 'MySQLMode' ), '' ) if verbose and mysqlMode: gLogger.notice( 'Configuring MySQL server as %s' % mysqlMode ) mysqlSmallMem = localCfg.getOption( cfgInstallPath( 'Database', 'MySQLSmallMem' ), False ) if verbose and mysqlSmallMem: gLogger.notice( 'Configuring MySQL server for Low Memory uasge' ) mysqlLargeMem = localCfg.getOption( cfgInstallPath( 'Database', 'MySQLLargeMem' ), False ) if verbose and mysqlLargeMem: gLogger.notice( 'Configuring MySQL server for Large Memory uasge' ) # FIXME: we probably need a better way to do this mysqlRootPwd = '' mysqlPassword = '' mysqlMode = '' localCfg = None cfgFile = '' setup = '' instance = '' logLevel = '' linkedRootPath = '' host = '' basePath = '' instancePath = '' runitDir = '' startDir = '' db = {} mysqlDir = '' mysqlDbDir = '' mysqlLogDir = '' mysqlMyOrg = '' mysqlMyCnf = '' mysqlStartupScript = '' mysqlUser = '' mysqlHost = '' mysqlPort = '' mysqlRootUser = '' mysqlSmallMem = '' mysqlLargeMem = '' loadDiracCfg() def getInfo( extensions ): result = getVersion() if not result['OK']: return result rDict = result['Value'] if setup: rDict['Setup'] = setup else: rDict['Setup'] = 'Unknown' return S_OK( rDict ) def getExtensions(): """ Get the list of installed extensions """ initList = glob.glob( os.path.join( rootPath, '*DIRAC', '__init__.py' ) ) extensions = [ os.path.basename( os.path.dirname( k ) ) for k in initList] try: extensions.remove( 'DIRAC' ) except Exception: error = 'DIRAC is not properly installed' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) return S_OK( extensions ) def _addCfgToDiracCfg( cfg, verbose = False ): """ Merge cfg into existing dirac.cfg file """ global localCfg if str( localCfg ): newCfg = localCfg.mergeWith( cfg ) else: newCfg = cfg result = newCfg.writeToFile( cfgFile ) if not result: return result loadDiracCfg( verbose ) return result def _addCfgToCS( cfg ): """ Merge cfg into central CS """ cfgClient = CSAPI() result = cfgClient.downloadCSData() if not result['OK']: return result result = cfgClient.mergeFromCFG( cfg ) if not result['OK']: return result result = cfgClient.commit() return result def _addCfgToLocalCS( cfg ): """ Merge cfg into local CS """ csName = localCfg.getOption( cfgPath( 'DIRAC', 'Configuration', 'Name' ) , '' ) if not csName: error = 'Missing %s' % cfgPath( 'DIRAC', 'Configuration', 'Name' ) if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) csCfg = CFG() csFile = os.path.join( rootPath, 'etc', '%s.cfg' % csName ) if os.path.exists( csFile ): csCfg.loadFromFile( csFile ) if str( csCfg ): newCfg = csCfg.mergeWith( cfg ) else: newCfg = cfg return newCfg.writeToFile( csFile ) def _getCentralCfg( installCfg ): """ Create the skeleton of central Cfg for an initial Master CS """ # First copy over from installation cfg centralCfg = CFG() # DIRAC/Extensions extensions = localCfg.getOption( cfgInstallPath( 'Extensions' ), [] ) while 'Web' in list( extensions ): extensions.remove( 'Web' ) centralCfg.createNewSection( 'DIRAC', '' ) if extensions: centralCfg['DIRAC'].addKey( 'Extensions', ','.join( extensions ), '' ) vo = localCfg.getOption( cfgInstallPath( 'VirtualOrganization' ), '' ) if vo: centralCfg['DIRAC'].addKey( 'VirtualOrganization', vo, '' ) for section in [ 'Systems', 'Resources', 'Resources/Sites', 'Resources/Domains', 'Operations', 'Website', 'Registry' ]: if installCfg.isSection( section ): centralCfg.createNewSection( section, contents = installCfg[section] ) # Now try to add things from the Installation section # Registry adminUserName = localCfg.getOption( cfgInstallPath( 'AdminUserName' ), '' ) adminUserDN = localCfg.getOption( cfgInstallPath( 'AdminUserDN' ), '' ) adminUserEmail = localCfg.getOption( cfgInstallPath( 'AdminUserEmail' ), '' ) adminGroupName = localCfg.getOption( cfgInstallPath( 'AdminGroupName' ), 'dirac_admin' ) hostDN = localCfg.getOption( cfgInstallPath( 'HostDN' ), '' ) defaultGroupName = 'user' adminGroupProperties = [ ALARMS_MANAGEMENT, SERVICE_ADMINISTRATOR, CS_ADMINISTRATOR, JOB_ADMINISTRATOR, FULL_DELEGATION, PROXY_MANAGEMENT, OPERATOR ] defaultGroupProperties = [ NORMAL_USER ] defaultHostProperties = [ TRUSTED_HOST, CS_ADMINISTRATOR, JOB_ADMINISTRATOR, FULL_DELEGATION, PROXY_MANAGEMENT, OPERATOR ] for section in ( cfgPath( 'Registry' ), cfgPath( 'Registry', 'Users' ), cfgPath( 'Registry', 'Groups' ), cfgPath( 'Registry', 'Hosts' ) ): if not centralCfg.isSection( section ): centralCfg.createNewSection( section ) if adminUserName: if not ( adminUserDN and adminUserEmail ): gLogger.error( 'AdminUserName is given but DN or Mail is missing it will not be configured' ) else: for section in [ cfgPath( 'Registry', 'Users', adminUserName ), cfgPath( 'Registry', 'Groups', defaultGroupName ), cfgPath( 'Registry', 'Groups', adminGroupName ) ]: if not centralCfg.isSection( section ): centralCfg.createNewSection( section ) if centralCfg['Registry'].existsKey( 'DefaultGroup' ): centralCfg['Registry'].deleteKey( 'DefaultGroup' ) centralCfg['Registry'].addKey( 'DefaultGroup', defaultGroupName, '' ) if centralCfg['Registry']['Users'][adminUserName].existsKey( 'DN' ): centralCfg['Registry']['Users'][adminUserName].deleteKey( 'DN' ) centralCfg['Registry']['Users'][adminUserName].addKey( 'DN', adminUserDN, '' ) if centralCfg['Registry']['Users'][adminUserName].existsKey( 'Email' ): centralCfg['Registry']['Users'][adminUserName].deleteKey( 'Email' ) centralCfg['Registry']['Users'][adminUserName].addKey( 'Email' , adminUserEmail, '' ) # Add Admin User to Admin Group and default group for group in [adminGroupName, defaultGroupName]: if not centralCfg['Registry']['Groups'][group].isOption( 'Users' ): centralCfg['Registry']['Groups'][group].addKey( 'Users', '', '' ) users = centralCfg['Registry']['Groups'][group].getOption( 'Users', [] ) if adminUserName not in users: centralCfg['Registry']['Groups'][group].appendToOption( 'Users', ', %s' % adminUserName ) if not centralCfg['Registry']['Groups'][group].isOption( 'Properties' ): centralCfg['Registry']['Groups'][group].addKey( 'Properties', '', '' ) properties = centralCfg['Registry']['Groups'][adminGroupName].getOption( 'Properties', [] ) for prop in adminGroupProperties: if prop not in properties: properties.append( prop ) centralCfg['Registry']['Groups'][adminGroupName].appendToOption( 'Properties', ', %s' % prop ) properties = centralCfg['Registry']['Groups'][defaultGroupName].getOption( 'Properties', [] ) for prop in defaultGroupProperties: if prop not in properties: properties.append( prop ) centralCfg['Registry']['Groups'][defaultGroupName].appendToOption( 'Properties', ', %s' % prop ) # Add the master Host description if hostDN: hostSection = cfgPath( 'Registry', 'Hosts', host ) if not centralCfg.isSection( hostSection ): centralCfg.createNewSection( hostSection ) if centralCfg['Registry']['Hosts'][host].existsKey( 'DN' ): centralCfg['Registry']['Hosts'][host].deleteKey( 'DN' ) centralCfg['Registry']['Hosts'][host].addKey( 'DN', hostDN, '' ) if not centralCfg['Registry']['Hosts'][host].isOption( 'Properties' ): centralCfg['Registry']['Hosts'][host].addKey( 'Properties', '', '' ) properties = centralCfg['Registry']['Hosts'][host].getOption( 'Properties', [] ) for prop in defaultHostProperties: if prop not in properties: properties.append( prop ) centralCfg['Registry']['Hosts'][host].appendToOption( 'Properties', ', %s' % prop ) # Operations if adminUserEmail: operationsCfg = __getCfg( cfgPath( 'Operations', 'Defaults', 'EMail' ), 'Production', adminUserEmail ) centralCfg = centralCfg.mergeWith( operationsCfg ) operationsCfg = __getCfg( cfgPath( 'Operations', 'Defaults', 'EMail' ), 'Logging', adminUserEmail ) centralCfg = centralCfg.mergeWith( operationsCfg ) # Website websiteCfg = __getCfg( cfgPath( 'Website', 'Authorization', 'systems', 'configuration' ), 'Default', 'all' ) websiteCfg['Website'].addKey( 'DefaultGroups', ', '.join( ['visitor', defaultGroupName, adminGroupName] ), '' ) websiteCfg['Website'].addKey( 'DefaultSetup', setup, '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].addKey( 'showHistory' , 'CSAdministrator' , '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].addKey( 'commitConfiguration' , 'CSAdministrator' , '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].addKey( 'showCurrentDiff' , 'CSAdministrator' , '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].addKey( 'showDiff' , 'CSAdministrator' , '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].addKey( 'rollbackToVersion' , 'CSAdministrator' , '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].addKey( 'manageRemoteConfig' , 'CSAdministrator' , '' ) websiteCfg['Website']['Authorization']['systems']['configuration'].appendToOption( 'manageRemoteConfig' , ', ServiceAdministrator' ) centralCfg = centralCfg.mergeWith( websiteCfg ) return centralCfg def __getCfg( section, option = '', value = '' ): """ Create a new Cfg with given info """ if not section: return None cfg = CFG() sectionList = [] for sect in cfgPathToList( section ): if not sect: continue sectionList.append( sect ) cfg.createNewSection( cfgPath( *sectionList ) ) if not sectionList: return None if option and value: sectionList.append( option ) cfg.setOption( cfgPath( *sectionList ), value ) return cfg def addOptionToDiracCfg( option, value ): """ Add Option to dirac.cfg """ optionList = cfgPathToList( option ) optionName = optionList[-1] section = cfgPath( *optionList[:-1] ) cfg = __getCfg( section, optionName, value ) if not cfg: return S_ERROR( 'Wrong option: %s = %s' % ( option, value ) ) if _addCfgToDiracCfg( cfg ): return S_OK() return S_ERROR( 'Could not merge %s=%s with local configuration' % ( option, value ) ) def addDefaultOptionsToCS( gConfig, componentType, systemName, component, extensions, mySetup = setup, specialOptions = {}, overwrite = False, addDefaultOptions = True ): """ Add the section with the component options to the CS """ system = systemName.replace( 'System', '' ) instanceOption = cfgPath( 'DIRAC', 'Setups', mySetup, system ) if gConfig: compInstance = gConfig.getValue( instanceOption, '' ) else: compInstance = localCfg.getOption( instanceOption, '' ) if not compInstance: return S_ERROR( '%s not defined in %s' % ( instanceOption, cfgFile ) ) sectionName = "Agents" if componentType == 'service': sectionName = "Services" elif componentType == 'executor': sectionName = "Executors" # Check if the component CS options exist addOptions = True componentSection = cfgPath( 'Systems', system, compInstance, sectionName, component ) if not overwrite: if gConfig: result = gConfig.getOptions( componentSection ) if result['OK']: addOptions = False if not addOptions: return S_OK( 'Component options already exist' ) # Add the component options now result = getComponentCfg( componentType, system, component, compInstance, extensions, specialOptions, addDefaultOptions ) if not result['OK']: return result compCfg = result['Value'] gLogger.notice( 'Adding to CS', '%s %s/%s' % ( componentType, system, component ) ) resultAddToCFG = _addCfgToCS( compCfg ) if componentType == 'executor': # Is it a container ? execList = compCfg.getOption( '%s/Load' % componentSection, [] ) for element in execList: result = addDefaultOptionsToCS( gConfig, componentType, systemName, element, extensions, setup, {}, overwrite ) resultAddToCFG.setdefault( 'Modules', {} ) resultAddToCFG['Modules'][element] = result['OK'] return resultAddToCFG def addDefaultOptionsToComponentCfg( componentType, systemName, component, extensions ): """ Add default component options local component cfg """ system = systemName.replace( 'System', '' ) instanceOption = cfgPath( 'DIRAC', 'Setups', setup, system ) compInstance = localCfg.getOption( instanceOption, '' ) if not compInstance: return S_ERROR( '%s not defined in %s' % ( instanceOption, cfgFile ) ) # Add the component options now result = getComponentCfg( componentType, system, component, compInstance, extensions ) if not result['OK']: return result compCfg = result['Value'] compCfgFile = os.path.join( rootPath, 'etc', '%s_%s.cfg' % ( system, component ) ) return compCfg.writeToFile( compCfgFile ) def addCfgToComponentCfg( componentType, systemName, component, cfg ): """ Add some extra configuration to the local component cfg """ sectionName = 'Services' if componentType == 'agent': sectionName = 'Agents' if not cfg: return S_OK() system = systemName.replace( 'System', '' ) instanceOption = cfgPath( 'DIRAC', 'Setups', setup, system ) compInstance = localCfg.getOption( instanceOption, '' ) if not compInstance: return S_ERROR( '%s not defined in %s' % ( instanceOption, cfgFile ) ) compCfgFile = os.path.join( rootPath, 'etc', '%s_%s.cfg' % ( system, component ) ) compCfg = CFG() if os.path.exists( compCfgFile ): compCfg.loadFromFile( compCfgFile ) sectionPath = cfgPath( 'Systems', system, compInstance, sectionName ) newCfg = __getCfg( sectionPath ) newCfg.createNewSection( cfgPath( sectionPath, component ), 'Added by InstallTools', cfg ) if newCfg.writeToFile( compCfgFile ): return S_OK( compCfgFile ) error = 'Can not write %s' % compCfgFile gLogger.error( error ) return S_ERROR( error ) def getComponentCfg( componentType, system, component, compInstance, extensions, specialOptions = {}, addDefaultOptions = True ): """ Get the CFG object of the component configuration """ sectionName = 'Services' if componentType == 'agent': sectionName = 'Agents' if componentType == 'executor': sectionName = 'Executors' componentModule = component if "Module" in specialOptions: componentModule = specialOptions['Module'] compCfg = CFG() if addDefaultOptions: extensionsDIRAC = [ x + 'DIRAC' for x in extensions ] + extensions for ext in extensionsDIRAC + ['DIRAC']: cfgTemplatePath = os.path.join( rootPath, ext, '%sSystem' % system, 'ConfigTemplate.cfg' ) if os.path.exists( cfgTemplatePath ): gLogger.notice( 'Loading configuration template', cfgTemplatePath ) # Look up the component in this template loadCfg = CFG() loadCfg.loadFromFile( cfgTemplatePath ) compCfg = loadCfg.mergeWith( compCfg ) compPath = cfgPath( sectionName, componentModule ) if not compCfg.isSection( compPath ): error = 'Can not find %s in template' % compPath gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) compCfg = compCfg[sectionName][componentModule] # Delete Dependencies section if any compCfg.deleteKey( 'Dependencies' ) sectionPath = cfgPath( 'Systems', system, compInstance, sectionName ) cfg = __getCfg( sectionPath ) cfg.createNewSection( cfgPath( sectionPath, component ), '', compCfg ) for option, value in specialOptions.items(): cfg.setOption( cfgPath( sectionPath, component, option ), value ) # Add the service URL if componentType == "service": port = compCfg.getOption( 'Port' , 0 ) if port and host: urlsPath = cfgPath( 'Systems', system, compInstance, 'URLs' ) cfg.createNewSection( urlsPath ) cfg.setOption( cfgPath( urlsPath, component ), 'dips://%s:%d/%s/%s' % ( host, port, system, component ) ) return S_OK( cfg ) def addDatabaseOptionsToCS( gConfig, systemName, dbName, mySetup = setup, overwrite = False ): """ Add the section with the database options to the CS """ system = systemName.replace( 'System', '' ) instanceOption = cfgPath( 'DIRAC', 'Setups', mySetup, system ) if gConfig: compInstance = gConfig.getValue( instanceOption, '' ) else: compInstance = localCfg.getOption( instanceOption, '' ) if not compInstance: return S_ERROR( '%s not defined in %s' % ( instanceOption, cfgFile ) ) # Check if the component CS options exist addOptions = True if not overwrite: databasePath = cfgPath( 'Systems', system, compInstance, 'Databases', dbName ) result = gConfig.getOptions( databasePath ) if result['OK']: addOptions = False if not addOptions: return S_OK( 'Database options already exist' ) # Add the component options now result = getDatabaseCfg( system, dbName, compInstance ) if not result['OK']: return result databaseCfg = result['Value'] gLogger.notice( 'Adding to CS', '%s/%s' % ( system, dbName ) ) return _addCfgToCS( databaseCfg ) def getDatabaseCfg( system, dbName, compInstance ): """ Get the CFG object of the database configuration """ databasePath = cfgPath( 'Systems', system, compInstance, 'Databases', dbName ) cfg = __getCfg( databasePath, 'DBName', dbName ) cfg.setOption( cfgPath( databasePath, 'Host' ), mysqlHost ) cfg.setOption( cfgPath( databasePath, 'Port' ), mysqlPort ) return S_OK( cfg ) def addSystemInstance( systemName, compInstance, mySetup = setup, myCfg = False ): """ Add a new system instance to dirac.cfg and CS """ system = systemName.replace( 'System', '' ) gLogger.notice( 'Adding %s system as %s instance for %s setup to dirac.cfg and CS' % ( system, compInstance, mySetup ) ) cfg = __getCfg( cfgPath( 'DIRAC', 'Setups', mySetup ), system, compInstance ) if myCfg: if not _addCfgToDiracCfg( cfg ): return S_ERROR( 'Failed to add system instance to dirac.cfg' ) return _addCfgToCS( cfg ) def printStartupStatus( rDict ): """ Print in nice format the return dictionary from getStartupComponentStatus (also returned by runsvctrlComponent) """ fields = ['Name','Runit','Uptime','PID'] records = [] try: for comp in rDict: records.append( [comp, rDict[comp]['RunitStatus'], rDict[comp]['Timeup'], str( rDict[comp]['PID'] ) ] ) printTable( fields, records ) except Exception, x: print "Exception while gathering data for printing: %s" % str( x ) return S_OK() def printOverallStatus( rDict ): """ Print in nice format the return dictionary from getOverallStatus """ fields = ['System','Name','Type','Setup','Installed','Runit','Uptime','PID'] records = [] try: for compType in rDict: for system in rDict[compType]: for component in rDict[compType][system]: record = [ system, component, compType.lower()[:-1] ] if rDict[compType][system][component]['Setup']: record.append( 'SetUp' ) else: record.append( 'NotSetUp' ) if rDict[compType][system][component]['Installed']: record.append( 'Installed' ) else: record.append( 'NotInstalled' ) record.append( str( rDict[compType][system][component]['RunitStatus'] ) ) record.append( str( rDict[compType][system][component]['Timeup'] ) ) record.append( str( rDict[compType][system][component]['PID'] ) ) records.append( record ) printTable( fields, records ) except Exception, x: print "Exception while gathering data for printing: %s" % str( x ) return S_OK() def getAvailableSystems( extensions ): """ Get the list of all systems (in all given extensions) locally available """ systems = [] for extension in extensions: extensionPath = os.path.join( DIRAC.rootPath, extension, '*System' ) for system in [ os.path.basename( k ).split( 'System' )[0] for k in glob.glob( extensionPath ) ]: if system not in systems: systems.append( system ) return systems def getSoftwareComponents( extensions ): """ Get the list of all the components ( services and agents ) for which the software is installed on the system """ # The Gateway does not need a handler services = { 'Framework' : ['Gateway'] } agents = {} executors = {} for extension in ['DIRAC'] + [ x + 'DIRAC' for x in extensions]: if not os.path.exists( os.path.join( rootPath, extension ) ): # Not all the extensions are necessarily installed in this instance continue systemList = os.listdir( os.path.join( rootPath, extension ) ) for sys in systemList: system = sys.replace( 'System', '' ) try: agentDir = os.path.join( rootPath, extension, sys, 'Agent' ) agentList = os.listdir( agentDir ) for agent in agentList: if agent[-3:] == ".py": agentFile = os.path.join( agentDir, agent ) afile = open( agentFile, 'r' ) body = afile.read() afile.close() if body.find( 'AgentModule' ) != -1 or body.find( 'OptimizerModule' ) != -1: if not agents.has_key( system ): agents[system] = [] agents[system].append( agent.replace( '.py', '' ) ) except OSError: pass try: serviceDir = os.path.join( rootPath, extension, sys, 'Service' ) serviceList = os.listdir( serviceDir ) for service in serviceList: if service.find( 'Handler' ) != -1 and service[-3:] == '.py': if not services.has_key( system ): services[system] = [] if system == 'Configuration' and service == 'ConfigurationHandler.py': service = 'ServerHandler.py' services[system].append( service.replace( '.py', '' ).replace( 'Handler', '' ) ) except OSError: pass try: executorDir = os.path.join( rootPath, extension, sys, 'Executor' ) executorList = os.listdir( executorDir ) for executor in executorList: if executor[-3:] == ".py": executorFile = os.path.join( executorDir, executor ) afile = open( executorFile, 'r' ) body = afile.read() afile.close() if body.find( 'OptimizerExecutor' ) != -1: if not executors.has_key( system ): executors[system] = [] executors[system].append( executor.replace( '.py', '' ) ) except OSError: pass resultDict = {} resultDict['Services'] = services resultDict['Agents'] = agents resultDict['Executors'] = executors return S_OK( resultDict ) def getInstalledComponents(): """ Get the list of all the components ( services and agents ) installed on the system in the runit directory """ services = {} agents = {} executors = {} systemList = os.listdir( runitDir ) for system in systemList: systemDir = os.path.join( runitDir, system ) components = os.listdir( systemDir ) for component in components: try: runFile = os.path.join( systemDir, component, 'run' ) rfile = open( runFile, 'r' ) body = rfile.read() rfile.close() if body.find( 'dirac-service' ) != -1: if not services.has_key( system ): services[system] = [] services[system].append( component ) elif body.find( 'dirac-agent' ) != -1: if not agents.has_key( system ): agents[system] = [] agents[system].append( component ) elif body.find( 'dirac-executor' ) != -1: if not executors.has_key( system ): executors[system] = [] executors[system].append( component ) except IOError: pass resultDict = {} resultDict['Services'] = services resultDict['Agents'] = agents resultDict['Executors'] = executors return S_OK( resultDict ) def getSetupComponents(): """ Get the list of all the components ( services and agents ) set up for running with runsvdir in startup directory """ services = {} agents = {} executors = {} if not os.path.isdir( startDir ): return S_ERROR( 'Startup Directory does not exit: %s' % startDir ) componentList = os.listdir( startDir ) for component in componentList: try: runFile = os.path.join( startDir, component, 'run' ) rfile = open( runFile, 'r' ) body = rfile.read() rfile.close() if body.find( 'dirac-service' ) != -1: system, service = component.split( '_' )[0:2] if not services.has_key( system ): services[system] = [] services[system].append( service ) elif body.find( 'dirac-agent' ) != -1: system, agent = component.split( '_' )[0:2] if not agents.has_key( system ): agents[system] = [] agents[system].append( agent ) elif body.find( 'dirac-executor' ) != -1: system, executor = component.split( '_' )[0:2] if not executors.has_key( system ): executors[system] = [] executors[system].append( executor ) except IOError: pass resultDict = {} resultDict['Services'] = services resultDict['Agents'] = agents resultDict['Executors'] = executors return S_OK( resultDict ) def getStartupComponentStatus( componentTupleList ): """ Get the list of all the components ( services and agents ) set up for running with runsvdir in startup directory """ try: if componentTupleList: cList = [] for componentTuple in componentTupleList: cList.extend( glob.glob( os.path.join( startDir, '_'.join( componentTuple ) ) ) ) else: cList = glob.glob( os.path.join( startDir, '*' ) ) except Exception: error = 'Failed to parse List of Components' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) result = execCommand( 0, ['runsvstat'] + cList ) if not result['OK']: return result output = result['Value'][1].strip().split( '\n' ) componentDict = {} for line in output: if not line: continue cname, routput = line.split( ':' ) cname = cname.replace( '%s/' % startDir, '' ) run = False reResult = re.search( '^ run', routput ) if reResult: run = True down = False reResult = re.search( '^ down', routput ) if reResult: down = True reResult = re.search( '([0-9]+) seconds', routput ) timeup = 0 if reResult: timeup = reResult.group( 1 ) reResult = re.search( 'pid ([0-9]+)', routput ) pid = 0 if reResult: pid = reResult.group( 1 ) runsv = "Not running" if run or down: runsv = "Running" reResult = re.search( 'runsv not running', routput ) if reResult: runsv = "Not running" runDict = {} runDict['Timeup'] = timeup runDict['PID'] = pid runDict['RunitStatus'] = "Unknown" if run: runDict['RunitStatus'] = "Run" if down: runDict['RunitStatus'] = "Down" if runsv == "Not running": runDict['RunitStatus'] = "NoRunitControl" componentDict[cname] = runDict return S_OK( componentDict ) def getComponentModule( gConfig, system, component, compType ): """ Get the component software module """ setup = CSGlobals.getSetup() instance = gConfig.getValue( cfgPath( 'DIRAC', 'Setups', setup, system ), '' ) if not instance: return S_OK( component ) module = gConfig.getValue( cfgPath( 'Systems', system, instance, compType, component, 'Module' ), '' ) if not module: module = component return S_OK( module ) def getOverallStatus( extensions ): """ Get the list of all the components ( services and agents ) set up for running with runsvdir in startup directory """ result = getSoftwareComponents( extensions ) if not result['OK']: return result softDict = result['Value'] result = getSetupComponents() if not result['OK']: return result setupDict = result['Value'] result = getInstalledComponents() if not result['OK']: return result installedDict = result['Value'] result = getStartupComponentStatus( [] ) if not result['OK']: return result runitDict = result['Value'] # Collect the info now resultDict = {'Services':{}, 'Agents':{}, 'Executors':{} } for compType in ['Services', 'Agents', 'Executors' ]: if softDict.has_key( 'Services' ): for system in softDict[compType]: resultDict[compType][system] = {} for component in softDict[compType][system]: if system == 'Configuration' and component == 'Configuration': # Fix to avoid missing CS due to different between Service name and Handler name component = 'Server' resultDict[compType][system][component] = {} resultDict[compType][system][component]['Setup'] = False resultDict[compType][system][component]['Installed'] = False resultDict[compType][system][component]['RunitStatus'] = 'Unknown' resultDict[compType][system][component]['Timeup'] = 0 resultDict[compType][system][component]['PID'] = 0 # TODO: why do we need a try here? try: if component in setupDict[compType][system]: resultDict[compType][system][component]['Setup'] = True except Exception: pass try: if component in installedDict[compType][system]: resultDict[compType][system][component]['Installed'] = True except Exception: pass try: compDir = system + '_' + component if runitDict.has_key( compDir ): resultDict[compType][system][component]['RunitStatus'] = runitDict[compDir]['RunitStatus'] resultDict[compType][system][component]['Timeup'] = runitDict[compDir]['Timeup'] resultDict[compType][system][component]['PID'] = runitDict[compDir]['PID'] except Exception: #print str(x) pass # Installed components can be not the same as in the software list if installedDict.has_key( 'Services' ): for system in installedDict[compType]: for component in installedDict[compType][system]: if compType in resultDict: if system in resultDict[compType]: if component in resultDict[compType][system]: continue resultDict[compType][system][component] = {} resultDict[compType][system][component]['Setup'] = False resultDict[compType][system][component]['Installed'] = True resultDict[compType][system][component]['RunitStatus'] = 'Unknown' resultDict[compType][system][component]['Timeup'] = 0 resultDict[compType][system][component]['PID'] = 0 # TODO: why do we need a try here? try: if component in setupDict[compType][system]: resultDict[compType][system][component]['Setup'] = True except Exception: pass try: compDir = system + '_' + component if runitDict.has_key( compDir ): resultDict[compType][system][component]['RunitStatus'] = runitDict[compDir]['RunitStatus'] resultDict[compType][system][component]['Timeup'] = runitDict[compDir]['Timeup'] resultDict[compType][system][component]['PID'] = runitDict[compDir]['PID'] except Exception: #print str(x) pass return S_OK( resultDict ) def checkComponentModule( componentType, system, module ): """ Check existence of the given module and if it inherits from the proper class """ if componentType == 'agent': loader = ModuleLoader( "Agent", PathFinder.getAgentSection, AgentModule ) elif componentType == 'service': loader = ModuleLoader( "Service", PathFinder.getServiceSection, RequestHandler, moduleSuffix = "Handler" ) elif componentType == 'executor': loader = ModuleLoader( "Executor", PathFinder.getExecutorSection, ExecutorModule ) else: return S_ERROR( 'Unknown component type %s' % componentType ) return loader.loadModule( "%s/%s" % ( system, module ) ) def checkComponentSoftware( componentType, system, component, extensions ): """ Check the component software """ result = getSoftwareComponents( extensions ) if not result['OK']: return result if componentType == 'service': softDict = result['Value']['Services'] elif componentType == 'agent': softDict = result['Value']['Agents'] else: return S_ERROR( 'Unknown component type %s' % componentType ) if system in softDict and component in softDict[system]: return S_OK() return S_ERROR( 'Unknown Component %s/%s' % ( system, component ) ) def runsvctrlComponent( system, component, mode ): """ Execute runsvctrl and check status of the specified component """ if not mode in ['u', 'd', 'o', 'p', 'c', 'h', 'a', 'i', 'q', '1', '2', 't', 'k', 'x', 'e']: return S_ERROR( 'Unknown runsvctrl mode "%s"' % mode ) startCompDirs = glob.glob( os.path.join( startDir, '%s_%s' % ( system, component ) ) ) # Make sure that the Configuration server restarts first and the SystemAdmin restarts last tmpList = list( startCompDirs ) for comp in tmpList: if "Framework_SystemAdministrator" in comp: startCompDirs.append( startCompDirs.pop( startCompDirs.index( comp ) ) ) if "Configuration_Server" in comp: startCompDirs.insert( 0, startCompDirs.pop( startCompDirs.index( comp ) ) ) startCompList = [ [k] for k in startCompDirs] for startComp in startCompList: result = execCommand( 0, ['runsvctrl', mode] + startComp ) if not result['OK']: return result time.sleep( 1 ) # Check the runsv status if system == '*' or component == '*': time.sleep( 5 ) # Final check result = getStartupComponentStatus( [( system, component )] ) if not result['OK']: return S_ERROR( 'Failed to start the component' ) return result def getLogTail( system, component, length = 100 ): """ Get the tail of the component log file """ retDict = {} for startCompDir in glob.glob( os.path.join( startDir, '%s_%s' % ( system, component ) ) ): compName = os.path.basename( startCompDir ) logFileName = os.path.join( startCompDir, 'log', 'current' ) if not os.path.exists( logFileName ): retDict[compName] = 'No log file found' else: logFile = open( logFileName, 'r' ) lines = [ line.strip() for line in logFile.readlines() ] logFile.close() if len( lines ) < length: retDict[compName] = '\n'.join( lines ) else: retDict[compName] = '\n'.join( lines[-length:] ) return S_OK( retDict ) def setupSite( scriptCfg, cfg = None ): """ Setup a new site using the options defined """ # First we need to find out what needs to be installed # by default use dirac.cfg, but if a cfg is given use it and # merge it into the dirac.cfg diracCfg = CFG() installCfg = None if cfg: try: installCfg = CFG() installCfg.loadFromFile( cfg ) for section in ['DIRAC', 'LocalSite', cfgInstallSection]: if installCfg.isSection( section ): diracCfg.createNewSection( section, contents = installCfg[section] ) if instancePath != basePath: if not diracCfg.isSection( 'LocalSite' ): diracCfg.createNewSection( 'LocalSite' ) diracCfg.setOption( cfgPath( 'LocalSite', 'InstancePath' ), instancePath ) _addCfgToDiracCfg( diracCfg, verbose = True ) except Exception: error = 'Failed to load %s' % cfg gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) # Now get the necessary info from localCfg setupSystems = localCfg.getOption( cfgInstallPath( 'Systems' ), ['Configuration', 'Framework'] ) installMySQLFlag = localCfg.getOption( cfgInstallPath( 'InstallMySQL' ), False ) setupDatabases = localCfg.getOption( cfgInstallPath( 'Databases' ), [] ) setupServices = [ k.split( '/' ) for k in localCfg.getOption( cfgInstallPath( 'Services' ), [] ) ] setupAgents = [ k.split( '/' ) for k in localCfg.getOption( cfgInstallPath( 'Agents' ), [] ) ] setupExecutors = [ k.split( '/' ) for k in localCfg.getOption( cfgInstallPath( 'Executors' ), [] ) ] setupWeb = localCfg.getOption( cfgInstallPath( 'WebPortal' ), False ) setupWebApp = localCfg.getOption( cfgInstallPath( 'WebApp' ), False ) setupConfigurationMaster = localCfg.getOption( cfgInstallPath( 'ConfigurationMaster' ), False ) setupPrivateConfiguration = localCfg.getOption( cfgInstallPath( 'PrivateConfiguration' ), False ) setupConfigurationName = localCfg.getOption( cfgInstallPath( 'ConfigurationName' ), setup ) setupAddConfiguration = localCfg.getOption( cfgInstallPath( 'AddConfiguration' ), True ) for serviceTuple in setupServices: error = '' if len( serviceTuple ) != 2: error = 'Wrong service specification: system/service' # elif serviceTuple[0] not in setupSystems: # error = 'System %s not available' % serviceTuple[0] if error: if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) serviceSysInstance = serviceTuple[0] if not serviceSysInstance in setupSystems: setupSystems.append( serviceSysInstance ) for agentTuple in setupAgents: error = '' if len( agentTuple ) != 2: error = 'Wrong agent specification: system/agent' # elif agentTuple[0] not in setupSystems: # error = 'System %s not available' % agentTuple[0] if error: if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) agentSysInstance = agentTuple[0] if not agentSysInstance in setupSystems: setupSystems.append( agentSysInstance ) for executorTuple in setupExecutors: error = '' if len( executorTuple ) != 2: error = 'Wrong executor specification: system/executor' if error: if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) executorSysInstance = executorTuple[0] if not executorSysInstance in setupSystems: setupSystems.append( executorSysInstance ) # And to find out the available extensions result = getExtensions() if not result['OK']: return result extensions = [ k.replace( 'DIRAC', '' ) for k in result['Value']] # Make sure the necessary directories are there if basePath != instancePath: if not os.path.exists( instancePath ): try: os.makedirs( instancePath ) except Exception: error = 'Can not create directory for instance %s' % instancePath if exitOnError: gLogger.exception( error ) DIRAC.exit( -1 ) return S_ERROR( error ) if not os.path.isdir( instancePath ): error = 'Instance directory %s is not valid' % instancePath if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) instanceEtcDir = os.path.join( instancePath, 'etc' ) etcDir = os.path.dirname( cfgFile ) if not os.path.exists( instanceEtcDir ): try: os.symlink( etcDir, instanceEtcDir ) except Exception: error = 'Can not create link to configuration %s' % instanceEtcDir if exitOnError: gLogger.exception( error ) DIRAC.exit( -1 ) return S_ERROR( error ) if os.path.realpath( instanceEtcDir ) != os.path.realpath( etcDir ): error = 'Instance etc (%s) is not the same as DIRAC etc (%s)' % ( instanceEtcDir, etcDir ) if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) # if any server or agent needs to be install we need the startup directory and runsvdir running if setupServices or setupAgents or setupExecutors or setupWeb: if not os.path.exists( startDir ): try: os.makedirs( startDir ) except Exception: error = 'Can not create %s' % startDir if exitOnError: gLogger.exception( error ) DIRAC.exit( -1 ) return S_ERROR( error ) # And need to make sure runsvdir is running result = execCommand( 0, ['ps', '-ef'] ) if not result['OK']: if exitOnError: gLogger.error( 'Failed to verify runsvdir running', result['Message'] ) DIRAC.exit( -1 ) return S_ERROR( result['Message'] ) processList = result['Value'][1].split( '\n' ) cmd = 'runsvdir %s' % startDir cmdFound = False for process in processList: if process.find( cmd ) != -1: cmdFound = True if not cmdFound: gLogger.notice( 'Starting runsvdir ...' ) os.system( "runsvdir %s 'log: DIRAC runsv' &" % startDir ) if ['Configuration', 'Server'] in setupServices and setupConfigurationMaster: # This server hosts the Master of the CS from DIRAC.ConfigurationSystem.Client.ConfigurationData import gConfigurationData gLogger.notice( 'Installing Master Configuration Server' ) cfg = __getCfg( cfgPath( 'DIRAC', 'Setups', setup ), 'Configuration', instance ) _addCfgToDiracCfg( cfg ) cfg = __getCfg( cfgPath( 'DIRAC', 'Configuration' ), 'Master' , 'yes' ) cfg.setOption( cfgPath( 'DIRAC', 'Configuration', 'Name' ) , setupConfigurationName ) serversCfgPath = cfgPath( 'DIRAC', 'Configuration', 'Servers' ) if not localCfg.getOption( serversCfgPath , [] ): serverUrl = 'dips://%s:9135/Configuration/Server' % host cfg.setOption( serversCfgPath, serverUrl ) gConfigurationData.setOptionInCFG( serversCfgPath, serverUrl ) instanceOptionPath = cfgPath( 'DIRAC', 'Setups', setup ) instanceCfg = __getCfg( instanceOptionPath, 'Configuration', instance ) cfg = cfg.mergeWith( instanceCfg ) _addCfgToDiracCfg( cfg ) result = getComponentCfg( 'service', 'Configuration', 'Server', instance, extensions, addDefaultOptions = True ) if not result['OK']: if exitOnError: DIRAC.exit( -1 ) else: return result compCfg = result['Value'] cfg = cfg.mergeWith( compCfg ) gConfigurationData.mergeWithLocal( cfg ) addDefaultOptionsToComponentCfg( 'service', 'Configuration', 'Server', [] ) if installCfg: centralCfg = _getCentralCfg( installCfg ) else: centralCfg = _getCentralCfg( localCfg ) _addCfgToLocalCS( centralCfg ) setupComponent( 'service', 'Configuration', 'Server', [], checkModule = False ) runsvctrlComponent( 'Configuration', 'Server', 't' ) while ['Configuration', 'Server'] in setupServices: setupServices.remove( ['Configuration', 'Server'] ) time.sleep( 5 ) # Now need to check if there is valid CS to register the info result = scriptCfg.enableCS() if not result['OK']: if exitOnError: DIRAC.exit( -1 ) return result cfgClient = CSAPI() if not cfgClient.initialize(): error = 'Configuration Server not defined' if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) # We need to make sure components are connecting to the Master CS, that is the only one being update from DIRAC import gConfig localServers = localCfg.getOption( cfgPath( 'DIRAC', 'Configuration', 'Servers' ) ) masterServer = gConfig.getValue( cfgPath( 'DIRAC', 'Configuration', 'MasterServer' ), '' ) initialCfg = __getCfg( cfgPath( 'DIRAC', 'Configuration' ), 'Servers' , localServers ) masterCfg = __getCfg( cfgPath( 'DIRAC', 'Configuration' ), 'Servers' , masterServer ) _addCfgToDiracCfg( masterCfg ) # 1.- Setup the instances in the CS # If the Configuration Server used is not the Master, it can take some time for this # info to be propagated, this may cause the later setup to fail if setupAddConfiguration: gLogger.notice( 'Registering System instances' ) for system in setupSystems: addSystemInstance( system, instance, setup, True ) for system, service in setupServices: if not addDefaultOptionsToCS( None, 'service', system, service, extensions, overwrite = True )['OK']: # If we are not allowed to write to the central CS, add the configuration to the local file addDefaultOptionsToComponentCfg( 'service', system, service, extensions ) for system, agent in setupAgents: if not addDefaultOptionsToCS( None, 'agent', system, agent, extensions, overwrite = True )['OK']: # If we are not allowed to write to the central CS, add the configuration to the local file addDefaultOptionsToComponentCfg( 'agent', system, agent, extensions ) for system, executor in setupExecutors: if not addDefaultOptionsToCS( None, 'executor', system, executor, extensions, overwrite = True )['OK']: # If we are not allowed to write to the central CS, add the configuration to the local file addDefaultOptionsToComponentCfg( 'executor', system, executor, extensions ) else: gLogger.warn( 'Configuration parameters definition is not requested' ) if ['Configuration', 'Server'] in setupServices and setupPrivateConfiguration: cfg = __getCfg( cfgPath( 'DIRAC', 'Configuration' ), 'AutoPublish' , 'no' ) _addCfgToDiracCfg( cfg ) # 2.- Check if MySQL is to be installed if installMySQLFlag: gLogger.notice( 'Installing MySQL' ) getMySQLPasswords() installMySQL() # 3.- Install requested Databases # if MySQL is not installed locally, we assume a host is given if setupDatabases: result = getDatabases() if not result['OK']: if exitOnError: gLogger.error( 'Failed to get databases', result['Message'] ) DIRAC.exit( -1 ) return result installedDatabases = result['Value'] for dbName in setupDatabases: if dbName not in installedDatabases: extension, system = installDatabase( dbName )['Value'] gLogger.notice( 'Database %s from %s/%s installed' % ( dbName, extension, system ) ) result = addDatabaseOptionsToCS( None, system, dbName, overwrite = True ) if not result['OK']: gLogger.error( 'Database %s CS registration failed: %s' % ( dbName, result['Message'] ) ) else: gLogger.notice( 'Database %s already installed' % dbName ) if mysqlPassword: if not _addMySQLToDiracCfg(): error = 'Failed to add MySQL user password to local configuration' if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) # 4.- Then installed requested services for system, service in setupServices: setupComponent( 'service', system, service, extensions ) # 5.- Now the agents for system, agent in setupAgents: setupComponent( 'agent', system, agent, extensions ) # 6.- Now the executors for system, executor in setupExecutors: setupComponent( 'executor', system, executor, extensions ) # 7.- And finally the Portal if setupWeb: if setupWebApp: setupNewPortal() else: setupPortal() if localServers != masterServer: _addCfgToDiracCfg( initialCfg ) for system, service in setupServices: runsvctrlComponent( system, service, 't' ) for system, agent in setupAgents: runsvctrlComponent( system, agent, 't' ) for system, executor in setupExecutors: runsvctrlComponent( system, executor, 't' ) return S_OK() def _createRunitLog( runitCompDir ): logDir = os.path.join( runitCompDir, 'log' ) os.makedirs( logDir ) logConfigFile = os.path.join( logDir, 'config' ) fd = open( logConfigFile, 'w' ) fd.write( """s10000000 n20 """ ) fd.close() logRunFile = os.path.join( logDir, 'run' ) fd = open( logRunFile, 'w' ) fd.write( """#!/bin/bash # rcfile=%(bashrc)s [ -e $rcfile ] && source $rcfile # exec svlogd . """ % { 'bashrc' : os.path.join( instancePath, 'bashrc' ) } ) fd.close() os.chmod( logRunFile, gDefaultPerms ) def installComponent( componentType, system, component, extensions, componentModule = '', checkModule = True ): """ Install runit directory for the specified component """ # Check if the component is already installed runitCompDir = os.path.join( runitDir, system, component ) if os.path.exists( runitCompDir ): msg = "%s %s_%s already installed" % ( componentType, system, component ) gLogger.notice( msg ) return S_OK( runitCompDir ) # Check that the software for the component is installed # Any "Load" or "Module" option in the configuration defining what modules the given "component" # needs to load will be taken care of by checkComponentModule. if checkModule: cModule = componentModule if not cModule: cModule = component result = checkComponentModule( componentType, system, cModule ) if not result['OK']: if not checkComponentSoftware( componentType, system, cModule, extensions )['OK'] and componentType != 'executor': error = 'Software for %s %s/%s is not installed' % ( componentType, system, component ) if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) gLogger.notice( 'Installing %s %s/%s' % ( componentType, system, component ) ) # Now do the actual installation try: componentCfg = os.path.join( linkedRootPath, 'etc', '%s_%s.cfg' % ( system, component ) ) if not os.path.exists( componentCfg ): fd = open( componentCfg, 'w' ) fd.close() _createRunitLog( runitCompDir ) runFile = os.path.join( runitCompDir, 'run' ) fd = open( runFile, 'w' ) fd.write( """#!/bin/bash rcfile=%(bashrc)s [ -e $rcfile ] && source $rcfile # exec 2>&1 # [ "%(componentType)s" = "agent" ] && renice 20 -p $$ # exec python $DIRAC/DIRAC/Core/scripts/dirac-%(componentType)s.py %(system)s/%(component)s %(componentCfg)s < /dev/null """ % {'bashrc': os.path.join( instancePath, 'bashrc' ), 'componentType': componentType, 'system' : system, 'component': component, 'componentCfg': componentCfg } ) fd.close() os.chmod( runFile, gDefaultPerms ) except Exception: error = 'Failed to prepare setup for %s %s/%s' % ( componentType, system, component ) gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) result = execCommand( 5, [runFile] ) gLogger.notice( result['Value'][1] ) return S_OK( runitCompDir ) def setupComponent( componentType, system, component, extensions, componentModule = '', checkModule = True ): """ Install and create link in startup """ result = installComponent( componentType, system, component, extensions, componentModule, checkModule ) if not result['OK']: return result # Create the startup entry now runitCompDir = result['Value'] startCompDir = os.path.join( startDir, '%s_%s' % ( system, component ) ) if not os.path.exists( startDir ): os.makedirs( startDir ) if not os.path.lexists( startCompDir ): gLogger.notice( 'Creating startup link at', startCompDir ) os.symlink( runitCompDir, startCompDir ) time.sleep( 10 ) # Check the runsv status start = time.time() while ( time.time() - 20 ) < start: result = getStartupComponentStatus( [ ( system, component )] ) if not result['OK']: continue if result['Value'] and result['Value']['%s_%s' % ( system, component )]['RunitStatus'] == "Run": break time.sleep( 1 ) # Final check result = getStartupComponentStatus( [( system, component )] ) if not result['OK']: return S_ERROR( 'Failed to start the component %s_%s' % ( system, component ) ) resDict = {} resDict['ComponentType'] = componentType resDict['RunitStatus'] = result['Value']['%s_%s' % ( system, component )]['RunitStatus'] return S_OK( resDict ) def unsetupComponent( system, component ): """ Remove link from startup """ for startCompDir in glob.glob( os.path.join( startDir, '%s_%s' % ( system, component ) ) ): try: os.unlink( startCompDir ) except Exception: gLogger.exception() return S_OK() def uninstallComponent( system, component ): """ Remove startup and runit directories """ result = runsvctrlComponent( system, component, 'd' ) if not result['OK']: pass result = unsetupComponent( system, component ) for runitCompDir in glob.glob( os.path.join( runitDir, system, component ) ): try: shutil.rmtree( runitCompDir ) except Exception: gLogger.exception() return S_OK() def installPortal(): """ Install runit directories for the Web Portal """ # Check that the software for the Web Portal is installed error = '' webDir = os.path.join( linkedRootPath, 'Web' ) if not os.path.exists( webDir ): error = 'Web extension not installed at %s' % webDir if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) # First the lighthttpd server # Check if the component is already installed runitHttpdDir = os.path.join( runitDir, 'Web', 'httpd' ) runitPasterDir = os.path.join( runitDir, 'Web', 'paster' ) if os.path.exists( runitHttpdDir ): msg = "lighthttpd already installed" gLogger.notice( msg ) else: gLogger.notice( 'Installing Lighttpd' ) # Now do the actual installation try: _createRunitLog( runitHttpdDir ) runFile = os.path.join( runitHttpdDir, 'run' ) fd = open( runFile, 'w' ) fd.write( """#!/bin/bash rcfile=%(bashrc)s [ -e $rcfile ] && source $rcfile # exec 2>&1 # exec lighttpdSvc.sh < /dev/null """ % {'bashrc': os.path.join( instancePath, 'bashrc' ), } ) fd.close() os.chmod( runFile, gDefaultPerms ) except Exception: error = 'Failed to prepare setup for lighttpd' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) result = execCommand( 5, [runFile] ) gLogger.notice( result['Value'][1] ) # Second the Web portal # Check if the component is already installed if os.path.exists( runitPasterDir ): msg = "Web Portal already installed" gLogger.notice( msg ) else: gLogger.notice( 'Installing Web Portal' ) # Now do the actual installation try: _createRunitLog( runitPasterDir ) runFile = os.path.join( runitPasterDir, 'run' ) fd = open( runFile, 'w' ) fd.write( """#!/bin/bash rcfile=%(bashrc)s [ -e $rcfile ] && source $rcfile # exec 2>&1 # cd %(DIRAC)s/Web exec paster serve --reload production.ini < /dev/null """ % {'bashrc': os.path.join( instancePath, 'bashrc' ), 'DIRAC': linkedRootPath} ) fd.close() os.chmod( runFile, gDefaultPerms ) except Exception: error = 'Failed to prepare setup for Web Portal' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) result = execCommand( 5, [runFile] ) gLogger.notice( result['Value'][1] ) return S_OK( [runitHttpdDir, runitPasterDir] ) def setupPortal(): """ Install and create link in startup """ result = installPortal() if not result['OK']: return result # Create the startup entries now runitCompDir = result['Value'] startCompDir = [ os.path.join( startDir, 'Web_httpd' ), os.path.join( startDir, 'Web_paster' ) ] if not os.path.exists( startDir ): os.makedirs( startDir ) for i in range( 2 ): if not os.path.lexists( startCompDir[i] ): gLogger.notice( 'Creating startup link at', startCompDir[i] ) os.symlink( runitCompDir[i], startCompDir[i] ) time.sleep( 1 ) time.sleep( 5 ) # Check the runsv status start = time.time() while ( time.time() - 10 ) < start: result = getStartupComponentStatus( [ ( 'Web', 'httpd' ), ( 'Web', 'paster' ) ] ) if not result['OK']: return S_ERROR( 'Failed to start the Portal' ) if result['Value'] and \ result['Value']['%s_%s' % ( 'Web', 'httpd' )]['RunitStatus'] == "Run" and \ result['Value']['%s_%s' % ( 'Web', 'paster' )]['RunitStatus'] == "Run" : break time.sleep( 1 ) # Final check return getStartupComponentStatus( [ ( 'Web', 'httpd' ), ( 'Web', 'paster' ) ] ) def setupNewPortal(): """ Install and create link in startup """ result = installNewPortal() if not result['OK']: return result # Create the startup entries now runitCompDir = result['Value'] startCompDir = os.path.join( startDir, 'Web_WebApp' ) if not os.path.exists( startDir ): os.makedirs( startDir ) if not os.path.lexists( startCompDir ): gLogger.notice( 'Creating startup link at', startCompDir ) os.symlink( runitCompDir, startCompDir ) time.sleep( 5 ) # Check the runsv status start = time.time() while ( time.time() - 10 ) < start: result = getStartupComponentStatus( [( 'Web', 'WebApp' )] ) if not result['OK']: return S_ERROR( 'Failed to start the Portal' ) if result['Value'] and \ result['Value']['%s_%s' % ( 'Web', 'WebApp' )]['RunitStatus'] == "Run": break time.sleep( 1 ) # Final check return getStartupComponentStatus( [ ('Web', 'WebApp') ] ) def installNewPortal(): """ Install runit directories for the Web Portal """ result = execCommand( False, ["pip", "install", "tornado"] ) if not result['OK']: error = "Tornado can not be installed:%s" % result['Value'] gLogger.error( error ) DIRAC.exit(-1) return error else: gLogger.notice("Tornado is installed successfully!") # Check that the software for the Web Portal is installed error = '' webDir = os.path.join( linkedRootPath, 'WebAppDIRAC' ) if not os.path.exists( webDir ): error = 'WebApp extension not installed at %s' % webDir if exitOnError: gLogger.error( error ) DIRAC.exit( -1 ) return S_ERROR( error ) #compile the JS code prodMode = "" webappCompileScript = os.path.join( linkedRootPath, "WebAppDIRAC/scripts", "dirac-webapp-compile.py" ) if os.path.isfile( webappCompileScript ): os.chmod( webappCompileScript , gDefaultPerms ) gLogger.notice( "Executing %s..." % webappCompileScript ) if os.system( "python '%s' > '%s.out' 2> '%s.err'" % ( webappCompileScript, webappCompileScript, webappCompileScript ) ): gLogger.error( "Compile script %s failed. Check %s.err" % ( webappCompileScript, webappCompileScript ) ) else: prodMode = "-p" # Check if the component is already installed runitWebAppDir = os.path.join( runitDir, 'Web', 'WebApp' ) # Check if the component is already installed if os.path.exists( runitWebAppDir ): msg = "Web Portal already installed" gLogger.notice( msg ) else: gLogger.notice( 'Installing Web Portal' ) # Now do the actual installation try: _createRunitLog( runitWebAppDir ) runFile = os.path.join( runitWebAppDir, 'run' ) fd = open( runFile, 'w' ) fd.write( """#!/bin/bash rcfile=%(bashrc)s [ -e $rcfile ] && source $rcfile # exec 2>&1 # exec python %(DIRAC)s/WebAppDIRAC/scripts/dirac-webapp-run.py %(prodMode)s < /dev/null """ % {'bashrc': os.path.join( instancePath, 'bashrc' ), 'DIRAC': linkedRootPath, 'prodMode':prodMode} ) fd.close() os.chmod( runFile, gDefaultPerms ) except Exception: error = 'Failed to prepare setup for Web Portal' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) result = execCommand( 5, [runFile] ) gLogger.notice( result['Value'][1] ) return S_OK( runitWebAppDir ) def fixMySQLScripts( startupScript = mysqlStartupScript ): """ Edit MySQL scripts to point to desired locations for db and my.cnf """ gLogger.verbose( 'Updating:', startupScript ) try: fd = open( startupScript, 'r' ) orgLines = fd.readlines() fd.close() fd = open( startupScript, 'w' ) for line in orgLines: if line.find( 'export HOME' ) == 0: continue if line.find( 'datadir=' ) == 0: line = 'datadir=%s\n' % mysqlDbDir gLogger.debug( line ) line += 'export HOME=%s\n' % mysqlDir if line.find( 'basedir=' ) == 0: platform = getPlatformString() line = 'basedir=%s\n' % os.path.join( rootPath, platform ) if line.find( 'extra_args=' ) == 0: line = 'extra_args="-n"\n' if line.find( '$bindir/mysqld_safe --' ) >= 0 and not ' --no-defaults ' in line: line = line.replace( 'mysqld_safe', 'mysqld_safe --no-defaults' ) fd.write( line ) fd.close() except Exception: error = 'Failed to Update MySQL startup script' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) return S_OK() def mysqlInstalled( doNotExit = False ): """ Check if MySQL is already installed """ if os.path.exists( mysqlDbDir ) or os.path.exists( mysqlLogDir ): return S_OK() if doNotExit: return S_ERROR() error = 'MySQL not properly Installed' gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) def getMySQLPasswords(): """ Get MySQL passwords from local configuration or prompt """ import getpass global mysqlRootPwd, mysqlPassword if not mysqlRootPwd: mysqlRootPwd = getpass.getpass( 'MySQL root password: ' ) if not mysqlPassword: # Take it if it is already defined mysqlPassword = localCfg.getOption( '/Systems/Databases/Password', '' ) if not mysqlPassword: mysqlPassword = getpass.getpass( 'MySQL Dirac password: ' ) return S_OK() def setMySQLPasswords( root = '', dirac = '' ): """ Set MySQL passwords """ global mysqlRootPwd, mysqlPassword if root: mysqlRootPwd = root if dirac: mysqlPassword = dirac return S_OK() def startMySQL(): """ Start MySQL server """ result = mysqlInstalled() if not result['OK']: return result return execCommand( 0, [mysqlStartupScript, 'start'] ) def stopMySQL(): """ Stop MySQL server """ result = mysqlInstalled() if not result['OK']: return result return execCommand( 0, [mysqlStartupScript, 'stop'] ) def installMySQL(): """ Attempt an installation of MySQL mode: -Master -Slave -None """ fixMySQLScripts() if mysqlInstalled( doNotExit = True )['OK']: gLogger.notice( 'MySQL already installed' ) return S_OK() if mysqlMode.lower() not in [ '', 'master', 'slave' ]: error = 'Unknown MySQL server Mode' if exitOnError: gLogger.fatal( error, mysqlMode ) DIRAC.exit( -1 ) gLogger.error( error, mysqlMode ) return S_ERROR( error ) if mysqlHost: gLogger.notice( 'Installing MySQL server at', mysqlHost ) if mysqlMode: gLogger.notice( 'This is a MySQl %s server' % mysqlMode ) try: os.makedirs( mysqlDbDir ) os.makedirs( mysqlLogDir ) except Exception: error = 'Can not create MySQL dirs' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) try: fd = open( mysqlMyOrg, 'r' ) myOrg = fd.readlines() fd.close() fd = open( mysqlMyCnf, 'w' ) for line in myOrg: if line.find( '[mysqld]' ) == 0: line += '\n'.join( [ 'innodb_file_per_table', '' ] ) elif line.find( 'innodb_log_arch_dir' ) == 0: line = '' elif line.find( 'innodb_data_file_path' ) == 0: line = line.replace( '2000M', '200M' ) elif line.find( 'server-id' ) == 0 and mysqlMode.lower() == 'master': # MySQL Configuration for Master Server line = '\n'.join( ['server-id = 1', '# DIRAC Master-Server', 'sync-binlog = 1', 'replicate-ignore-table = mysql.MonitorData', '# replicate-ignore-db=db_name', 'log-bin = mysql-bin', 'log-slave-updates', '' ] ) elif line.find( 'server-id' ) == 0 and mysqlMode.lower() == 'slave': # MySQL Configuration for Slave Server line = '\n'.join( ['server-id = %s' % int( time.time() ), '# DIRAC Slave-Server', 'sync-binlog = 1', 'replicate-ignore-table = mysql.MonitorData', '# replicate-ignore-db=db_name', 'log-bin = mysql-bin', 'log-slave-updates', '' ] ) elif line.find( '/opt/dirac/mysql' ) > -1: line = line.replace( '/opt/dirac/mysql', mysqlDir ) if mysqlSmallMem: if line.find( 'innodb_buffer_pool_size' ) == 0: line = 'innodb_buffer_pool_size = 200M\n' elif mysqlLargeMem: if line.find( 'innodb_buffer_pool_size' ) == 0: line = 'innodb_buffer_pool_size = 10G\n' fd.write( line ) fd.close() except Exception: error = 'Can not create my.cnf' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) gLogger.notice( 'Initializing MySQL...' ) result = execCommand( 0, ['mysql_install_db', '--defaults-file=%s' % mysqlMyCnf, '--datadir=%s' % mysqlDbDir ] ) if not result['OK']: return result gLogger.notice( 'Starting MySQL...' ) result = startMySQL() if not result['OK']: return result gLogger.notice( 'Setting MySQL root password' ) result = execCommand( 0, ['mysqladmin', '-u', mysqlRootUser, 'password', mysqlRootPwd] ) if not result['OK']: return result # MySQL tends to define root@host user rather than root@host.domain hostName = mysqlHost.split('.')[0] result = execMySQL( "UPDATE user SET Host='%s' WHERE Host='%s'" % (mysqlHost,hostName), localhost=True ) if not result['OK']: return result result = execMySQL( "FLUSH PRIVILEGES" ) if not result['OK']: return result if mysqlHost and socket.gethostbyname( mysqlHost ) != '127.0.0.1' : result = execCommand( 0, ['mysqladmin', '-u', mysqlRootUser, '-h', mysqlHost, 'password', mysqlRootPwd] ) if not result['OK']: return result result = execMySQL( "DELETE from user WHERE Password=''", localhost=True ) if not _addMySQLToDiracCfg(): return S_ERROR( 'Failed to add MySQL user password to local configuration' ) return S_OK() def getMySQLStatus(): """ Get the status of the MySQL database installation """ result = execCommand( 0, ['mysqladmin', 'status' ] ) if not result['OK']: return result output = result['Value'][1] _d1, uptime, nthreads, nquestions, nslow, nopens, nflash, nopen, nqpersec = output.split( ':' ) resDict = {} resDict['UpTime'] = uptime.strip().split()[0] resDict['NumberOfThreads'] = nthreads.strip().split()[0] resDict['NumberOfQuestions'] = nquestions.strip().split()[0] resDict['NumberOfSlowQueries'] = nslow.strip().split()[0] resDict['NumberOfOpens'] = nopens.strip().split()[0] resDict['OpenTables'] = nopen.strip().split()[0] resDict['FlushTables'] = nflash.strip().split()[0] resDict['QueriesPerSecond'] = nqpersec.strip().split()[0] return S_OK( resDict ) def getAvailableDatabases( extensions ): dbDict = {} for extension in extensions + ['']: databases = glob.glob( os.path.join( rootPath, '%sDIRAC' % extension, '*', 'DB', '*.sql' ) ) for dbPath in databases: dbName = os.path.basename( dbPath ).replace( '.sql', '' ) dbDict[dbName] = {} dbDict[dbName]['Extension'] = extension dbDict[dbName]['System'] = dbPath.split( '/' )[-3].replace( 'System', '' ) return S_OK( dbDict ) def getDatabases(): """ Get the list of installed databases """ result = execMySQL( 'SHOW DATABASES' ) if not result['OK']: return result dbList = [] for dbName in result['Value']: if not dbName[0] in ['Database', 'information_schema', 'mysql', 'test']: dbList.append( dbName[0] ) return S_OK( dbList ) def installDatabase( dbName ): """ Install requested DB in MySQL server """ global mysqlRootPwd, mysqlPassword if not mysqlRootPwd: rootPwdPath = cfgInstallPath( 'Database', 'RootPwd' ) return S_ERROR( 'Missing %s in %s' % ( rootPwdPath, cfgFile ) ) if not mysqlPassword: mysqlPassword = localCfg.getOption( cfgPath( 'Systems', 'Databases', 'Password' ), mysqlPassword ) if not mysqlPassword: mysqlPwdPath = cfgPath( 'Systems', 'Databases', 'Password' ) return S_ERROR( 'Missing %s in %s' % ( mysqlPwdPath, cfgFile ) ) gLogger.notice( 'Installing', dbName ) dbFile = glob.glob( os.path.join( rootPath, '*', '*', 'DB', '%s.sql' % dbName ) ) if not dbFile: error = 'Database %s not found' % dbName gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) dbFile = dbFile[0] # just check result = execMySQL( 'SHOW STATUS' ) if not result['OK']: error = 'Could not connect to MySQL server' gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) # now creating the Database result = execMySQL( 'CREATE DATABASE `%s`' % dbName ) if not result['OK']: gLogger.error( 'Failed to create databases', result['Message'] ) if exitOnError: DIRAC.exit( -1 ) return result perms = "SELECT,INSERT,LOCK TABLES,UPDATE,DELETE,CREATE,DROP,ALTER,CREATE VIEW, SHOW VIEW" for cmd in ["GRANT %s ON `%s`.* TO '%s'@'localhost' IDENTIFIED BY '%s'" % ( perms, dbName, mysqlUser, mysqlPassword ), "GRANT %s ON `%s`.* TO '%s'@'%s' IDENTIFIED BY '%s'" % ( perms, dbName, mysqlUser, mysqlHost, mysqlPassword ), "GRANT %s ON `%s`.* TO '%s'@'%%' IDENTIFIED BY '%s'" % ( perms, dbName, mysqlUser, mysqlPassword ) ]: result = execMySQL( cmd ) if not result['OK']: error = "Error executing '%s'" % cmd gLogger.error( error, result['Message'] ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) result = execMySQL( 'FLUSH PRIVILEGES' ) if not result['OK']: gLogger.error( 'Failed to flush provileges', result['Message'] ) if exitOnError: exit( -1 ) return result # first getting the lines to be executed, and then execute them try: cmdLines = _createMySQLCMDLines( dbFile ) # We need to run one SQL cmd at once, mysql is much happier that way. # Create a string of commands, ignoring comment lines sqlString = '\n'.join( x for x in cmdLines if not x.startswith( "--" ) ) # Now run each command (They are seperated by ;) # Ignore any empty ones cmds = [ x.strip() for x in sqlString.split( ";" ) if x.strip() ] for cmd in cmds: result = execMySQL( cmd, dbName ) if not result['OK']: error = 'Failed to initialize Database' gLogger.notice( cmd ) gLogger.error( error, result['Message'] ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) except Exception, e: gLogger.error( str( e ) ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) return S_OK( dbFile.split( '/' )[-4:-2] ) def _createMySQLCMDLines( dbFile ): """ Creates a list of MYSQL commands to be executed, inspecting the dbFile(s) """ cmdLines = [] fd = open( dbFile ) dbLines = fd.readlines() fd.close() for line in dbLines: # Should we first source an SQL file (is this sql file an extension)? if line.lower().startswith('source'): sourcedDBbFileName = line.split( ' ' )[1].replace( '\n', '' ) gLogger.info( "Found file to source: %s" % sourcedDBbFileName ) sourcedDBbFile = os.path.join( rootPath, sourcedDBbFileName ) fdSourced = open( sourcedDBbFile ) dbLinesSourced = fdSourced.readlines() fdSourced.close() for lineSourced in dbLinesSourced: if lineSourced.strip(): cmdLines.append( lineSourced.strip() ) # Creating/adding cmdLines else: if line.strip(): cmdLines.append( line.strip() ) return cmdLines def execMySQL( cmd, dbName = 'mysql', localhost=False ): """ Execute MySQL Command """ global db from DIRAC.Core.Utilities.MySQL import MySQL if not mysqlRootPwd: return S_ERROR( 'MySQL root password is not defined' ) if dbName not in db: dbHost = mysqlHost if localhost: dbHost = 'localhost' db[dbName] = MySQL( dbHost, mysqlRootUser, mysqlRootPwd, dbName, mysqlPort ) if not db[dbName]._connected: error = 'Could not connect to MySQL server' gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) return db[dbName]._query( cmd ) def _addMySQLToDiracCfg(): """ Add the database access info to the local configuration """ if not mysqlPassword: return S_ERROR( 'Missing %s in %s' % ( cfgInstallPath( 'Database', 'Password' ), cfgFile ) ) sectionPath = cfgPath( 'Systems', 'Databases' ) cfg = __getCfg( sectionPath, 'User', mysqlUser ) cfg.setOption( cfgPath( sectionPath, 'Password' ), mysqlPassword ) return _addCfgToDiracCfg( cfg ) def configureCE( ceName = '', ceType = '', cfg = None, currentSectionPath = '' ): """ Produce new dirac.cfg including configuration for new CE """ from DIRAC.Resources.Computing.ComputingElementFactory import ComputingElementFactory from DIRAC import gConfig cesCfg = ResourcesDefaults.getComputingElementDefaults( ceName, ceType, cfg, currentSectionPath ) ceNameList = cesCfg.listSections() if not ceNameList: error = 'No CE Name provided' gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) for ceName in ceNameList: if 'CEType' not in cesCfg[ceName]: error = 'Missing Type for CE "%s"' % ceName gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) localsiteCfg = localCfg['LocalSite'] # Replace Configuration under LocalSite with new Configuration for ceName in ceNameList: if localsiteCfg.existsKey( ceName ): gLogger.notice( ' Removing existing CE:', ceName ) localsiteCfg.deleteKey( ceName ) gLogger.notice( 'Configuring CE:', ceName ) localsiteCfg.createNewSection( ceName, contents = cesCfg[ceName] ) # Apply configuration and try to instantiate the CEs gConfig.loadCFG( localCfg ) for ceName in ceNameList: ceFactory = ComputingElementFactory() try: ceInstance = ceFactory.getCE( ceType, ceName ) except Exception: error = 'Fail to instantiate CE' gLogger.exception( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) if not ceInstance['OK']: error = 'Fail to instantiate CE: %s' % ceInstance['Message'] gLogger.error( error ) if exitOnError: DIRAC.exit( -1 ) return S_ERROR( error ) # Everything is OK, we can save the new cfg localCfg.writeToFile( cfgFile ) gLogger.always( 'LocalSite section in %s has been uptdated with new configuration:' % os.path.basename( cfgFile ) ) gLogger.always( str( localCfg['LocalSite'] ) ) return S_OK( ceNameList ) def configureLocalDirector( ceNameList = '' ): """ Install a Local DIRAC TaskQueueDirector, basically write the proper configuration file """ if ceNameList: result = setupComponent( 'agent', 'WorkloadManagement', 'TaskQueueDirector', [] ) if not result['OK']: return result # Now write a local Configuration for the Director directorCfg = CFG() directorCfg.addKey( 'SubmitPools', 'DIRAC', 'Added by InstallTools' ) directorCfg.addKey( 'DefaultSubmitPools', 'DIRAC', 'Added by InstallTools' ) directorCfg.addKey( 'ComputingElements', ', '.join( ceNameList ), 'Added by InstallTools' ) result = addCfgToComponentCfg( 'agent', 'WorkloadManagement', 'TaskQueueDirector', directorCfg ) if not result['OK']: return result return runsvctrlComponent( 'WorkloadManagement', 'TaskQueueDirector', 't' ) def execCommand( timeout, cmd ): """ Execute command tuple and handle Error cases """ result = systemCall( timeout, cmd ) if not result['OK']: if timeout and result['Message'].find( 'Timeout' ) == 0: return result gLogger.error( 'Failed to execute', '%s: %s' % ( cmd[0], result['Message'] ) ) if exitOnError: DIRAC.exit( -1 ) return result if result['Value'][0]: error = 'Failed to execute' gLogger.error( error, cmd[0] ) gLogger.error( 'Exit code:' , ( '%s\n' % result['Value'][0] ) + '\n'.join( result['Value'][1:] ) ) if exitOnError: DIRAC.exit( -1 ) error = S_ERROR( error ) error['Value'] = result['Value'] return error gLogger.verbose( result['Value'][1] ) return result
Sbalbp/DIRAC
Core/Utilities/InstallTools.py
Python
gpl-3.0
88,169
package com.brian.knu.coap.medicalmonitor; import org.eclipse.om2m.commons.resource.StatusCode; import org.eclipse.om2m.commons.rest.RequestIndication; import org.eclipse.om2m.commons.rest.ResponseConfirm; import org.eclipse.om2m.ipu.service.IpuService; /* * Execute received requests from OM2M to the specific technologies4 * Its work is to start and stop the */ public class Controller implements IpuService { @Override public ResponseConfirm doExecute(RequestIndication requestIndication) { // TODO Auto-generated method stub String[] parts = requestIndication.getTargetID().split("/"); String appId = parts[2]; return new ResponseConfirm(StatusCode.STATUS_NOT_FOUND, appId + "not found"); } @Override public ResponseConfirm doRetrieve(RequestIndication requestIndication) { // TODO Auto-generated method stub String[] parts = requestIndication.getTargetID().split("/"); String appId = parts[2]; String content; if (appId.equals(MedicationMonitor.sensorId)) { content = Mapper.getSensorDataRep(MedicationMonitor.sensorValue); return new ResponseConfirm(StatusCode.STATUS_OK, content); } else { return new ResponseConfirm(StatusCode.STATUS_NOT_FOUND, appId + "not found"); } } @Override public ResponseConfirm doUpdate(RequestIndication requestIndication) { // TODO Auto-generated method stub return new ResponseConfirm(StatusCode.STATUS_NOT_IMPLEMENTED, requestIndication.getMethod() + " not Implemented"); } @Override public ResponseConfirm doDelete(RequestIndication requestIndication) { // TODO Auto-generated method stub return new ResponseConfirm(StatusCode.STATUS_NOT_IMPLEMENTED, requestIndication.getMethod() + " not Implemented"); } @Override public ResponseConfirm doCreate(RequestIndication requestIndication) { // TODO Auto-generated method stub return new ResponseConfirm(StatusCode.STATUS_NOT_IMPLEMENTED, requestIndication.getMethod() + " not Implemented"); } @Override public String getAPOCPath() { // TODO Auto-generated method stub return MedicationMonitor.tempId; } }
AINLAB/OHP-M2M
M2M Server/com.brian.knu.coap.medicalmonitor/src/main/java/com/brian/knu/coap/medicalmonitor/Controller.java
Java
gpl-3.0
2,110
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeBlock.Context.PCAT { class ReturnNode : BaseNode { public override string AcceptedTypeNames => "return"; protected override IEnumerable<IEnumerable<Interruption>> InnerExecute(Return.ReturnSetter me) { if(Child.ContainsKey("return_value")) { Return rhs = new Return(); yield return Child["return_value"].Execute(rhs); Mediator.Instance.ExecutingNameSpace.Reassign("@return", rhs.Object); } yield return NewInterrupt("return", null); yield break; // Will never execute to there } } }
instr3/TejiLang-Toy
CodeBlock/Context/PCAT/ReturnNode.cs
C#
gpl-3.0
770
/* ComLibrary - A library plugin for Minecraft Copyright (C) 2015 comdude2 (Matt Armer) 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/>. Contact: admin@mcviral.net */ package net.comdude2.plugins.comlibrary.util; import java.text.SimpleDateFormat; import java.util.Date; import java.util.logging.Formatter; import java.util.logging.Handler; import java.util.logging.LogRecord; public class LogFormatter extends Formatter{ private String name = null; //Name is the name of the plugin public LogFormatter(String name){ this.name = name; } @Override public String format(LogRecord rec) { StringBuilder builder = new StringBuilder(1000); //builder.append("\n"); builder.append("["); builder.append(getDate(rec.getMillis())); builder.append("]"); builder.append(" "); builder.append("["); builder.append(name); builder.append("]"); builder.append(" "); builder.append("["); builder.append(rec.getLevel()); builder.append("]"); builder.append(" - "); builder.append(formatMessage(rec)); builder.append(System.lineSeparator()); return builder.toString(); } public String getDate(long millisecs){ SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); Date resultDate = new Date(millisecs); return date_format.format(resultDate); } public String getHead(Handler h){ return super.getHead(h); } public String getTail(Handler h){ return super.getTail(h); } }
comdude2/ComLibrary
src/net/comdude2/plugins/comlibrary/util/LogFormatter.java
Java
gpl-3.0
2,088
import { Injectable } from '@angular/core'; import { Select } from '@ngxs/store'; import { Observable, Subject } from 'rxjs'; import { Alignment, Allegiance, ChatMode, GameServerEvent, Hostility, IAccount, ICharacter, ICharacterCreateInfo, IDialogChatAction, IMapData, INPC, IPlayer, isHostileTo } from '../../interfaces'; import { AccountState, GameState, LobbyState, SettingsState } from '../../stores'; import { ModalService } from './modal.service'; import { SocketService } from './socket.service'; @Injectable({ providedIn: 'root' }) export class GameService { private playGame: Subject<boolean> = new Subject(); public get playGame$() { return this.playGame.asObservable(); } private quitGame: Subject<void> = new Subject(); public get quitGame$() { return this.quitGame.asObservable(); } @Select(GameState.inGame) inGame$: Observable<boolean>; @Select(GameState.player) currentPlayer$: Observable<IPlayer>; @Select(GameState.map) currentMap$: Observable<IMapData>; @Select(AccountState.loggedIn) loggedIn$: Observable<boolean>; @Select(AccountState.account) account$: Observable<IAccount>; @Select(LobbyState.charCreateData) charCreateData$: Observable<ICharacterCreateInfo>; @Select(SettingsState.accounts) accounts$: Observable<IAccount[]>; @Select(SettingsState.charSlot) charSlot$: Observable<{ slot: number }>; @Select(SettingsState.chatMode) chatMode$: Observable<ChatMode>; @Select(SettingsState.currentCommand) currentCommand$: Observable<string>; @Select(SettingsState.currentLogMode) logMode$: Observable<string>; constructor( private socketService: SocketService, private modalService: ModalService ) {} init() { this.inGame$.subscribe(val => { if (val) { this.playGame.next(true); return; } this.playGame.next(false); this.quitGame.next(); }); } public sendCommandString(cmdString: string, target?: string) { if (cmdString.startsWith('#')) cmdString = cmdString.substring(1); cmdString.split(';').forEach(cmd => { cmd = cmd.trim(); let command = ''; let args = ''; if (cmd.includes(',')) { command = '!privatesay'; args = cmd; } else { [command, args] = this.parseCommand(cmd); } if (target) { args = `${args} ${target}`.trim(); } this.sendAction(GameServerEvent.DoCommand, { command, args }); }); } public sendAction(action: GameServerEvent, args: any) { this.socketService.emit(action, args); } private parseCommand(cmd: string) { const arr = cmd.split(' '); const multiPrefixes = ['party', 'look', 'show', 'cast', 'stance', 'powerword', 'art']; let argsIndex = 1; let command = arr[0]; if (multiPrefixes.includes(command)) { command = `${arr[0]} ${arr[1]}`; argsIndex = 2; } // factor in the space because otherwise indexOf can do funky things. const args = arr.length > argsIndex ? cmd.substring(cmd.indexOf(' ' + arr[argsIndex])).trim() : ''; return [command, args]; } // get the direction from a character to another one public directionTo(from: ICharacter, to: ICharacter) { if (!to || !from) return ''; const diffX = to.x - from.x; const diffY = to.y - from.y; if (diffX < 0 && diffY > 0) return '↙'; if (diffX > 0 && diffY < 0) return '↗'; if (diffX > 0 && diffY > 0) return '↘'; if (diffX < 0 && diffY < 0) return '↖'; if (diffX > 0) return '→'; if (diffY > 0) return '↓'; if (diffX < 0) return '←'; if (diffY < 0) return '↑'; return '✧'; } // check the hostility level between two characters // any changes here _might_ need to be made to server/checkTargetForHostility public hostilityLevelFor(origin: ICharacter, compare: ICharacter): 'hostile'|'neutral'|'friendly' { if (!origin) return 'neutral'; if (origin.allegiance === Allegiance.GM) return 'neutral'; if (compare.allegiance === Allegiance.NaturalResource) return 'neutral'; if ((origin as IPlayer).partyName && (origin as IPlayer).partyName === (compare as IPlayer).partyName) return 'neutral'; if (compare.agro[origin.uuid] || origin.agro[compare.uuid]) return 'hostile'; // TODO: disguise // if(me.hasEffect('Disguise') && me.getTotalStat('cha') > compare.getTotalStat('wil')) return 'neutral'; const hostility = (compare as INPC).hostility; if (!hostility) return 'neutral'; if (hostility === Hostility.Never) return 'friendly'; if (hostility === Hostility.Faction) { if (isHostileTo(origin, compare.allegiance) || isHostileTo(compare, origin.allegiance)) return 'hostile'; } if (origin.allegiance === compare.allegiance) return 'neutral'; if (hostility === Hostility.Always) return 'hostile'; if (origin.alignment === Alignment.Evil && compare.alignment === Alignment.Good) return 'hostile'; return 'neutral'; } public showNPCDialog(dialogInfo: IDialogChatAction) { const res = this.modalService.npcDialog(dialogInfo); if (!res) return; res.subscribe(result => { if (result && result !== 'noop') { this.sendCommandString(`#${dialogInfo.displayNPCUUID || dialogInfo.displayNPCName}, ${result}`); } }); } }
LandOfTheRair/landoftherair
client/src/app/services/game.service.ts
TypeScript
gpl-3.0
5,364
package com.phonemetra.turbo.store.views.swap; import android.app.Activity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v4.app.NavUtils; import android.support.v7.app.ActionBarActivity; import android.util.Log; import com.phonemetra.turbo.store.AppDetails; import com.phonemetra.turbo.store.R; import com.phonemetra.turbo.store.data.AppProvider; import com.phonemetra.turbo.store.data.Repo; import com.phonemetra.turbo.store.data.RepoProvider; import com.phonemetra.turbo.store.views.AppListAdapter; import com.phonemetra.turbo.store.views.AvailableAppListAdapter; import com.phonemetra.turbo.store.views.fragments.AppListFragment; public class SwapAppListActivity extends ActionBarActivity { private static final String TAG = "SwapAppListActivity"; public static final String EXTRA_REPO_ID = "repoId"; private Repo repo; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState == null) { // Necessary to run on an Android 2.3.[something] device. new Handler().post(new Runnable() { @Override public void run() { getSupportFragmentManager() .beginTransaction() .add(android.R.id.content, new SwapAppListFragment()) .commit(); } }); } } @Override protected void onResume() { super.onResume(); long repoAddress = getIntent().getLongExtra(EXTRA_REPO_ID, -1); repo = RepoProvider.Helper.findById(this, repoAddress); if (repo == null) { Log.e(TAG, "Couldn't show swap app list for repo " + repoAddress); finish(); } } public Repo getRepo() { return repo; } public static class SwapAppListFragment extends AppListFragment { private Repo repo; @Override public void onAttach(Activity activity) { super.onAttach(activity); repo = ((SwapAppListActivity)activity).getRepo(); } @Override protected int getHeaderLayout() { return R.layout.swap_success_header; } @Override protected AppListAdapter getAppListAdapter() { return new AvailableAppListAdapter(getActivity(), null); } @Nullable @Override protected String getEmptyMessage() { return getActivity().getString(R.string.empty_swap_app_list); } @Override protected String getFromTitle() { return getString(R.string.swap); } @Override protected Uri getDataUri() { return AppProvider.getRepoUri(repo); } protected Intent getAppDetailsIntent() { Intent intent = new Intent(getActivity(), SwapAppDetails.class); intent.putExtra(EXTRA_REPO_ID, repo.getId()); return intent; } } /** * Only difference from base class is that it navigates up to a different task. * It will go to the {@link com.phonemetra.turbo.store.views.swap.SwapAppListActivity} * whereas the baseclass will go back to the main list of apps. Need to juggle * the repoId in order to be able to return to an appropriately configured swap * list (see {@link com.phonemetra.turbo.store.views.swap.SwapAppListActivity.SwapAppListFragment#getAppDetailsIntent()}). */ public static class SwapAppDetails extends AppDetails { private long repoId; @Override protected void onResume() { super.onResume(); repoId = getIntent().getLongExtra(EXTRA_REPO_ID, -1); } @Override protected void navigateUp() { Intent parentIntent = NavUtils.getParentActivityIntent(this); parentIntent.putExtra(EXTRA_REPO_ID, repoId); NavUtils.navigateUpTo(this, parentIntent); } } }
Phonemetra/TurboStore
app/src/com/phonemetra/turbo/store/views/swap/SwapAppListActivity.java
Java
gpl-3.0
4,154
<?php /** * ANGIE - The site restoration script for backup archives created by Akeeba Backup and Akeeba Solo * * @package angie * @copyright Copyright (c)2009-2019 Nicholas K. Dionysopoulos / Akeeba Ltd * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL v3 or later */ defined('_AKEEBA') or die(); /** * This file may contain code from the Joomla! Platform, Copyright (c) 2005 - * 2012 Open Source Matters, Inc. This file is NOT part of the Joomla! Platform. * It is derivative work and clearly marked as such as per the provisions of the * GNU General Public License. */ class AUri { /** @var string Original URI */ protected $uri = null; /** @var string Protocol */ protected $scheme = null; /** @var string Host */ protected $host = null; /** @var integer Port */ protected $port = null; /** @var string Username */ protected $user = null; /** @var string Password */ protected $pass = null; /** @var string Path */ protected $path = null; /** @var string Query */ protected $query = null; /** @var string Anchor */ protected $fragment = null; /** @var array Query variable hash */ protected $vars = array(); /** @var array An array of AURI instances. */ protected static $instances = array(); /** @var array The current calculated base url segments. */ protected static $base = array(); /** @var array The current calculated root url segments. */ protected static $root = array(); protected static $current; /** * Constructor. * You can pass a URI string to the constructor to initialise a specific URI. * * @param string $uri The optional URI string */ public function __construct($uri = null) { if (!is_null($uri)) { $this->parse($uri); } } /** * Magic method to get the string representation of the URI object. * * @return string */ public function __toString() { return $this->toString(); } /** * Returns the global AURI object, only creating it * if it doesn't already exist. * * @param string $uri The URI to parse. [optional: if null uses script URI] * * @return AURI The URI object. */ public static function getInstance($uri = 'SERVER') { if (empty(self::$instances[$uri])) { // Are we obtaining the URI from the server? if ($uri == 'SERVER') { // Determine if the request was over SSL (HTTPS). if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) && (strtolower($_SERVER['HTTPS']) != 'off')) { $https = 's://'; } else { $https = '://'; } /* * Since we are assigning the URI from the server variables, we first need * to determine if we are running on apache or IIS. If PHP_SELF and REQUEST_URI * are present, we will assume we are running on apache. */ if (!empty($_SERVER['PHP_SELF']) && !empty($_SERVER['REQUEST_URI'])) { // To build the entire URI we need to prepend the protocol, and the http host // to the URI string. $theURI = 'http' . $https . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; } else { /* * Since we do not have REQUEST_URI to work with, we will assume we are * running on IIS and will therefore need to work some magic with the SCRIPT_NAME and * QUERY_STRING environment variables. * * IIS uses the SCRIPT_NAME variable instead of a REQUEST_URI variable... thanks, MS */ $theURI = 'http' . $https . $_SERVER['HTTP_HOST'] . $_SERVER['SCRIPT_NAME']; // If the query string exists append it to the URI string if (isset($_SERVER['QUERY_STRING']) && !empty($_SERVER['QUERY_STRING'])) { $theURI .= '?' . $_SERVER['QUERY_STRING']; } } } else { // We were given a URI $theURI = $uri; } self::$instances[$uri] = new AURI($theURI); } return self::$instances[$uri]; } /** * Returns the base URI for the request. * * @param boolean $pathonly If false, prepend the scheme, host and port information. Default is false. * * @return string The base URI string */ public static function base($pathonly = false) { // Get the base request path. if (empty(self::$base)) { $uri = self::getInstance(); self::$base['prefix'] = $uri->toString(array('scheme', 'host', 'port')); if (strpos(php_sapi_name(), 'cgi') !== false && !ini_get('cgi.fix_pathinfo') && !empty($_SERVER['REQUEST_URI'])) { // PHP-CGI on Apache with "cgi.fix_pathinfo = 0" // We shouldn't have user-supplied PATH_INFO in PHP_SELF in this case // because PHP will not work with PATH_INFO at all. $script_name = $_SERVER['PHP_SELF']; } else { // Others $script_name = $_SERVER['SCRIPT_NAME']; } self::$base['path'] = rtrim(dirname($script_name), '/\\'); } return $pathonly === false ? self::$base['prefix'] . self::$base['path'] . '/' : self::$base['path']; } /** * Returns the root URI for the request. * * @param boolean $pathonly If false, prepend the scheme, host and port information. Default is false. * @param string $path The path * * @return string The root URI string. */ public static function root($pathonly = false, $path = null) { // Get the scheme if (empty(self::$root)) { $uri = self::getInstance(self::base()); self::$root['prefix'] = $uri->toString(array('scheme', 'host', 'port')); self::$root['path'] = rtrim($uri->toString(array('path')), '/\\'); } // Get the scheme if (isset($path)) { self::$root['path'] = $path; } return $pathonly === false ? self::$root['prefix'] . self::$root['path'] . '/' : self::$root['path']; } /** * Returns the URL for the request, minus the query. * * @return string */ public static function current() { // Get the current URL. if (empty(self::$current)) { $uri = self::getInstance(); self::$current = $uri->toString(array('scheme', 'host', 'port', 'path')); } return self::$current; } /** * Method to reset class static members for testing and other various issues. * * @return void */ public static function reset() { self::$instances = array(); self::$base = array(); self::$root = array(); self::$current = ''; } /** * Parse a given URI and populate the class fields. * * @param string $uri The URI string to parse. * * @return boolean True on success. */ public function parse($uri) { // Set the original URI to fall back on $this->uri = $uri; // Parse the URI and populate the object fields. If URI is parsed properly, // set method return value to true. $parts = self::parse_url($uri); $retval = ($parts) ? true : false; // We need to replace &amp; with & for parse_str to work right... if (isset($parts['query']) && strpos($parts['query'], '&amp;')) { $parts['query'] = str_replace('&amp;', '&', $parts['query']); } $this->scheme = isset($parts['scheme']) ? $parts['scheme'] : null; $this->user = isset($parts['user']) ? $parts['user'] : null; $this->pass = isset($parts['pass']) ? $parts['pass'] : null; $this->host = isset($parts['host']) ? $parts['host'] : null; $this->port = isset($parts['port']) ? $parts['port'] : null; $this->path = isset($parts['path']) ? $parts['path'] : null; $this->query = isset($parts['query']) ? $parts['query'] : null; $this->fragment = isset($parts['fragment']) ? $parts['fragment'] : null; // Parse the query if (isset($parts['query'])) { parse_str($parts['query'], $this->vars); } return $retval; } /** * Returns full uri string. * * @param array $parts An array specifying the parts to render. * * @return string The rendered URI string. */ public function toString(array $parts = array('scheme', 'user', 'pass', 'host', 'port', 'path', 'query', 'fragment')) { // Make sure the query is created $query = $this->getQuery(); $uri = ''; $uri .= in_array('scheme', $parts) ? (!empty($this->scheme) ? $this->scheme . '://' : '') : ''; $uri .= in_array('user', $parts) ? $this->user : ''; $uri .= in_array('pass', $parts) ? (!empty($this->pass) ? ':' : '') . $this->pass . (!empty($this->user) ? '@' : '') : ''; $uri .= in_array('host', $parts) ? $this->host : ''; $uri .= in_array('port', $parts) ? (!empty($this->port) ? ':' : '') . $this->port : ''; $uri .= in_array('path', $parts) ? $this->path : ''; $uri .= in_array('query', $parts) ? (!empty($query) ? '?' . $query : '') : ''; $uri .= in_array('fragment', $parts) ? (!empty($this->fragment) ? '#' . $this->fragment : '') : ''; return $uri; } /** * Adds a query variable and value, replacing the value if it * already exists and returning the old value. * * @param string $name Name of the query variable to set. * @param string $value Value of the query variable. * * @return string Previous value for the query variable. */ public function setVar($name, $value) { $tmp = isset($this->vars[$name]) ? $this->vars[$name] : null; $this->vars[$name] = $value; // Empty the query $this->query = null; return $tmp; } /** * Checks if variable exists. * * @param string $name Name of the query variable to check. * * @return boolean True if the variable exists. */ public function hasVar($name) { return array_key_exists($name, $this->vars); } /** * Returns a query variable by name. * * @param string $name Name of the query variable to get. * @param string $default Default value to return if the variable is not set. * * @return array Query variables. */ public function getVar($name, $default = null) { if (array_key_exists($name, $this->vars)) { return $this->vars[$name]; } return $default; } /** * Removes an item from the query string variables if it exists. * * @param string $name Name of variable to remove. * * @return void */ public function delVar($name) { if (array_key_exists($name, $this->vars)) { unset($this->vars[$name]); // Empty the query $this->query = null; } } /** * Sets the query to a supplied string in format: * foo=bar&x=y * * @param mixed $query The query string or array. * * @return void */ public function setQuery($query) { if (is_array($query)) { $this->vars = $query; } else { if (strpos($query, '&amp;') !== false) { $query = str_replace('&amp;', '&', $query); } parse_str($query, $this->vars); } // Empty the query $this->query = null; } /** * Returns flat query string. * * @param boolean $toArray True to return the query as a key => value pair array. * * @return string Query string. */ public function getQuery($toArray = false) { if ($toArray) { return $this->vars; } // If the query is empty build it first if (is_null($this->query)) { $this->query = self::buildQuery($this->vars); } return $this->query; } /** * Build a query from a array (reverse of the PHP parse_str()). * * @param array $params The array of key => value pairs to return as a query string. * * @return string The resulting query string. * * @see parse_str() */ public static function buildQuery(array $params) { if (count($params) == 0) { return false; } return urldecode(http_build_query($params, '', '&')); } /** * Get URI scheme (protocol) * ie. http, https, ftp, etc... * * @return string The URI scheme. */ public function getScheme() { return $this->scheme; } /** * Set URI scheme (protocol) * ie. http, https, ftp, etc... * * @param string $scheme The URI scheme. * * @return void */ public function setScheme($scheme) { $this->scheme = $scheme; } /** * Get URI username * Returns the username, or null if no username was specified. * * @return string The URI username. */ public function getUser() { return $this->user; } /** * Set URI username. * * @param string $user The URI username. * * @return void */ public function setUser($user) { $this->user = $user; } /** * Get URI password * Returns the password, or null if no password was specified. * * @return string The URI password. */ public function getPass() { return $this->pass; } /** * Set URI password. * * @param string $pass The URI password. * * @return void */ public function setPass($pass) { $this->pass = $pass; } /** * Get URI host * Returns the hostname/ip or null if no hostname/ip was specified. * * @return string The URI host. */ public function getHost() { return $this->host; } /** * Set URI host. * * @param string $host The URI host. * * @return void */ public function setHost($host) { $this->host = $host; } /** * Get URI port * Returns the port number, or null if no port was specified. * * @return integer The URI port number. */ public function getPort() { return (isset($this->port)) ? $this->port : null; } /** * Set URI port. * * @param integer $port The URI port number. * * @return void */ public function setPort($port) { $this->port = $port; } /** * Gets the URI path string. * * @return string The URI path string. */ public function getPath() { return $this->path; } /** * Set the URI path string. * * @param string $path The URI path string. * * @return void */ public function setPath($path) { $this->path = $this->_cleanPath($path); } /** * Get the URI archor string * Everything after the "#". * * @return string The URI anchor string. */ public function getFragment() { return $this->fragment; } /** * Set the URI anchor string * everything after the "#". * * @param string $anchor The URI anchor string. * * @return void */ public function setFragment($anchor) { $this->fragment = $anchor; } /** * Checks whether the current URI is using HTTPS. * * @return boolean True if using SSL via HTTPS. */ public function isSSL() { return $this->getScheme() == 'https' ? true : false; } /** * Checks if the supplied URL is internal * * @param string $url The URL to check. * * @return boolean True if Internal. */ public static function isInternal($url) { $uri = self::getInstance($url); $base = $uri->toString(array('scheme', 'host', 'port', 'path')); $host = $uri->toString(array('scheme', 'host', 'port')); if (stripos($base, self::base()) !== 0 && !empty($host)) { return false; } return true; } /** * Resolves //, ../ and ./ from a path and returns * the result. Eg: * * /foo/bar/../boo.php => /foo/boo.php * /foo/bar/../../boo.php => /boo.php * /foo/bar/.././/boo.php => /foo/boo.php * * @param string $path The URI path to clean. * * @return string Cleaned and resolved URI path. */ protected function _cleanPath($path) { $path = explode('/', preg_replace('#(/+)#', '/', $path)); for ($i = 0, $n = count($path); $i < $n; $i++) { if ($path[$i] == '.' || $path[$i] == '..') { if (($path[$i] == '.') || ($path[$i] == '..' && $i == 1 && $path[0] == '')) { unset($path[$i]); $path = array_values($path); $i--; $n--; } elseif ($path[$i] == '..' && ($i > 1 || ($i == 1 && $path[0] != ''))) { unset($path[$i]); unset($path[$i - 1]); $path = array_values($path); $i -= 2; $n -= 2; } } } return implode('/', $path); } public static function parse_url($url) { $result = array(); // Build arrays of values we need to decode before parsing $entities = array('%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'); $replacements = array('!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "$", ",", "/", "?", "%", "#", "[", "]"); // Create encoded URL with special URL characters decoded so it can be parsed // All other characters will be encoded $encodedURL = str_replace($entities, $replacements, urlencode($url)); // Parse the encoded URL $encodedParts = parse_url($encodedURL); // Now, decode each value of the resulting array foreach ($encodedParts as $key => $value) { $result[$key] = urldecode($value); } return $result; } }
akeeba/angie
angie/installation/framework/uri/uri.php
PHP
gpl-3.0
16,396
/* Memory-Mapped File Buffer. * * Copyright (C) 2010-2013 Reece H. Dunn * * This file is part of cainteoir-engine. * * cainteoir-engine 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. * * cainteoir-engine 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 cainteoir-engine. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" #include "compatibility.hpp" #include <cainteoir/buffer.hpp> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <fcntl.h> #include <unistd.h> #include <stdexcept> #include <string.h> #include <errno.h> class mmap_buffer : public cainteoir::buffer { int fd; public: mmap_buffer(const char *path); ~mmap_buffer(); }; mmap_buffer::mmap_buffer(const char *path) : buffer(nullptr, nullptr) , fd(-1) { fd = open(path, O_RDONLY); if (fd == -1) throw std::runtime_error(strerror(errno)); struct stat sb; if (fstat(fd, &sb) == -1) throw std::runtime_error(strerror(errno)); first = (const char *)mmap(nullptr, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (first == MAP_FAILED) throw std::runtime_error(strerror(errno)); last = first + sb.st_size; } mmap_buffer::~mmap_buffer() { if (fd != -1) close(fd); if (first) munmap((void *)first, size()); } std::shared_ptr<cainteoir::buffer> cainteoir::make_file_buffer(const char *path) { return std::make_shared<mmap_buffer>(path); }
rhdunn/cainteoir-engine
src/libcainteoir/buffers/mmap_buffer.cpp
C++
gpl-3.0
1,825
// Decompiled with JetBrains decompiler // Type: System.Xml.DocumentXmlWriterType // Assembly: System.Xml, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 // MVID: 50ABAB51-7DC3-4F0A-A797-0D0C2D124D60 // Assembly location: C:\Windows\Microsoft.NET\Framework\v4.0.30319\System.Xml.dll namespace System.Xml { internal enum DocumentXmlWriterType { InsertSiblingAfter, InsertSiblingBefore, PrependChild, AppendChild, AppendAttribute, ReplaceToFollowingSibling, } }
mater06/LEGOChimaOnlineReloaded
LoCO Client Files/Decompressed Client/Extracted DLL/System.Xml/System/Xml/DocumentXmlWriterType.cs
C#
gpl-3.0
513
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2008, Robert D. Eden All Rights Reserved. // Copyright (c) 2009, Jeff Randall All Rights Reserved. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. /////////////////////////////////////////////////////////////////////////////// package main.java.gnu.trove.impl.unmodifiable; ////////////////////////////////////////////////// // THIS IS A GENERATED CLASS. DO NOT HAND EDIT! // ////////////////////////////////////////////////// //////////////////////////////////////////////////////////// // THIS IS AN IMPLEMENTATION CLASS. DO NOT USE DIRECTLY! // // Access to these methods should be through TCollections // //////////////////////////////////////////////////////////// import java.util.Collection; import java.util.Iterator; import java.util.Set; import java.util.Map; import java.util.RandomAccess; import java.util.Random; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; import main.java.gnu.trove.*; import main.java.gnu.trove.function.*; import main.java.gnu.trove.iterator.*; import main.java.gnu.trove.list.*; import main.java.gnu.trove.map.*; import main.java.gnu.trove.procedure.*; import main.java.gnu.trove.set.*; public class TUnmodifiableShortFloatMap implements TShortFloatMap, Serializable { private static final long serialVersionUID = -1034234728574286014L; private final TShortFloatMap m; public TUnmodifiableShortFloatMap( TShortFloatMap m ) { if ( m == null ) throw new NullPointerException(); this.m = m; } public int size() { return m.size(); } public boolean isEmpty() { return m.isEmpty(); } public boolean containsKey( short key ) { return m.containsKey( key ); } public boolean containsValue( float val ) { return m.containsValue( val ); } public float get( short key) { return m.get( key ); } public float put( short key, float value ) { throw new UnsupportedOperationException(); } public float remove( short key ) { throw new UnsupportedOperationException(); } public void putAll( TShortFloatMap m ) { throw new UnsupportedOperationException(); } public void putAll( Map<? extends Short, ? extends Float> map ) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } private transient TShortSet keySet = null; private transient TFloatCollection values = null; public TShortSet keySet() { if ( keySet == null ) keySet = TCollections.unmodifiableSet( m.keySet() ); return keySet; } public short[] keys() { return m.keys(); } public short[] keys( short[] array ) { return m.keys( array ); } public TFloatCollection valueCollection() { if ( values == null ) values = TCollections.unmodifiableCollection( m.valueCollection() ); return values; } public float[] values() { return m.values(); } public float[] values( float[] array ) { return m.values( array ); } public boolean equals(Object o) { return o == this || m.equals(o); } public int hashCode() { return m.hashCode(); } public String toString() { return m.toString(); } public short getNoEntryKey() { return m.getNoEntryKey(); } public float getNoEntryValue() { return m.getNoEntryValue(); } public boolean forEachKey( TShortProcedure procedure ) { return m.forEachKey( procedure ); } public boolean forEachValue( TFloatProcedure procedure ) { return m.forEachValue( procedure ); } public boolean forEachEntry( TShortFloatProcedure procedure ) { return m.forEachEntry( procedure ); } public TShortFloatIterator iterator() { return new TShortFloatIterator() { TShortFloatIterator iter = m.iterator(); public short key() { return iter.key(); } public float value() { return iter.value(); } public void advance() { iter.advance(); } public boolean hasNext() { return iter.hasNext(); } public float setValue( float val ) { throw new UnsupportedOperationException(); } public void remove() { throw new UnsupportedOperationException(); } }; } public float putIfAbsent( short key, float value ) { throw new UnsupportedOperationException(); } public void transformValues( TFloatFunction function ) { throw new UnsupportedOperationException(); } public boolean retainEntries( TShortFloatProcedure procedure ) { throw new UnsupportedOperationException(); } public boolean increment( short key ) { throw new UnsupportedOperationException(); } public boolean adjustValue( short key, float amount ) { throw new UnsupportedOperationException(); } public float adjustOrPutValue( short key, float adjust_amount, float put_amount ) { throw new UnsupportedOperationException(); } }
achraftriki/test2
src/main/java/gnu/trove/impl/unmodifiable/TUnmodifiableShortFloatMap.java
Java
gpl-3.0
5,427
<?php use System\config; use System\database\query; use System\input; use System\route; use System\uri; use System\view; Route::collection(['before' => 'auth,csrf,install_exists'], function () { /** * List all posts and paginate through them */ Route::get([ 'admin/posts', 'admin/posts/(:num)' ], function ($page = 1) { $perpage = Config::get('admin.posts_per_page'); $total = Post::count(); $url = Uri::to('admin/posts'); $posts = Post::sort('created', 'desc') ->take($perpage) ->skip(($page - 1) * $perpage) ->get(); $pagination = new Paginator($posts, $total, $page, $perpage, $url); $vars['posts'] = $pagination; $vars['categories'] = Category::sort('title')->get(); $vars['status'] = 'all'; return View::create('posts/index', $vars) ->partial('header', 'partials/header') ->partial('footer', 'partials/footer'); }); /** * List posts by category and paginate through them */ Route::get([ 'admin/posts/category/(:any)', 'admin/posts/category/(:any)/(:num)' ], function ($slug, $page = 1) { if ( ! $category = Category::slug($slug)) { return Response::error(404); } $query = Post::where('category', '=', $category->id); $perpage = Config::get('admin.posts_per_page'); $total = $query->count(); $url = Uri::to('admin/posts/category/' . $category->slug); $posts = $query->sort('created', 'desc') ->take($perpage) ->skip(($page - 1) * $perpage) ->get(); $pagination = new Paginator($posts, $total, $page, $perpage, $url); $vars['posts'] = $pagination; $vars['category'] = $category; $vars['categories'] = Category::sort('title')->get(); $vars['status'] = 'all'; return View::create('posts/index', $vars) ->partial('header', 'partials/header') ->partial('footer', 'partials/footer'); }); /** * List posts by status and paginate through them */ Route::get([ 'admin/posts/status/(:any)', 'admin/posts/status/(:any)/(:num)' ], function ($status, $post = 1) { $query = Post::where('status', '=', $status); $perpage = Config::get('admin.posts_per_page'); $total = $query->count(); $url = Uri::to('admin/posts/status/' . $status); $posts = $query->sort('title') ->take($perpage) ->skip(($post - 1) * $perpage) ->get(); $pagination = new Paginator($posts, $total, $post, $perpage, $url); $vars['posts'] = $pagination; $vars['status'] = $status; $vars['categories'] = Category::sort('title')->get(); return View::create('posts/index', $vars) ->partial('header', 'partials/header') ->partial('footer', 'partials/footer'); }); /** * Edit post */ Route::get('admin/posts/edit/(:num)', function ($id) { $vars['token'] = Csrf::token(); $vars['article'] = Post::find($id); $vars['page'] = Registry::get('posts_page'); // extended fields $vars['fields'] = Extend::fields('post', $id); $vars['categories'] = Category::dropdown(); $vars['statuses'] = [ 'published' => __('global.published'), 'draft' => __('global.draft'), 'archived' => __('global.archived') ]; return View::create('posts/edit', $vars) ->partial('header', 'partials/header') ->partial('footer', 'partials/footer') ->partial('editor', 'partials/editor'); }); Route::post('admin/posts/edit/(:num)', function ($id) { $input = Input::get([ 'title', 'slug', 'description', 'created', 'markdown', 'css', 'js', 'category', 'status', 'comments' ]); // if there is no slug try and create one from the title if (empty($input['slug'])) { $input['slug'] = $input['title']; } // convert to ascii $input['slug'] = slug($input['slug']); // an array of items that we shouldn't encode - they're no XSS threat $dont_encode = ['description', 'markdown', 'css', 'js']; foreach ($input as $key => &$value) { if (in_array($key, $dont_encode)) { continue; } $value = eq($value); } $validator = new Validator($input); $validator->add('duplicate', function ($str) use ($id) { return Post::where('slug', '=', $str) ->where('id', '<>', $id) ->count() == 0; }); $validator->check('title') ->is_max(3, __('posts.title_missing')); $validator->check('slug') ->is_max(3, __('posts.slug_missing')) ->is_duplicate(__('posts.slug_duplicate')) ->not_regex('#^[0-9_-]+$#', __('posts.slug_invalid')); $validator->check('created') ->is_regex( '#^[0-9]{4}\-[0-9]{2}\-[0-9]{2} [0-9]{2}\:[0-9]{2}\:[0-9]{2}$#', __('posts.time_invalid') ); if ($errors = $validator->errors()) { Input::flash(); // Notify::error($errors); return Response::json([ 'id' => $id, 'errors' => array_flatten($errors, []) ]); } if (empty($input['comments'])) { $input['comments'] = 0; } if (empty($input['markdown'])) { $input['status'] = 'draft'; } $input['html'] = parse($input['markdown']); Post::update($id, $input); Extend::process('post', $id); // Notify::success(__('posts.updated')); return Response::json([ 'id' => $id, 'notification' => __('posts.updated') ]); }); /** * Add new post */ Route::get('admin/posts/add', function () { $vars['token'] = Csrf::token(); $vars['page'] = Registry::get('posts_page'); // extended fields $vars['fields'] = Extend::fields('post'); $vars['categories'] = Category::dropdown(); $vars['statuses'] = [ 'published' => __('global.published'), 'draft' => __('global.draft'), 'archived' => __('global.archived') ]; $table = Base::table('meta'); $meta = []; // load database metadata foreach (Query::table($table)->get() as $item) { $meta[$item->key] = $item->value; } $checked_comments = Input::previous('auto_published_comments', $meta['auto_published_comments']) ? ' checked' : ''; $vars['checked_comments'] = $checked_comments; return View::create('posts/add', $vars) ->partial('header', 'partials/header') ->partial('footer', 'partials/footer') ->partial('editor', 'partials/editor'); }); Route::post('admin/posts/add', function () { $input = Input::get([ 'title', 'slug', 'description', 'created', 'markdown', 'css', 'js', 'category', 'status', 'comments' ]); // if there is no slug try and create one from the title if (empty($input['slug'])) { $input['slug'] = $input['title']; } // convert to ascii $input['slug'] = slug($input['slug']); // an array of items that we shouldn't encode - they're no XSS threat $dont_encode = ['description', 'markdown', 'css', 'js']; foreach ($input as $key => &$value) { if (in_array($key, $dont_encode)) { continue; } $value = eq($value); } $validator = new Validator($input); $validator->add('duplicate', function ($str) { return Post::where('slug', '=', $str)->count() == 0; }); $validator->check('title') ->is_max(3, __('posts.title_missing')); $validator->check('slug') ->is_max(3, __('posts.slug_missing')) ->is_duplicate(__('posts.slug_duplicate')) ->not_regex('#^[0-9_-]+$#', __('posts.slug_invalid')); if ($errors = $validator->errors()) { Input::flash(); // Notify::error($errors); // TODO: $id is undefined and will throw return Response::json([ 'id' => $id, 'errors' => array_flatten($errors, []) ]); } if (empty($input['created'])) { $input['created'] = Date::mysql('now'); } $user = Auth::user(); $input['author'] = $user->id; if (empty($input['comments'])) { $input['comments'] = 0; } if (empty($input['markdown'])) { $input['status'] = 'draft'; } $input['html'] = parse($input['markdown']); $post = Post::create($input); $id = $post->id; Extend::process('post', $id); // Notify::success(__('posts.created')); if (Input::get('autosave') === 'true') { return Response::json([ 'id' => $id, 'notification' => __('posts.updated'), ]); } else { return Response::json([ 'id' => $id, 'notification' => __('posts.created'), 'redirect' => Uri::to('admin/posts/edit/' . $id) ]); } }); /** * Preview post */ Route::post('admin/posts/preview', function () { $markdown = Input::get('markdown'); // apply markdown processing $output = Json::encode(['markdown' => parse($markdown)]); return Response::create($output, 200, ['content-type' => 'application/json']); }); /** * Delete post */ Route::get('admin/posts/delete/(:num)', function ($id) { Post::find($id)->delete(); Comment::where('post', '=', $id)->delete(); Query::table(Base::table('post_meta')) ->where('post', '=', $id) ->delete(); Notify::success(__('posts.deleted')); return Response::redirect('admin/posts'); }); });
TheBrenny/anchor-cms
anchor/routes/posts.php
PHP
gpl-3.0
11,031
class PagesController < ApplicationController include PagesModule::PagesUtil layout :select_layout helper_method :render_hiki hide_action :render_hiki skip_before_filter :authenticate, :only => %w[index] before_filter :authenticate_with_api_or_login_required, :only => %w[index] before_filter :setup_current_note_as_wikipedia, :only => %w[root] before_filter :is_wiki_initialized?, :except => %w[create] before_filter :explicit_user_required, :except => %w[index show root] def index @pages = accessible_pages(true).fulltext(params[:keyword]). labeled(params[:label_index_id]). authored(*safe_split(params[:authors])). scoped(page_order_white_list(params[:order])) respond_to do |format| format.html do @pages = @pages.paginate(paginate_option(Page)) option = params[:note_id].blank? ? {:template => "pages/index", :layout => "application"} : {:template => "pages/notes_index", :layout => "notes"} render(option) end format.js do render :json => @pages.all(:include => :note).map{ |p| {:page => page_to_json(p)} } end format.rss do @pages = @pages.paginate(paginate_option(Page).merge(:per_page => 20)) render :layout => false end end end def show @note = current_note @page = accessible_pages.find(params[:id], :include => :note) respond_to(:html) rescue ActiveRecord::RecordNotFound render_not_found end def new format_type = cookies[:editor_mode] == 'hiki' ? 'hiki' : 'html' @page = current_note.pages.build(:format_type => format_type) respond_to(:html) end def create @note = current_note begin ActiveRecord::Base.transaction do @page = @note.pages.add(params[:page], current_user) @page.file_attach_user = current_user @page.published = true if @note.wikipedia? # TODO nested_attributeを使ってもっとスマートにできるのではないか if params[:label] && !params[:label]['display_name'].blank? label = LabelIndex.create(params[:label].merge!({:default_label => false})) @note.label_indices << label @page.label_index_id = label.id end @page.save! end flash[:notice] = _("The page %{page} is successfully created") % {:page=>@page.display_name} respond_to do |format| format.html{ redirect_to note_page_path(@note, @page) } end rescue ActiveRecord::RecordNotSaved, ActiveRecord::RecordInvalid respond_to do |format| format.html{ render :action => "new", :status => :unprocessable_entity } end end end def preview respond_to do |format| format.js do render :text=> render_hiki(params[:page][:content_hiki]) end end end def edit @note = current_note @page = accessible_pages(true).find(params[:id]) respond_to(:html) end def update @note = current_note begin ActiveRecord::Base.transaction do @page = accessible_pages.find(params[:id]) @page.attributes = params[:page].except(:content) @page.save! end respond_to do |format| format.html{ flash[:notice] = _("The page %{page} is successfully updated") % {:page=>@page.display_name} redirect_to note_page_path(@note, @page) } format.js{ head(:ok, :location => note_page_path(@note, @page)) } end rescue ActiveRecord::RecordInvalid respond_to do |format| format.html{ render :action => "edit", :status => :unprocessable_entity } end end end def destroy @page = accessible_pages.find(params[:id]) if !@page.front_page? and @page.logical_destroy flash[:notice] = _("Page was deleted successfully") redirect_to(note_path(current_note)) else flash[:warn] = _("Failed to delete page.") redirect_to(edit_note_page_url(current_note, @page)) end end def recovery @page = accessible_pages(true).find(params[:id]) if @page.recover flash[:notice] = _("Page was recovered successfully") redirect_to(note_pages_path(current_note)) end end def root @note = current_note @page = @note.front_page @page ? render(:action => :show) : render_not_found end private # TODO 回帰テストを書く def accessible_pages(include_deleted = false, user = current_user, note = nil) if params[:note_id] && note ||= current_note if include_deleted && user.accessible?(note) note.pages elsif user.page_editable?(note) note.pages.active else note.pages.active.published end else if skip_gid = params[:skip_gid] && skip_group = SkipGroup.find_by_name(params[:skip_gid]) user.accessible_pages(skip_group.group) else user.accessible_pages end end end def select_layout case params[:action] when *%w[new create] then "notes" else "pages" end end def page_to_json(page) returning(page.attributes.slice("display_name")) do |json| json[:path] = note_page_path(page.note, page) json[:updated_at] = page.updated_at.strftime("%Y/%m/%d %H:%M") json[:created_at] = page.created_at.strftime("%Y/%m/%d %H:%M") json[:note] = page.note.attributes.slice("display_name") end end def setup_current_note_as_wikipedia if note = Note.wikipedia self.current_note = note else raise ActiveRecord::RecordNotFound end end end
openskip/skip-wiki
app/controllers/pages_controller.rb
Ruby
gpl-3.0
5,674
// ------------------------------------------- // OGRE-IMGUI bindings // See file 'README-OgreImGui.txt' for details // ------------------------------------------- /* This source file is part of Rigs of Rods Copyright 2016-2017 Petr Ohlidal & contributors For more information, see http://www.rigsofrods.org/ Rigs of Rods is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. Rigs of Rods 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 Rigs of Rods. If not, see <http://www.gnu.org/licenses/>. */ #include "OgreImGui.h" #include <imgui.h> #include <OgreMaterialManager.h> #include <OgreMesh.h> #include <OgreMeshManager.h> #include <OgreSubMesh.h> #include <OgreTexture.h> #include <OgreTextureManager.h> #include <OgreString.h> #include <OgreStringConverter.h> #include <OgreViewport.h> #include <OgreHighLevelGpuProgramManager.h> #include <OgreHighLevelGpuProgram.h> #include <OgreUnifiedHighLevelGpuProgram.h> #include <OgreRoot.h> #include <OgreTechnique.h> #include <OgreViewport.h> #include <OgreHardwareBufferManager.h> #include <OgreHardwarePixelBuffer.h> #include <OgreRenderTarget.h> void OgreImGui::Init(Ogre::SceneManager* scenemgr) { mSceneMgr = scenemgr; ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = OIS::KC_TAB; // Keyboard mapping. ImGui will use those indices to peek into the io.KeyDown[] array that we will update during the application lifetime. io.KeyMap[ImGuiKey_LeftArrow] = OIS::KC_LEFT; io.KeyMap[ImGuiKey_RightArrow] = OIS::KC_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = OIS::KC_UP; io.KeyMap[ImGuiKey_DownArrow] = OIS::KC_DOWN; io.KeyMap[ImGuiKey_PageUp] = OIS::KC_PGUP; io.KeyMap[ImGuiKey_PageDown] = OIS::KC_PGDOWN; io.KeyMap[ImGuiKey_Home] = OIS::KC_HOME; io.KeyMap[ImGuiKey_End] = OIS::KC_END; io.KeyMap[ImGuiKey_Delete] = OIS::KC_DELETE; io.KeyMap[ImGuiKey_Backspace] = OIS::KC_BACK; io.KeyMap[ImGuiKey_Enter] = OIS::KC_RETURN; io.KeyMap[ImGuiKey_Escape] = OIS::KC_ESCAPE; io.KeyMap[ImGuiKey_A] = OIS::KC_A; io.KeyMap[ImGuiKey_C] = OIS::KC_C; io.KeyMap[ImGuiKey_V] = OIS::KC_V; io.KeyMap[ImGuiKey_X] = OIS::KC_X; io.KeyMap[ImGuiKey_Y] = OIS::KC_Y; io.KeyMap[ImGuiKey_Z] = OIS::KC_Z; createFontTexture(); createMaterial(); } //Inherhited from OIS::MouseListener void OgreImGui::InjectMouseMoved( const OIS::MouseEvent &arg ) { ImGuiIO& io = ImGui::GetIO(); io.MousePos.x = arg.state.X.abs; io.MousePos.y = arg.state.Y.abs; } void OgreImGui::InjectMousePressed( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) { ImGuiIO& io = ImGui::GetIO(); if (id<5) { io.MouseDown[id] = true; } } void OgreImGui::InjectMouseReleased( const OIS::MouseEvent &arg, OIS::MouseButtonID id ) { ImGuiIO& io = ImGui::GetIO(); if (id<5) { io.MouseDown[id] = false; } } // Inherhited from OIS::KeyListener void OgreImGui::InjectKeyPressed( const OIS::KeyEvent &arg ) { ImGuiIO& io = ImGui::GetIO(); io.KeysDown[arg.key] = true; if (arg.text>0) { io.AddInputCharacter((unsigned short)arg.text); } } void OgreImGui::InjectKeyReleased( const OIS::KeyEvent &arg ) { ImGuiIO& io = ImGui::GetIO(); io.KeysDown[arg.key] = false; } void OgreImGui::Render() { // Construct projection matrix, taking texel offset corrections in account (important for DirectX9) // See also: // - OGRE-API specific hint: http://www.ogre3d.org/forums/viewtopic.php?f=5&p=536881#p536881 // - IMGUI Dx9 demo solution: https://github.com/ocornut/imgui/blob/master/examples/directx9_example/imgui_impl_dx9.cpp#L127-L138 ImGuiIO& io = ImGui::GetIO(); Ogre::RenderSystem* renderSys = Ogre::Root::getSingletonPtr()->getRenderSystem(); const float texelOffsetX = renderSys->getHorizontalTexelOffset(); const float texelOffsetY = renderSys->getVerticalTexelOffset(); const float L = texelOffsetX; const float R = io.DisplaySize.x + texelOffsetX; const float T = texelOffsetY; const float B = io.DisplaySize.y + texelOffsetY; Ogre::Matrix4 projMatrix( 2.0f/(R-L), 0.0f, 0.0f, (L+R)/(L-R), 0.0f, -2.0f/(B-T), 0.0f, (T+B)/(B-T), 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); mPass->getVertexProgramParameters()->setNamedConstant("ProjectionMatrix", projMatrix); // Instruct ImGui to Render() and process the resulting CmdList-s /// Adopted from https://bitbucket.org/ChaosCreator/imgui-ogre2.1-binding /// ... Commentary on OGRE forums: http://www.ogre3d.org/forums/viewtopic.php?f=5&t=89081#p531059 ImGui::Render(); ImDrawData* draw_data = ImGui::GetDrawData(); int vpWidth = 2000; // Dummy viewport size int vpHeight = 2000; Ogre::Viewport* vp = renderSys->_getViewport(); if (vp != nullptr) // Viewport is sometimes 'null' on Windows/Dx9 right after game startup or map load - probably related to switching Ogre::Camera-s ~ only_a_ptr, 01/2018 { vpWidth = vp->getActualWidth(); vpHeight = vp->getActualHeight(); } for (int i = 0; i < draw_data->CmdListsCount; ++i) { const ImDrawList* draw_list = draw_data->CmdLists[i]; unsigned int startIdx = 0; for (int j = 0; j < draw_list->CmdBuffer.Size; ++j) { // Create a renderable and fill it's buffers ImGUIRenderable renderable; const ImDrawCmd *drawCmd = &draw_list->CmdBuffer[j]; renderable.updateVertexData(draw_list->VtxBuffer.Data, &draw_list->IdxBuffer.Data[startIdx], draw_list->VtxBuffer.Size, drawCmd->ElemCount); // Set scissoring int scLeft = static_cast<int>(drawCmd->ClipRect.x); // Obtain bounds int scTop = static_cast<int>(drawCmd->ClipRect.y); int scRight = static_cast<int>(drawCmd->ClipRect.z); int scBottom = static_cast<int>(drawCmd->ClipRect.w); scLeft = scLeft < 0 ? 0 : (scLeft > vpWidth ? vpWidth : scLeft); // Clamp bounds to viewport dimensions scRight = scRight < 0 ? 0 : (scRight > vpWidth ? vpWidth : scRight); scTop = scTop < 0 ? 0 : (scTop > vpHeight ? vpHeight : scTop); scBottom = scBottom < 0 ? 0 : (scBottom > vpHeight ? vpHeight : scBottom); renderSys->setScissorTest(true, scLeft, scTop, scRight, scBottom); // Render! mSceneMgr->_injectRenderWithPass(mPass, &renderable, false, false, nullptr); // Update counts startIdx += drawCmd->ElemCount; } } renderSys->setScissorTest(false); } void OgreImGui::createMaterial() { static const char* vertexShaderSrcD3D11 = { "cbuffer vertexBuffer : register(b0) \n" "{\n" "float4x4 ProjectionMatrix; \n" "};\n" "struct VS_INPUT\n" "{\n" "float2 pos : POSITION;\n" "float4 col : COLOR0;\n" "float2 uv : TEXCOORD0;\n" "};\n" "struct PS_INPUT\n" "{\n" "float4 pos : SV_POSITION;\n" "float4 col : COLOR0;\n" "float2 uv : TEXCOORD0;\n" "};\n" "PS_INPUT main(VS_INPUT input)\n" "{\n" "PS_INPUT output;\n" "output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\n" "output.col = input.col;\n" "output.uv = input.uv;\n" "return output;\n" "}" }; static const char* pixelShaderSrcD3D11 = { "struct PS_INPUT\n" "{\n" "float4 pos : SV_POSITION;\n" "float4 col : COLOR0;\n" "float2 uv : TEXCOORD0;\n" "};\n" "sampler sampler0;\n" "Texture2D texture0;\n" "\n" "float4 main(PS_INPUT input) : SV_Target\n" "{\n" "float4 out_col = input.col * texture0.Sample(sampler0, input.uv); \n" "return out_col; \n" "}" }; static const char* vertexShaderSrcD3D9 = { "uniform float4x4 ProjectionMatrix; \n" "struct VS_INPUT\n" "{\n" "float2 pos : POSITION;\n" "float4 col : COLOR0;\n" "float2 uv : TEXCOORD0;\n" "};\n" "struct PS_INPUT\n" "{\n" "float4 pos : POSITION;\n" "float4 col : COLOR0;\n" "float2 uv : TEXCOORD0;\n" "};\n" "PS_INPUT main(VS_INPUT input)\n" "{\n" "PS_INPUT output;\n" "output.pos = mul( ProjectionMatrix, float4(input.pos.xy, 0.f, 1.f));\n" "output.col = input.col;\n" "output.uv = input.uv;\n" "return output;\n" "}" }; static const char* pixelShaderSrcSrcD3D9 = { "struct PS_INPUT\n" "{\n" "float4 pos : SV_POSITION;\n" "float4 col : COLOR0;\n" "float2 uv : TEXCOORD0;\n" "};\n" "sampler2D sampler0;\n" "\n" "float4 main(PS_INPUT input) : SV_Target\n" "{\n" "float4 out_col = input.col.bgra * tex2D(sampler0, input.uv); \n" "return out_col; \n" "}" }; static const char* vertexShaderSrcGLSL = { // See https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#OpenGL_and_GLSL_versions "#version 130\n" "uniform mat4 ProjectionMatrix; \n" "in vec2 vertex;\n" "in vec2 uv0;\n" "in vec4 colour;\n" "out vec2 Texcoord;\n" "out vec4 col;\n" "void main()\n" "{\n" "gl_Position = ProjectionMatrix* vec4(vertex.xy, 0.f, 1.f);\n" "Texcoord = uv0;\n" "col = colour;\n" "}" }; static const char* pixelShaderSrcGLSL = { // See https://www.khronos.org/opengl/wiki/Core_Language_(GLSL)#OpenGL_and_GLSL_versions "#version 130\n" "in vec2 Texcoord;\n" "in vec4 col;\n" "uniform sampler2D sampler0;\n" "out vec4 out_col;\n" "void main()\n" "{\n" "out_col = col * texture(sampler0, Texcoord); \n" "}" }; //create the default shadows material Ogre::HighLevelGpuProgramManager& mgr = Ogre::HighLevelGpuProgramManager::getSingleton(); Ogre::HighLevelGpuProgramPtr vertexShaderUnified = mgr.getByName("imgui/VP"); Ogre::HighLevelGpuProgramPtr pixelShaderUnified = mgr.getByName("imgui/FP"); Ogre::HighLevelGpuProgramPtr vertexShaderD3D11 = mgr.getByName("imgui/VP/D3D11"); Ogre::HighLevelGpuProgramPtr pixelShaderD3D11 = mgr.getByName("imgui/FP/D3D11"); Ogre::HighLevelGpuProgramPtr vertexShaderD3D9 = mgr.getByName("imgui/VP/D3D9"); Ogre::HighLevelGpuProgramPtr pixelShaderD3D9 = mgr.getByName("imgui/FP/D3D9"); Ogre::HighLevelGpuProgramPtr vertexShaderGL = mgr.getByName("imgui/VP/GL130"); Ogre::HighLevelGpuProgramPtr pixelShaderGL = mgr.getByName("imgui/FP/GL130"); if (vertexShaderUnified.isNull()) { vertexShaderUnified = mgr.createProgram("imgui/VP",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,"unified",Ogre::GPT_VERTEX_PROGRAM); } if (pixelShaderUnified.isNull()) { pixelShaderUnified = mgr.createProgram("imgui/FP",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,"unified",Ogre::GPT_FRAGMENT_PROGRAM); } Ogre::UnifiedHighLevelGpuProgram* vertexShaderPtr = static_cast<Ogre::UnifiedHighLevelGpuProgram*>(vertexShaderUnified.get()); Ogre::UnifiedHighLevelGpuProgram* pixelShaderPtr = static_cast<Ogre::UnifiedHighLevelGpuProgram*>(pixelShaderUnified.get()); if (vertexShaderD3D11.isNull()) { vertexShaderD3D11 = mgr.createProgram("imgui/VP/D3D11", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "hlsl", Ogre::GPT_VERTEX_PROGRAM); vertexShaderD3D11->setParameter("target", "vs_4_0"); vertexShaderD3D11->setParameter("entry_point", "main"); vertexShaderD3D11->setSource(vertexShaderSrcD3D11); vertexShaderD3D11->load(); vertexShaderPtr->addDelegateProgram(vertexShaderD3D11->getName()); } if (pixelShaderD3D11.isNull()) { pixelShaderD3D11 = mgr.createProgram("imgui/FP/D3D11", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "hlsl", Ogre::GPT_FRAGMENT_PROGRAM); pixelShaderD3D11->setParameter("target", "ps_4_0"); pixelShaderD3D11->setParameter("entry_point", "main"); pixelShaderD3D11->setSource(pixelShaderSrcD3D11); pixelShaderD3D11->load(); pixelShaderPtr->addDelegateProgram(pixelShaderD3D11->getName()); } if (vertexShaderD3D9.isNull()) { vertexShaderD3D9 = mgr.createProgram("imgui/VP/D3D9", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "hlsl", Ogre::GPT_VERTEX_PROGRAM); vertexShaderD3D9->setParameter("target", "vs_2_0"); vertexShaderD3D9->setParameter("entry_point", "main"); vertexShaderD3D9->setSource(vertexShaderSrcD3D9); vertexShaderD3D9->load(); vertexShaderPtr->addDelegateProgram(vertexShaderD3D9->getName()); } if (pixelShaderD3D9.isNull()) { pixelShaderD3D9 = mgr.createProgram("imgui/FP/D3D9", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "hlsl", Ogre::GPT_FRAGMENT_PROGRAM); pixelShaderD3D9->setParameter("target", "ps_2_0"); pixelShaderD3D9->setParameter("entry_point", "main"); pixelShaderD3D9->setSource(pixelShaderSrcSrcD3D9); pixelShaderD3D9->load(); pixelShaderPtr->addDelegateProgram(pixelShaderD3D9->getName()); } if (vertexShaderGL.isNull()) { vertexShaderGL = mgr.createProgram("imgui/VP/GL130", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "glsl", Ogre::GPT_VERTEX_PROGRAM); vertexShaderGL->setSource(vertexShaderSrcGLSL); vertexShaderGL->load(); vertexShaderPtr->addDelegateProgram(vertexShaderGL->getName()); } if (pixelShaderGL.isNull()) { pixelShaderGL = mgr.createProgram("imgui/FP/GL130", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME, "glsl", Ogre::GPT_FRAGMENT_PROGRAM); pixelShaderGL->setSource(pixelShaderSrcGLSL); pixelShaderGL->load(); pixelShaderGL->setParameter("sampler0","int 0"); pixelShaderPtr->addDelegateProgram(pixelShaderGL->getName()); } Ogre::MaterialPtr imguiMaterial = Ogre::MaterialManager::getSingleton().create("imgui/material", Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME); mPass = imguiMaterial->getTechnique(0)->getPass(0); mPass->setFragmentProgram("imgui/FP"); mPass->setVertexProgram("imgui/VP"); mPass->setCullingMode(Ogre::CULL_NONE); mPass->setDepthFunction(Ogre::CMPF_ALWAYS_PASS); mPass->setLightingEnabled(false); mPass->setSceneBlending(Ogre::SBT_TRANSPARENT_ALPHA); mPass->setSeparateSceneBlendingOperation(Ogre::SBO_ADD,Ogre::SBO_ADD); mPass->setSeparateSceneBlending(Ogre::SBF_SOURCE_ALPHA,Ogre::SBF_ONE_MINUS_SOURCE_ALPHA,Ogre::SBF_ONE_MINUS_SOURCE_ALPHA,Ogre::SBF_ZERO); mPass->createTextureUnitState()->setTextureName("ImguiFontTex"); } void OgreImGui::createFontTexture() { // Build texture atlas ImGuiIO& io = ImGui::GetIO(); unsigned char* pixels; int width, height; io.Fonts->GetTexDataAsRGBA32(&pixels, &width, &height); mFontTex = Ogre::TextureManager::getSingleton().createManual("ImguiFontTex",Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,Ogre::TEX_TYPE_2D,width,height,1,1,Ogre::PF_BYTE_RGBA); // Lock texture for writing const Ogre::PixelBox & lockBox = mFontTex->getBuffer()->lock(Ogre::Box(0, 0, width, height), Ogre::HardwareBuffer::HBL_DISCARD); // Copy texture to ImGui size_t texDepth = Ogre::PixelUtil::getNumElemBytes(lockBox.format); memcpy(lockBox.data,pixels, width*height*texDepth); // Unlock mFontTex->getBuffer()->unlock(); } void OgreImGui::NewFrame(float deltaTime, float displayWidth, float displayHeight, bool ctrl, bool alt, bool shift) { ImGuiIO& io = ImGui::GetIO(); io.DeltaTime = deltaTime; // Read keyboard modifiers inputs io.KeyCtrl = ctrl; io.KeyShift = shift; io.KeyAlt = alt; io.KeySuper = false; // Setup display size (every frame to accommodate for window resizing) io.DisplaySize = ImVec2(displayWidth, displayHeight); // Start the frame ImGui::NewFrame(); } // -------------------------- ImGui Renderable ------------------------------ // OgreImGui::ImGUIRenderable::ImGUIRenderable(): mVertexBufferSize(5000), mIndexBufferSize(10000) { this->initImGUIRenderable(); //By default we want ImGUIRenderables to still work in wireframe mode this->setPolygonModeOverrideable( false ); } void OgreImGui::ImGUIRenderable::initImGUIRenderable(void) { // use identity projection and view matrices mUseIdentityProjection = true; mUseIdentityView = true; mRenderOp.vertexData = OGRE_NEW Ogre::VertexData(); mRenderOp.indexData = OGRE_NEW Ogre::IndexData(); mRenderOp.vertexData->vertexCount = 0; mRenderOp.vertexData->vertexStart = 0; mRenderOp.indexData->indexCount = 0; mRenderOp.indexData->indexStart = 0; mRenderOp.operationType = Ogre::RenderOperation::OT_TRIANGLE_LIST; mRenderOp.useIndexes = true; mRenderOp.useGlobalInstancingVertexBufferIsAvailable = false; Ogre::VertexDeclaration* decl = mRenderOp.vertexData->vertexDeclaration; // vertex declaration size_t offset = 0; decl->addElement(0,offset,Ogre::VET_FLOAT2,Ogre::VES_POSITION); offset += Ogre::VertexElement::getTypeSize( Ogre::VET_FLOAT2 ); decl->addElement(0,offset,Ogre::VET_FLOAT2,Ogre::VES_TEXTURE_COORDINATES,0); offset += Ogre::VertexElement::getTypeSize( Ogre::VET_FLOAT2 ); decl->addElement(0,offset,Ogre::VET_COLOUR,Ogre::VES_DIFFUSE); // set basic white material this->setMaterial( "imgui/material" ); } OgreImGui::ImGUIRenderable::~ImGUIRenderable() { OGRE_DELETE mRenderOp.vertexData; OGRE_DELETE mRenderOp.indexData; mMaterial.setNull(); } void OgreImGui::ImGUIRenderable::setMaterial( const Ogre::String& matName ) { mMaterial = Ogre::MaterialManager::getSingleton().getByName( matName ); if ( !mMaterial.isNull() ) { return; } // Won't load twice anyway mMaterial->load(); } void OgreImGui::ImGUIRenderable::setMaterial(const Ogre::MaterialPtr & material) { mMaterial = material; } const Ogre::MaterialPtr& OgreImGui::ImGUIRenderable::getMaterial(void) const { return mMaterial; } /// @author https://bitbucket.org/ChaosCreator/imgui-ogre2.1-binding/src/8f1a01db510f543a987c3c16859d0a33400d9097/ImguiRenderable.cpp?at=master&fileviewer=file-view-default /// Commentary on OGRE forums: http://www.ogre3d.org/forums/viewtopic.php?f=5&t=89081#p531059 void OgreImGui::ImGUIRenderable::updateVertexData(const ImDrawVert* vtxBuf, const ImDrawIdx* idxBuf, unsigned int vtxCount, unsigned int idxCount) { Ogre::VertexBufferBinding* bind = mRenderOp.vertexData->vertexBufferBinding; if (bind->getBindings().empty() || mVertexBufferSize != vtxCount) { mVertexBufferSize = vtxCount; bind->setBinding(0, Ogre::HardwareBufferManager::getSingleton().createVertexBuffer(sizeof(ImDrawVert), mVertexBufferSize, Ogre::HardwareBuffer::HBU_WRITE_ONLY)); } if (mRenderOp.indexData->indexBuffer.isNull() || mIndexBufferSize != idxCount) { mIndexBufferSize = idxCount; mRenderOp.indexData->indexBuffer = Ogre::HardwareBufferManager::getSingleton().createIndexBuffer(Ogre::HardwareIndexBuffer::IT_16BIT, mIndexBufferSize, Ogre::HardwareBuffer::HBU_WRITE_ONLY); } // Copy all vertices ImDrawVert* vtxDst = (ImDrawVert*)(bind->getBuffer(0)->lock(Ogre::HardwareBuffer::HBL_DISCARD)); ImDrawIdx* idxDst = (ImDrawIdx*)(mRenderOp.indexData->indexBuffer->lock(Ogre::HardwareBuffer::HBL_DISCARD)); memcpy(vtxDst, vtxBuf, mVertexBufferSize * sizeof(ImDrawVert)); memcpy(idxDst, idxBuf, mIndexBufferSize * sizeof(ImDrawIdx)); mRenderOp.vertexData->vertexStart = 0; mRenderOp.vertexData->vertexCount = vtxCount; mRenderOp.indexData->indexStart = 0; mRenderOp.indexData->indexCount = idxCount; bind->getBuffer(0)->unlock(); mRenderOp.indexData->indexBuffer->unlock(); } void OgreImGui::ImGUIRenderable::getWorldTransforms( Ogre::Matrix4* xform ) const { *xform = Ogre::Matrix4::IDENTITY; } void OgreImGui::ImGUIRenderable::getRenderOperation(Ogre::RenderOperation& op) { op = mRenderOp; } const Ogre::LightList& OgreImGui::ImGUIRenderable::getLights(void) const { static const Ogre::LightList light_list; return light_list; } bool OgreImGui::frameRenderingQueued(const Ogre::FrameEvent& evt) { this->Render(); return true; }
Speciesx/rigs-of-rods
source/main/gui/imgui/OgreImGui.cpp
C++
gpl-3.0
21,070
#!/usr/bin/env python # encoding:utf-8 # __author__: huxianglin # date: 2016-09-17 # blog: http://huxianglin.cnblogs.com/ http://xianglinhu.blog.51cto.com/ import os from module import actions from module import db_handler from conf import settings ATM_AUTH_DIR = settings.DATABASE["path"] ATM_CARD_LIST=os.listdir(ATM_AUTH_DIR) atm_auth_flag = False atm_auth_admin = False atm_auth_card_id = "" def atm_auth_log(atm_log): def atm_auth(func): def wrapper(*args, **kwargs): global ATM_CARD_LIST,atm_auth_flag, atm_auth_admin, atm_auth_card_id if atm_auth_flag: return func(*args, **kwargs) else: print("欢迎登陆华夏银行".center(50, "*")) auth_count = 0 auth_id = "" while auth_count < 3: auth_id = input("请输入卡号:").strip() auth_passwd = input("请输入密码:").strip() atm_log.info("Card:%s try %s login!"%(auth_id,auth_count+1)) if auth_id in ATM_CARD_LIST and actions.encry_passwd(auth_passwd) == db_handler.read_data(auth_id)["password"]: auth_user_data=db_handler.read_data(auth_id) atm_log.info("Card:%s login auth successful!"%auth_id) if auth_user_data["freeze"]: print("抱歉,您的信用卡:%s已被冻结,请联系管理人员解除冻结..." % auth_id) atm_log.warning("Card:%s is freezed!login fail"%auth_id) break elif auth_user_data["privilege"] == "admin": atm_auth_flag = True atm_auth_admin = True atm_auth_card_id = auth_user_data["card_id"] atm_log.info("Card:%s is administrator!"%auth_id) return func(*args, **kwargs) break else: atm_auth_flag = True atm_auth_card_id = auth_user_data["card_id"] atm_log.info("Card:%s is user!"%auth_id) return func(*args, **kwargs) break else: print("抱歉,您输入的用户名或密码错误,请重新输入...") atm_log.warning("Card:%s try %s login failed!"%(auth_id,auth_count+1)) auth_count += 1 else: print("抱歉,您已连续三次输入错误,您的账户将会被冻结...") if auth_id in ATM_CARD_LIST: auth_user_data=db_handler.read_data(auth_id) auth_user_data["freeze"] = True db_handler.write_data(auth_id,auth_user_data) atm_log.warning("Card:%s will be freeze!"%auth_id) return wrapper return atm_auth
huxianglin/pythonstudy
week05-胡湘林/ATM/ATM/module/auth.py
Python
gpl-3.0
3,084
<?php /** * Contao Open Source CMS * * Copyright (c) 2005-2013 Leo Feyer * * @package Core * @link https://contao.org * @license http://www.gnu.org/licenses/lgpl-3.0.html LGPL */ /** * Load tl_user language file */ System::loadLanguageFile('tl_user'); /** * Table tl_user_group */ $GLOBALS['TL_DCA']['tl_user_group'] = array ( // Config 'config' => array ( 'dataContainer' => 'Table', 'enableVersioning' => true, 'sql' => array ( 'keys' => array ( 'id' => 'primary' ) ) ), // List 'list' => array ( 'sorting' => array ( 'mode' => 1, 'fields' => array('name'), 'flag' => 1, 'panelLayout' => 'filter,search,limit', ), 'label' => array ( 'fields' => array('name'), 'format' => '%s', 'label_callback' => array('tl_user_group', 'addIcon') ), 'global_operations' => array ( 'all' => array ( 'label' => &$GLOBALS['TL_LANG']['MSC']['all'], 'href' => 'act=select', 'class' => 'header_edit_all', 'attributes' => 'onclick="Backend.getScrollOffset()" accesskey="e"' ) ), 'operations' => array ( 'edit' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['edit'], 'href' => 'act=edit', 'icon' => 'edit.gif' ), 'copy' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['copy'], 'href' => 'act=copy', 'icon' => 'copy.gif' ), 'delete' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['delete'], 'href' => 'act=delete', 'icon' => 'delete.gif', 'attributes' => 'onclick="if(!confirm(\'' . $GLOBALS['TL_LANG']['MSC']['deleteConfirm'] . '\'))return false;Backend.getScrollOffset()"' ), 'toggle' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['toggle'], 'icon' => 'visible.gif', 'attributes' => 'onclick="Backend.getScrollOffset();return AjaxRequest.toggleVisibility(this,%s)"', 'button_callback' => array('tl_user_group', 'toggleIcon') ), 'show' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['show'], 'href' => 'act=show', 'icon' => 'show.gif' ) ) ), // Palettes 'palettes' => array ( 'default' => '{title_legend},name;{modules_legend},modules,themes;{pagemounts_legend},pagemounts,alpty;{filemounts_legend},filemounts,fop;{forms_legend},forms,formp;{alexf_legend:hide},alexf;{account_legend},disable,start,stop', ), // Fields 'fields' => array ( 'id' => array ( 'sql' => "int(10) unsigned NOT NULL auto_increment" ), 'tstamp' => array ( 'sql' => "int(10) unsigned NOT NULL default '0'" ), 'name' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['name'], 'exclude' => true, 'search' => true, 'inputType' => 'text', 'eval' => array('mandatory'=>true, 'unique'=>true, 'maxlength'=>255), 'sql' => "varchar(255) NOT NULL default ''" ), 'modules' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['modules'], 'exclude' => true, 'inputType' => 'checkbox', 'options_callback' => array('tl_user_group', 'getModules'), 'reference' => &$GLOBALS['TL_LANG']['MOD'], 'eval' => array('multiple'=>true, 'helpwizard'=>true), 'sql' => "blob NULL" ), 'themes' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['themes'], 'exclude' => true, 'inputType' => 'checkbox', 'options' => array('css', 'modules', 'layout'), 'reference' => &$GLOBALS['TL_LANG']['MOD'], 'eval' => array('multiple'=>true), 'sql' => "blob NULL" ), 'pagemounts' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['pagemounts'], 'exclude' => true, 'inputType' => 'pageTree', 'eval' => array('multiple'=>true, 'fieldType'=>'checkbox'), 'sql' => "blob NULL" ), 'alpty' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['alpty'], 'default' => array('regular', 'redirect', 'forward'), 'exclude' => true, 'inputType' => 'checkbox', 'options' => array_keys($GLOBALS['TL_PTY']), 'reference' => &$GLOBALS['TL_LANG']['PTY'], 'eval' => array('multiple'=>true, 'helpwizard'=>true), 'sql' => "blob NULL" ), 'filemounts' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['filemounts'], 'exclude' => true, 'inputType' => 'fileTree', 'eval' => array('multiple'=>true, 'fieldType'=>'checkbox'), 'sql' => "blob NULL" ), 'fop' => array ( 'label' => &$GLOBALS['TL_LANG']['FOP']['fop'], 'exclude' => true, 'default' => array('f1', 'f2', 'f3'), 'inputType' => 'checkbox', 'options' => array('f1', 'f2', 'f3', 'f4', 'f5', 'f6'), 'reference' => &$GLOBALS['TL_LANG']['FOP'], 'eval' => array('multiple'=>true), 'sql' => "blob NULL" ), 'forms' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['forms'], 'exclude' => true, 'inputType' => 'checkbox', 'foreignKey' => 'tl_form.title', 'eval' => array('multiple'=>true), 'sql' => "blob NULL" ), 'formp' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user']['formp'], 'exclude' => true, 'inputType' => 'checkbox', 'options' => array('create', 'delete'), 'reference' => &$GLOBALS['TL_LANG']['MSC'], 'eval' => array('multiple'=>true), 'sql' => "blob NULL" ), 'alexf' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['alexf'], 'exclude' => true, 'inputType' => 'checkbox', 'options_callback' => array('tl_user_group', 'getExcludedFields'), 'eval' => array('multiple'=>true, 'size'=>36), 'sql' => "blob NULL" ), 'disable' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['disable'], 'exclude' => true, 'filter' => true, 'inputType' => 'checkbox', 'sql' => "char(1) NOT NULL default ''" ), 'start' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['start'], 'exclude' => true, 'inputType' => 'text', 'eval' => array('rgxp'=>'datim', 'datepicker'=>true, 'tl_class'=>'w50 wizard'), 'sql' => "varchar(10) NOT NULL default ''" ), 'stop' => array ( 'label' => &$GLOBALS['TL_LANG']['tl_user_group']['stop'], 'exclude' => true, 'inputType' => 'text', 'eval' => array('rgxp'=>'datim', 'datepicker'=>true, 'tl_class'=>'w50 wizard'), 'sql' => "varchar(10) NOT NULL default ''" ) ) ); /** * Class tl_user_group * * Provide miscellaneous methods that are used by the data configuration array. * @copyright Leo Feyer 2005-2013 * @author Leo Feyer <https://contao.org> * @package Core */ class tl_user_group extends Backend { /** * Import the back end user object */ public function __construct() { parent::__construct(); $this->import('BackendUser', 'User'); } /** * Add an image to each record * @param array * @param string * @return string */ public function addIcon($row, $label) { $image = 'group'; if ($row['disable'] || strlen($row['start']) && $row['start'] > time() || strlen($row['stop']) && $row['stop'] < time()) { $image .= '_'; } return sprintf('<div class="list_icon" style="background-image:url(\'%ssystem/themes/%s/images/%s.gif\')">%s</div>', TL_ASSETS_URL, Backend::getTheme(), $image, $label); } /** * Return all modules except profile modules * @return array */ public function getModules() { $arrModules = array(); foreach ($GLOBALS['BE_MOD'] as $k=>$v) { if (!empty($v)) { unset($v['undo']); $arrModules[$k] = array_keys($v); } } return $arrModules; } /** * Return all excluded fields as HTML drop down menu * @return array */ public function getExcludedFields() { $included = array(); foreach ($this->Config->getActiveModules() as $strModule) { $strDir = 'system/modules/' . $strModule . '/dca'; if (!is_dir(TL_ROOT . '/' . $strDir)) { continue; } foreach (scan(TL_ROOT . '/' . $strDir) as $strFile) { // Ignore non PHP files and files which have been included before if (substr($strFile, -4) != '.php' || in_array($strFile, $included)) { continue; } $included[] = $strFile; $strTable = substr($strFile, 0, -4); System::loadLanguageFile($strTable); $this->loadDataContainer($strTable); } } $arrReturn = array(); // Get all excluded fields foreach ($GLOBALS['TL_DCA'] as $k=>$v) { if (is_array($v['fields'])) { foreach ($v['fields'] as $kk=>$vv) { if ($vv['exclude'] || $vv['orig_exclude']) { $arrReturn[$k][specialchars($k.'::'.$kk)] = $vv['label'][0] ?: $kk; } } } } ksort($arrReturn); return $arrReturn; } /** * Return the "toggle visibility" button * @param array * @param string * @param string * @param string * @param string * @param string * @return string */ public function toggleIcon($row, $href, $label, $title, $icon, $attributes) { if (strlen(Input::get('tid'))) { $this->toggleVisibility(Input::get('tid'), (Input::get('state') == 1)); $this->redirect($this->getReferer()); } // Check permissions AFTER checking the tid, so hacking attempts are logged if (!$this->User->isAdmin && !$this->User->hasAccess('tl_user_group::disable', 'alexf')) { return ''; } $href .= '&amp;tid='.$row['id'].'&amp;state='.$row['disable']; if ($row['disable']) { $icon = 'invisible.gif'; } return '<a href="'.$this->addToUrl($href).'" title="'.specialchars($title).'"'.$attributes.'>'.Image::getHtml($icon, $label).'</a> '; } /** * Disable/enable a user group * @param integer * @param boolean */ public function toggleVisibility($intId, $blnVisible) { // Check permissions if (!$this->User->isAdmin && !$this->User->hasAccess('tl_user_group::disable', 'alexf')) { $this->log('Not enough permissions to activate/deactivate user group ID "'.$intId.'"', 'tl_user_group toggleVisibility', TL_ERROR); $this->redirect('contao/main.php?act=error'); } $objVersions = new Versions('tl_user_group', $intId); $objVersions->initialize(); // Trigger the save_callback if (is_array($GLOBALS['TL_DCA']['tl_user_group']['fields']['disable']['save_callback'])) { foreach ($GLOBALS['TL_DCA']['tl_user_group']['fields']['disable']['save_callback'] as $callback) { $this->import($callback[0]); $blnVisible = $this->$callback[0]->$callback[1]($blnVisible, $this); } } // Update the database $this->Database->prepare("UPDATE tl_user_group SET tstamp=". time() .", disable='" . ($blnVisible ? '' : 1) . "' WHERE id=?") ->execute($intId); $objVersions->create(); $this->log('A new version of record "tl_user_group.id='.$intId.'" has been created'.$this->getParentEntries('tl_user_group', $intId), 'tl_user_group toggleVisibility()', TL_GENERAL); } }
Coheed/Shiny-Portfolio
system/modules/core/dca/tl_user_group.php
PHP
gpl-3.0
12,482
<?php /****************************************************** * @package Pav Product Tabs module for Opencart 1.5.x * @version 1.0 * @author http://www.pavothemes.com * @copyright Copyright (C) Feb 2012 PavoThemes.com <@emai:pavothemes@gmail.com>.All rights reserved. * @license GNU General Public License version 2 *******************************************************/ class ControllerModulePavproducttabs extends Controller { private $error = array(); public function index() { $this->language->load('module/pavproducttabs'); $this->document->setTitle($this->language->get('heading_title')); $this->load->model('setting/setting'); if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) { $this->model_setting_setting->editSetting('pavproducttabs', $this->request->post); $this->session->data['success'] = $this->language->get('text_success'); $this->redirect($this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL')); } $this->data['heading_title'] = $this->language->get('heading_title'); $this->data['text_enabled'] = $this->language->get('text_enabled'); $this->data['text_disabled'] = $this->language->get('text_disabled'); $this->data['text_content_top'] = $this->language->get('text_content_top'); $this->data['text_content_bottom'] = $this->language->get('text_content_bottom'); $this->data['text_column_left'] = $this->language->get('text_column_left'); $this->data['text_column_right'] = $this->language->get('text_column_right'); $this->data['entry_description'] = $this->language->get('entry_description'); $this->data['entry_tabs'] = $this->language->get('entry_tabs'); $this->data['entry_banner'] = $this->language->get('entry_banner'); $this->data['entry_dimension'] = $this->language->get('entry_dimension'); $this->data['entry_carousel'] = $this->language->get('entry_carousel'); $this->data['entry_layout'] = $this->language->get('entry_layout'); $this->data['entry_position'] = $this->language->get('entry_position'); $this->data['entry_status'] = $this->language->get('entry_status'); $this->data['entry_sort_order'] = $this->language->get('entry_sort_order'); $this->data['button_save'] = $this->language->get('button_save'); $this->data['button_cancel'] = $this->language->get('button_cancel'); $this->data['button_add_module'] = $this->language->get('button_add_module'); $this->data['button_remove'] = $this->language->get('button_remove'); $this->load->model('localisation/language'); $this->data['tab_module'] = $this->language->get('tab_module'); $this->data['languages'] = $this->model_localisation_language->getLanguages(); $this->data['token'] = $this->session->data['token']; $this->data['positions'] = array( 'mainmenu', 'slideshow', 'showcase', 'promotion', 'content_top', 'column_left', 'column_right', 'content_bottom', 'mass_bottom', 'footer_top', 'footer_center', 'footer_bottom' ); if (isset($this->error['warning'])) { $this->data['error_warning'] = $this->error['warning']; } else { $this->data['error_warning'] = ''; } if (isset($this->error['dimension'])) { $this->data['error_dimension'] = $this->error['dimension']; } else { $this->data['error_dimension'] = array(); } $this->data['breadcrumbs'] = array(); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_home'), 'href' => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => false ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('text_module'), 'href' => $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => ' :: ' ); $this->data['breadcrumbs'][] = array( 'text' => $this->language->get('heading_title'), 'href' => $this->url->link('module/pavproducttabs', 'token=' . $this->session->data['token'], 'SSL'), 'separator' => ' :: ' ); $this->data['action'] = $this->url->link('module/pavproducttabs', 'token=' . $this->session->data['token'], 'SSL'); $this->data['cancel'] = $this->url->link('extension/module', 'token=' . $this->session->data['token'], 'SSL'); $this->data['modules'] = array(); if (isset($this->request->post['pavproducttabs_module'])) { $this->data['modules'] = $this->request->post['pavproducttabs_module']; } elseif ($this->config->get('pavproducttabs_module')) { $this->data['modules'] = $this->config->get('pavproducttabs_module'); } $this->load->model('design/layout'); $this->data['layouts'] = array(); $this->data['layouts'][] = array('layout_id'=>99999, 'name' => $this->language->get('all_page') ); $this->data['layouts'] = array_merge($this->data['layouts'],$this->model_design_layout->getLayouts()); $this->load->model('design/banner'); $this->data['banners'] = $this->model_design_banner->getBanners(); $tabs = array( 'latest' => $this->language->get('text_latest'), 'featured' => $this->language->get('text_featured'), 'bestseller' => $this->language->get('text_bestseller'), 'special' => $this->language->get('text_special'), 'mostviewed' => $this->language->get('text_mostviewed') ); $this->data['tabs'] = $tabs; $this->template = 'module/pavproducttabs.tpl'; $this->children = array( 'common/header', 'common/footer' ); $this->response->setOutput($this->render()); } protected function validate() { if (!$this->user->hasPermission('modify', 'module/pavproducttabs')) { $this->error['warning'] = $this->language->get('error_permission'); } if (isset($this->request->post['pavproducttabs_module'])) { foreach ($this->request->post['pavproducttabs_module'] as $key => $value) { if (!$value['width'] || !$value['height']) { $this->error['dimension'][$key] = $this->language->get('error_dimension'); } if (!$value['limit'] || !$value['cols'] || !$value['itemsperpage'] ) { $this->error['dimension'][$key] = $this->language->get('error_carousel'); } } } if (!$this->error) { return true; } else { return false; } } } ?>
hellocc2/yii
admin/controller/module/pavproducttabs.php
PHP
gpl-3.0
6,468
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) 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/ **********************************************************************/ /* * KeelToPropertyList.java */ package keel.Algorithms.Preprocess.Converter; import java.io.FileWriter; import java.io.File; import org.jdom.*; import org.jdom.output.XMLOutputter; import org.jdom.output.Format; /** * <p> * <b> KeelToPropertyList </b> * </p> * * This class extends from the Exporter class. It is used to read * data with KEEL format and transform them to the PropertyList (xml) format. * * @author Teresa Prieto López (UCO) * @version 1.0 */ public class KeelToPropertyList extends Exporter { /** KeelToPropertyList class Constructor. * Initializes the variable that stores the symbols used to identify null * values */ public KeelToPropertyList() { nullValue = ""; } /** * Method used to transform the data from the KEEL file given as parameter to * PropertyList format file which will be stored in the second file given. It calls the method * Start of its super class Exporter and then call the method Save. * * @param pathnameInput KEEL file path. * @param pathnameOutput PropertyList file path. * * @throws Exception if the files can not be read or written. */ public void Start(String pathnameInput, String pathnameOutput) throws Exception { super.Start(pathnameInput); Save(pathnameOutput); }//end Start() /** * Method that creates the output file with PropertyList format given as parameter * using all the structures built by the start method of the Exporter class. * @param pathnameOutput PropertyList file path to generate. * @throws Exception if the file can not be written. */ public void Save(String pathnameOutput) throws Exception { int i; int j; int k; int type; int numInstances; String valueAttribute = new String(); String filename = new String(); String nameElement = new String(); String labelType = new String(); Element children; String vowel[] = {"a", "e", "i", "o", "u", "A", "E", "I", "O", "U"}; String vowel_accent[] = {"á", "é", "í", "ó", "ú", "Á", "É", "Í", "Ó", "Ú"}; /* Comprobamos si el nombre del fichero tiene la extensión .xml, si no la tiene * se la ponemos */ if (pathnameOutput.endsWith(".plist")) { filename = pathnameOutput; } else { filename = pathnameOutput.concat(".plist"); } Element root = new Element("plist"); Document myDocument = new Document(root); org.jdom.Attribute attributePlist = new org.jdom.Attribute("version", "1.0"); root.setAttribute(attributePlist); numInstances = data[0].size(); for (i = 0; i < numInstances; i++) { Element childrenDict = new Element("dict"); for (j = 0; j < numAttributes; j++) { type = attribute[j].getType(); nameElement = attribute[j].getName(); nameElement = nameElement.replace("\"", ""); nameElement = nameElement.replace("'", ""); if (nameElement.startsWith("\"") && nameElement.endsWith("\"")) { nameElement = nameElement.substring(1, (nameElement.length()) - 1).replaceAll(" ", "_"); } children = new Element("key").addContent(nameElement); childrenDict.addContent(children); valueAttribute = (String) data[j].elementAt(i); valueAttribute = valueAttribute.replace("\"", ""); for (k = 0; k < vowel.length; k++) { valueAttribute = valueAttribute.replace(vowel_accent[k], "&" + vowel[k] + "acute;"); } if (valueAttribute.equals("?") || valueAttribute.equals("<null>")) { valueAttribute = ""; } if (type == INTEGER) { labelType = "integer"; } if (type == REAL) { labelType = "real"; } if (type == NOMINAL || type == -1) { labelType = "string"; } children = new Element(labelType).addContent(valueAttribute); childrenDict.addContent(children); } root.addContent(childrenDict); } try { XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat()); outputter.output(myDocument, new FileWriter(pathnameOutput)); File f = new File(filename); System.out.println("Fichero " + f.getName() + " creado correctamente"); } catch (java.io.IOException e) { e.printStackTrace(); } }//end Savd() }// end class KeelToPropertyList
SCI2SUGR/KEEL
src/keel/Algorithms/Preprocess/Converter/KeelToPropertyList.java
Java
gpl-3.0
6,198