repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
invy/far2l
far2l/help.hpp
6334
#pragma once /* help.hpp Помощь */ /* Copyright (c) 1996 Eugene Roshal Copyright (c) 2000 Far Group All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. The name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "frame.hpp" #include "keybar.hpp" #include "array.hpp" class CallBackStack; #define HelpBeginLink L'<' #define HelpEndLink L'>' #define HelpFormatLink L"<%s\\>%s" #define HELPMODE_CLICKOUTSIDE 0x20000000 // было нажатие мыши вне хелпа? struct StackHelpData { DWORD Flags; // флаги int TopStr; // номер верхней видимой строки темы int CurX,CurY; // координаты (???) FARString strHelpMask; // значение маски FARString strHelpPath; // путь к хелпам FARString strHelpTopic; // текущий топик FARString strSelTopic; // выделенный топик (???) void Clear() { Flags=0; TopStr=0; CurX=CurY=0; strHelpMask.Clear(); strHelpPath.Clear(); strHelpTopic.Clear(); strSelTopic.Clear(); } }; enum HELPDOCUMENTSHELPTYPE { HIDX_PLUGINS, // Индекс плагинов HIDX_DOCUMS, // Индекс документов }; enum { FHELPOBJ_ERRCANNOTOPENHELP = 0x80000000, }; class HelpRecord { public: wchar_t *HelpStr; HelpRecord(const wchar_t *HStr=nullptr) { HelpStr = nullptr; if (HStr ) HelpStr = xf_wcsdup(HStr); }; const HelpRecord& operator=(const HelpRecord &rhs) { if (this != &rhs) { HelpStr = xf_wcsdup(rhs.HelpStr); } return *this; }; bool operator==(const HelpRecord &rhs) const { return !StrCmpI(HelpStr,rhs.HelpStr); }; int operator<(const HelpRecord &rhs) const { return StrCmpI(HelpStr,rhs.HelpStr) < 0; }; ~HelpRecord() { if (HelpStr) xf_free(HelpStr); } }; class Help:public Frame { private: BOOL ErrorHelp; // TRUE - ошибка! Например - нет такого топика SaveScreen *TopScreen; // область сохранения под хелпом KeyBar HelpKeyBar; // кейбар CallBackStack *Stack; // стек возврата FARString strFullHelpPathName; StackHelpData StackData; TArray<HelpRecord> HelpList; // "хелп" в памяти. int StrCount; // количество строк в теме int FixCount; // количество строк непрокручиваемой области int FixSize; // Размер непрокручиваемой области int TopicFound; // TRUE - топик найден int IsNewTopic; // это новый топик? int MouseDown; FARString strCtrlColorChar; // CtrlColorChar - опция! для спецсимвола- // символа - для атрибутов int CurColor; // CurColor - текущий цвет отрисовки int CtrlTabSize; // CtrlTabSize - опция! размер табуляции int PrevMacroMode; // предыдущий режим макроса FARString strCurPluginContents; // помним PluginContents (для отображения в заголовке) DWORD LastStartPos; DWORD StartPos; FARString strCtrlStartPosChar; private: virtual void DisplayObject(); int ReadHelp(const wchar_t *Mask=nullptr); void AddLine(const wchar_t *Line); void AddTitle(const wchar_t *Title); void HighlightsCorrection(FARString &strStr); void FastShow(); void DrawWindowFrame(); void OutString(const wchar_t *Str); int StringLen(const wchar_t *Str); void CorrectPosition(); int IsReferencePresent(); void MoveToReference(int Forward,int CurScreen); void ReadDocumentsHelp(int TypeIndex); int JumpTopic(const wchar_t *JumpTopic=nullptr); const HelpRecord* GetHelpItem(int Pos); public: Help(const wchar_t *Topic,const wchar_t *Mask=nullptr,DWORD Flags=0); virtual ~Help(); public: virtual void Hide(); virtual int ProcessKey(int Key); virtual int ProcessMouse(MOUSE_EVENT_RECORD *MouseEvent); virtual void InitKeyBar(); BOOL GetError() {return ErrorHelp;} virtual void SetScreenPosition(); virtual void OnChangeFocus(int focus); // вызывается при смене фокуса virtual void ResizeConsole(); virtual int FastHide(); // Введена для нужд CtrlAltShift virtual const wchar_t *GetTypeName() {return L"[Help]";} virtual int GetTypeAndName(FARString &strType, FARString &strName); virtual int GetType() { return MODALTYPE_HELP; } virtual int64_t VMProcess(int OpCode,void *vParam,int64_t iParam); static FARString &MkTopic(INT_PTR PluginNumber,const wchar_t *HelpTopic,FARString &strTopic); };
gpl-2.0
freenet/legacy
src/freenet/node/simulator/whackysim/ProbabilityOnlyRouteEstimator.java
1146
package freenet.node.simulator.whackysim; import java.io.PrintWriter; import freenet.Key; import freenet.node.rt.BucketDistribution; import freenet.node.rt.KeyspaceEstimator; import freenet.node.rt.KeyspaceEstimatorFactory; /** * RouteEstimator using pSuccess only. */ public class ProbabilityOnlyRouteEstimator implements RouteEstimator { final KeyspaceEstimator pFailure; // the lower the better! public ProbabilityOnlyRouteEstimator(KeyspaceEstimatorFactory kef) { pFailure = kef.createProbability(0.0, null); } public double estimate(Key k) { return pFailure.guessProbability(k); } public void succeeded(Key k, long time) { pFailure.reportProbability(k, 0.0); } public void failed(Key k, long time) { pFailure.reportProbability(k, 1.0); } public void dump(PrintWriter pw, String dumpFilename) { pw.println(getClass().getName()); BucketDistribution bd = new BucketDistribution(); pFailure.getBucketDistribution(bd); pw.println(bd.toString()); } public long hits() { return pFailure.countReports(); } }
gpl-2.0
acappellamaniac/eva_website
sites/all/modules/civicrm/ang/crmMailingAB/services.js
8785
(function (angular, $, _) { function OptionGroup(values) { this.get = function get(value) { var r = _.where(values, {value: '' + value}); return r.length > 0 ? r[0] : null; }; this.getByName = function get(name) { var r = _.where(values, {name: '' + name}); return r.length > 0 ? r[0] : null; }; this.getAll = function getAll() { return values; }; } angular.module('crmMailingAB').factory('crmMailingABCriteria', function () { // TODO Get data from server var values = { '1': {value: 'subject', name: 'subject', label: ts('Test different "Subject" lines')}, '2': {value: 'from', name: 'from', label: ts('Test different "From" lines')}, '3': {value: 'full_email', name: 'full_email', label: ts('Test entirely different emails')} }; return new OptionGroup(values); }); angular.module('crmMailingAB').factory('crmMailingABStatus', function () { // TODO Get data from server var values = { '1': {value: '1', name: 'Draft', label: ts('Draft')}, '2': {value: '2', name: 'Testing', label: ts('Testing')}, '3': {value: '3', name: 'Final', label: ts('Final')} }; return new OptionGroup(values); }); // CrmMailingAB is a data-model which combines an AB test (APIv3 "MailingAB"), three mailings (APIv3 "Mailing"), // and three sets of attachments (APIv3 "Attachment"). // // example: // var abtest = new CrmMailingAB(123); // abtest.load().then(function(){ // alert("Mailing A is named "+abtest.mailings.a.name); // }); angular.module('crmMailingAB').factory('CrmMailingAB', function (crmApi, crmMailingMgr, $q, CrmAttachments) { function CrmMailingAB(id) { this.id = id; this.mailings = {}; this.attachments = {}; } angular.extend(CrmMailingAB.prototype, { getAutosaveSignature: function() { return [ this.ab, this.mailings, this.attachments.a.getAutosaveSignature(), this.attachments.b.getAutosaveSignature(), this.attachments.c.getAutosaveSignature() ]; }, // @return Promise CrmMailingAB load: function load() { var crmMailingAB = this; if (!crmMailingAB.id) { crmMailingAB.ab = { name: '', status: 'Draft', mailing_id_a: null, mailing_id_b: null, mailing_id_c: null, domain_id: null, testing_criteria: 'subject', winner_criteria: null, specific_url: '', declare_winning_time: null, group_percentage: 10 }; var mailingDefaults = { // Most defaults provided by Mailing.create API, but we // want to force-enable tracking. open_tracking: "1", url_tracking: "1", mailing_type:"experiment" }; crmMailingAB.mailings.a = crmMailingMgr.create(mailingDefaults); crmMailingAB.mailings.b = crmMailingMgr.create(mailingDefaults); mailingDefaults.mailing_type = 'winner'; crmMailingAB.mailings.c = crmMailingMgr.create(mailingDefaults); crmMailingAB.attachments.a = new CrmAttachments(function () { return {entity_table: 'civicrm_mailing', entity_id: crmMailingAB.ab.mailing_id_a}; }); crmMailingAB.attachments.b = new CrmAttachments(function () { return {entity_table: 'civicrm_mailing', entity_id: crmMailingAB.ab.mailing_id_b}; }); crmMailingAB.attachments.c = new CrmAttachments(function () { return {entity_table: 'civicrm_mailing', entity_id: crmMailingAB.ab.mailing_id_c}; }); var dfr = $q.defer(); dfr.resolve(crmMailingAB); return dfr.promise; } else { return crmApi('MailingAB', 'get', {id: crmMailingAB.id}) .then(function (abResult) { if (abResult.count != 1) { throw "Failed to load AB Test"; } crmMailingAB.ab = abResult.values[abResult.id]; return crmMailingAB._loadMailings(); }); } }, // @return Promise CrmMailingAB save: function save() { var crmMailingAB = this; return crmMailingAB._saveMailings() .then(function () { return crmApi('MailingAB', 'create', crmMailingAB.ab) .then(function (abResult) { if (!crmMailingAB.id) { crmMailingAB.id = crmMailingAB.ab.id = abResult.id; } }); }) .then(function () { return crmMailingAB; }); }, // Schedule the test // @return Promise CrmMailingAB // Note: Submission may cause the server state to change. Consider abtest.submit().then(...abtest.load()...) submitTest: function submitTest() { var crmMailingAB = this; var params = { id: this.ab.id, status: 'Testing', approval_date: 'now', scheduled_date: this.mailings.a.scheduled_date ? this.mailings.a.scheduled_date : 'now' }; return crmApi('MailingAB', 'submit', params) .then(function () { return crmMailingAB.load(); }); }, // Schedule the final mailing // @return Promise CrmMailingAB // Note: Submission may cause the server state to change. Consider abtest.submit().then(...abtest.load()...) submitFinal: function submitFinal() { var crmMailingAB = this; var params = { id: this.ab.id, status: 'Final', approval_date: 'now', scheduled_date: this.mailings.c.scheduled_date ? this.mailings.c.scheduled_date : 'now' }; return crmApi('MailingAB', 'submit', params) .then(function () { return crmMailingAB.load(); }); }, // @param mailing Object (per APIv3) // @return Promise 'delete': function () { if (this.id) { return crmApi('MailingAB', 'delete', {id: this.id}); } else { var d = $q.defer(); d.resolve(); return d.promise; } }, // Load mailings A, B, and C (if available) // @return Promise CrmMailingAB _loadMailings: function _loadMailings() { var crmMailingAB = this; var todos = {}; _.each(['a', 'b', 'c'], function (mkey) { if (crmMailingAB.ab['mailing_id_' + mkey]) { todos[mkey] = crmMailingMgr.get(crmMailingAB.ab['mailing_id_' + mkey]) .then(function (mailing) { crmMailingAB.mailings[mkey] = mailing; crmMailingAB.attachments[mkey] = new CrmAttachments(function () { return {entity_table: 'civicrm_mailing', entity_id: crmMailingAB.ab['mailing_id_' + mkey]}; }); return crmMailingAB.attachments[mkey].load(); }); } else { crmMailingAB.mailings[mkey] = crmMailingMgr.create(); crmMailingAB.attachments[mkey] = new CrmAttachments(function () { return {entity_table: 'civicrm_mailing', entity_id: crmMailingAB.ab['mailing_id_' + mkey]}; }); } }); return $q.all(todos).then(function () { return crmMailingAB; }); }, // Save mailings A, B, and C (if available) // @return Promise CrmMailingAB _saveMailings: function _saveMailings() { var crmMailingAB = this; var todos = {}; var p = $q.when(true); _.each(['a', 'b', 'c'], function (mkey) { if (!crmMailingAB.mailings[mkey]) { return; } if (crmMailingAB.ab['mailing_id_' + mkey]) { // paranoia: in case caller forgot to manage id on mailing crmMailingAB.mailings[mkey].id = crmMailingAB.ab['mailing_id_' + mkey]; } p = p.then(function(){ return crmMailingMgr.save(crmMailingAB.mailings[mkey]) .then(function () { crmMailingAB.ab['mailing_id_' + mkey] = crmMailingAB.mailings[mkey].id; return crmMailingAB.attachments[mkey].save(); }); }); }); return p.then(function () { return crmMailingAB; }); } }); return CrmMailingAB; }); })(angular, CRM.$, CRM._);
gpl-2.0
abhinavjain241/acousticbrainz-server
fabfile.py
1424
from __future__ import with_statement from fabric.api import local from fabric.colors import green, yellow, red from db import cache import config import os def vpsql(): """Connect to the acousticbrainz database running on vagrant.""" local("psql -h localhost -p 15432 -U postgres acousticbrainz") def vssh(): """SSH to a running vagrant host.""" curdir = os.path.dirname(os.path.abspath(__file__)) configfile = os.path.join(curdir, '.vagrant', 'ssh_config') if not os.path.exists(configfile): local('vagrant ssh-config acousticbrainz > .vagrant/ssh_config') local("ssh -F .vagrant/ssh_config -o 'ControlMaster auto' -o 'ControlPath ~/.ssh/ab_vagrant_control' -o 'ControlPersist 4h' acousticbrainz") def git_pull(): local("git pull origin") print(green("Updated local code.", bold=True)) def install_requirements(): local("pip install -r requirements.txt") print(green("Installed requirements.", bold=True)) def build_static(): local("./node_modules/.bin/gulp") def clear_memcached(): try: cache.init(config.MEMCACHED_SERVERS) cache.flush_all() print(green("Flushed everything from memcached.", bold=True)) except AttributeError as e: print(red("Failed to clear memcached! Check your config file.\nError: %s" % e)) def deploy(): git_pull() install_requirements() build_static() clear_memcached()
gpl-2.0
netroby/hotspot8
src/share/vm/oops/klassVtable.cpp
61366
/* * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #include "precompiled.hpp" #include "classfile/systemDictionary.hpp" #include "classfile/vmSymbols.hpp" #include "gc_implementation/shared/markSweep.inline.hpp" #include "memory/gcLocker.hpp" #include "memory/resourceArea.hpp" #include "memory/universe.inline.hpp" #include "oops/instanceKlass.hpp" #include "oops/klassVtable.hpp" #include "oops/method.hpp" #include "oops/objArrayOop.hpp" #include "oops/oop.inline.hpp" #include "prims/jvmtiRedefineClassesTrace.hpp" #include "runtime/arguments.hpp" #include "runtime/handles.inline.hpp" #include "utilities/copy.hpp" PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC inline InstanceKlass* klassVtable::ik() const { Klass* k = _klass(); assert(k->oop_is_instance(), "not an InstanceKlass"); return (InstanceKlass*)k; } // this function computes the vtable size (including the size needed for miranda // methods) and the number of miranda methods in this class. // Note on Miranda methods: Let's say there is a class C that implements // interface I, and none of C's superclasses implements I. // Let's say there is an abstract method m in I that neither C // nor any of its super classes implement (i.e there is no method of any access, // with the same name and signature as m), then m is a Miranda method which is // entered as a public abstract method in C's vtable. From then on it should // treated as any other public method in C for method over-ride purposes. void klassVtable::compute_vtable_size_and_num_mirandas( int* vtable_length_ret, int* num_new_mirandas, GrowableArray<Method*>* all_mirandas, Klass* super, Array<Method*>* methods, AccessFlags class_flags, Handle classloader, Symbol* classname, Array<Klass*>* local_interfaces, TRAPS) { No_Safepoint_Verifier nsv; // set up default result values int vtable_length = 0; // start off with super's vtable length InstanceKlass* sk = (InstanceKlass*)super; vtable_length = super == NULL ? 0 : sk->vtable_length(); // go thru each method in the methods table to see if it needs a new entry int len = methods->length(); for (int i = 0; i < len; i++) { assert(methods->at(i)->is_method(), "must be a Method*"); methodHandle mh(THREAD, methods->at(i)); if (needs_new_vtable_entry(mh, super, classloader, classname, class_flags, THREAD)) { vtable_length += vtableEntry::size(); // we need a new entry } } GrowableArray<Method*> new_mirandas(20); // compute the number of mirandas methods that must be added to the end get_mirandas(&new_mirandas, all_mirandas, super, methods, NULL, local_interfaces); *num_new_mirandas = new_mirandas.length(); // Interfaces do not need interface methods in their vtables // This includes miranda methods and during later processing, default methods if (!class_flags.is_interface()) { vtable_length += *num_new_mirandas * vtableEntry::size(); } if (Universe::is_bootstrapping() && vtable_length == 0) { // array classes don't have their superclass set correctly during // bootstrapping vtable_length = Universe::base_vtable_size(); } if (super == NULL && !Universe::is_bootstrapping() && vtable_length != Universe::base_vtable_size()) { // Someone is attempting to redefine java.lang.Object incorrectly. The // only way this should happen is from // SystemDictionary::resolve_from_stream(), which will detect this later // and throw a security exception. So don't assert here to let // the exception occur. vtable_length = Universe::base_vtable_size(); } assert(super != NULL || vtable_length == Universe::base_vtable_size(), "bad vtable size for class Object"); assert(vtable_length % vtableEntry::size() == 0, "bad vtable length"); assert(vtable_length >= Universe::base_vtable_size(), "vtable too small"); *vtable_length_ret = vtable_length; } int klassVtable::index_of(Method* m, int len) const { assert(m->has_vtable_index(), "do not ask this of non-vtable methods"); return m->vtable_index(); } // Copy super class's vtable to the first part (prefix) of this class's vtable, // and return the number of entries copied. Expects that 'super' is the Java // super class (arrays can have "array" super classes that must be skipped). int klassVtable::initialize_from_super(KlassHandle super) { if (super.is_null()) { return 0; } else { // copy methods from superKlass // can't inherit from array class, so must be InstanceKlass assert(super->oop_is_instance(), "must be instance klass"); InstanceKlass* sk = (InstanceKlass*)super(); klassVtable* superVtable = sk->vtable(); assert(superVtable->length() <= _length, "vtable too short"); #ifdef ASSERT superVtable->verify(tty, true); #endif superVtable->copy_vtable_to(table()); #ifndef PRODUCT if (PrintVtables && Verbose) { ResourceMark rm; tty->print_cr("copy vtable from %s to %s size %d", sk->internal_name(), klass()->internal_name(), _length); } #endif return superVtable->length(); } } // // Revised lookup semantics introduced 1.3 (Kestrel beta) void klassVtable::initialize_vtable(bool checkconstraints, TRAPS) { // Note: Arrays can have intermediate array supers. Use java_super to skip them. KlassHandle super (THREAD, klass()->java_super()); int nofNewEntries = 0; if (PrintVtables && !klass()->oop_is_array()) { ResourceMark rm(THREAD); tty->print_cr("Initializing: %s", _klass->name()->as_C_string()); } #ifdef ASSERT oop* end_of_obj = (oop*)_klass() + _klass()->size(); oop* end_of_vtable = (oop*)&table()[_length]; assert(end_of_vtable <= end_of_obj, "vtable extends beyond end"); #endif if (Universe::is_bootstrapping()) { // just clear everything for (int i = 0; i < _length; i++) table()[i].clear(); return; } int super_vtable_len = initialize_from_super(super); if (klass()->oop_is_array()) { assert(super_vtable_len == _length, "arrays shouldn't introduce new methods"); } else { assert(_klass->oop_is_instance(), "must be InstanceKlass"); Array<Method*>* methods = ik()->methods(); int len = methods->length(); int initialized = super_vtable_len; // Check each of this class's methods against super; // if override, replace in copy of super vtable, otherwise append to end for (int i = 0; i < len; i++) { // update_inherited_vtable can stop for gc - ensure using handles HandleMark hm(THREAD); assert(methods->at(i)->is_method(), "must be a Method*"); methodHandle mh(THREAD, methods->at(i)); bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, -1, checkconstraints, CHECK); if (needs_new_entry) { put_method_at(mh(), initialized); mh()->set_vtable_index(initialized); // set primary vtable index initialized++; } } // update vtable with default_methods Array<Method*>* default_methods = ik()->default_methods(); if (default_methods != NULL) { len = default_methods->length(); if (len > 0) { Array<int>* def_vtable_indices = NULL; if ((def_vtable_indices = ik()->default_vtable_indices()) == NULL) { def_vtable_indices = ik()->create_new_default_vtable_indices(len, CHECK); } else { assert(def_vtable_indices->length() == len, "reinit vtable len?"); } for (int i = 0; i < len; i++) { HandleMark hm(THREAD); assert(default_methods->at(i)->is_method(), "must be a Method*"); methodHandle mh(THREAD, default_methods->at(i)); bool needs_new_entry = update_inherited_vtable(ik(), mh, super_vtable_len, i, checkconstraints, CHECK); // needs new entry if (needs_new_entry) { put_method_at(mh(), initialized); def_vtable_indices->at_put(i, initialized); //set vtable index initialized++; } } } } // add miranda methods; it will also return the updated initialized // Interfaces do not need interface methods in their vtables // This includes miranda methods and during later processing, default methods if (!ik()->is_interface()) { initialized = fill_in_mirandas(initialized); } // In class hierarchies where the accessibility is not increasing (i.e., going from private -> // package_private -> public/protected), the vtable might actually be smaller than our initial // calculation. assert(initialized <= _length, "vtable initialization failed"); for(;initialized < _length; initialized++) { put_method_at(NULL, initialized); } NOT_PRODUCT(verify(tty, true)); } } // Called for cases where a method does not override its superclass' vtable entry // For bytecodes not produced by javac together it is possible that a method does not override // the superclass's method, but might indirectly override a super-super class's vtable entry // If none found, return a null superk, else return the superk of the method this does override // For public and protected methods: if they override a superclass, they will // also be overridden themselves appropriately. // Private methods do not override and are not overridden. // Package Private methods are trickier: // e.g. P1.A, pub m // P2.B extends A, package private m // P1.C extends B, public m // P1.C.m needs to override P1.A.m and can not override P2.B.m // Therefore: all package private methods need their own vtable entries for // them to be the root of an inheritance overriding decision // Package private methods may also override other vtable entries InstanceKlass* klassVtable::find_transitive_override(InstanceKlass* initialsuper, methodHandle target_method, int vtable_index, Handle target_loader, Symbol* target_classname, Thread * THREAD) { InstanceKlass* superk = initialsuper; while (superk != NULL && superk->super() != NULL) { InstanceKlass* supersuperklass = InstanceKlass::cast(superk->super()); klassVtable* ssVtable = supersuperklass->vtable(); if (vtable_index < ssVtable->length()) { Method* super_method = ssVtable->method_at(vtable_index); #ifndef PRODUCT Symbol* name= target_method()->name(); Symbol* signature = target_method()->signature(); assert(super_method->name() == name && super_method->signature() == signature, "vtable entry name/sig mismatch"); #endif if (supersuperklass->is_override(super_method, target_loader, target_classname, THREAD)) { #ifndef PRODUCT if (PrintVtables && Verbose) { ResourceMark rm(THREAD); char* sig = target_method()->name_and_sig_as_C_string(); tty->print("transitive overriding superclass %s with %s::%s index %d, original flags: ", supersuperklass->internal_name(), _klass->internal_name(), sig, vtable_index); super_method->access_flags().print_on(tty); if (super_method->is_default_method()) { tty->print("default "); } tty->print("overriders flags: "); target_method->access_flags().print_on(tty); if (target_method->is_default_method()) { tty->print("default "); } } #endif /*PRODUCT*/ break; // return found superk } } else { // super class has no vtable entry here, stop transitive search superk = (InstanceKlass*)NULL; break; } // if no override found yet, continue to search up superk = InstanceKlass::cast(superk->super()); } return superk; } // Update child's copy of super vtable for overrides // OR return true if a new vtable entry is required. // Only called for InstanceKlass's, i.e. not for arrays // If that changed, could not use _klass as handle for klass bool klassVtable::update_inherited_vtable(InstanceKlass* klass, methodHandle target_method, int super_vtable_len, int default_index, bool checkconstraints, TRAPS) { ResourceMark rm; bool allocate_new = true; assert(klass->oop_is_instance(), "must be InstanceKlass"); Array<int>* def_vtable_indices = NULL; bool is_default = false; // default methods are concrete methods in superinterfaces which are added to the vtable // with their real method_holder // Since vtable and itable indices share the same storage, don't touch // the default method's real vtable/itable index // default_vtable_indices stores the vtable value relative to this inheritor if (default_index >= 0 ) { is_default = true; def_vtable_indices = klass->default_vtable_indices(); assert(def_vtable_indices != NULL, "def vtable alloc?"); assert(default_index <= def_vtable_indices->length(), "def vtable len?"); } else { assert(klass == target_method()->method_holder(), "caller resp."); // Initialize the method's vtable index to "nonvirtual". // If we allocate a vtable entry, we will update it to a non-negative number. target_method()->set_vtable_index(Method::nonvirtual_vtable_index); } // Static and <init> methods are never in if (target_method()->is_static() || target_method()->name() == vmSymbols::object_initializer_name()) { return false; } if (target_method->is_final_method(klass->access_flags())) { // a final method never needs a new entry; final methods can be statically // resolved and they have to be present in the vtable only if they override // a super's method, in which case they re-use its entry allocate_new = false; } else if (klass->is_interface()) { allocate_new = false; // see note below in needs_new_vtable_entry // An interface never allocates new vtable slots, only inherits old ones. // This method will either be assigned its own itable index later, // or be assigned an inherited vtable index in the loop below. // default methods inherited by classes store their vtable indices // in the inheritor's default_vtable_indices // default methods inherited by interfaces may already have a // valid itable index, if so, don't change it // overpass methods in an interface will be assigned an itable index later // by an inheriting class if (!is_default || !target_method()->has_itable_index()) { target_method()->set_vtable_index(Method::pending_itable_index); } } // we need a new entry if there is no superclass if (klass->super() == NULL) { return allocate_new; } // private methods in classes always have a new entry in the vtable // specification interpretation since classic has // private methods not overriding // JDK8 adds private methods in interfaces which require invokespecial if (target_method()->is_private()) { return allocate_new; } // search through the vtable and update overridden entries // Since check_signature_loaders acquires SystemDictionary_lock // which can block for gc, once we are in this loop, use handles // For classfiles built with >= jdk7, we now look for transitive overrides Symbol* name = target_method()->name(); Symbol* signature = target_method()->signature(); KlassHandle target_klass(THREAD, target_method()->method_holder()); if (target_klass == NULL) { target_klass = _klass; } Handle target_loader(THREAD, target_klass->class_loader()); Symbol* target_classname = target_klass->name(); for(int i = 0; i < super_vtable_len; i++) { Method* super_method = method_at(i); // Check if method name matches if (super_method->name() == name && super_method->signature() == signature) { // get super_klass for method_holder for the found method InstanceKlass* super_klass = super_method->method_holder(); if (is_default || ((super_klass->is_override(super_method, target_loader, target_classname, THREAD)) || ((klass->major_version() >= VTABLE_TRANSITIVE_OVERRIDE_VERSION) && ((super_klass = find_transitive_override(super_klass, target_method, i, target_loader, target_classname, THREAD)) != (InstanceKlass*)NULL)))) { // Package private methods always need a new entry to root their own // overriding. They may also override other methods. if (!target_method()->is_package_private()) { allocate_new = false; } if (checkconstraints) { // Override vtable entry if passes loader constraint check // if loader constraint checking requested // No need to visit his super, since he and his super // have already made any needed loader constraints. // Since loader constraints are transitive, it is enough // to link to the first super, and we get all the others. Handle super_loader(THREAD, super_klass->class_loader()); if (target_loader() != super_loader()) { ResourceMark rm(THREAD); Symbol* failed_type_symbol = SystemDictionary::check_signature_loaders(signature, target_loader, super_loader, true, CHECK_(false)); if (failed_type_symbol != NULL) { const char* msg = "loader constraint violation: when resolving " "overridden method \"%s\" the class loader (instance" " of %s) of the current class, %s, and its superclass loader " "(instance of %s), have different Class objects for the type " "%s used in the signature"; char* sig = target_method()->name_and_sig_as_C_string(); const char* loader1 = SystemDictionary::loader_name(target_loader()); char* current = target_klass->name()->as_C_string(); const char* loader2 = SystemDictionary::loader_name(super_loader()); char* failed_type_name = failed_type_symbol->as_C_string(); size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) + strlen(current) + strlen(loader2) + strlen(failed_type_name); char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen); jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2, failed_type_name); THROW_MSG_(vmSymbols::java_lang_LinkageError(), buf, false); } } } put_method_at(target_method(), i); if (!is_default) { target_method()->set_vtable_index(i); } else { if (def_vtable_indices != NULL) { def_vtable_indices->at_put(default_index, i); } assert(super_method->is_default_method() || super_method->is_overpass() || super_method->is_abstract(), "default override error"); } #ifndef PRODUCT if (PrintVtables && Verbose) { ResourceMark rm(THREAD); char* sig = target_method()->name_and_sig_as_C_string(); tty->print("overriding with %s::%s index %d, original flags: ", target_klass->internal_name(), sig, i); super_method->access_flags().print_on(tty); if (super_method->is_default_method()) { tty->print("default "); } if (super_method->is_overpass()) { tty->print("overpass"); } tty->print("overriders flags: "); target_method->access_flags().print_on(tty); if (target_method->is_default_method()) { tty->print("default "); } if (target_method->is_overpass()) { tty->print("overpass"); } tty->cr(); } #endif /*PRODUCT*/ } else { // allocate_new = true; default. We might override one entry, // but not override another. Once we override one, not need new #ifndef PRODUCT if (PrintVtables && Verbose) { ResourceMark rm(THREAD); char* sig = target_method()->name_and_sig_as_C_string(); tty->print("NOT overriding with %s::%s index %d, original flags: ", target_klass->internal_name(), sig,i); super_method->access_flags().print_on(tty); if (super_method->is_default_method()) { tty->print("default "); } if (super_method->is_overpass()) { tty->print("overpass"); } tty->print("overriders flags: "); target_method->access_flags().print_on(tty); if (target_method->is_default_method()) { tty->print("default "); } if (target_method->is_overpass()) { tty->print("overpass"); } tty->cr(); } #endif /*PRODUCT*/ } } } return allocate_new; } void klassVtable::put_method_at(Method* m, int index) { #ifndef PRODUCT if (PrintVtables && Verbose) { ResourceMark rm; const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>"; tty->print("adding %s at index %d, flags: ", sig, index); if (m != NULL) { m->access_flags().print_on(tty); if (m->is_default_method()) { tty->print("default "); } if (m->is_overpass()) { tty->print("overpass"); } } tty->cr(); } #endif table()[index].set(m); } // Find out if a method "m" with superclass "super", loader "classloader" and // name "classname" needs a new vtable entry. Let P be a class package defined // by "classloader" and "classname". // NOTE: The logic used here is very similar to the one used for computing // the vtables indices for a method. We cannot directly use that function because, // we allocate the InstanceKlass at load time, and that requires that the // superclass has been loaded. // However, the vtable entries are filled in at link time, and therefore // the superclass' vtable may not yet have been filled in. bool klassVtable::needs_new_vtable_entry(methodHandle target_method, Klass* super, Handle classloader, Symbol* classname, AccessFlags class_flags, TRAPS) { if (class_flags.is_interface()) { // Interfaces do not use vtables, except for java.lang.Object methods, // so there is no point to assigning // a vtable index to any of their local methods. If we refrain from doing this, // we can use Method::_vtable_index to hold the itable index return false; } if (target_method->is_final_method(class_flags) || // a final method never needs a new entry; final methods can be statically // resolved and they have to be present in the vtable only if they override // a super's method, in which case they re-use its entry (target_method()->is_static()) || // static methods don't need to be in vtable (target_method()->name() == vmSymbols::object_initializer_name()) // <init> is never called dynamically-bound ) { return false; } // Concrete interface methods do not need new entries, they override // abstract method entries using default inheritance rules if (target_method()->method_holder() != NULL && target_method()->method_holder()->is_interface() && !target_method()->is_abstract() ) { return false; } // we need a new entry if there is no superclass if (super == NULL) { return true; } // private methods in classes always have a new entry in the vtable // specification interpretation since classic has // private methods not overriding // JDK8 adds private methods in interfaces which require invokespecial if (target_method()->is_private()) { return true; } // Package private methods always need a new entry to root their own // overriding. This allows transitive overriding to work. if (target_method()->is_package_private()) { return true; } // search through the super class hierarchy to see if we need // a new entry ResourceMark rm; Symbol* name = target_method()->name(); Symbol* signature = target_method()->signature(); Klass* k = super; Method* super_method = NULL; InstanceKlass *holder = NULL; Method* recheck_method = NULL; while (k != NULL) { // lookup through the hierarchy for a method with matching name and sign. super_method = InstanceKlass::cast(k)->lookup_method(name, signature); if (super_method == NULL) { break; // we still have to search for a matching miranda method } // get the class holding the matching method // make sure you use that class for is_override InstanceKlass* superk = super_method->method_holder(); // we want only instance method matches // pretend private methods are not in the super vtable // since we do override around them: e.g. a.m pub/b.m private/c.m pub, // ignore private, c.m pub does override a.m pub // For classes that were not javac'd together, we also do transitive overriding around // methods that have less accessibility if ((!super_method->is_static()) && (!super_method->is_private())) { if (superk->is_override(super_method, classloader, classname, THREAD)) { return false; // else keep looking for transitive overrides } } // Start with lookup result and continue to search up k = superk->super(); // haven't found an override match yet; continue to look } // if the target method is public or protected it may have a matching // miranda method in the super, whose entry it should re-use. // Actually, to handle cases that javac would not generate, we need // this check for all access permissions. InstanceKlass *sk = InstanceKlass::cast(super); if (sk->has_miranda_methods()) { if (sk->lookup_method_in_all_interfaces(name, signature, Klass::normal) != NULL) { return false; // found a matching miranda; we do not need a new entry } } return true; // found no match; we need a new entry } // Support for miranda methods // get the vtable index of a miranda method with matching "name" and "signature" int klassVtable::index_of_miranda(Symbol* name, Symbol* signature) { // search from the bottom, might be faster for (int i = (length() - 1); i >= 0; i--) { Method* m = table()[i].method(); if (is_miranda_entry_at(i) && m->name() == name && m->signature() == signature) { return i; } } return Method::invalid_vtable_index; } // check if an entry at an index is miranda // requires that method m at entry be declared ("held") by an interface. bool klassVtable::is_miranda_entry_at(int i) { Method* m = method_at(i); Klass* method_holder = m->method_holder(); InstanceKlass *mhk = InstanceKlass::cast(method_holder); // miranda methods are public abstract instance interface methods in a class's vtable if (mhk->is_interface()) { assert(m->is_public(), "should be public"); assert(ik()->implements_interface(method_holder) , "this class should implement the interface"); // the search could find a miranda or a default method if (is_miranda(m, ik()->methods(), ik()->default_methods(), ik()->super())) { return true; } } return false; } // check if a method is a miranda method, given a class's methods table, // its default_method table and its super // Miranda methods are calculated twice: // first: before vtable size calculation: including abstract and default // This is seen by default method creation // Second: recalculated during vtable initialization: only abstract // This is seen by link resolution and selection. // "miranda" means not static, not defined by this class. // private methods in interfaces do not belong in the miranda list. // the caller must make sure that the method belongs to an interface implemented by the class // Miranda methods only include public interface instance methods // Not private methods, not static methods, not default == concrete abstract // Miranda methods also do not include overpass methods in interfaces bool klassVtable::is_miranda(Method* m, Array<Method*>* class_methods, Array<Method*>* default_methods, Klass* super) { if (m->is_static() || m->is_private() || m->is_overpass()) { return false; } Symbol* name = m->name(); Symbol* signature = m->signature(); if (InstanceKlass::find_instance_method(class_methods, name, signature) == NULL) { // did not find it in the method table of the current class if ((default_methods == NULL) || InstanceKlass::find_method(default_methods, name, signature) == NULL) { if (super == NULL) { // super doesn't exist return true; } Method* mo = InstanceKlass::cast(super)->lookup_method(name, signature); while (mo != NULL && mo->access_flags().is_static() && mo->method_holder() != NULL && mo->method_holder()->super() != NULL) { mo = mo->method_holder()->super()->uncached_lookup_method(name, signature, Klass::normal); } if (mo == NULL || mo->access_flags().is_private() ) { // super class hierarchy does not implement it or protection is different return true; } } } return false; } // Scans current_interface_methods for miranda methods that do not // already appear in new_mirandas, or default methods, and are also not defined-and-non-private // in super (superclass). These mirandas are added to all_mirandas if it is // not null; in addition, those that are not duplicates of miranda methods // inherited by super from its interfaces are added to new_mirandas. // Thus, new_mirandas will be the set of mirandas that this class introduces, // all_mirandas will be the set of all mirandas applicable to this class // including all defined in superclasses. void klassVtable::add_new_mirandas_to_lists( GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas, Array<Method*>* current_interface_methods, Array<Method*>* class_methods, Array<Method*>* default_methods, Klass* super) { // iterate thru the current interface's method to see if it a miranda int num_methods = current_interface_methods->length(); for (int i = 0; i < num_methods; i++) { Method* im = current_interface_methods->at(i); bool is_duplicate = false; int num_of_current_mirandas = new_mirandas->length(); // check for duplicate mirandas in different interfaces we implement for (int j = 0; j < num_of_current_mirandas; j++) { Method* miranda = new_mirandas->at(j); if ((im->name() == miranda->name()) && (im->signature() == miranda->signature())) { is_duplicate = true; break; } } if (!is_duplicate) { // we don't want duplicate miranda entries in the vtable if (is_miranda(im, class_methods, default_methods, super)) { // is it a miranda at all? InstanceKlass *sk = InstanceKlass::cast(super); // check if it is a duplicate of a super's miranda if (sk->lookup_method_in_all_interfaces(im->name(), im->signature(), Klass::normal) == NULL) { new_mirandas->append(im); } if (all_mirandas != NULL) { all_mirandas->append(im); } } } } } void klassVtable::get_mirandas(GrowableArray<Method*>* new_mirandas, GrowableArray<Method*>* all_mirandas, Klass* super, Array<Method*>* class_methods, Array<Method*>* default_methods, Array<Klass*>* local_interfaces) { assert((new_mirandas->length() == 0) , "current mirandas must be 0"); // iterate thru the local interfaces looking for a miranda int num_local_ifs = local_interfaces->length(); for (int i = 0; i < num_local_ifs; i++) { InstanceKlass *ik = InstanceKlass::cast(local_interfaces->at(i)); add_new_mirandas_to_lists(new_mirandas, all_mirandas, ik->methods(), class_methods, default_methods, super); // iterate thru each local's super interfaces Array<Klass*>* super_ifs = ik->transitive_interfaces(); int num_super_ifs = super_ifs->length(); for (int j = 0; j < num_super_ifs; j++) { InstanceKlass *sik = InstanceKlass::cast(super_ifs->at(j)); add_new_mirandas_to_lists(new_mirandas, all_mirandas, sik->methods(), class_methods, default_methods, super); } } } // Discover miranda methods ("miranda" = "interface abstract, no binding"), // and append them into the vtable starting at index initialized, // return the new value of initialized. // Miranda methods use vtable entries, but do not get assigned a vtable_index // The vtable_index is discovered by searching from the end of the vtable int klassVtable::fill_in_mirandas(int initialized) { GrowableArray<Method*> mirandas(20); get_mirandas(&mirandas, NULL, ik()->super(), ik()->methods(), ik()->default_methods(), ik()->local_interfaces()); for (int i = 0; i < mirandas.length(); i++) { if (PrintVtables && Verbose) { Method* meth = mirandas.at(i); ResourceMark rm(Thread::current()); if (meth != NULL) { char* sig = meth->name_and_sig_as_C_string(); tty->print("fill in mirandas with %s index %d, flags: ", sig, initialized); meth->access_flags().print_on(tty); if (meth->is_default_method()) { tty->print("default "); } tty->cr(); } } put_method_at(mirandas.at(i), initialized); ++initialized; } return initialized; } // Copy this class's vtable to the vtable beginning at start. // Used to copy superclass vtable to prefix of subclass's vtable. void klassVtable::copy_vtable_to(vtableEntry* start) { Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size()); } #if INCLUDE_JVMTI bool klassVtable::adjust_default_method(int vtable_index, Method* old_method, Method* new_method) { // If old_method is default, find this vtable index in default_vtable_indices // and replace that method in the _default_methods list bool updated = false; Array<Method*>* default_methods = ik()->default_methods(); if (default_methods != NULL) { int len = default_methods->length(); for (int idx = 0; idx < len; idx++) { if (vtable_index == ik()->default_vtable_indices()->at(idx)) { if (default_methods->at(idx) == old_method) { default_methods->at_put(idx, new_method); updated = true; } break; } } } return updated; } // search the vtable for uses of either obsolete or EMCP methods void klassVtable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) { int prn_enabled = 0; for (int index = 0; index < length(); index++) { Method* old_method = unchecked_method_at(index); if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) { continue; // skip uninteresting entries } assert(!old_method->is_deleted(), "vtable methods may not be deleted"); Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum()); assert(new_method != NULL, "method_with_idnum() should not be NULL"); assert(old_method != new_method, "sanity check"); put_method_at(new_method, index); // For default methods, need to update the _default_methods array // which can only have one method entry for a given signature bool updated_default = false; if (old_method->is_default_method()) { updated_default = adjust_default_method(index, old_method, new_method); } if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) { if (!(*trace_name_printed)) { // RC_TRACE_MESG macro has an embedded ResourceMark RC_TRACE_MESG(("adjust: klassname=%s for methods from name=%s", klass()->external_name(), old_method->method_holder()->external_name())); *trace_name_printed = true; } // RC_TRACE macro has an embedded ResourceMark RC_TRACE(0x00100000, ("vtable method update: %s(%s), updated default = %s", new_method->name()->as_C_string(), new_method->signature()->as_C_string(), updated_default ? "true" : "false")); } } } // a vtable should never contain old or obsolete methods bool klassVtable::check_no_old_or_obsolete_entries() { for (int i = 0; i < length(); i++) { Method* m = unchecked_method_at(i); if (m != NULL && (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) { return false; } } return true; } void klassVtable::dump_vtable() { tty->print_cr("vtable dump --"); for (int i = 0; i < length(); i++) { Method* m = unchecked_method_at(i); if (m != NULL) { tty->print(" (%5d) ", i); m->access_flags().print_on(tty); if (m->is_default_method()) { tty->print("default "); } if (m->is_overpass()) { tty->print("overpass"); } tty->print(" -- "); m->print_name(tty); tty->cr(); } } } #endif // INCLUDE_JVMTI // CDS/RedefineClasses support - clear vtables so they can be reinitialized void klassVtable::clear_vtable() { for (int i = 0; i < _length; i++) table()[i].clear(); } bool klassVtable::is_initialized() { return _length == 0 || table()[0].method() != NULL; } //----------------------------------------------------------------------------------------- // Itable code // Initialize a itableMethodEntry void itableMethodEntry::initialize(Method* m) { if (m == NULL) return; _method = m; } klassItable::klassItable(instanceKlassHandle klass) { _klass = klass; if (klass->itable_length() > 0) { itableOffsetEntry* offset_entry = (itableOffsetEntry*)klass->start_of_itable(); if (offset_entry != NULL && offset_entry->interface_klass() != NULL) { // Check that itable is initialized // First offset entry points to the first method_entry intptr_t* method_entry = (intptr_t *)(((address)klass()) + offset_entry->offset()); intptr_t* end = klass->end_of_itable(); _table_offset = (intptr_t*)offset_entry - (intptr_t*)klass(); _size_offset_table = (method_entry - ((intptr_t*)offset_entry)) / itableOffsetEntry::size(); _size_method_table = (end - method_entry) / itableMethodEntry::size(); assert(_table_offset >= 0 && _size_offset_table >= 0 && _size_method_table >= 0, "wrong computation"); return; } } // The length of the itable was either zero, or it has not yet been initialized. _table_offset = 0; _size_offset_table = 0; _size_method_table = 0; } static int initialize_count = 0; // Initialization void klassItable::initialize_itable(bool checkconstraints, TRAPS) { if (_klass->is_interface()) { // This needs to go after vtable indices are assigned but // before implementors need to know the number of itable indices. assign_itable_indices_for_interface(_klass()); } // Cannot be setup doing bootstrapping, interfaces don't have // itables, and klass with only ones entry have empty itables if (Universe::is_bootstrapping() || _klass->is_interface() || _klass->itable_length() == itableOffsetEntry::size()) return; // There's alway an extra itable entry so we can null-terminate it. guarantee(size_offset_table() >= 1, "too small"); int num_interfaces = size_offset_table() - 1; if (num_interfaces > 0) { if (TraceItables) tty->print_cr("%3d: Initializing itables for %s", ++initialize_count, _klass->name()->as_C_string()); // Iterate through all interfaces int i; for(i = 0; i < num_interfaces; i++) { itableOffsetEntry* ioe = offset_entry(i); HandleMark hm(THREAD); KlassHandle interf_h (THREAD, ioe->interface_klass()); assert(interf_h() != NULL && ioe->offset() != 0, "bad offset entry in itable"); initialize_itable_for_interface(ioe->offset(), interf_h, checkconstraints, CHECK); } } // Check that the last entry is empty itableOffsetEntry* ioe = offset_entry(size_offset_table() - 1); guarantee(ioe->interface_klass() == NULL && ioe->offset() == 0, "terminator entry missing"); } inline bool interface_method_needs_itable_index(Method* m) { if (m->is_static()) return false; // e.g., Stream.empty if (m->is_initializer()) return false; // <init> or <clinit> // If an interface redeclares a method from java.lang.Object, // it should already have a vtable index, don't touch it. // e.g., CharSequence.toString (from initialize_vtable) // if (m->has_vtable_index()) return false; // NO! return true; } int klassItable::assign_itable_indices_for_interface(Klass* klass) { // an interface does not have an itable, but its methods need to be numbered if (TraceItables) tty->print_cr("%3d: Initializing itable for interface %s", ++initialize_count, klass->name()->as_C_string()); Array<Method*>* methods = InstanceKlass::cast(klass)->methods(); int nof_methods = methods->length(); int ime_num = 0; for (int i = 0; i < nof_methods; i++) { Method* m = methods->at(i); if (interface_method_needs_itable_index(m)) { assert(!m->is_final_method(), "no final interface methods"); // If m is already assigned a vtable index, do not disturb it. if (TraceItables && Verbose) { ResourceMark rm; const char* sig = (m != NULL) ? m->name_and_sig_as_C_string() : "<NULL>"; if (m->has_vtable_index()) { tty->print("itable index %d for method: %s, flags: ", m->vtable_index(), sig); } else { tty->print("itable index %d for method: %s, flags: ", ime_num, sig); } if (m != NULL) { m->access_flags().print_on(tty); if (m->is_default_method()) { tty->print("default "); } if (m->is_overpass()) { tty->print("overpass"); } } tty->cr(); } if (!m->has_vtable_index()) { assert(m->vtable_index() == Method::pending_itable_index, "set by initialize_vtable"); m->set_itable_index(ime_num); // Progress to next itable entry ime_num++; } } } assert(ime_num == method_count_for_interface(klass), "proper sizing"); return ime_num; } int klassItable::method_count_for_interface(Klass* interf) { assert(interf->oop_is_instance(), "must be"); assert(interf->is_interface(), "must be"); Array<Method*>* methods = InstanceKlass::cast(interf)->methods(); int nof_methods = methods->length(); while (nof_methods > 0) { Method* m = methods->at(nof_methods-1); if (m->has_itable_index()) { int length = m->itable_index() + 1; #ifdef ASSERT while (nof_methods = 0) { m = methods->at(--nof_methods); assert(!m->has_itable_index() || m->itable_index() < length, ""); } #endif //ASSERT return length; // return the rightmost itable index, plus one } nof_methods -= 1; } // no methods have itable indices return 0; } void klassItable::initialize_itable_for_interface(int method_table_offset, KlassHandle interf_h, bool checkconstraints, TRAPS) { Array<Method*>* methods = InstanceKlass::cast(interf_h())->methods(); int nof_methods = methods->length(); HandleMark hm; assert(nof_methods > 0, "at least one method must exist for interface to be in vtable"); Handle interface_loader (THREAD, InstanceKlass::cast(interf_h())->class_loader()); int ime_count = method_count_for_interface(interf_h()); for (int i = 0; i < nof_methods; i++) { Method* m = methods->at(i); methodHandle target; if (m->has_itable_index()) { // This search must match the runtime resolution, i.e. selection search for invokeinterface // to correctly enforce loader constraints for interface method inheritance LinkResolver::lookup_instance_method_in_klasses(target, _klass, m->name(), m->signature(), CHECK); } if (target == NULL || !target->is_public() || target->is_abstract()) { // Entry does not resolve. Leave it empty for AbstractMethodError. if (!(target == NULL) && !target->is_public()) { // Stuff an IllegalAccessError throwing method in there instead. itableOffsetEntry::method_entry(_klass(), method_table_offset)[m->itable_index()]. initialize(Universe::throw_illegal_access_error()); } } else { // Entry did resolve, check loader constraints before initializing // if checkconstraints requested if (checkconstraints) { Handle method_holder_loader (THREAD, target->method_holder()->class_loader()); if (method_holder_loader() != interface_loader()) { ResourceMark rm(THREAD); Symbol* failed_type_symbol = SystemDictionary::check_signature_loaders(m->signature(), method_holder_loader, interface_loader, true, CHECK); if (failed_type_symbol != NULL) { const char* msg = "loader constraint violation in interface " "itable initialization: when resolving method \"%s\" the class" " loader (instance of %s) of the current class, %s, " "and the class loader (instance of %s) for interface " "%s have different Class objects for the type %s " "used in the signature"; char* sig = target()->name_and_sig_as_C_string(); const char* loader1 = SystemDictionary::loader_name(method_holder_loader()); char* current = _klass->name()->as_C_string(); const char* loader2 = SystemDictionary::loader_name(interface_loader()); char* iface = InstanceKlass::cast(interf_h())->name()->as_C_string(); char* failed_type_name = failed_type_symbol->as_C_string(); size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) + strlen(current) + strlen(loader2) + strlen(iface) + strlen(failed_type_name); char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen); jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2, iface, failed_type_name); THROW_MSG(vmSymbols::java_lang_LinkageError(), buf); } } } // ime may have moved during GC so recalculate address int ime_num = m->itable_index(); assert(ime_num < ime_count, "oob"); itableOffsetEntry::method_entry(_klass(), method_table_offset)[ime_num].initialize(target()); if (TraceItables && Verbose) { ResourceMark rm(THREAD); if (target() != NULL) { char* sig = target()->name_and_sig_as_C_string(); tty->print("interface: %s, ime_num: %d, target: %s, method_holder: %s ", interf_h()->internal_name(), ime_num, sig, target()->method_holder()->internal_name()); tty->print("target_method flags: "); target()->access_flags().print_on(tty); if (target()->is_default_method()) { tty->print("default "); } tty->cr(); } } } } } // Update entry for specific Method* void klassItable::initialize_with_method(Method* m) { itableMethodEntry* ime = method_entry(0); for(int i = 0; i < _size_method_table; i++) { if (ime->method() == m) { ime->initialize(m); } ime++; } } #if INCLUDE_JVMTI // search the itable for uses of either obsolete or EMCP methods void klassItable::adjust_method_entries(InstanceKlass* holder, bool * trace_name_printed) { itableMethodEntry* ime = method_entry(0); for (int i = 0; i < _size_method_table; i++, ime++) { Method* old_method = ime->method(); if (old_method == NULL || old_method->method_holder() != holder || !old_method->is_old()) { continue; // skip uninteresting entries } assert(!old_method->is_deleted(), "itable methods may not be deleted"); Method* new_method = holder->method_with_idnum(old_method->orig_method_idnum()); assert(new_method != NULL, "method_with_idnum() should not be NULL"); assert(old_method != new_method, "sanity check"); ime->initialize(new_method); if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) { if (!(*trace_name_printed)) { // RC_TRACE_MESG macro has an embedded ResourceMark RC_TRACE_MESG(("adjust: name=%s", old_method->method_holder()->external_name())); *trace_name_printed = true; } // RC_TRACE macro has an embedded ResourceMark RC_TRACE(0x00200000, ("itable method update: %s(%s)", new_method->name()->as_C_string(), new_method->signature()->as_C_string())); } } } // an itable should never contain old or obsolete methods bool klassItable::check_no_old_or_obsolete_entries() { itableMethodEntry* ime = method_entry(0); for (int i = 0; i < _size_method_table; i++) { Method* m = ime->method(); if (m != NULL && (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) { return false; } ime++; } return true; } void klassItable::dump_itable() { itableMethodEntry* ime = method_entry(0); tty->print_cr("itable dump --"); for (int i = 0; i < _size_method_table; i++) { Method* m = ime->method(); if (m != NULL) { tty->print(" (%5d) ", i); m->access_flags().print_on(tty); if (m->is_default_method()) { tty->print("default "); } tty->print(" -- "); m->print_name(tty); tty->cr(); } ime++; } } #endif // INCLUDE_JVMTI // Setup class InterfaceVisiterClosure : public StackObj { public: virtual void doit(Klass* intf, int method_count) = 0; }; // Visit all interfaces with at least one itable method void visit_all_interfaces(Array<Klass*>* transitive_intf, InterfaceVisiterClosure *blk) { // Handle array argument for(int i = 0; i < transitive_intf->length(); i++) { Klass* intf = transitive_intf->at(i); assert(intf->is_interface(), "sanity check"); // Find no. of itable methods int method_count = 0; // method_count = klassItable::method_count_for_interface(intf); Array<Method*>* methods = InstanceKlass::cast(intf)->methods(); if (methods->length() > 0) { for (int i = methods->length(); --i >= 0; ) { if (interface_method_needs_itable_index(methods->at(i))) { method_count++; } } } // Only count interfaces with at least one method if (method_count > 0) { blk->doit(intf, method_count); } } } class CountInterfacesClosure : public InterfaceVisiterClosure { private: int _nof_methods; int _nof_interfaces; public: CountInterfacesClosure() { _nof_methods = 0; _nof_interfaces = 0; } int nof_methods() const { return _nof_methods; } int nof_interfaces() const { return _nof_interfaces; } void doit(Klass* intf, int method_count) { _nof_methods += method_count; _nof_interfaces++; } }; class SetupItableClosure : public InterfaceVisiterClosure { private: itableOffsetEntry* _offset_entry; itableMethodEntry* _method_entry; address _klass_begin; public: SetupItableClosure(address klass_begin, itableOffsetEntry* offset_entry, itableMethodEntry* method_entry) { _klass_begin = klass_begin; _offset_entry = offset_entry; _method_entry = method_entry; } itableMethodEntry* method_entry() const { return _method_entry; } void doit(Klass* intf, int method_count) { int offset = ((address)_method_entry) - _klass_begin; _offset_entry->initialize(intf, offset); _offset_entry++; _method_entry += method_count; } }; int klassItable::compute_itable_size(Array<Klass*>* transitive_interfaces) { // Count no of interfaces and total number of interface methods CountInterfacesClosure cic; visit_all_interfaces(transitive_interfaces, &cic); // There's alway an extra itable entry so we can null-terminate it. int itable_size = calc_itable_size(cic.nof_interfaces() + 1, cic.nof_methods()); // Statistics update_stats(itable_size * HeapWordSize); return itable_size; } // Fill out offset table and interface klasses into the itable space void klassItable::setup_itable_offset_table(instanceKlassHandle klass) { if (klass->itable_length() == 0) return; assert(!klass->is_interface(), "Should have zero length itable"); // Count no of interfaces and total number of interface methods CountInterfacesClosure cic; visit_all_interfaces(klass->transitive_interfaces(), &cic); int nof_methods = cic.nof_methods(); int nof_interfaces = cic.nof_interfaces(); // Add one extra entry so we can null-terminate the table nof_interfaces++; assert(compute_itable_size(klass->transitive_interfaces()) == calc_itable_size(nof_interfaces, nof_methods), "mismatch calculation of itable size"); // Fill-out offset table itableOffsetEntry* ioe = (itableOffsetEntry*)klass->start_of_itable(); itableMethodEntry* ime = (itableMethodEntry*)(ioe + nof_interfaces); intptr_t* end = klass->end_of_itable(); assert((oop*)(ime + nof_methods) <= (oop*)klass->start_of_nonstatic_oop_maps(), "wrong offset calculation (1)"); assert((oop*)(end) == (oop*)(ime + nof_methods), "wrong offset calculation (2)"); // Visit all interfaces and initialize itable offset table SetupItableClosure sic((address)klass(), ioe, ime); visit_all_interfaces(klass->transitive_interfaces(), &sic); #ifdef ASSERT ime = sic.method_entry(); oop* v = (oop*) klass->end_of_itable(); assert( (oop*)(ime) == v, "wrong offset calculation (2)"); #endif } // inverse to itable_index Method* klassItable::method_for_itable_index(Klass* intf, int itable_index) { assert(InstanceKlass::cast(intf)->is_interface(), "sanity check"); assert(intf->verify_itable_index(itable_index), ""); Array<Method*>* methods = InstanceKlass::cast(intf)->methods(); if (itable_index < 0 || itable_index >= method_count_for_interface(intf)) return NULL; // help caller defend against bad indices int index = itable_index; Method* m = methods->at(index); int index2 = -1; while (!m->has_itable_index() || (index2 = m->itable_index()) != itable_index) { assert(index2 < itable_index, "monotonic"); if (++index == methods->length()) return NULL; m = methods->at(index); } assert(m->itable_index() == itable_index, "correct inverse"); return m; } void klassVtable::verify(outputStream* st, bool forced) { // make sure table is initialized if (!Universe::is_fully_initialized()) return; #ifndef PRODUCT // avoid redundant verifies if (!forced && _verify_count == Universe::verify_count()) return; _verify_count = Universe::verify_count(); #endif oop* end_of_obj = (oop*)_klass() + _klass()->size(); oop* end_of_vtable = (oop *)&table()[_length]; if (end_of_vtable > end_of_obj) { fatal(err_msg("klass %s: klass object too short (vtable extends beyond " "end)", _klass->internal_name())); } for (int i = 0; i < _length; i++) table()[i].verify(this, st); // verify consistency with superKlass vtable Klass* super = _klass->super(); if (super != NULL) { InstanceKlass* sk = InstanceKlass::cast(super); klassVtable* vt = sk->vtable(); for (int i = 0; i < vt->length(); i++) { verify_against(st, vt, i); } } } void klassVtable::verify_against(outputStream* st, klassVtable* vt, int index) { vtableEntry* vte = &vt->table()[index]; if (vte->method()->name() != table()[index].method()->name() || vte->method()->signature() != table()[index].method()->signature()) { fatal("mismatched name/signature of vtable entries"); } } #ifndef PRODUCT void klassVtable::print() { ResourceMark rm; tty->print("klassVtable for klass %s (length %d):\n", _klass->internal_name(), length()); for (int i = 0; i < length(); i++) { table()[i].print(); tty->cr(); } } #endif void vtableEntry::verify(klassVtable* vt, outputStream* st) { NOT_PRODUCT(FlagSetting fs(IgnoreLockingAssertions, true)); assert(method() != NULL, "must have set method"); method()->verify(); // we sub_type, because it could be a miranda method if (!vt->klass()->is_subtype_of(method()->method_holder())) { #ifndef PRODUCT print(); #endif fatal(err_msg("vtableEntry " PTR_FORMAT ": method is from subclass", this)); } } #ifndef PRODUCT void vtableEntry::print() { ResourceMark rm; tty->print("vtableEntry %s: ", method()->name()->as_C_string()); if (Verbose) { tty->print("m %#lx ", (address)method()); } } class VtableStats : AllStatic { public: static int no_klasses; // # classes with vtables static int no_array_klasses; // # array classes static int no_instance_klasses; // # instanceKlasses static int sum_of_vtable_len; // total # of vtable entries static int sum_of_array_vtable_len; // total # of vtable entries in array klasses only static int fixed; // total fixed overhead in bytes static int filler; // overhead caused by filler bytes static int entries; // total bytes consumed by vtable entries static int array_entries; // total bytes consumed by array vtable entries static void do_class(Klass* k) { Klass* kl = k; klassVtable* vt = kl->vtable(); if (vt == NULL) return; no_klasses++; if (kl->oop_is_instance()) { no_instance_klasses++; kl->array_klasses_do(do_class); } if (kl->oop_is_array()) { no_array_klasses++; sum_of_array_vtable_len += vt->length(); } sum_of_vtable_len += vt->length(); } static void compute() { SystemDictionary::classes_do(do_class); fixed = no_klasses * oopSize; // vtable length // filler size is a conservative approximation filler = oopSize * (no_klasses - no_instance_klasses) * (sizeof(InstanceKlass) - sizeof(ArrayKlass) - 1); entries = sizeof(vtableEntry) * sum_of_vtable_len; array_entries = sizeof(vtableEntry) * sum_of_array_vtable_len; } }; int VtableStats::no_klasses = 0; int VtableStats::no_array_klasses = 0; int VtableStats::no_instance_klasses = 0; int VtableStats::sum_of_vtable_len = 0; int VtableStats::sum_of_array_vtable_len = 0; int VtableStats::fixed = 0; int VtableStats::filler = 0; int VtableStats::entries = 0; int VtableStats::array_entries = 0; void klassVtable::print_statistics() { ResourceMark rm; HandleMark hm; VtableStats::compute(); tty->print_cr("vtable statistics:"); tty->print_cr("%6d classes (%d instance, %d array)", VtableStats::no_klasses, VtableStats::no_instance_klasses, VtableStats::no_array_klasses); int total = VtableStats::fixed + VtableStats::filler + VtableStats::entries; tty->print_cr("%6d bytes fixed overhead (refs + vtable object header)", VtableStats::fixed); tty->print_cr("%6d bytes filler overhead", VtableStats::filler); tty->print_cr("%6d bytes for vtable entries (%d for arrays)", VtableStats::entries, VtableStats::array_entries); tty->print_cr("%6d bytes total", total); } int klassItable::_total_classes; // Total no. of classes with itables long klassItable::_total_size; // Total no. of bytes used for itables void klassItable::print_statistics() { tty->print_cr("itable statistics:"); tty->print_cr("%6d classes with itables", _total_classes); tty->print_cr("%6d K uses for itables (average by class: %d bytes)", _total_size / K, _total_size / _total_classes); } #endif // PRODUCT
gpl-2.0
Sirbu/ProjetWeb
src/publication.php
2288
<?php include("fonctions.php"); base_start("publications"); ?> <!-- CONTENU --> <div class="content-container"> <fieldset><legend> <?php $query = "SELECT titre, datePubli, urlpub FROM Publication WHERE idPubli='" .$_GET["idpublication"]."'"; $pub = send_query($query); if( $pub[0]['titre'] == null){ echo "<script> window.location.replace('erreur.php?error=Publication+non+trouvée') </script>"; } echo $pub[0]['titre'] . " publiée le ". $pub[0]['datepubli']; echo "</legend>"; $query = "SELECT nomch, prenomch FROM Publie, Chercheur, Publication " ."WHERE Publie.idch = Chercheur.idch " ."AND Publie.idpubli ='" . $_GET["idpublication"] . "';"; $auteur = send_query($query); echo "<p>Auteur/s : " ."<a href=\"" . "chercheur.php?nomchercheur=" . $auteur[0]['nomch'] . "\">" . $auteur[0]['prenomch'] . " " . $auteur[0]['nomch']."</a>" ."</p>"; if(file_exists($pub[0]['urlpub'])) { echo "<object class=\"pdf\" data=\"". $pub[0]['urlpub'] . "\" >Balise non supportée</object>"; } else { echo "<p>Le fichier est inaccessible !</p>"; } ?> </fieldset> </div> <?php base_end(); ?>
gpl-2.0
laszlo-gazsi/brokenlinkscheck
Database/src/main/java/info/lacyg/brokenlinkscheck/service/GenericHibernateWriteService.java
2039
package info.lacyg.brokenlinkscheck.service; import info.lacyg.brokenlinkscheck.database.IDatabaseWriteService; import info.lacyg.brokenlinkscheck.model.AbstractPersistentObject; import org.hibernate.Session; import org.hibernate.exception.GenericJDBCException; public class GenericHibernateWriteService<T extends AbstractPersistentObject> extends HibernateService implements IDatabaseWriteService<T> { public void create(T... objects) { synchronized (MUTEX) { Object obj = new Object(); try { Session session = getSessionFactory().getCurrentSession(); session.beginTransaction(); for (Object object : objects) { obj = object; session.saveOrUpdate(object); } session.getTransaction().commit(); } catch (Exception ex) { ex.printStackTrace(); } } } public void update(T... objects) { synchronized (MUTEX) { Session session = getSessionFactory().getCurrentSession(); session.beginTransaction(); for (Object object : objects) { session.saveOrUpdate(object); } session.getTransaction().commit(); } } public void delete(T... objects) { synchronized (MUTEX) { Session session = getSessionFactory().getCurrentSession(); session.beginTransaction(); for (Object object : objects) { session.delete(object); } session.getTransaction().commit(); } } public void executeSqlQuery(String sql) { synchronized (MUTEX) { Session session = getSessionFactory().getCurrentSession(); session.beginTransaction(); session.createSQLQuery(sql).executeUpdate(); } } }
gpl-2.0
bbqbailey/geeksHome
geeksHomeApp/testing-pycharm.py
213
__author__ = 'superben' import subprocess p = subprocess.Popen("date", stdout=subprocess.PIPE, shell=True) (output, err) = p.communicate() print("Today is", output) subprocess.call(["ls", "-l", "/home/superben"])
gpl-2.0
BenjaminMoore/JPhysics
JPhysics/Unity/Test.cs
132
namespace JPhysics.Unity { using UnityEngine; //TEST CLASS FOR SOMETHING class Test : MonoBehaviour { } }
gpl-2.0
luo2chun1lei2/think
src/native/Graphviz.cpp
2351
#include <native/Graphviz.hpp> #include <vector> #include <misc/Misc.hpp> using namespace std; Graphviz::Graphviz(const string name, Graphviz::Option option, Graphviz::Type type) : option(option) , type(type) { } Graphviz::~Graphviz() { } void Graphviz::set_output_filepath(const std::string path) { output_file_path = path; } std::string Graphviz::get_output_filepath() { return output_file_path; } bool Graphviz::prepare_graphviz() { /* set up a graphviz context */ gvc = gvContext(); // 创建一个有向图 Agdirected g = agopen("g", Agdirected, 0); return true; } void Graphviz::finish_graphviz() { // 设定layout是格式的,可以是“circo dot fdp neato nop nop1 nop2 osage // patchwork sfdp twopi”。 // dot: 是按照层级来安排节点 // circo: 是一个中心,显然其他的节点向四周扩散的方法。 // neato: 会重叠,和circo有点像。 // ... if (type == TYPE_LIST) { // LIST时,横屏显示。 agsafeset(g, "rankdir", "LR", ""); } gvLayout(gvc, g, "dot"); /* Write the graph to file, svg、plain是导出的格式。 */ if (option == GRAPH_TEXT) { gvRenderFilename(gvc, g, "plain", this->output_file_path.c_str()); } else { // GRAPH_SVG : 缺省! gvRenderFilename(gvc, g, "svg", this->output_file_path.c_str()); } /* Free layout data */ gvFreeLayout(gvc, g); // TODO: 单独运行时,发现有重复释放资源的问题,将这个注释,就没有了。 /* Free graph structures */ agclose(g); /* close output file, free context */ gvFreeContext(gvc); } Agnode_t *Graphviz::add_node(const std::string str, bool is_node) { Agnode_t *n; n = agnode(g, NULL, 1); // 1 是固定的。 agsafeset(n, "label", (char *)str.c_str(), ""); /* 设置节点的属性 */ if (is_node) { agsafeset(n, "color", "blue", ""); agsafeset(n, "shape", "box", ""); } else { agsafeset(n, "color", "green", ""); agsafeset(n, "shape", "diamond", ""); } return n; } Agedge_t *Graphviz::add_edge(const std::string str, Agnode_t *f, Agnode_t *t) { Agedge_t *e = agedge(g, f, t, NULL, 1); agsafeset(e, "label", (char *)str.c_str(), ""); agsafeset(e, "color", "black", ""); return e; }
gpl-2.0
johnbeard/kicad-git
pcbnew/dragsegm.cpp
12312
/** * @file dragsegm.cpp * @brief Classes to find track segments connected to a pad or a module * for drag commands */ /* * This program source code file is part of KiCad, a free EDA CAD application. * * Copyright (C) 2004-2012 Jean-Pierre Charras, jp.charras at wanadoo.fr * Copyright (C) 1992-2012 KiCad Developers, see change_log.txt for contributors. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, you may find one here: * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * or you may search the http://www.gnu.org website for the version 2 license, * or you may write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ #include <fctsys.h> #include <common.h> #include <trigo.h> #include <gr_basic.h> #include <class_drawpanel.h> #include <wxBasePcbFrame.h> #include <macros.h> #include <drag.h> #include <pcbnew.h> #include <class_module.h> #include <class_board.h> #include <connect.h> /* a list of DRAG_SEGM_PICKER items used to move or drag tracks */ std::vector<DRAG_SEGM_PICKER> g_DragSegmentList; /* helper class to handle a list of track segments to drag or move */ DRAG_SEGM_PICKER::DRAG_SEGM_PICKER( TRACK* aTrack ) { m_Track = aTrack; m_startInitialValue = m_Track->GetStart(); m_endInitialValue = m_Track->GetEnd(); m_Pad_Start = m_Track->GetState( START_ON_PAD ) ? (D_PAD*)m_Track->start : NULL; m_Pad_End = m_Track->GetState( END_ON_PAD ) ? (D_PAD*)m_Track->end : NULL; m_Flag = 0; m_RotationOffset = 0.0; m_Flipped = false; } void DRAG_SEGM_PICKER::SetAuxParameters() { MODULE* module = NULL; if( m_Pad_Start ) { module = (MODULE *) m_Pad_Start->GetParent(); m_PadStartOffset = m_Track->GetStart() - m_Pad_Start->GetPosition(); } if( m_Pad_End ) { if( module == NULL ) module = (MODULE *) m_Pad_End->GetParent(); m_PadEndOffset = m_Track->GetEnd() - m_Pad_End->GetPosition(); } if( module ) { m_Flipped = module->IsFlipped(); m_RotationOffset = module->GetOrientation(); } } void DRAG_SEGM_PICKER::SetTrackEndsCoordinates( wxPoint aOffset ) { // the track start position is the pad position + m_PadStartOffset // however m_PadStartOffset is known for the initial rotation/flip // this is also true for track end position and m_PadEndOffset // Therefore, because rotation/flipping is allowed during a drag // and move module, we should recalculate the pad offset, // depending on the current orientation/flip state of the module // relative to its initial orientation. // (although most of time, offset is 0,0) double curr_rot_offset = m_RotationOffset; MODULE* module = NULL; bool flip = false; if( m_Pad_Start ) module = (MODULE *) m_Pad_Start->GetParent(); if( module == NULL && m_Pad_End ) module = (MODULE *) m_Pad_End->GetParent(); if( module ) { flip = m_Flipped != module->IsFlipped(); curr_rot_offset = module->GetOrientation() - m_RotationOffset; if( flip ) // when flipping, module orientation is negated curr_rot_offset = - module->GetOrientation() - m_RotationOffset; } if( m_Pad_Start ) { wxPoint padoffset = m_PadStartOffset; if( curr_rot_offset != 0.0 ) RotatePoint(&padoffset, curr_rot_offset); if( flip ) NEGATE( padoffset.y ); m_Track->SetStart( m_Pad_Start->GetPosition() - aOffset + padoffset ); } if( m_Pad_End ) { wxPoint padoffset = m_PadEndOffset; if( curr_rot_offset != 0.0 ) RotatePoint( &padoffset, curr_rot_offset ); if( flip ) NEGATE( padoffset.y ); m_Track->SetEnd( m_Pad_End->GetPosition() - aOffset + padoffset ); } } // A sort function needed to build ordered pads lists extern bool sortPadsByXthenYCoord( D_PAD* const & ref, D_PAD* const & comp ); void DRAG_LIST::BuildDragListe( MODULE* aModule ) { m_Pad = NULL; m_Module = aModule; // Build connections info CONNECTIONS connections( m_Brd ); std::vector<D_PAD*>&padList = connections.GetPadsList(); for( D_PAD* pad = aModule->Pads(); pad; pad = pad->Next() ) padList.push_back( pad ); sort( padList.begin(), padList.end(), sortPadsByXthenYCoord ); fillList( connections ); } void DRAG_LIST::BuildDragListe( D_PAD* aPad ) { m_Pad = aPad; m_Module = NULL; // Build connections info CONNECTIONS connections( m_Brd ); std::vector<D_PAD*>&padList = connections.GetPadsList(); padList.push_back( aPad ); fillList( connections ); } // A helper function to sort track list per tracks bool sort_tracklist( const DRAG_SEGM_PICKER& ref, const DRAG_SEGM_PICKER& tst ) { return ref.m_Track < tst.m_Track; } void DRAG_LIST::fillList( CONNECTIONS& aConnections ) { aConnections.BuildTracksCandidatesList( m_Brd->m_Track, NULL); // Build connections info tracks to pads // Rebuild pads to track info only) aConnections.SearchTracksConnectedToPads( false, true ); std::vector<D_PAD*>padList = aConnections.GetPadsList(); // clear flags and variables of selected tracks for( unsigned ii = 0; ii < padList.size(); ii++ ) { D_PAD * pad = padList[ii]; // store track connected to the pad for( unsigned jj = 0; jj < pad->m_TracksConnected.size(); jj++ ) { TRACK * track = pad->m_TracksConnected[jj]; track->start = NULL; track->end = NULL; track->SetState( START_ON_PAD|END_ON_PAD|BUSY, false ); } } // store tracks connected to pads for( unsigned ii = 0; ii < padList.size(); ii++ ) { D_PAD * pad = padList[ii]; // store track connected to the pad for( unsigned jj = 0; jj < pad->m_TracksConnected.size(); jj++ ) { TRACK * track = pad->m_TracksConnected[jj]; if( pad->HitTest( track->GetStart() ) ) { track->start = pad; track->SetState( START_ON_PAD, true ); } if( pad->HitTest( track->GetEnd() ) ) { track->end = pad; track->SetState( END_ON_PAD, true ); } DRAG_SEGM_PICKER wrapper( track ); m_DragList.push_back( wrapper ); } } // remove duplicate in m_DragList: // a track can be stored more than once if connected to 2 overlapping pads, or // each track end connected to 2 moving pads // to avoid artifact in draw function, items should be not duplicated // However, there is not a lot of items to be removed, so there ir no optimization. // sort the drag list by track pointers sort( m_DragList.begin(), m_DragList.end(), sort_tracklist ); // Explore the list, merge duplicates for( int ii = 0; ii < (int)m_DragList.size()-1; ii++ ) { int jj = ii+1; if( m_DragList[ii].m_Track != m_DragList[jj].m_Track ) continue; // duplicate found: merge info and remove duplicate if( m_DragList[ii].m_Pad_Start == NULL ) m_DragList[ii].m_Pad_Start = m_DragList[jj].m_Pad_Start; if( m_DragList[ii].m_Pad_End == NULL ) m_DragList[ii].m_Pad_End = m_DragList[jj].m_Pad_End; m_DragList.erase( m_DragList.begin() + jj ); ii--; } // Initialize pad offsets and other params for( unsigned ii = 0; ii < m_DragList.size(); ii++ ) m_DragList[ii].SetAuxParameters(); // Copy the list in global list g_DragSegmentList = m_DragList; } void DRAG_LIST::ClearList() { for( unsigned ii = 0; ii < m_DragList.size(); ii++ ) m_DragList[ii].m_Track->ClearFlags(); m_DragList.clear(); m_Module = NULL; m_Pad = NULL; } // Redraw the list of segments stored in g_DragSegmentList, while moving a footprint void DrawSegmentWhileMovingFootprint( EDA_DRAW_PANEL* panel, wxDC* DC ) { for( unsigned ii = 0; ii < g_DragSegmentList.size(); ii++ ) { TRACK* track = g_DragSegmentList[ii].m_Track; #ifndef USE_WX_OVERLAY track->Draw( panel, DC, GR_XOR ); // erase from screen at old position #endif g_DragSegmentList[ii].SetTrackEndsCoordinates( g_Offset_Module ); track->Draw( panel, DC, GR_XOR ); } } void EraseDragList() { for( unsigned ii = 0; ii < g_DragSegmentList.size(); ii++ ) g_DragSegmentList[ii].m_Track->ClearFlags(); g_DragSegmentList.clear(); } void AddSegmentToDragList( int flag, TRACK* aTrack ) { DRAG_SEGM_PICKER wrapper( aTrack ); if( flag & STARTPOINT ) wrapper.m_Flag |= 1; if( flag & ENDPOINT ) wrapper.m_Flag |= 2; if( flag & STARTPOINT ) aTrack->SetFlags( STARTPOINT ); if( flag & ENDPOINT ) aTrack->SetFlags( ENDPOINT ); g_DragSegmentList.push_back( wrapper ); } void Collect_TrackSegmentsToDrag( BOARD* aPcb, const wxPoint& aRefPos, LAYER_MSK aLayerMask, int aNetCode, int aMaxDist ) { TRACK* track = aPcb->m_Track->GetStartNetCode( aNetCode ); for( ; track; track = track->Next() ) { if( track->GetNetCode() != aNetCode ) // not the same netcode: all candidates tested break; if( ( aLayerMask & track->GetLayerMask() ) == 0 ) continue; // Cannot be connected, not on the same layer if( track->IsDragging() ) continue; // already put in list STATUS_FLAGS flag = 0; int maxdist = std::max( aMaxDist, track->GetWidth() / 2 ); if( (track->GetFlags() & STARTPOINT) == 0 ) { wxPoint delta = track->GetStart() - aRefPos; if( std::abs( delta.x ) <= maxdist && std::abs( delta.y ) <= maxdist ) { int dist = KiROUND( EuclideanNorm( delta ) ); if( dist <= maxdist ) { flag |= STARTPOINT; if( track->Type() == PCB_VIA_T ) flag |= ENDPOINT; } } } if( (track->GetFlags() & ENDPOINT) == 0 ) { wxPoint delta = track->GetEnd() - aRefPos; if( std::abs( delta.x ) <= maxdist && std::abs( delta.y ) <= maxdist ) { int dist = KiROUND( EuclideanNorm( delta ) ); if( dist <= maxdist ) flag |= ENDPOINT; } } // Note: vias will be flagged with both STARTPOINT and ENDPOINT // and must not be entered twice. if( flag ) { AddSegmentToDragList( flag, track ); // If a connected via is found at location aRefPos, // collect also tracks connected by this via. if( track->Type() == PCB_VIA_T ) Collect_TrackSegmentsToDrag( aPcb, aRefPos, track->GetLayerMask(), aNetCode, track->GetWidth() / 2 ); } } } void UndrawAndMarkSegmentsToDrag( EDA_DRAW_PANEL* aCanvas, wxDC* aDC ) { for( unsigned ii = 0; ii < g_DragSegmentList.size(); ii++ ) { TRACK* track = g_DragSegmentList[ii].m_Track; track->Draw( aCanvas, aDC, GR_XOR ); track->SetState( IN_EDIT, false ); track->SetFlags( IS_DRAGGED ); if( g_DragSegmentList[ii].m_Flag & STARTPOINT ) track->SetFlags( STARTPOINT ); if( g_DragSegmentList[ii].m_Flag & ENDPOINT ) track->SetFlags( ENDPOINT ); track->Draw( aCanvas, aDC, GR_XOR ); } }
gpl-2.0
Thunnissen/ODataQuery-PHP
src/ODataCount.php
608
<?php /** * Created by PhpStorm. * User: alexboyce * Date: 12/21/14 * Time: 3:57 PM */ namespace ODataQuery; class ODataCount implements ODataQueryOptionInterface { protected $property; public function __construct($property = NULL) { $this->property($property); } public function property($property = NULL) { if (isset($property)) { $this->property = $property; return $this; } return $this->property; } public function __toString() { $property = $this->property(); return "$property/\$count"; } }
gpl-2.0
piratskul/MyAwesomeDrupal
sites/default/files/php/twig/590e4b87c5da1_form.html.twig_VjurTDgEkPIRJ-KdA0zn7ApAT/7Fp-mEWq2ams-lHEoRHF7h4jODECL3sTa_Hv-oYlgVk.php
2595
<?php /* core/themes/classy/templates/form/form.html.twig */ class __TwigTemplate_4d9f7fb46a30a09a1493a83bf55b525e60b9d0f46f4789d9b55fd7ca9b2e7b39 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 13 echo "<form"; echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["attributes"]) ? $context["attributes"] : null), "html", null, true)); echo "> "; // line 14 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["children"]) ? $context["children"] : null), "html", null, true)); echo " </form> "; } public function getTemplateName() { return "core/themes/classy/templates/form/form.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 48 => 14, 43 => 13,); } public function getSource() { return "{# /** * @file * Theme override for a 'form' element. * * Available variables * - attributes: A list of HTML attributes for the wrapper element. * - children: The child elements of the form. * * @see template_preprocess_form() */ #} <form{{ attributes }}> {{ children }} </form> "; } }
gpl-2.0
fredtoulouse/ScoreCard
js/consult.js
7563
// GOLF SCore Card webapp // 2013-06-19 // Copyright (c) 2013, FBM // Released under the GPL license v2 // http://www.gnu.org/licenses/gpl-2.0.html //Manage the history and display it //ToDo split display and data var selected; var myHistoryScore= new oldScore(); var myChoosenScore; var myInfoScoreDisplay; // Array Remove - By John Resig (MIT Licensed) Array.prototype.remove = function(from, to) { var rest = this.slice((to || from) + 1 || this.length); this.length = from < 0 ? this.length + from : from; return this.push.apply(this, rest); }; //Classe that store the all score from the player in the local storage filessystem. function oldScore() { var listScore; this.getListScore = function () { var data=localStorage["scorecard_history"]; if (data != null) { this.listScore=JSON.parse(data); } else { this.listScore=[]; } ScoreCardLog ("The History "+data); return this.listScore; } this.addScore = function (score, par) { var myConfiguration = Configuration.getInstance(); var cpt=0; var retry=1; var found=0; var tmpnameGolf=score.nameGolf; while (retry == 1) { this.listScore.forEach(function(item, i) { if ((score.date == item[0]) && (tmpnameGolf == item[1])) { cpt=cpt+1; tmpnameGolf=score.nameGolf+"--"+cpt; found=1; } }) if (found==1) { retry=1; found=0; } else { retry=0; } } this.listScore.push([score.date, score.nameGolf, myConfiguration.playerName, score.weather, score.note, score.typeGolf, score.arrayResult,score.arrayDistance,par]) var data=JSON.stringify (this.listScore); ScoreCardLog ("\n------------NEW HISTORY \n"+data); localStorage["scorecard_history"]=data; } this.suppressScore = function (index) { ScoreCardLog("remove " + this.listScore[index][0]); this.listScore.remove(index); var data=JSON.stringify (this.listScore); ScoreCardLog ("OLD HISTORY "+data); localStorage["scorecard_history"]=data; } try { var data=localStorage["scorecard_history"]; if(typeof(data)=='undefined'){ this.listScore=[]; } else { this.listScore=JSON.parse(data); } } catch(e) { ScoreCardLog ("Error on store history "+e.toString()); } } //Genere l'affichage selon la conf Historique this.generateList = function() { myHistory=myHistoryScore.getListScore(); var cache_UL=$('#listScoreDiv ul'); cache_UL.empty(); var newHtml=""; var cpt=0; var reg=/\-.*/ var year; //Garante that Score displayed are from the more recent to the older myHistory.sort().reverse().forEach(function(item, i) { if (i ==0) { year=item[0].replace(reg,""); newHtml+='<li data-role="list-divider">'+ year +'</li>'; } if (item[0].replace(reg,"") != year) { year=item[0].replace(reg,""); newHtml+='<li data-role="list-divider">'+ year +'</li>'; } newHtml+='<li><a href="#mypanel">'+ item[0] +' '+ item[1] +'</a> <div style="visibility:hidden;">=='+cpt+'</div></li>'; cpt++; }) cache_UL.append(newHtml); cache_UL.children('li').bind('touchstart mousedown', function(e) { selected=$(this)[0].textContent; selectedId = parseInt(selected.replace(/.*==/, "")); ScoreCardLog("Selected index " + selectedId); myChoosenScore=myHistory[selectedId]; myChoosenIndex=selectedId updateInfoScore(myChoosenScore, 0); }) //Refresh the view $('#listScore').listview('refresh'); } this.updateInfoScore = function(item, id) { if (item != null) { $('#infoScore'+id)[0].innerHTML= "<h2>"+item[1]+"</h2><h3>"+item[0]+"<br/></h3>"+jQuery.i18n.prop("msg_player_name")+":"+item[2]+"<br/>"+jQuery.i18n.prop("msg_climat")+":"; $('#infoScore'+id)[0].innerHTML=$('#infoScore'+id)[0].innerHTML+"<IMG class='meteo' SRC='img/"+item[3]+".png' ALT='"+jQuery.i18n.prop(item[3])+"'><br/>" $('#infoScore'+id)[0].innerHTML= $('#infoScore'+id)[0].innerHTML+"<div style='font-size:90%;'>"+jQuery.i18n.prop("msg_result_score")+"&nbsp;:&nbsp;"+Score.getInstance().computeAnotherResult(item[6])+"<br/></div>"; $('#infoScore'+id)[0].innerHTML= $('#infoScore'+id)[0].innerHTML+"<div style='font-size:65%;'>"+jQuery.i18n.prop("msg_golf_note")+":"+item[4]+"<br/></div>"; } } this.table9 = function(score, par) { par.forEach(function(item, i) { if ( i<9 ) { $('#info_score_dis'+i)[0].innerHTML=score[i]; $('#info_t'+i).addClass("yet"); if (item != "ND") { $('#info_score_par'+i)[0].innerHTML="Par<br>"+item; if (par[i]==0) { $('#info_t'+i).css({ 'border': '5px solid #c8d0d6'}); } else if ( score[i] < (item -1) ) { //Eagles //document.getElementById('tt').style.border = '4em solid black'; $('#info_t'+i).css({ 'border': '5px solid #20fc0c'}); } else if ( score[i] == (item -1) ) { //Birdie $('#info_t'+i).css({ 'border': '5px solid #47c639'}); } else if ( score[i] == (item) ) { //Par $('#info_t'+i).css({ 'border': '5px solid #6481e5'}); } else if ( score[i] == (item +1) ) { //Bogey $('#info_t'+i).css({ 'border': '5px solid #e1a42d'}); } else if ( score[i] > (item +1) ) { //More $('#info_t'+i).css({ 'border': '5px solid #d61c0f'}); } } else { $('#info_t'+i).css({ 'border': '5px solid white'}); } } }); } $( '#confirm_supress' ).live( 'pageshow',function(event){ updateInfoScore(myChoosenScore, 3); Cache.getInstance().CACHE_SC_CONFIRMSUPRESSSCORE.on('click',function(event, ui){ //other code ScoreCardLog("Supress " + myChoosenScore[0] +' ' +myChoosenScore[1]); myHistoryScore.suppressScore(myChoosenIndex); }); }) $( '#plus_info' ).live( 'pagebeforeshow',function(event){ if (myChoosenScore != null) { updateInfoScore(myChoosenScore, 1); myInfoScoreDisplay = new ScoreDisplay(); myInfoScoreDisplay.init("#info_carte_score", "#info_prev", "#info_next"); //display the 9 holes, ToDo support for 18 holes table9(myChoosenScore[6], myChoosenScore[8]); Cache.getInstance().CACHE_SC_INFO_SEND_EMAIL.on('click',function(event, ui){ myCurrentScore=new Score(); ScoreCardLog("MAIL !!!!"); myCurrentScore.typeGolf=myChoosenScore[5]; //9 ou 18 trou myCurrentScore.arrayResult=myChoosenScore[6]; myCurrentScore.nameGolf=myChoosenScore[1]; myCurrentScore.note=myChoosenScore[4]; myCurrentScore.weather=myChoosenScore[3]; myCurrentScore.date=myChoosenScore[0]; myCurrentScore.arrayDistance=myChoosenScore[7]; myMail = new PushData(); myMail.mail(myCurrentScore, myChoosenScore[8]); }); } }) $( '#plus_info' ).live( 'pageshow',function(event){ //FBM a voir si on doit le deplacer sur l'init ou le laisser sur pageshow if (myInfoScoreDisplay != null) { myInfoScoreDisplay.run(); } //myInfoScoreDisplay.fixArrow(); }) $( '#consult' ).live( 'pageshow',function(event){ ScoreCardLog ("Consult appear -> load the score stored on Local"); generateList(); }) //Init the cache $( '#consult' ).live( 'pageinit',function(event){ //Init jquery-cache Cache.getInstance().init("consult.js"); }); //Init the cache $( '#plus_info' ).live( 'pageinit',function(event){ //Init jquery-cache Cache.getInstance().init("plus_info"); }); //Init the cache $( '#confirm_supress' ).live( 'pageinit',function(event){ //Init jquery-cache Cache.getInstance().init("confirm_supress"); });
gpl-2.0
nidalhajaj/ac
plugins/cck_field/jform_user/jform_user.php
4859
<?php /** * @version SEBLOD 2.x Core * @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder) * @url http://www.seblod.com * @editor Octopoos - www.octopoos.com * @copyright Copyright (C) 2012 SEBLOD. All Rights Reserved. * @license GNU General Public License version 2 or later; see _LICENSE.php **/ // No Direct Access defined( '_JEXEC' ) or die; // Plugin class plgCCK_FieldJForm_User extends JCckPluginField { protected static $type = 'jform_user'; protected static $type2 = 'user'; protected static $path; // -------- -------- -------- -------- -------- -------- -------- -------- // Construct // onCCK_FieldConstruct public function onCCK_FieldConstruct( $type, &$data = array() ) { if ( self::$type != $type ) { return; } parent::g_onCCK_FieldConstruct( $data ); } // -------- -------- -------- -------- -------- -------- -------- -------- // Prepare // onCCK_FieldPrepareContent public function onCCK_FieldPrepareContent( &$field, $value = '', &$config = array() ) { if ( self::$type != $field->type ) { return; } parent::g_onCCK_FieldPrepareContent( $field, $config ); $field->value = $value; $field->text = JCckDatabase::loadResult( 'SELECT name FROM #__users WHERE id = '.(int)$value ); $field->typo_target = 'text'; } // onCCK_FieldPrepareForm public function onCCK_FieldPrepareForm( &$field, $value = '', &$config = array(), $inherit = array(), $return = false ) { if ( self::$type != $field->type ) { return; } self::$path = parent::g_getPath( self::$type.'/' ); parent::g_onCCK_FieldPrepareForm( $field, $config ); // Init if ( count( $inherit ) ) { $id = ( @$inherit['id'] != '' ) ? $inherit['id'] : $field->name; $name = ( @$inherit['name'] != '' ) ? $inherit['name'] : $field->name; } else { $id = $field->name; $name = $field->name; } $value = ( $value !== '' ) ? $value : $field->defaultvalue; $userid = JFactory::getUser()->get( 'id' ); if ( ( ! $value && $userid && $field->storage_field != 'modified_by' ) || ( $config['pk'] > 0 && $field->storage_field == 'modified_by' ) ) { $value = $userid; } // Validate $validate = ''; if ( $config['doValidation'] > 1 ) { plgCCK_Field_ValidationRequired::onCCK_Field_ValidationPrepareForm( $field, $id, $config ); $validate = ( count( $field->validate ) ) ? ' validate['.implode( ',', $field->validate ).']' : ''; } // Prepare $class = 'inputbox text'.$validate.' '.$field->css; $xml = ' <form> <field type="'.self::$type2.'" name="'.$name.'" id="'.$id.'" label="'.htmlspecialchars( $field->label ).'" class="'.$class.'" size="18" /> </form> '; $form = JForm::getInstance( $id, $xml ); $form = $form->getInput( $name, '', $value ); // Set if ( ! $field->variation ) { $field->form = $form; if ( $field->script ) { parent::g_addScriptDeclaration( $field->script ); } } else { parent::g_getDisplayVariation( $field, $field->variation, $value, $value, $form, $id, $name, '<input' ); } $field->value = $value; // Return if ( $return === true ) { return $field; } } // onCCK_FieldPrepareSearch public function onCCK_FieldPrepareSearch( &$field, $value = '', &$config = array(), $inherit = array(), $return = false ) { if ( self::$type != $field->type ) { return; } // Prepare self::onCCK_FieldPrepareForm( $field, $value, $config, $inherit, $return ); // Return if ( $return === true ) { return $field; } } // onCCK_FieldPrepareStore public function onCCK_FieldPrepareStore( &$field, $value = '', &$config = array(), $inherit = array(), $return = false ) { if ( self::$type != $field->type ) { return; } // Init if ( count( $inherit ) ) { $name = ( @$inherit['name'] != '' ) ? $inherit['name'] : $field->name; } else { $name = $field->name; } // Validate $value = ( $value > 0 ) ? $value : ''; parent::g_onCCK_FieldPrepareStore_Validation( $field, $name, $value, $config ); // Set or Return if ( $return === true ) { return $value; } $field->value = $value; parent::g_onCCK_FieldPrepareStore( $field, $name, $value, $config ); } // -------- -------- -------- -------- -------- -------- -------- -------- // Render // onCCK_FieldRenderContent public static function onCCK_FieldRenderContent( $field, &$config = array() ) { return parent::g_onCCK_FieldRenderContent( $field, 'text' ); } // onCCK_FieldRenderForm public static function onCCK_FieldRenderForm( $field, &$config = array() ) { return parent::g_onCCK_FieldRenderForm( $field ); } } ?>
gpl-2.0
pxai/cordova-core-api
www/js/vibration.js
2703
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ var app = { // Application Constructor initialize: function() { this.bindEvents(); }, // Bind Event Listeners // // Bind any events that are required on startup. Common events are: // 'load', 'deviceready', 'offline', and 'online'. bindEvents: function() { document.addEventListener('deviceready', this.onDeviceReady, false); }, // deviceready Event Handler // // The scope of 'this' is the event. In order to call the 'receivedEvent' // function, we must explicitly call 'app.receivedEvent(...);' onDeviceReady: function() { app.receivedEvent('deviceready'); // Vibrate 1 second navigator.vibrate(1000); $('#vibrateOnce').click(function () { // Vibrate 2 seconds navigator.vibrate([2000]); var msg = 'Vibrating 2sec.'; $('#status').html(msg); console.log(msg); }); $('#vibratePaused').click(function () { // Vibrate three times with pauses navigator.vibrate([2000,1000,1000,500,3000]); var msg = 'Vibrating 2sec., 1sec pause,..'; $('#status').html(msg); console.log(msg); }); $('#cancelVibration').click(function () { // Cancel vibration navigator.vibrate([0]); // Other options // navigator.vibrate([]); // navigator.vibrate(0); // navigator.notification.cancelVibration(); var msg = 'Cancel vibration'; $('#status').html(msg); console.log(msg); }); }, // Update DOM on a Received Event receivedEvent: function(id) { var parentElement = document.getElementById(id); var listeningElement = parentElement.querySelector('.listening'); var receivedElement = parentElement.querySelector('.received'); listeningElement.setAttribute('style', 'display:none;'); receivedElement.setAttribute('style', 'display:block;'); console.log('Received Event: ' + id); } }; app.initialize();
gpl-2.0
teamfx/openjfx-8u-dev-rt
modules/web/src/main/native/Source/ThirdParty/icu/source/i18n/nfrs.cpp
32392
// © 2016 and later: Unicode, Inc. and others. // License & terms of use: http://www.unicode.org/copyright.html /* ****************************************************************************** * Copyright (C) 1997-2015, International Business Machines * Corporation and others. All Rights Reserved. ****************************************************************************** * file name: nfrs.cpp * encoding: UTF-8 * tab size: 8 (not used) * indentation:4 * * Modification history * Date Name Comments * 10/11/2001 Doug Ported from ICU4J */ #include "nfrs.h" #if U_HAVE_RBNF #include "unicode/uchar.h" #include "nfrule.h" #include "nfrlist.h" #include "patternprops.h" #include "putilimp.h" #ifdef RBNF_DEBUG #include "cmemory.h" #endif enum { /** -x */ NEGATIVE_RULE_INDEX = 0, /** x.x */ IMPROPER_FRACTION_RULE_INDEX = 1, /** 0.x */ PROPER_FRACTION_RULE_INDEX = 2, /** x.0 */ MASTER_RULE_INDEX = 3, /** Inf */ INFINITY_RULE_INDEX = 4, /** NaN */ NAN_RULE_INDEX = 5, NON_NUMERICAL_RULE_LENGTH = 6 }; U_NAMESPACE_BEGIN #if 0 // euclid's algorithm works with doubles // note, doubles only get us up to one quadrillion or so, which // isn't as much range as we get with longs. We probably still // want either 64-bit math, or BigInteger. static int64_t util_lcm(int64_t x, int64_t y) { x.abs(); y.abs(); if (x == 0 || y == 0) { return 0; } else { do { if (x < y) { int64_t t = x; x = y; y = t; } x -= y * (x/y); } while (x != 0); return y; } } #else /** * Calculates the least common multiple of x and y. */ static int64_t util_lcm(int64_t x, int64_t y) { // binary gcd algorithm from Knuth, "The Art of Computer Programming," // vol. 2, 1st ed., pp. 298-299 int64_t x1 = x; int64_t y1 = y; int p2 = 0; while ((x1 & 1) == 0 && (y1 & 1) == 0) { ++p2; x1 >>= 1; y1 >>= 1; } int64_t t; if ((x1 & 1) == 1) { t = -y1; } else { t = x1; } while (t != 0) { while ((t & 1) == 0) { t = t >> 1; } if (t > 0) { x1 = t; } else { y1 = -t; } t = x1 - y1; } int64_t gcd = x1 << p2; // x * y == gcd(x, y) * lcm(x, y) return x / gcd * y; } #endif static const UChar gPercent = 0x0025; static const UChar gColon = 0x003a; static const UChar gSemicolon = 0x003b; static const UChar gLineFeed = 0x000a; static const UChar gPercentPercent[] = { 0x25, 0x25, 0 }; /* "%%" */ static const UChar gNoparse[] = { 0x40, 0x6E, 0x6F, 0x70, 0x61, 0x72, 0x73, 0x65, 0 }; /* "@noparse" */ NFRuleSet::NFRuleSet(RuleBasedNumberFormat *_owner, UnicodeString* descriptions, int32_t index, UErrorCode& status) : name() , rules(0) , owner(_owner) , fractionRules() , fIsFractionRuleSet(FALSE) , fIsPublic(FALSE) , fIsParseable(TRUE) { for (int32_t i = 0; i < NON_NUMERICAL_RULE_LENGTH; ++i) { nonNumericalRules[i] = NULL; } if (U_FAILURE(status)) { return; } UnicodeString& description = descriptions[index]; // !!! make sure index is valid if (description.length() == 0) { // throw new IllegalArgumentException("Empty rule set description"); status = U_PARSE_ERROR; return; } // if the description begins with a rule set name (the rule set // name can be omitted in formatter descriptions that consist // of only one rule set), copy it out into our "name" member // and delete it from the description if (description.charAt(0) == gPercent) { int32_t pos = description.indexOf(gColon); if (pos == -1) { // throw new IllegalArgumentException("Rule set name doesn't end in colon"); status = U_PARSE_ERROR; } else { name.setTo(description, 0, pos); while (pos < description.length() && PatternProps::isWhiteSpace(description.charAt(++pos))) { } description.remove(0, pos); } } else { name.setTo(UNICODE_STRING_SIMPLE("%default")); } if (description.length() == 0) { // throw new IllegalArgumentException("Empty rule set description"); status = U_PARSE_ERROR; } fIsPublic = name.indexOf(gPercentPercent, 2, 0) != 0; if ( name.endsWith(gNoparse,8) ) { fIsParseable = FALSE; name.truncate(name.length()-8); // remove the @noparse from the name } // all of the other members of NFRuleSet are initialized // by parseRules() } void NFRuleSet::parseRules(UnicodeString& description, UErrorCode& status) { // start by creating a Vector whose elements are Strings containing // the descriptions of the rules (one rule per element). The rules // are separated by semicolons (there's no escape facility: ALL // semicolons are rule delimiters) if (U_FAILURE(status)) { return; } // ensure we are starting with an empty rule list rules.deleteAll(); // dlf - the original code kept a separate description array for no reason, // so I got rid of it. The loop was too complex so I simplified it. UnicodeString currentDescription; int32_t oldP = 0; while (oldP < description.length()) { int32_t p = description.indexOf(gSemicolon, oldP); if (p == -1) { p = description.length(); } currentDescription.setTo(description, oldP, p - oldP); NFRule::makeRules(currentDescription, this, rules.last(), owner, rules, status); oldP = p + 1; } // for rules that didn't specify a base value, their base values // were initialized to 0. Make another pass through the list and // set all those rules' base values. We also remove any special // rules from the list and put them into their own member variables int64_t defaultBaseValue = 0; // (this isn't a for loop because we might be deleting items from // the vector-- we want to make sure we only increment i when // we _didn't_ delete aything from the vector) int32_t rulesSize = rules.size(); for (int32_t i = 0; i < rulesSize; i++) { NFRule* rule = rules[i]; int64_t baseValue = rule->getBaseValue(); if (baseValue == 0) { // if the rule's base value is 0, fill in a default // base value (this will be 1 plus the preceding // rule's base value for regular rule sets, and the // same as the preceding rule's base value in fraction // rule sets) rule->setBaseValue(defaultBaseValue, status); } else { // if it's a regular rule that already knows its base value, // check to make sure the rules are in order, and update // the default base value for the next rule if (baseValue < defaultBaseValue) { // throw new IllegalArgumentException("Rules are not in order"); status = U_PARSE_ERROR; return; } defaultBaseValue = baseValue; } if (!fIsFractionRuleSet) { ++defaultBaseValue; } } } /** * Set one of the non-numerical rules. * @param rule The rule to set. */ void NFRuleSet::setNonNumericalRule(NFRule *rule) { int64_t baseValue = rule->getBaseValue(); if (baseValue == NFRule::kNegativeNumberRule) { delete nonNumericalRules[NEGATIVE_RULE_INDEX]; nonNumericalRules[NEGATIVE_RULE_INDEX] = rule; } else if (baseValue == NFRule::kImproperFractionRule) { setBestFractionRule(IMPROPER_FRACTION_RULE_INDEX, rule, TRUE); } else if (baseValue == NFRule::kProperFractionRule) { setBestFractionRule(PROPER_FRACTION_RULE_INDEX, rule, TRUE); } else if (baseValue == NFRule::kMasterRule) { setBestFractionRule(MASTER_RULE_INDEX, rule, TRUE); } else if (baseValue == NFRule::kInfinityRule) { delete nonNumericalRules[INFINITY_RULE_INDEX]; nonNumericalRules[INFINITY_RULE_INDEX] = rule; } else if (baseValue == NFRule::kNaNRule) { delete nonNumericalRules[NAN_RULE_INDEX]; nonNumericalRules[NAN_RULE_INDEX] = rule; } } /** * Determine the best fraction rule to use. Rules matching the decimal point from * DecimalFormatSymbols become the main set of rules to use. * @param originalIndex The index into nonNumericalRules * @param newRule The new rule to consider * @param rememberRule Should the new rule be added to fractionRules. */ void NFRuleSet::setBestFractionRule(int32_t originalIndex, NFRule *newRule, UBool rememberRule) { if (rememberRule) { fractionRules.add(newRule); } NFRule *bestResult = nonNumericalRules[originalIndex]; if (bestResult == NULL) { nonNumericalRules[originalIndex] = newRule; } else { // We have more than one. Which one is better? const DecimalFormatSymbols *decimalFormatSymbols = owner->getDecimalFormatSymbols(); if (decimalFormatSymbols->getSymbol(DecimalFormatSymbols::kDecimalSeparatorSymbol).charAt(0) == newRule->getDecimalPoint()) { nonNumericalRules[originalIndex] = newRule; } // else leave it alone } } NFRuleSet::~NFRuleSet() { for (int i = 0; i < NON_NUMERICAL_RULE_LENGTH; i++) { if (i != IMPROPER_FRACTION_RULE_INDEX && i != PROPER_FRACTION_RULE_INDEX && i != MASTER_RULE_INDEX) { delete nonNumericalRules[i]; } // else it will be deleted via NFRuleList fractionRules } } static UBool util_equalRules(const NFRule* rule1, const NFRule* rule2) { if (rule1) { if (rule2) { return *rule1 == *rule2; } } else if (!rule2) { return TRUE; } return FALSE; } UBool NFRuleSet::operator==(const NFRuleSet& rhs) const { if (rules.size() == rhs.rules.size() && fIsFractionRuleSet == rhs.fIsFractionRuleSet && name == rhs.name) { // ...then compare the non-numerical rule lists... for (int i = 0; i < NON_NUMERICAL_RULE_LENGTH; i++) { if (!util_equalRules(nonNumericalRules[i], rhs.nonNumericalRules[i])) { return FALSE; } } // ...then compare the rule lists... for (uint32_t i = 0; i < rules.size(); ++i) { if (*rules[i] != *rhs.rules[i]) { return FALSE; } } return TRUE; } return FALSE; } void NFRuleSet::setDecimalFormatSymbols(const DecimalFormatSymbols &newSymbols, UErrorCode& status) { for (uint32_t i = 0; i < rules.size(); ++i) { rules[i]->setDecimalFormatSymbols(newSymbols, status); } // Switch the fraction rules to mirror the DecimalFormatSymbols. for (int32_t nonNumericalIdx = IMPROPER_FRACTION_RULE_INDEX; nonNumericalIdx <= MASTER_RULE_INDEX; nonNumericalIdx++) { if (nonNumericalRules[nonNumericalIdx]) { for (uint32_t fIdx = 0; fIdx < fractionRules.size(); fIdx++) { NFRule *fractionRule = fractionRules[fIdx]; if (nonNumericalRules[nonNumericalIdx]->getBaseValue() == fractionRule->getBaseValue()) { setBestFractionRule(nonNumericalIdx, fractionRule, FALSE); } } } } for (uint32_t nnrIdx = 0; nnrIdx < NON_NUMERICAL_RULE_LENGTH; nnrIdx++) { NFRule *rule = nonNumericalRules[nnrIdx]; if (rule) { rule->setDecimalFormatSymbols(newSymbols, status); } } } #define RECURSION_LIMIT 64 void NFRuleSet::format(int64_t number, UnicodeString& toAppendTo, int32_t pos, int32_t recursionCount, UErrorCode& status) const { if (recursionCount >= RECURSION_LIMIT) { // stop recursion status = U_INVALID_STATE_ERROR; return; } const NFRule *rule = findNormalRule(number); if (rule) { // else error, but can't report it rule->doFormat(number, toAppendTo, pos, ++recursionCount, status); } } void NFRuleSet::format(double number, UnicodeString& toAppendTo, int32_t pos, int32_t recursionCount, UErrorCode& status) const { if (recursionCount >= RECURSION_LIMIT) { // stop recursion status = U_INVALID_STATE_ERROR; return; } const NFRule *rule = findDoubleRule(number); if (rule) { // else error, but can't report it rule->doFormat(number, toAppendTo, pos, ++recursionCount, status); } } const NFRule* NFRuleSet::findDoubleRule(double number) const { // if this is a fraction rule set, use findFractionRuleSetRule() if (isFractionRuleSet()) { return findFractionRuleSetRule(number); } if (uprv_isNaN(number)) { const NFRule *rule = nonNumericalRules[NAN_RULE_INDEX]; if (!rule) { rule = owner->getDefaultNaNRule(); } return rule; } // if the number is negative, return the negative number rule // (if there isn't a negative-number rule, we pretend it's a // positive number) if (number < 0) { if (nonNumericalRules[NEGATIVE_RULE_INDEX]) { return nonNumericalRules[NEGATIVE_RULE_INDEX]; } else { number = -number; } } if (uprv_isInfinite(number)) { const NFRule *rule = nonNumericalRules[INFINITY_RULE_INDEX]; if (!rule) { rule = owner->getDefaultInfinityRule(); } return rule; } // if the number isn't an integer, we use one of the fraction rules... if (number != uprv_floor(number)) { // if the number is between 0 and 1, return the proper // fraction rule if (number < 1 && nonNumericalRules[PROPER_FRACTION_RULE_INDEX]) { return nonNumericalRules[PROPER_FRACTION_RULE_INDEX]; } // otherwise, return the improper fraction rule else if (nonNumericalRules[IMPROPER_FRACTION_RULE_INDEX]) { return nonNumericalRules[IMPROPER_FRACTION_RULE_INDEX]; } } // if there's a master rule, use it to format the number if (nonNumericalRules[MASTER_RULE_INDEX]) { return nonNumericalRules[MASTER_RULE_INDEX]; } // and if we haven't yet returned a rule, use findNormalRule() // to find the applicable rule int64_t r = util64_fromDouble(number + 0.5); return findNormalRule(r); } const NFRule * NFRuleSet::findNormalRule(int64_t number) const { // if this is a fraction rule set, use findFractionRuleSetRule() // to find the rule (we should only go into this clause if the // value is 0) if (fIsFractionRuleSet) { return findFractionRuleSetRule((double)number); } // if the number is negative, return the negative-number rule // (if there isn't one, pretend the number is positive) if (number < 0) { if (nonNumericalRules[NEGATIVE_RULE_INDEX]) { return nonNumericalRules[NEGATIVE_RULE_INDEX]; } else { number = -number; } } // we have to repeat the preceding two checks, even though we // do them in findRule(), because the version of format() that // takes a long bypasses findRule() and goes straight to this // function. This function does skip the fraction rules since // we know the value is an integer (it also skips the master // rule, since it's considered a fraction rule. Skipping the // master rule in this function is also how we avoid infinite // recursion) // {dlf} unfortunately this fails if there are no rules except // special rules. If there are no rules, use the master rule. // binary-search the rule list for the applicable rule // (a rule is used for all values from its base value to // the next rule's base value) int32_t hi = rules.size(); if (hi > 0) { int32_t lo = 0; while (lo < hi) { int32_t mid = (lo + hi) / 2; if (rules[mid]->getBaseValue() == number) { return rules[mid]; } else if (rules[mid]->getBaseValue() > number) { hi = mid; } else { lo = mid + 1; } } if (hi == 0) { // bad rule set, minimum base > 0 return NULL; // want to throw exception here } NFRule *result = rules[hi - 1]; // use shouldRollBack() to see whether we need to invoke the // rollback rule (see shouldRollBack()'s documentation for // an explanation of the rollback rule). If we do, roll back // one rule and return that one instead of the one we'd normally // return if (result->shouldRollBack(number)) { if (hi == 1) { // bad rule set, no prior rule to rollback to from this base return NULL; } result = rules[hi - 2]; } return result; } // else use the master rule return nonNumericalRules[MASTER_RULE_INDEX]; } /** * If this rule is a fraction rule set, this function is used by * findRule() to select the most appropriate rule for formatting * the number. Basically, the base value of each rule in the rule * set is treated as the denominator of a fraction. Whichever * denominator can produce the fraction closest in value to the * number passed in is the result. If there's a tie, the earlier * one in the list wins. (If there are two rules in a row with the * same base value, the first one is used when the numerator of the * fraction would be 1, and the second rule is used the rest of the * time. * @param number The number being formatted (which will always be * a number between 0 and 1) * @return The rule to use to format this number */ const NFRule* NFRuleSet::findFractionRuleSetRule(double number) const { // the obvious way to do this (multiply the value being formatted // by each rule's base value until you get an integral result) // doesn't work because of rounding error. This method is more // accurate // find the least common multiple of the rules' base values // and multiply this by the number being formatted. This is // all the precision we need, and we can do all of the rest // of the math using integer arithmetic int64_t leastCommonMultiple = rules[0]->getBaseValue(); int64_t numerator; { for (uint32_t i = 1; i < rules.size(); ++i) { leastCommonMultiple = util_lcm(leastCommonMultiple, rules[i]->getBaseValue()); } numerator = util64_fromDouble(number * (double)leastCommonMultiple + 0.5); } // for each rule, do the following... int64_t tempDifference; int64_t difference = util64_fromDouble(uprv_maxMantissa()); int32_t winner = 0; for (uint32_t i = 0; i < rules.size(); ++i) { // "numerator" is the numerator of the fraction if the // denominator is the LCD. The numerator if the rule's // base value is the denominator is "numerator" times the // base value divided bythe LCD. Here we check to see if // that's an integer, and if not, how close it is to being // an integer. tempDifference = numerator * rules[i]->getBaseValue() % leastCommonMultiple; // normalize the result of the above calculation: we want // the numerator's distance from the CLOSEST multiple // of the LCD if (leastCommonMultiple - tempDifference < tempDifference) { tempDifference = leastCommonMultiple - tempDifference; } // if this is as close as we've come, keep track of how close // that is, and the line number of the rule that did it. If // we've scored a direct hit, we don't have to look at any more // rules if (tempDifference < difference) { difference = tempDifference; winner = i; if (difference == 0) { break; } } } // if we have two successive rules that both have the winning base // value, then the first one (the one we found above) is used if // the numerator of the fraction is 1 and the second one is used if // the numerator of the fraction is anything else (this lets us // do things like "one third"/"two thirds" without haveing to define // a whole bunch of extra rule sets) if ((unsigned)(winner + 1) < rules.size() && rules[winner + 1]->getBaseValue() == rules[winner]->getBaseValue()) { double n = ((double)rules[winner]->getBaseValue()) * number; if (n < 0.5 || n >= 2) { ++winner; } } // finally, return the winning rule return rules[winner]; } /** * Parses a string. Matches the string to be parsed against each * of its rules (with a base value less than upperBound) and returns * the value produced by the rule that matched the most charcters * in the source string. * @param text The string to parse * @param parsePosition The initial position is ignored and assumed * to be 0. On exit, this object has been updated to point to the * first character position this rule set didn't consume. * @param upperBound Limits the rules that can be allowed to match. * Only rules whose base values are strictly less than upperBound * are considered. * @return The numerical result of parsing this string. This will * be the matching rule's base value, composed appropriately with * the results of matching any of its substitutions. The object * will be an instance of Long if it's an integral value; otherwise, * it will be an instance of Double. This function always returns * a valid object: If nothing matched the input string at all, * this function returns new Long(0), and the parse position is * left unchanged. */ #ifdef RBNF_DEBUG #include <stdio.h> static void dumpUS(FILE* f, const UnicodeString& us) { int len = us.length(); char* buf = (char *)uprv_malloc((len+1)*sizeof(char)); //new char[len+1]; if (buf != NULL) { us.extract(0, len, buf); buf[len] = 0; fprintf(f, "%s", buf); uprv_free(buf); //delete[] buf; } } #endif UBool NFRuleSet::parse(const UnicodeString& text, ParsePosition& pos, double upperBound, uint32_t nonNumericalExecutedRuleMask, Formattable& result) const { // try matching each rule in the rule set against the text being // parsed. Whichever one matches the most characters is the one // that determines the value we return. result.setLong(0); // dump out if there's no text to parse if (text.length() == 0) { return 0; } ParsePosition highWaterMark; ParsePosition workingPos = pos; #ifdef RBNF_DEBUG fprintf(stderr, "<nfrs> %x '", this); dumpUS(stderr, name); fprintf(stderr, "' text '"); dumpUS(stderr, text); fprintf(stderr, "'\n"); fprintf(stderr, " parse negative: %d\n", this, negativeNumberRule != 0); #endif // Try each of the negative rules, fraction rules, infinity rules and NaN rules for (int i = 0; i < NON_NUMERICAL_RULE_LENGTH; i++) { if (nonNumericalRules[i] && ((nonNumericalExecutedRuleMask >> i) & 1) == 0) { // Mark this rule as being executed so that we don't try to execute it again. nonNumericalExecutedRuleMask |= 1 << i; Formattable tempResult; UBool success = nonNumericalRules[i]->doParse(text, workingPos, 0, upperBound, nonNumericalExecutedRuleMask, tempResult); if (success && (workingPos.getIndex() > highWaterMark.getIndex())) { result = tempResult; highWaterMark = workingPos; } workingPos = pos; } } #ifdef RBNF_DEBUG fprintf(stderr, "<nfrs> continue other with text '"); dumpUS(stderr, text); fprintf(stderr, "' hwm: %d\n", highWaterMark.getIndex()); #endif // finally, go through the regular rules one at a time. We start // at the end of the list because we want to try matching the most // sigificant rule first (this helps ensure that we parse // "five thousand three hundred six" as // "(five thousand) (three hundred) (six)" rather than // "((five thousand three) hundred) (six)"). Skip rules whose // base values are higher than the upper bound (again, this helps // limit ambiguity by making sure the rules that match a rule's // are less significant than the rule containing the substitutions)/ { int64_t ub = util64_fromDouble(upperBound); #ifdef RBNF_DEBUG { char ubstr[64]; util64_toa(ub, ubstr, 64); char ubstrhex[64]; util64_toa(ub, ubstrhex, 64, 16); fprintf(stderr, "ub: %g, i64: %s (%s)\n", upperBound, ubstr, ubstrhex); } #endif for (int32_t i = rules.size(); --i >= 0 && highWaterMark.getIndex() < text.length();) { if ((!fIsFractionRuleSet) && (rules[i]->getBaseValue() >= ub)) { continue; } Formattable tempResult; UBool success = rules[i]->doParse(text, workingPos, fIsFractionRuleSet, upperBound, nonNumericalExecutedRuleMask, tempResult); if (success && workingPos.getIndex() > highWaterMark.getIndex()) { result = tempResult; highWaterMark = workingPos; } workingPos = pos; } } #ifdef RBNF_DEBUG fprintf(stderr, "<nfrs> exit\n"); #endif // finally, update the parse postion we were passed to point to the // first character we didn't use, and return the result that // corresponds to that string of characters pos = highWaterMark; return 1; } void NFRuleSet::appendRules(UnicodeString& result) const { uint32_t i; // the rule set name goes first... result.append(name); result.append(gColon); result.append(gLineFeed); // followed by the regular rules... for (i = 0; i < rules.size(); i++) { rules[i]->_appendRuleText(result); result.append(gLineFeed); } // followed by the special rules (if they exist) for (i = 0; i < NON_NUMERICAL_RULE_LENGTH; ++i) { NFRule *rule = nonNumericalRules[i]; if (nonNumericalRules[i]) { if (rule->getBaseValue() == NFRule::kImproperFractionRule || rule->getBaseValue() == NFRule::kProperFractionRule || rule->getBaseValue() == NFRule::kMasterRule) { for (uint32_t fIdx = 0; fIdx < fractionRules.size(); fIdx++) { NFRule *fractionRule = fractionRules[fIdx]; if (fractionRule->getBaseValue() == rule->getBaseValue()) { fractionRule->_appendRuleText(result); result.append(gLineFeed); } } } else { rule->_appendRuleText(result); result.append(gLineFeed); } } } } // utility functions int64_t util64_fromDouble(double d) { int64_t result = 0; if (!uprv_isNaN(d)) { double mant = uprv_maxMantissa(); if (d < -mant) { d = -mant; } else if (d > mant) { d = mant; } UBool neg = d < 0; if (neg) { d = -d; } result = (int64_t)uprv_floor(d); if (neg) { result = -result; } } return result; } uint64_t util64_pow(uint32_t base, uint16_t exponent) { if (base == 0) { return 0; } uint64_t result = 1; uint64_t pow = base; while (true) { if ((exponent & 1) == 1) { result *= pow; } exponent >>= 1; if (exponent == 0) { break; } pow *= pow; } return result; } static const uint8_t asciiDigits[] = { 0x30u, 0x31u, 0x32u, 0x33u, 0x34u, 0x35u, 0x36u, 0x37u, 0x38u, 0x39u, 0x61u, 0x62u, 0x63u, 0x64u, 0x65u, 0x66u, 0x67u, 0x68u, 0x69u, 0x6au, 0x6bu, 0x6cu, 0x6du, 0x6eu, 0x6fu, 0x70u, 0x71u, 0x72u, 0x73u, 0x74u, 0x75u, 0x76u, 0x77u, 0x78u, 0x79u, 0x7au, }; static const UChar kUMinus = (UChar)0x002d; #ifdef RBNF_DEBUG static const char kMinus = '-'; static const uint8_t digitInfo[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x80u, 0x81u, 0x82u, 0x83u, 0x84u, 0x85u, 0x86u, 0x87u, 0x88u, 0x89u, 0, 0, 0, 0, 0, 0, 0, 0x8au, 0x8bu, 0x8cu, 0x8du, 0x8eu, 0x8fu, 0x90u, 0x91u, 0x92u, 0x93u, 0x94u, 0x95u, 0x96u, 0x97u, 0x98u, 0x99u, 0x9au, 0x9bu, 0x9cu, 0x9du, 0x9eu, 0x9fu, 0xa0u, 0xa1u, 0xa2u, 0xa3u, 0, 0, 0, 0, 0, 0, 0x8au, 0x8bu, 0x8cu, 0x8du, 0x8eu, 0x8fu, 0x90u, 0x91u, 0x92u, 0x93u, 0x94u, 0x95u, 0x96u, 0x97u, 0x98u, 0x99u, 0x9au, 0x9bu, 0x9cu, 0x9du, 0x9eu, 0x9fu, 0xa0u, 0xa1u, 0xa2u, 0xa3u, 0, 0, 0, 0, 0, }; int64_t util64_atoi(const char* str, uint32_t radix) { if (radix > 36) { radix = 36; } else if (radix < 2) { radix = 2; } int64_t lradix = radix; int neg = 0; if (*str == kMinus) { ++str; neg = 1; } int64_t result = 0; uint8_t b; while ((b = digitInfo[*str++]) && ((b &= 0x7f) < radix)) { result *= lradix; result += (int32_t)b; } if (neg) { result = -result; } return result; } int64_t util64_utoi(const UChar* str, uint32_t radix) { if (radix > 36) { radix = 36; } else if (radix < 2) { radix = 2; } int64_t lradix = radix; int neg = 0; if (*str == kUMinus) { ++str; neg = 1; } int64_t result = 0; UChar c; uint8_t b; while (((c = *str++) < 0x0080) && (b = digitInfo[c]) && ((b &= 0x7f) < radix)) { result *= lradix; result += (int32_t)b; } if (neg) { result = -result; } return result; } uint32_t util64_toa(int64_t w, char* buf, uint32_t len, uint32_t radix, UBool raw) { if (radix > 36) { radix = 36; } else if (radix < 2) { radix = 2; } int64_t base = radix; char* p = buf; if (len && (w < 0) && (radix == 10) && !raw) { w = -w; *p++ = kMinus; --len; } else if (len && (w == 0)) { *p++ = (char)raw ? 0 : asciiDigits[0]; --len; } while (len && w != 0) { int64_t n = w / base; int64_t m = n * base; int32_t d = (int32_t)(w-m); *p++ = raw ? (char)d : asciiDigits[d]; w = n; --len; } if (len) { *p = 0; // null terminate if room for caller convenience } len = p - buf; if (*buf == kMinus) { ++buf; } while (--p > buf) { char c = *p; *p = *buf; *buf = c; ++buf; } return len; } #endif uint32_t util64_tou(int64_t w, UChar* buf, uint32_t len, uint32_t radix, UBool raw) { if (radix > 36) { radix = 36; } else if (radix < 2) { radix = 2; } int64_t base = radix; UChar* p = buf; if (len && (w < 0) && (radix == 10) && !raw) { w = -w; *p++ = kUMinus; --len; } else if (len && (w == 0)) { *p++ = (UChar)raw ? 0 : asciiDigits[0]; --len; } while (len && (w != 0)) { int64_t n = w / base; int64_t m = n * base; int32_t d = (int32_t)(w-m); *p++ = (UChar)(raw ? d : asciiDigits[d]); w = n; --len; } if (len) { *p = 0; // null terminate if room for caller convenience } len = (uint32_t)(p - buf); if (*buf == kUMinus) { ++buf; } while (--p > buf) { UChar c = *p; *p = *buf; *buf = c; ++buf; } return len; } U_NAMESPACE_END /* U_HAVE_RBNF */ #endif
gpl-2.0
victoralex/gameleon
includes/classes/class.npc.js_files/npcScript.217.js
1171
"use strict"; var log = require( "../class.log" ); var realmConfig = require( "../../config.realm" ).config; exports.script = function( npcObject ) { // // Variables // var _iO = npcObject.getArgs().createdByInstanceObject, _cooldownPointer = null; var zoneIdConstant_6 = 57; // // Events override // npcObject.events._add( "use", function( args ) { var byCharacterObject_1 = args.byCharacterObject; byCharacterObject_1.command_disconnect_for_zone_pool_id({ zone_pool_id: zoneIdConstant_6, onComplete: function( args ) { }, }, function() { log.addNotice( "Flying to another zone" ); } ); }); // // Post all objects initialisation // this.postInit = function() { } // // Initialize // // bind to instance npcObject.events._add( "afterInit", function( args ) { npcObject.bindToInstance( _iO, function() { } ); }); }
gpl-2.0
Furt/JMaNGOS
Commons/src/main/java/org/jmangos/commons/threadpool/ThreadPoolManager.java
2224
/******************************************************************************* * Copyright (C) 2012 JMaNGOS <http://jmangos.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.jmangos.commons.threadpool; import java.util.concurrent.ScheduledFuture; import org.jmangos.commons.service.Service; import org.jmangos.commons.threadpool.model.PoolStats; import org.jmangos.commons.threadpool.model.ThreadPoolType; /** * The Interface ThreadPoolManager. */ public interface ThreadPoolManager extends Service { /** * Schedule. * * @param r * the r * @param delay * the delay * @return the scheduled future */ ScheduledFuture<?> schedule(Runnable r, long delay); /** * Schedule at fixed rate. * * @param r * the r * @param delay * the delay * @param period * the period * @return the scheduled future */ ScheduledFuture<?> scheduleAtFixedRate(Runnable r, long delay, long period); /** * Execute instant. * * @param r * the r */ void executeInstant(Runnable r); /** * Purges all thread pools. */ void purge(); /** * Fill pool stats. * * @param poolType * the pool type * @return the pool stats */ PoolStats fillPoolStats(ThreadPoolType poolType); }
gpl-2.0
codearachnid/jquery-relative-events
jquery.relativeEvents.demo.js
5090
/** * DEMO EVENTS */ var single_day = [ // 3x1 events { hour: "7", min: "00", duration: "30" }, { hour: "7", min: "00", duration: "30" }, { hour: "7", min: "15", duration: "30" }, // 1x1 event { hour: "7", min: "45", duration: "45" }, // 2x1 events { hour: "8", min: "30", duration: "30" }, { hour: "8", min: "30", duration: "30" }, // 7x2.5 events { hour: "9", min: "00", duration: "105" }, { hour: "9", min: "00", duration: "30" }, { hour: "9", min: "00", duration: "30" }, { hour: "9", min: "00", duration: "30" }, { hour: "9", min: "00", duration: "30" }, { hour: "9", min: "00", duration: "30" }, { hour: "9", min: "00", duration: "30" }, { hour: "10", min: "00", duration: "60" }, { hour: "10", min: "00", duration: "30" }, { hour: "10", min: "00", duration: "30" }, { hour: "10", min: "00", duration: "30" }, { hour: "10", min: "00", duration: "30" }, // 4x1 event { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, // 5x1 event { hour: "11", min: "30", duration: "30" }, { hour: "11", min: "30", duration: "30" }, { hour: "11", min: "30", duration: "30" }, { hour: "11", min: "30", duration: "30" }, { hour: "11", min: "30", duration: "30" }, // 6x5 events { hour: "12", min: "00", duration: "90" }, { hour: "12", min: "15", duration: "285" }, { hour: "13", min: "00", duration: "60" }, { hour: "13", min: "30", duration: "90" }, { hour: "13", min: "45", duration: "60" }, { hour: "14", min: "00", duration: "60" }, { hour: "14", min: "00", duration: "45" }, { hour: "14", min: "30", duration: "60" }, { hour: "15", min: "00", duration: "45" }, { hour: "15", min: "00", duration: "60" }, { hour: "15", min: "15", duration: "60" }, ]; var full_week = [ { date: '2013-11-10', events: [ { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, { hour: "12", min: "00", duration: "30" }, { hour: "13", min: "00", duration: "30" }, ]}, { date: '2013-11-11', events: [ { hour: "9", min: "00", duration: "105" }, { hour: "9", min: "00", duration: "30" }, { hour: "9", min: "00", duration: "30" }, { hour: "10", min: "00", duration: "60" }, { hour: "10", min: "00", duration: "30" }, ]}, { date: '2013-11-12', events: [ { hour: "7", min: "00", duration: "30" }, { hour: "7", min: "00", duration: "30" }, { hour: "7", min: "15", duration: "30" }, { hour: "7", min: "45", duration: "45" }, { hour: "8", min: "30", duration: "30" }, { hour: "8", min: "30", duration: "30" }, ]}, { date: '2013-11-13', events: [ { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, { hour: "11", min: "00", duration: "30" }, ]}, { date: '2013-11-14', events: [ { hour: "7", min: "45", duration: "45" }, { hour: "8", min: "30", duration: "120" }, { hour: "8", min: "30", duration: "90" }, ]}, { date: '2013-11-15', events: []}, { date: '2013-11-16', events: [ { hour: "7", min: "45", duration: "300" }, ]}]; /** * EVENT OVERLAP DEMO */ jQuery(document).ready(function($){ // DUMMY DATA // loop through single day event data $.each(single_day, function(i,item){ // create event divs for single day $('#single_day .day').append($('<div>').attr( { class: 'event', id: 'event-' + i, 'data-hour':item.hour, 'data-minute': item.min, 'data-duration':item.duration }).text( "Event " + (i+1) )); if( single_day.length-1 == i ){ // loop through full week event data $.each(full_week, function(index, column){ // create daily event columns // <div class="events day" data-day="2013-11-11"></div> $('#full_week').append( $('<div>').attr({ class: 'events day', 'data-date': column.date })); $.each(column.events, function(ii,item){ // create event divs $('#full_week').find('.day[data-date=' +column.date+ ']').append($('<div>').attr( { class: 'event', id: 'event-' + ii, 'data-hour':item.hour, 'data-minute': item.min, 'data-duration':item.duration }).text( "Event " + (ii+1) )); }); // once done with full week fire off relativeEvents if( full_week.length-1 == index ){ $('.calendar').relativeEvents({ dayStart: 7, debug: true }); } }); } }); });
gpl-2.0
lobermann/xbmc
xbmc/Application.cpp
173054
/* * Copyright (C) 2005-2015 Team XBMC * http://kodi.tv * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, 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 Kodi; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "network/Network.h" #include "threads/SystemClock.h" #include "system.h" #include "Application.h" #include "events/EventLog.h" #include "events/NotificationEvent.h" #include "interfaces/builtins/Builtins.h" #include "utils/JobManager.h" #include "utils/Variant.h" #include "utils/Splash.h" #include "LangInfo.h" #include "utils/Screenshot.h" #include "Util.h" #include "URL.h" #include "guilib/TextureManager.h" #include "cores/IPlayer.h" #include "cores/VideoPlayer/DVDFileInfo.h" #include "cores/AudioEngine/Engines/ActiveAE/AudioDSPAddons/ActiveAEDSP.h" #include "cores/AudioEngine/Interfaces/AE.h" #include "cores/AudioEngine/Utils/AEUtil.h" #include "cores/playercorefactory/PlayerCoreFactory.h" #include "PlayListPlayer.h" #include "Autorun.h" #include "video/Bookmark.h" #include "video/VideoLibraryQueue.h" #include "guilib/GUIControlProfiler.h" #include "utils/LangCodeExpander.h" #include "GUIInfoManager.h" #include "playlists/PlayListFactory.h" #include "guilib/GUIFontManager.h" #include "guilib/GUIColorManager.h" #include "guilib/StereoscopicsManager.h" #include "addons/BinaryAddonCache.h" #include "addons/LanguageResource.h" #include "addons/Skin.h" #include "addons/VFSEntry.h" #include "interfaces/generic/ScriptInvocationManager.h" #ifdef HAS_PYTHON #include "interfaces/python/XBPython.h" #endif #include "input/ButtonTranslator.h" #include "guilib/GUIAudioManager.h" #include "GUIPassword.h" #include "input/InertialScrollingHandler.h" #include "messaging/ThreadMessage.h" #include "messaging/ApplicationMessenger.h" #include "messaging/helpers/DialogHelper.h" #include "SectionLoader.h" #include "cores/DllLoader/DllLoaderContainer.h" #include "GUIUserMessages.h" #include "filesystem/Directory.h" #include "filesystem/DirectoryCache.h" #include "filesystem/StackDirectory.h" #include "filesystem/SpecialProtocol.h" #include "filesystem/DllLibCurl.h" #include "filesystem/PluginDirectory.h" #include "utils/SystemInfo.h" #include "utils/TimeUtils.h" #include "GUILargeTextureManager.h" #include "TextureCache.h" #include "playlists/SmartPlayList.h" #include "playlists/PlayList.h" #include "profiles/ProfilesManager.h" #include "windowing/WindowingFactory.h" #include "powermanagement/PowerManager.h" #include "powermanagement/DPMSSupport.h" #include "settings/Settings.h" #include "settings/AdvancedSettings.h" #include "settings/DisplaySettings.h" #include "settings/MediaSettings.h" #include "settings/SkinSettings.h" #include "guilib/LocalizeStrings.h" #include "utils/CPUInfo.h" #include "utils/log.h" #include "utils/SeekHandler.h" #include "input/KeyboardLayoutManager.h" #ifdef HAS_SDL #include <SDL/SDL.h> #endif #ifdef HAS_UPNP #include "network/upnp/UPnP.h" #include "filesystem/UPnPDirectory.h" #endif #if defined(TARGET_POSIX) && defined(HAS_FILESYSTEM_SMB) #include "filesystem/SMBDirectory.h" #endif #ifdef HAS_FILESYSTEM_NFS #include "filesystem/NFSFile.h" #endif #ifdef HAS_FILESYSTEM_SFTP #include "filesystem/SFTPFile.h" #endif #include "PartyModeManager.h" #include "network/ZeroconfBrowser.h" #ifndef TARGET_POSIX #include "threads/platform/win/Win32Exception.h" #endif #ifdef HAS_EVENT_SERVER #include "network/EventServer.h" #endif #ifdef HAS_DBUS #include <dbus/dbus.h> #endif #ifdef HAS_JSONRPC #include "interfaces/json-rpc/JSONRPC.h" #endif #include "interfaces/AnnouncementManager.h" #include "peripherals/Peripherals.h" #include "peripherals/devices/PeripheralImon.h" #include "music/infoscanner/MusicInfoScanner.h" // Windows includes #include "guilib/GUIWindowManager.h" #include "video/dialogs/GUIDialogVideoInfo.h" #include "windows/GUIWindowScreensaver.h" #include "video/VideoInfoScanner.h" #include "video/PlayerController.h" // Dialog includes #include "video/dialogs/GUIDialogVideoBookmarks.h" #include "dialogs/GUIDialogOK.h" #include "dialogs/GUIDialogKaiToast.h" #include "dialogs/GUIDialogSubMenu.h" #include "dialogs/GUIDialogButtonMenu.h" #include "dialogs/GUIDialogSimpleMenu.h" #include "addons/settings/GUIDialogAddonSettings.h" // PVR related include Files #include "pvr/PVRGUIActions.h" #include "pvr/PVRManager.h" #include "video/dialogs/GUIDialogFullScreenInfo.h" #include "guilib/GUIControlFactory.h" #include "dialogs/GUIDialogCache.h" #include "dialogs/GUIDialogPlayEject.h" #include "utils/URIUtils.h" #include "utils/XMLUtils.h" #include "addons/AddonInstaller.h" #include "addons/AddonManager.h" #include "addons/RepositoryUpdater.h" #include "music/tags/MusicInfoTag.h" #include "music/tags/MusicInfoTagLoaderFactory.h" #include "CompileInfo.h" #ifdef HAS_PERFORMANCE_SAMPLE #include "utils/PerformanceSample.h" #else #define MEASURE_FUNCTION #endif #ifdef TARGET_WINDOWS #include "win32util.h" #endif #ifdef TARGET_DARWIN_OSX #include "platform/darwin/osx/CocoaInterface.h" #include "platform/darwin/osx/XBMCHelper.h" #endif #ifdef TARGET_DARWIN #include "platform/darwin/DarwinUtils.h" #endif #ifdef HAS_DVD_DRIVE #include <cdio/logging.h> #endif #include "storage/MediaManager.h" #include "utils/SaveFileStateJob.h" #include "utils/AlarmClock.h" #include "utils/StringUtils.h" #include "DatabaseManager.h" #include "input/InputManager.h" #ifdef TARGET_POSIX #include "XHandle.h" #include "XTimeUtils.h" #include "filesystem/posix/PosixDirectory.h" #endif #if defined(TARGET_ANDROID) #include <androidjni/Build.h> #include "platform/android/activity/XBMCApp.h" #include "platform/android/activity/AndroidFeatures.h" #endif #ifdef TARGET_WINDOWS #include "utils/Environment.h" #endif #if defined(HAS_LIBAMCODEC) #include "utils/AMLUtils.h" #endif #include "cores/FFmpeg.h" #include "utils/CharsetConverter.h" #include "pictures/GUIWindowSlideShow.h" #include "windows/GUIWindowLoginScreen.h" using namespace ADDON; using namespace XFILE; #ifdef HAS_DVD_DRIVE using namespace MEDIA_DETECT; #endif using namespace PLAYLIST; using namespace VIDEO; using namespace MUSIC_INFO; #ifdef HAS_EVENT_SERVER using namespace EVENTSERVER; #endif #ifdef HAS_JSONRPC using namespace JSONRPC; #endif using namespace ANNOUNCEMENT; using namespace PVR; using namespace PERIPHERALS; using namespace KODI::MESSAGING; using namespace ActiveAE; using namespace XbmcThreads; using KODI::MESSAGING::HELPERS::DialogResponse; #define MAX_FFWD_SPEED 5 //extern IDirectSoundRenderer* m_pAudioDecoder; CApplication::CApplication(void) : m_pPlayer(new CApplicationPlayer) #ifdef HAS_DVD_DRIVE , m_Autorun(new CAutorun()) #endif , m_iScreenSaveLock(0) , m_bPlaybackStarting(false) , m_ePlayState(PLAY_STATE_NONE) , m_confirmSkinChange(true) , m_ignoreSkinSettingChanges(false) , m_saveSkinOnUnloading(true) , m_autoExecScriptExecuted(false) , m_screensaverActive(false) , m_bInhibitIdleShutdown(false) , m_dpmsIsActive(false) , m_dpmsIsManual(false) , m_itemCurrentFile(new CFileItem) , m_currentStack(new CFileItemList) , m_stackFileItemToUpdate(new CFileItem) , m_threadID(0) , m_bInitializing(true) , m_bPlatformDirectories(true) , m_progressTrackingVideoResumeBookmark(*new CBookmark) , m_progressTrackingItem(new CFileItem) , m_progressTrackingPlayCountUpdate(false) , m_currentStackPosition(0) , m_nextPlaylistItem(-1) , m_lastRenderTime(0) , m_skipGuiRender(false) , m_bStandalone(false) , m_bEnableLegacyRes(false) , m_bTestMode(false) , m_bSystemScreenSaverEnable(false) , m_musicInfoScanner(new CMusicInfoScanner) , m_muted(false) , m_volumeLevel(VOLUME_MAXIMUM) , m_pInertialScrollingHandler(new CInertialScrollingHandler()) , m_network(nullptr) , m_fallbackLanguageLoaded(false) , m_WaitingExternalCalls(0) , m_ProcessedExternalCalls(0) { TiXmlBase::SetCondenseWhiteSpace(false); #ifdef HAS_GLX XInitThreads(); #endif } CApplication::~CApplication(void) { delete &m_progressTrackingVideoResumeBookmark; delete m_pInertialScrollingHandler; m_actionListeners.clear(); } bool CApplication::OnEvent(XBMC_Event& newEvent) { switch(newEvent.type) { case XBMC_QUIT: if (!g_application.m_bStop) CApplicationMessenger::GetInstance().PostMsg(TMSG_QUIT); break; case XBMC_VIDEORESIZE: if (g_windowManager.Initialized()) { g_Windowing.SetWindowResolution(newEvent.resize.w, newEvent.resize.h); if (!g_advancedSettings.m_fullScreen) { g_graphicsContext.SetVideoResolution(RES_WINDOW, true); CServiceBroker::GetSettings().SetInt(CSettings::SETTING_WINDOW_WIDTH, newEvent.resize.w); CServiceBroker::GetSettings().SetInt(CSettings::SETTING_WINDOW_HEIGHT, newEvent.resize.h); CServiceBroker::GetSettings().Save(); } } break; case XBMC_VIDEOMOVE: #ifdef TARGET_WINDOWS if (g_advancedSettings.m_fullScreen) { // when fullscreen, remain fullscreen and resize to the dimensions of the new screen RESOLUTION newRes = (RESOLUTION) g_Windowing.DesktopResolution(g_Windowing.GetCurrentScreen()); CDisplaySettings::GetInstance().SetCurrentResolution(newRes, true); g_graphicsContext.SetVideoResolution(g_graphicsContext.GetVideoResolution(), true); } else #endif { g_Windowing.OnMove(newEvent.move.x, newEvent.move.y); } break; case XBMC_USEREVENT: CApplicationMessenger::GetInstance().PostMsg(static_cast<uint32_t>(newEvent.user.code)); break; case XBMC_APPCOMMAND: return g_application.OnAppCommand(newEvent.appcommand.action); case XBMC_SETFOCUS: // Reset the screensaver g_application.ResetScreenSaver(); g_application.WakeUpScreenSaverAndDPMS(); // Send a mouse motion event with no dx,dy for getting the current guiitem selected g_application.OnAction(CAction(ACTION_MOUSE_MOVE, 0, static_cast<float>(newEvent.focus.x), static_cast<float>(newEvent.focus.y), 0, 0)); break; default: return CInputManager::GetInstance().OnEvent(newEvent); } return true; } extern "C" void __stdcall init_emu_environ(); extern "C" void __stdcall update_emu_environ(); extern "C" void __stdcall cleanup_emu_environ(); // // Utility function used to copy files from the application bundle // over to the user data directory in Application Support/Kodi. // static void CopyUserDataIfNeeded(const std::string &strPath, const std::string &file, const std::string &destname = "") { std::string destPath; if (destname == "") destPath = URIUtils::AddFileToFolder(strPath, file); else destPath = URIUtils::AddFileToFolder(strPath, destname); if (!CFile::Exists(destPath)) { // need to copy it across std::string srcPath = URIUtils::AddFileToFolder("special://xbmc/userdata/", file); CFile::Copy(srcPath, destPath); } } void CApplication::Preflight() { #ifdef HAS_DBUS // call 'dbus_threads_init_default' before any other dbus calls in order to // avoid race conditions with other threads using dbus connections dbus_threads_init_default(); #endif // run any platform preflight scripts. #if defined(TARGET_DARWIN_OSX) std::string install_path; install_path = CUtil::GetHomePath(); setenv("KODI_HOME", install_path.c_str(), 0); install_path += "/tools/darwin/runtime/preflight"; system(install_path.c_str()); #endif } bool CApplication::SetupNetwork() { #if defined(HAS_LINUX_NETWORK) m_network = new CNetworkLinux(); #elif defined(HAS_WIN32_NETWORK) m_network = new CNetworkWin32(); #else m_network = new CNetwork(); #endif return m_network != NULL; } bool CApplication::Create() { // Grab a handle to our thread to be used later in identifying the render thread. m_threadID = CThread::GetCurrentThreadId(); m_ServiceManager.reset(new CServiceManager()); if (!m_ServiceManager->Init1()) { return false; } SetupNetwork(); Preflight(); // here we register all global classes for the CApplicationMessenger, // after that we can send messages to the corresponding modules CApplicationMessenger::GetInstance().RegisterReceiver(this); CApplicationMessenger::GetInstance().RegisterReceiver(&g_playlistPlayer); CApplicationMessenger::GetInstance().RegisterReceiver(&g_infoManager); CApplicationMessenger::GetInstance().SetGUIThread(m_threadID); for (int i = RES_HDTV_1080i; i <= RES_PAL60_16x9; i++) { g_graphicsContext.ResetScreenParameters((RESOLUTION)i); g_graphicsContext.ResetOverscan((RESOLUTION)i, CDisplaySettings::GetInstance().GetResolutionInfo(i).Overscan); } //! @todo - move to CPlatformXXX #ifdef TARGET_POSIX tzset(); // Initialize timezone information variables #endif //! @todo - move to CPlatformXXX #if defined(TARGET_POSIX) // set special://envhome CSpecialProtocol::SetEnvHomePath(getenv("HOME")); #endif // only the InitDirectories* for the current platform should return true bool inited = InitDirectoriesLinux(); if (!inited) inited = InitDirectoriesOSX(); if (!inited) inited = InitDirectoriesWin32(); // copy required files CopyUserDataIfNeeded("special://masterprofile/", "RssFeeds.xml"); CopyUserDataIfNeeded("special://masterprofile/", "favourites.xml"); CopyUserDataIfNeeded("special://masterprofile/", "Lircmap.xml"); //! @todo - move to CPlatformXXX #ifdef TARGET_DARWIN_IOS CopyUserDataIfNeeded("special://masterprofile/", "iOS/sources.xml", "sources.xml"); #endif if (!CLog::Init(CSpecialProtocol::TranslatePath("special://logpath").c_str())) { fprintf(stderr,"Could not init logging classes. Log folder error (%s)\n", CSpecialProtocol::TranslatePath("special://logpath").c_str()); return false; } // Init our DllLoaders emu env init_emu_environ(); CProfilesManager::GetInstance().Load(); CLog::Log(LOGNOTICE, "-----------------------------------------------------------------------"); CLog::Log(LOGNOTICE, "Starting %s (%s). Platform: %s %s %d-bit", CSysInfo::GetAppName().c_str(), CSysInfo::GetVersion().c_str(), g_sysinfo.GetBuildTargetPlatformName().c_str(), g_sysinfo.GetBuildTargetCpuFamily().c_str(), g_sysinfo.GetXbmcBitness()); std::string buildType; #if defined(_DEBUG) buildType = "Debug"; #elif defined(NDEBUG) buildType = "Release"; #else buildType = "Unknown"; #endif std::string specialVersion; //! @todo - move to CPlatformXXX #if defined(TARGET_RASPBERRY_PI) specialVersion = " (version for Raspberry Pi)"; //#elif defined(some_ID) // uncomment for special version/fork // specialVersion = " (version for XXXX)"; #endif CLog::Log(LOGNOTICE, "Using %s %s x%d build%s", buildType.c_str(), CSysInfo::GetAppName().c_str(), g_sysinfo.GetXbmcBitness(), specialVersion.c_str()); CLog::Log(LOGNOTICE, "%s compiled " __DATE__ " by %s for %s %s %d-bit %s (%s)", CSysInfo::GetAppName().c_str(), g_sysinfo.GetUsedCompilerNameAndVer().c_str(), g_sysinfo.GetBuildTargetPlatformName().c_str(), g_sysinfo.GetBuildTargetCpuFamily().c_str(), g_sysinfo.GetXbmcBitness(), g_sysinfo.GetBuildTargetPlatformVersionDecoded().c_str(), g_sysinfo.GetBuildTargetPlatformVersion().c_str()); std::string deviceModel(g_sysinfo.GetModelName()); if (!g_sysinfo.GetManufacturerName().empty()) deviceModel = g_sysinfo.GetManufacturerName() + " " + (deviceModel.empty() ? std::string("device") : deviceModel); if (!deviceModel.empty()) CLog::Log(LOGNOTICE, "Running on %s with %s, kernel: %s %s %d-bit version %s", deviceModel.c_str(), g_sysinfo.GetOsPrettyNameWithVersion().c_str(), g_sysinfo.GetKernelName().c_str(), g_sysinfo.GetKernelCpuFamily().c_str(), g_sysinfo.GetKernelBitness(), g_sysinfo.GetKernelVersionFull().c_str()); else CLog::Log(LOGNOTICE, "Running on %s, kernel: %s %s %d-bit version %s", g_sysinfo.GetOsPrettyNameWithVersion().c_str(), g_sysinfo.GetKernelName().c_str(), g_sysinfo.GetKernelCpuFamily().c_str(), g_sysinfo.GetKernelBitness(), g_sysinfo.GetKernelVersionFull().c_str()); CLog::Log(LOGNOTICE, "FFmpeg version/source: %s", av_version_info()); std::string cpuModel(g_cpuInfo.getCPUModel()); if (!cpuModel.empty()) CLog::Log(LOGNOTICE, "Host CPU: %s, %d core%s available", cpuModel.c_str(), g_cpuInfo.getCPUCount(), (g_cpuInfo.getCPUCount() == 1) ? "" : "s"); else CLog::Log(LOGNOTICE, "%d CPU core%s available", g_cpuInfo.getCPUCount(), (g_cpuInfo.getCPUCount() == 1) ? "" : "s"); //! @todo - move to CPlatformXXX ??? #if defined(TARGET_WINDOWS) CLog::Log(LOGNOTICE, "%s", CWIN32Util::GetResInfoString().c_str()); CLog::Log(LOGNOTICE, "Running with %s rights", (CWIN32Util::IsCurrentUserLocalAdministrator() == TRUE) ? "administrator" : "restricted"); CLog::Log(LOGNOTICE, "Aero is %s", (g_sysinfo.IsAeroDisabled() == true) ? "disabled" : "enabled"); #endif #if defined(TARGET_ANDROID) CLog::Log(LOGNOTICE, "Product: %s, Device: %s, Board: %s - Manufacturer: %s, Brand: %s, Model: %s, Hardware: %s", CJNIBuild::PRODUCT.c_str(), CJNIBuild::DEVICE.c_str(), CJNIBuild::BOARD.c_str(), CJNIBuild::MANUFACTURER.c_str(), CJNIBuild::BRAND.c_str(), CJNIBuild::MODEL.c_str(), CJNIBuild::HARDWARE.c_str()); std::string extstorage; bool extready = CXBMCApp::GetExternalStorage(extstorage); CLog::Log(LOGNOTICE, "External storage path = %s; status = %s", extstorage.c_str(), extready ? "ok" : "nok"); #endif #if defined(__arm__) || defined(__aarch64__) if (g_cpuInfo.GetCPUFeatures() & CPU_FEATURE_NEON) CLog::Log(LOGNOTICE, "ARM Features: Neon enabled"); else CLog::Log(LOGNOTICE, "ARM Features: Neon disabled"); #endif CSpecialProtocol::LogPaths(); std::string executable = CUtil::ResolveExecutablePath(); CLog::Log(LOGNOTICE, "The executable running is: %s", executable.c_str()); std::string hostname("[unknown]"); m_network->GetHostName(hostname); CLog::Log(LOGNOTICE, "Local hostname: %s", hostname.c_str()); std::string lowerAppName = CCompileInfo::GetAppName(); StringUtils::ToLower(lowerAppName); CLog::Log(LOGNOTICE, "Log File is located: %s/%s.log", CSpecialProtocol::TranslatePath("special://logpath").c_str(), lowerAppName.c_str()); CRegExp::LogCheckUtf8Support(); CLog::Log(LOGNOTICE, "-----------------------------------------------------------------------"); std::string strExecutablePath = CUtil::GetHomePath(); // for python scripts that check the OS //! @todo - move to CPlatformXXX #if defined(TARGET_DARWIN) setenv("OS","OS X",true); #elif defined(TARGET_POSIX) setenv("OS","Linux",true); #elif defined(TARGET_WINDOWS) CEnvironment::setenv("OS", "win32"); #endif // register ffmpeg lockmanager callback av_lockmgr_register(&ffmpeg_lockmgr_cb); // register avcodec avcodec_register_all(); // register avformat av_register_all(); // register avfilter avfilter_register_all(); // initialize network protocols avformat_network_init(); // set avutil callback av_log_set_callback(ff_avutil_log); g_powerManager.Initialize(); // Load the AudioEngine before settings as they need to query the engine if (!m_ServiceManager->CreateAudioEngine()) { CLog::Log(LOGFATAL, "CApplication::Create: Failed to load an AudioEngine"); return false; } // Initialize default Settings - don't move CLog::Log(LOGNOTICE, "load settings..."); if (!m_ServiceManager->GetSettings().Initialize()) return false; // load the actual values if (!m_ServiceManager->GetSettings().Load()) { CLog::Log(LOGFATAL, "unable to load settings"); return false; } m_ServiceManager->GetSettings().SetLoaded(); CLog::Log(LOGINFO, "creating subdirectories"); CLog::Log(LOGINFO, "userdata folder: %s", CURL::GetRedacted(CProfilesManager::GetInstance().GetProfileUserDataFolder()).c_str()); CLog::Log(LOGINFO, "recording folder: %s", CURL::GetRedacted(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_AUDIOCDS_RECORDINGPATH)).c_str()); CLog::Log(LOGINFO, "screenshots folder: %s", CURL::GetRedacted(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_DEBUG_SCREENSHOTPATH)).c_str()); CDirectory::Create(CProfilesManager::GetInstance().GetUserDataFolder()); CDirectory::Create(CProfilesManager::GetInstance().GetProfileUserDataFolder()); CProfilesManager::GetInstance().CreateProfileFolders(); update_emu_environ();//apply the GUI settings //! @todo - move to CPlatformXXX #ifdef TARGET_WINDOWS CWIN32Util::SetThreadLocalLocale(true); // enable independent locale for each thread, see https://connect.microsoft.com/VisualStudio/feedback/details/794122 #endif // TARGET_WINDOWS // initialize the addon database (must be before the addon manager is init'd) CDatabaseManager::GetInstance().Initialize(true); if (!m_ServiceManager->Init2()) { return false; } // start the AudioEngine if(!m_ServiceManager->StartAudioEngine()) { CLog::Log(LOGFATAL, "CApplication::Create: Failed to start the AudioEngine"); return false; } // restore AE's previous volume state SetHardwareVolume(m_volumeLevel); m_ServiceManager->GetActiveAE().SetMute(m_muted); m_ServiceManager->GetActiveAE().SetSoundMode(m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_AUDIOOUTPUT_GUISOUNDMODE)); // initialize m_replayGainSettings m_replayGainSettings.iType = m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_MUSICPLAYER_REPLAYGAINTYPE); m_replayGainSettings.iPreAmp = m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_MUSICPLAYER_REPLAYGAINPREAMP); m_replayGainSettings.iNoGainPreAmp = m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_MUSICPLAYER_REPLAYGAINNOGAINPREAMP); m_replayGainSettings.bAvoidClipping = m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MUSICPLAYER_REPLAYGAINAVOIDCLIPPING); // Create the Mouse, Keyboard and Remote CInputManager::GetInstance().InitializeInputs(); // load the keyboard layouts if (!CKeyboardLayoutManager::GetInstance().Load()) { CLog::Log(LOGFATAL, "CApplication::Create: Unable to load keyboard layouts"); return false; } //! @todo - move to CPlatformXXX #if defined(TARGET_DARWIN_OSX) // Configure and possible manually start the helper. XBMCHelper::GetInstance().Configure(); #endif CUtil::InitRandomSeed(); g_mediaManager.Initialize(); m_lastRenderTime = XbmcThreads::SystemClockMillis(); return true; } bool CApplication::CreateGUI() { m_frameMoveGuard.lock(); m_renderGUI = true; #ifdef HAS_SDL CLog::Log(LOGNOTICE, "Setup SDL"); /* Clean up on exit, exit on window close and interrupt */ atexit(SDL_Quit); uint32_t sdlFlags = 0; #if defined(TARGET_DARWIN_OSX) sdlFlags |= SDL_INIT_VIDEO; #endif //depending on how it's compiled, SDL periodically calls XResetScreenSaver when it's fullscreen //this might bring the monitor out of standby, so we have to disable it explicitly //by passing 0 for overwrite to setsenv, the user can still override this by setting the environment variable #if defined(TARGET_POSIX) && !defined(TARGET_DARWIN) setenv("SDL_VIDEO_ALLOW_SCREENSAVER", "1", 0); #endif #endif // HAS_SDL m_bSystemScreenSaverEnable = g_Windowing.IsSystemScreenSaverEnabled(); g_Windowing.EnableSystemScreenSaver(false); #ifdef HAS_SDL if (SDL_Init(sdlFlags) != 0) { CLog::Log(LOGFATAL, "XBAppEx: Unable to initialize SDL: %s", SDL_GetError()); return false; } #if defined(TARGET_DARWIN) // SDL_Init will install a handler for segfaults, restore the default handler. signal(SIGSEGV, SIG_DFL); #endif #endif // Initialize core peripheral port support. Note: If these parameters // are 0 and NULL, respectively, then the default number and types of // controllers will be initialized. if (!g_Windowing.InitWindowSystem()) { CLog::Log(LOGFATAL, "CApplication::Create: Unable to init windowing system"); return false; } // Retrieve the matching resolution based on GUI settings bool sav_res = false; CDisplaySettings::GetInstance().SetCurrentResolution(CDisplaySettings::GetInstance().GetDisplayResolution()); CLog::Log(LOGNOTICE, "Checking resolution %i", CDisplaySettings::GetInstance().GetCurrentResolution()); if (!g_graphicsContext.IsValidResolution(CDisplaySettings::GetInstance().GetCurrentResolution())) { CLog::Log(LOGNOTICE, "Setting safe mode %i", RES_DESKTOP); // defer saving resolution after window was created CDisplaySettings::GetInstance().SetCurrentResolution(RES_DESKTOP); sav_res = true; } // update the window resolution g_Windowing.SetWindowResolution(m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_WINDOW_WIDTH), m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_WINDOW_HEIGHT)); if (g_advancedSettings.m_startFullScreen && CDisplaySettings::GetInstance().GetCurrentResolution() == RES_WINDOW) { // defer saving resolution after window was created CDisplaySettings::GetInstance().SetCurrentResolution(RES_DESKTOP); sav_res = true; } if (!g_graphicsContext.IsValidResolution(CDisplaySettings::GetInstance().GetCurrentResolution())) { // Oh uh - doesn't look good for starting in their wanted screenmode CLog::Log(LOGERROR, "The screen resolution requested is not valid, resetting to a valid mode"); CDisplaySettings::GetInstance().SetCurrentResolution(RES_DESKTOP); sav_res = true; } if (!InitWindow()) { return false; } if (sav_res) CDisplaySettings::GetInstance().SetCurrentResolution(RES_DESKTOP, true); CSplash::GetInstance().Show(); // The key mappings may already have been loaded by a peripheral CLog::Log(LOGINFO, "load keymapping"); if (!CButtonTranslator::GetInstance().Load()) return false; RESOLUTION_INFO info = g_graphicsContext.GetResInfo(); CLog::Log(LOGINFO, "GUI format %ix%i, Display %s", info.iWidth, info.iHeight, info.strMode.c_str()); g_windowManager.Initialize(); return true; } bool CApplication::InitWindow(RESOLUTION res) { if (res == RES_INVALID) res = CDisplaySettings::GetInstance().GetCurrentResolution(); bool bFullScreen = res != RES_WINDOW; if (!g_Windowing.CreateNewWindow(CSysInfo::GetAppName(), bFullScreen, CDisplaySettings::GetInstance().GetResolutionInfo(res))) { CLog::Log(LOGFATAL, "CApplication::Create: Unable to create window"); return false; } if (!g_Windowing.InitRenderSystem()) { CLog::Log(LOGFATAL, "CApplication::Create: Unable to init rendering system"); return false; } // set GUI res and force the clear of the screen g_graphicsContext.SetVideoResolution(res); return true; } bool CApplication::DestroyWindow() { return g_Windowing.DestroyWindow(); } bool CApplication::InitDirectoriesLinux() { /* The following is the directory mapping for Platform Specific Mode: special://xbmc/ => [read-only] system directory (/usr/share/kodi) special://home/ => [read-write] user's directory that will override special://kodi/ system-wide installations like skins, screensavers, etc. ($HOME/.kodi) NOTE: XBMC will look in both special://xbmc/addons and special://home/addons for addons. special://masterprofile/ => [read-write] userdata of master profile. It will by default be mapped to special://home/userdata ($HOME/.kodi/userdata) special://profile/ => [read-write] current profile's userdata directory. Generally special://masterprofile for the master profile or special://masterprofile/profiles/<profile_name> for other profiles. NOTE: All these root directories are lowercase. Some of the sub-directories might be mixed case. */ #if defined(TARGET_POSIX) && !defined(TARGET_DARWIN) std::string userName; if (getenv("USER")) userName = getenv("USER"); else userName = "root"; std::string userHome; if (getenv("HOME")) userHome = getenv("HOME"); else userHome = "/root"; std::string binaddonAltDir; if (getenv("KODI_BINADDON_PATH")) binaddonAltDir = getenv("KODI_BINADDON_PATH"); std::string appPath; std::string appName = CCompileInfo::GetAppName(); std::string dotLowerAppName = "." + appName; StringUtils::ToLower(dotLowerAppName); const char* envAppHome = "KODI_HOME"; const char* envAppBinHome = "KODI_BIN_HOME"; const char* envAppTemp = "KODI_TEMP"; auto appBinPath = CUtil::GetHomePath(envAppBinHome); // overridden by user if (getenv(envAppHome)) appPath = getenv(envAppHome); else { // use build time default appPath = INSTALL_PATH; /* Check if binaries and arch independent data files are being kept in * separate locations. */ if (!CDirectory::Exists(URIUtils::AddFileToFolder(appPath, "userdata"))) { /* Attempt to locate arch independent data files. */ appPath = CUtil::GetHomePath(appBinPath); if (!CDirectory::Exists(URIUtils::AddFileToFolder(appPath, "userdata"))) { fprintf(stderr, "Unable to find path to %s data files!\n", appName.c_str()); exit(1); } } } /* Set some environment variables */ setenv(envAppBinHome, appBinPath.c_str(), 0); setenv(envAppHome, appPath.c_str(), 0); if (m_bPlatformDirectories) { // map our special drives CSpecialProtocol::SetXBMCBinPath(appBinPath); CSpecialProtocol::SetXBMCAltBinAddonPath(binaddonAltDir); CSpecialProtocol::SetXBMCPath(appPath); CSpecialProtocol::SetHomePath(userHome + "/" + dotLowerAppName); CSpecialProtocol::SetMasterProfilePath(userHome + "/" + dotLowerAppName + "/userdata"); std::string strTempPath = userHome; strTempPath = URIUtils::AddFileToFolder(strTempPath, dotLowerAppName + "/temp"); if (getenv(envAppTemp)) strTempPath = getenv(envAppTemp); CSpecialProtocol::SetTempPath(strTempPath); CSpecialProtocol::SetLogPath(strTempPath); CreateUserDirs(); } else { URIUtils::AddSlashAtEnd(appPath); CSpecialProtocol::SetXBMCBinPath(appBinPath); CSpecialProtocol::SetXBMCAltBinAddonPath(binaddonAltDir); CSpecialProtocol::SetXBMCPath(appPath); CSpecialProtocol::SetHomePath(URIUtils::AddFileToFolder(appPath, "portable_data")); CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(appPath, "portable_data/userdata")); std::string strTempPath = appPath; strTempPath = URIUtils::AddFileToFolder(strTempPath, "portable_data/temp"); if (getenv(envAppTemp)) strTempPath = getenv(envAppTemp); CSpecialProtocol::SetTempPath(strTempPath); CSpecialProtocol::SetLogPath(strTempPath); CreateUserDirs(); } CSpecialProtocol::SetXBMCBinAddonPath(appBinPath + "/addons"); #if defined(TARGET_ANDROID) CXBMCApp::InitDirectories(); #endif return true; #else return false; #endif } bool CApplication::InitDirectoriesOSX() { #if defined(TARGET_DARWIN) std::string userName; if (getenv("USER")) userName = getenv("USER"); else userName = "root"; std::string userHome; if (getenv("HOME")) userHome = getenv("HOME"); else userHome = "/root"; std::string binaddonAltDir; if (getenv("KODI_BINADDON_PATH")) binaddonAltDir = getenv("KODI_BINADDON_PATH"); std::string appPath = CUtil::GetHomePath(); setenv("KODI_HOME", appPath.c_str(), 0); #if defined(TARGET_DARWIN_IOS) std::string fontconfigPath; fontconfigPath = appPath + "/system/players/VideoPlayer/etc/fonts/fonts.conf"; setenv("FONTCONFIG_FILE", fontconfigPath.c_str(), 0); #endif // setup path to our internal dylibs so loader can find them std::string frameworksPath = CUtil::GetFrameworksPath(); CSpecialProtocol::SetXBMCFrameworksPath(frameworksPath); // OSX always runs with m_bPlatformDirectories == true if (m_bPlatformDirectories) { // map our special drives CSpecialProtocol::SetXBMCBinPath(appPath); CSpecialProtocol::SetXBMCAltBinAddonPath(binaddonAltDir); CSpecialProtocol::SetXBMCPath(appPath); #if defined(TARGET_DARWIN_IOS) std::string appName = CCompileInfo::GetAppName(); CSpecialProtocol::SetHomePath(userHome + "/" + CDarwinUtils::GetAppRootFolder() + "/" + appName); CSpecialProtocol::SetMasterProfilePath(userHome + "/" + CDarwinUtils::GetAppRootFolder() + "/" + appName + "/userdata"); #else std::string appName = CCompileInfo::GetAppName(); CSpecialProtocol::SetHomePath(userHome + "/Library/Application Support/" + appName); CSpecialProtocol::SetMasterProfilePath(userHome + "/Library/Application Support/" + appName + "/userdata"); #endif std::string dotLowerAppName = "." + appName; StringUtils::ToLower(dotLowerAppName); // location for temp files #if defined(TARGET_DARWIN_IOS) std::string strTempPath = URIUtils::AddFileToFolder(userHome, std::string(CDarwinUtils::GetAppRootFolder()) + "/" + appName + "/temp"); #else std::string strTempPath = URIUtils::AddFileToFolder(userHome, dotLowerAppName + "/"); CDirectory::Create(strTempPath); strTempPath = URIUtils::AddFileToFolder(userHome, dotLowerAppName + "/temp"); #endif CSpecialProtocol::SetTempPath(strTempPath); // xbmc.log file location #if defined(TARGET_DARWIN_IOS) strTempPath = userHome + "/" + std::string(CDarwinUtils::GetAppRootFolder()); #else strTempPath = userHome + "/Library/Logs"; #endif CSpecialProtocol::SetLogPath(strTempPath); CreateUserDirs(); } else { URIUtils::AddSlashAtEnd(appPath); CSpecialProtocol::SetXBMCBinPath(appPath); CSpecialProtocol::SetXBMCAltBinAddonPath(binaddonAltDir); CSpecialProtocol::SetXBMCPath(appPath); CSpecialProtocol::SetHomePath(URIUtils::AddFileToFolder(appPath, "portable_data")); CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(appPath, "portable_data/userdata")); std::string strTempPath = URIUtils::AddFileToFolder(appPath, "portable_data/temp"); CSpecialProtocol::SetTempPath(strTempPath); CSpecialProtocol::SetLogPath(strTempPath); } CSpecialProtocol::SetXBMCBinAddonPath(appPath + "/addons"); return true; #else return false; #endif } bool CApplication::InitDirectoriesWin32() { #ifdef TARGET_WINDOWS std::string xbmcPath = CUtil::GetHomePath(); CEnvironment::setenv("KODI_HOME", xbmcPath); CSpecialProtocol::SetXBMCBinPath(xbmcPath); CSpecialProtocol::SetXBMCPath(xbmcPath); CSpecialProtocol::SetXBMCBinAddonPath(xbmcPath + "/addons"); std::string strWin32UserFolder = CWIN32Util::GetProfilePath(); CSpecialProtocol::SetLogPath(strWin32UserFolder); CSpecialProtocol::SetHomePath(strWin32UserFolder); CSpecialProtocol::SetMasterProfilePath(URIUtils::AddFileToFolder(strWin32UserFolder, "userdata")); CSpecialProtocol::SetTempPath(URIUtils::AddFileToFolder(strWin32UserFolder,"cache")); CEnvironment::setenv("KODI_PROFILE_USERDATA", CSpecialProtocol::TranslatePath("special://masterprofile/")); CreateUserDirs(); return true; #else return false; #endif } void CApplication::CreateUserDirs() const { CDirectory::Create("special://home/"); CDirectory::Create("special://home/addons"); CDirectory::Create("special://home/addons/packages"); CDirectory::Create("special://home/addons/temp"); CDirectory::Create("special://home/media"); CDirectory::Create("special://home/system"); CDirectory::Create("special://masterprofile/"); CDirectory::Create("special://temp/"); CDirectory::Create("special://logpath"); CDirectory::Create("special://temp/temp"); // temp directory for python and dllGetTempPathA //Let's clear our archive cache before starting up anything more auto archiveCachePath = CSpecialProtocol::TranslatePath("special://temp/archive_cache/"); if (CDirectory::Exists(archiveCachePath)) if (!CDirectory::RemoveRecursive(archiveCachePath)) CLog::Log(LOGWARNING, "Failed to remove the archive cache at %s", archiveCachePath.c_str()); CDirectory::Create(archiveCachePath); } bool CApplication::Initialize() { #if defined(HAS_DVD_DRIVE) && !defined(TARGET_WINDOWS) // somehow this throws an "unresolved external symbol" on win32 // turn off cdio logging cdio_loglevel_default = CDIO_LOG_ERROR; #endif #ifdef TARGET_POSIX //! @todo Win32 has no special://home/ mapping by default, so we //! must create these here. Ideally this should be using special://home/ and //! be platform agnostic (i.e. unify the InitDirectories*() functions) if (!m_bPlatformDirectories) #endif { CDirectory::Create("special://xbmc/addons"); } // load the language and its translated strings if (!LoadLanguage(false)) return false; CEventLog::GetInstance().Add(EventPtr(new CNotificationEvent( StringUtils::Format(g_localizeStrings.Get(177).c_str(), g_sysinfo.GetAppName().c_str()), StringUtils::Format(g_localizeStrings.Get(178).c_str(), g_sysinfo.GetAppName().c_str()), "special://xbmc/media/icon256x256.png", EventLevel::Basic))); getNetwork().WaitForNet(); // Load curl so curl_global_init gets called before any service threads // are started. Unloading will have no effect as curl is never fully unloaded. // To quote man curl_global_init: // "This function is not thread safe. You must not call it when any other // thread in the program (i.e. a thread sharing the same memory) is running. // This doesn't just mean no other thread that is using libcurl. Because // curl_global_init() calls functions of other libraries that are similarly // thread unsafe, it could conflict with any other thread that // uses these other libraries." g_curlInterface.Load(); g_curlInterface.Unload(); // initialize (and update as needed) our databases CEvent event(true); CJobManager::GetInstance().Submit([&event]() { CDatabaseManager::GetInstance().Initialize(); event.Set(); }); std::string localizedStr = g_localizeStrings.Get(24150); int iDots = 1; while (!event.WaitMSec(1000)) { if (CDatabaseManager::GetInstance().m_bIsUpgrading) CSplash::GetInstance().Show(std::string(iDots, ' ') + localizedStr + std::string(iDots, '.')); if (iDots == 3) iDots = 1; else ++iDots; } CSplash::GetInstance().Show(); StartServices(); // Init DPMS, before creating the corresponding setting control. m_dpms.reset(new DPMSSupport()); bool uiInitializationFinished = true; if (g_windowManager.Initialized()) { m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_POWERMANAGEMENT_DISPLAYSOFF)->SetRequirementsMet(m_dpms->IsSupported()); g_windowManager.CreateWindows(); m_confirmSkinChange = false; std::vector<std::string> incompatibleAddons; event.Reset(); std::atomic<bool> isMigratingAddons(false); CJobManager::GetInstance().Submit([&event, &incompatibleAddons, &isMigratingAddons]() { incompatibleAddons = CAddonSystemSettings::GetInstance().MigrateAddons([&isMigratingAddons]() { isMigratingAddons = true; }); event.Set(); }, CJob::PRIORITY_DEDICATED); localizedStr = g_localizeStrings.Get(24151); iDots = 1; while (!event.WaitMSec(1000)) { if (isMigratingAddons) CSplash::GetInstance().Show(std::string(iDots, ' ') + localizedStr + std::string(iDots, '.')); if (iDots == 3) iDots = 1; else ++iDots; } CSplash::GetInstance().Show(); m_incompatibleAddons = incompatibleAddons; m_confirmSkinChange = true; std::string defaultSkin = std::static_pointer_cast<const CSettingString>(m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_SKIN))->GetDefault(); if (!LoadSkin(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_SKIN))) { CLog::Log(LOGERROR, "Failed to load skin '%s'", m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_SKIN).c_str()); if (!LoadSkin(defaultSkin)) { CLog::Log(LOGFATAL, "Default skin '%s' could not be loaded! Terminating..", defaultSkin.c_str()); return false; } } // initialize splash window after splash screen disappears // because we need a real window in the background which gets // rendered while we load the main window or enter the master lock key if (g_advancedSettings.m_splashImage) g_windowManager.ActivateWindow(WINDOW_SPLASH); if (m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MASTERLOCK_STARTUPLOCK) && CProfilesManager::GetInstance().GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE && !CProfilesManager::GetInstance().GetMasterProfile().getLockCode().empty()) { g_passwordManager.CheckStartUpLock(); } // check if we should use the login screen if (CProfilesManager::GetInstance().UsingLoginScreen()) { // the login screen still needs to perform additional initialization uiInitializationFinished = false; g_windowManager.ActivateWindow(WINDOW_LOGIN_SCREEN); } else { #ifdef HAS_JSONRPC CJSONRPC::Initialize(); #endif ADDON::CAddonMgr::GetInstance().StartServices(false); // activate the configured start window int firstWindow = g_SkinInfo->GetFirstWindow(); g_windowManager.ActivateWindow(firstWindow); if (g_windowManager.GetActiveWindowID() == WINDOW_STARTUP_ANIM) { CLog::Log(LOGWARNING, "CApplication::Initialize - startup.xml taints init process"); } // the startup window is considered part of the initialization as it most likely switches to the final window uiInitializationFinished = firstWindow != WINDOW_STARTUP_ANIM; CStereoscopicsManager::GetInstance().Initialize(); if (!m_ServiceManager->Init3()) { CLog::Log(LOGERROR, "Application - Init3 failed"); } } } else //No GUI Created { #ifdef HAS_JSONRPC CJSONRPC::Initialize(); #endif ADDON::CAddonMgr::GetInstance().StartServices(false); } g_sysinfo.Refresh(); CLog::Log(LOGINFO, "removing tempfiles"); CUtil::RemoveTempFiles(); if (!CProfilesManager::GetInstance().UsingLoginScreen()) { UpdateLibraries(); SetLoggingIn(false); } m_slowTimer.StartZero(); CAddonMgr::GetInstance().StartServices(true); // configure seek handler CSeekHandler::GetInstance().Configure(); // register action listeners RegisterActionListener(&CSeekHandler::GetInstance()); RegisterActionListener(&CPlayerController::GetInstance()); CRepositoryUpdater::GetInstance().Start(); CLog::Log(LOGNOTICE, "initialize done"); // reset our screensaver (starts timers etc.) ResetScreenSaver(); // if the user interfaces has been fully initialized let everyone know if (uiInitializationFinished) { CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UI_READY); g_windowManager.SendThreadMessage(msg); } return true; } bool CApplication::StartServer(enum ESERVERS eServer, bool bStart, bool bWait/* = false*/) { bool ret = false; switch(eServer) { case ES_WEBSERVER: // the callback will take care of starting/stopping webserver ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_WEBSERVER, bStart); break; case ES_AIRPLAYSERVER: // the callback will take care of starting/stopping airplay ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_AIRPLAY, bStart); break; case ES_JSONRPCSERVER: // the callback will take care of starting/stopping jsonrpc server ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_ESENABLED, bStart); break; case ES_UPNPSERVER: // the callback will take care of starting/stopping upnp server ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_UPNPSERVER, bStart); break; case ES_UPNPRENDERER: // the callback will take care of starting/stopping upnp renderer ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_UPNPRENDERER, bStart); break; case ES_EVENTSERVER: // the callback will take care of starting/stopping event server ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_ESENABLED, bStart); break; case ES_ZEROCONF: // the callback will take care of starting/stopping zeroconf ret = m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_SERVICES_ZEROCONF, bStart); break; default: ret = false; break; } m_ServiceManager->GetSettings().Save(); return ret; } void CApplication::StartServices() { #if !defined(TARGET_WINDOWS) && defined(HAS_DVD_DRIVE) // Start Thread for DVD Mediatype detection CLog::Log(LOGNOTICE, "start dvd mediatype detection"); m_DetectDVDType.Create(false, THREAD_MINSTACKSIZE); #endif } void CApplication::StopServices() { m_network->NetworkMessage(CNetwork::SERVICES_DOWN, 0); #if !defined(TARGET_WINDOWS) && defined(HAS_DVD_DRIVE) CLog::Log(LOGNOTICE, "stop dvd detect media"); m_DetectDVDType.StopThread(); #endif } void CApplication::OnSettingChanged(std::shared_ptr<const CSetting> setting) { if (setting == NULL) return; const std::string &settingId = setting->GetId(); if (settingId == CSettings::SETTING_LOOKANDFEEL_SKIN || settingId == CSettings::SETTING_LOOKANDFEEL_FONT || settingId == CSettings::SETTING_LOOKANDFEEL_SKINTHEME || settingId == CSettings::SETTING_LOOKANDFEEL_SKINCOLORS) { // check if we should ignore this change event due to changing skins in which case we have to // change several settings and each one of them could lead to a complete skin reload which would // result in multiple skin reloads. Therefore we manually specify to ignore specific settings // which are going to be changed. if (m_ignoreSkinSettingChanges) return; // if the skin changes and the current color/theme/font is not the default one, reset // the it to the default value if (settingId == CSettings::SETTING_LOOKANDFEEL_SKIN) { SettingPtr skinRelatedSetting = m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_SKINCOLORS); if (!skinRelatedSetting->IsDefault()) { m_ignoreSkinSettingChanges = true; skinRelatedSetting->Reset(); } skinRelatedSetting = m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_SKINTHEME); if (!skinRelatedSetting->IsDefault()) { m_ignoreSkinSettingChanges = true; skinRelatedSetting->Reset(); } skinRelatedSetting = m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_FONT); if (!skinRelatedSetting->IsDefault()) { m_ignoreSkinSettingChanges = true; skinRelatedSetting->Reset(); } } else if (settingId == CSettings::SETTING_LOOKANDFEEL_SKINTHEME) { std::shared_ptr<CSettingString> skinColorsSetting = std::static_pointer_cast<CSettingString>(m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_SKINCOLORS)); m_ignoreSkinSettingChanges = true; // we also need to adjust the skin color setting std::string colorTheme = std::static_pointer_cast<const CSettingString>(setting)->GetValue(); URIUtils::RemoveExtension(colorTheme); if (setting->IsDefault() || StringUtils::EqualsNoCase(colorTheme, "Textures")) skinColorsSetting->Reset(); else skinColorsSetting->SetValue(colorTheme); } m_ignoreSkinSettingChanges = false; if (g_SkinInfo) { // now we can finally reload skins std::string builtin("ReloadSkin"); if (settingId == CSettings::SETTING_LOOKANDFEEL_SKIN && m_confirmSkinChange) builtin += "(confirm)"; CApplicationMessenger::GetInstance().PostMsg(TMSG_EXECUTE_BUILT_IN, -1, -1, nullptr, builtin); } } else if (settingId == CSettings::SETTING_LOOKANDFEEL_SKINZOOM) { CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_WINDOW_RESIZE); g_windowManager.SendThreadMessage(msg); } else if (StringUtils::StartsWithNoCase(settingId, "audiooutput.")) { // AE is master of audio settings and needs to be informed first m_ServiceManager->GetActiveAE().OnSettingsChange(settingId); if (settingId == CSettings::SETTING_AUDIOOUTPUT_GUISOUNDMODE) { m_ServiceManager->GetActiveAE().SetSoundMode((std::static_pointer_cast<const CSettingInt>(setting))->GetValue()); } // this tells player whether to open an audio stream passthrough or PCM // if this is changed, audio stream has to be reopened else if (settingId == CSettings::SETTING_AUDIOOUTPUT_PASSTHROUGH) { CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_RESTART); } } else if (StringUtils::EqualsNoCase(settingId, CSettings::SETTING_MUSICPLAYER_REPLAYGAINTYPE)) m_replayGainSettings.iType = std::static_pointer_cast<const CSettingInt>(setting)->GetValue(); else if (StringUtils::EqualsNoCase(settingId, CSettings::SETTING_MUSICPLAYER_REPLAYGAINPREAMP)) m_replayGainSettings.iPreAmp = std::static_pointer_cast<const CSettingInt>(setting)->GetValue(); else if (StringUtils::EqualsNoCase(settingId, CSettings::SETTING_MUSICPLAYER_REPLAYGAINNOGAINPREAMP)) m_replayGainSettings.iNoGainPreAmp = std::static_pointer_cast<const CSettingInt>(setting)->GetValue(); else if (StringUtils::EqualsNoCase(settingId, CSettings::SETTING_MUSICPLAYER_REPLAYGAINAVOIDCLIPPING)) m_replayGainSettings.bAvoidClipping = std::static_pointer_cast<const CSettingBool>(setting)->GetValue(); } void CApplication::OnSettingAction(std::shared_ptr<const CSetting> setting) { if (setting == NULL) return; const std::string &settingId = setting->GetId(); if (settingId == CSettings::SETTING_LOOKANDFEEL_SKINSETTINGS) g_windowManager.ActivateWindow(WINDOW_SKIN_SETTINGS); else if (settingId == CSettings::SETTING_SCREENSAVER_PREVIEW) ActivateScreenSaver(true); else if (settingId == CSettings::SETTING_SCREENSAVER_SETTINGS) { AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_SCREENSAVER_MODE), addon, ADDON_SCREENSAVER)) CGUIDialogAddonSettings::ShowForAddon(addon); } else if (settingId == CSettings::SETTING_AUDIOCDS_SETTINGS) { AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_AUDIOCDS_ENCODER), addon, ADDON_AUDIOENCODER)) CGUIDialogAddonSettings::ShowForAddon(addon); } else if (settingId == CSettings::SETTING_VIDEOSCREEN_GUICALIBRATION) g_windowManager.ActivateWindow(WINDOW_SCREEN_CALIBRATION); else if (settingId == CSettings::SETTING_VIDEOSCREEN_TESTPATTERN) g_windowManager.ActivateWindow(WINDOW_TEST_PATTERN); else if (settingId == CSettings::SETTING_SOURCE_VIDEOS) { std::vector<std::string> params{"library://video/files.xml", "return"}; g_windowManager.ActivateWindow(WINDOW_VIDEO_NAV, params); } else if (settingId == CSettings::SETTING_SOURCE_MUSIC) { std::vector<std::string> params{"library://music/files.xml", "return"}; g_windowManager.ActivateWindow(WINDOW_MUSIC_NAV, params); } else if (settingId == CSettings::SETTING_SOURCE_PICTURES) g_windowManager.ActivateWindow(WINDOW_PICTURES); } bool CApplication::OnSettingUpdate(std::shared_ptr<CSetting> setting, const char *oldSettingId, const TiXmlNode *oldSettingNode) { if (setting == NULL) return false; #if defined(HAS_LIBAMCODEC) if (setting->GetId() == CSettings::SETTING_VIDEOPLAYER_USEAMCODEC) { // Do not permit amcodec to be used on non-aml platforms. // The setting will be hidden but the default value is true, // so change it to false. if (!aml_present()) { std::shared_ptr<CSettingBool> useamcodec = std::static_pointer_cast<CSettingBool>(setting); return useamcodec->SetValue(false); } } #endif #if defined(TARGET_DARWIN_OSX) if (setting->GetId() == CSettings::SETTING_AUDIOOUTPUT_AUDIODEVICE) { std::shared_ptr<CSettingString> audioDevice = std::static_pointer_cast<CSettingString>(setting); // Gotham and older didn't enumerate audio devices per stream on osx // add stream0 per default which should be ok for all old settings. if (!StringUtils::EqualsNoCase(audioDevice->GetValue(), "DARWINOSX:default") && StringUtils::FindWords(audioDevice->GetValue().c_str(), ":stream") == std::string::npos) { std::string newSetting = audioDevice->GetValue(); newSetting += ":stream0"; return audioDevice->SetValue(newSetting); } } #endif return false; } bool CApplication::OnSettingsSaving() const { // don't save settings when we're busy stopping the application // a lot of screens try to save settings on deinit and deinit is // called for every screen when the application is stopping if (m_bStop) return false; return true; } void CApplication::ReloadSkin(bool confirm/*=false*/) { if (!g_SkinInfo || m_bInitializing) return; // Don't allow reload before skin is loaded by system std::string oldSkin = g_SkinInfo->ID(); CGUIMessage msg(GUI_MSG_LOAD_SKIN, -1, g_windowManager.GetActiveWindow()); g_windowManager.SendMessage(msg); std::string newSkin = m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_SKIN); if (LoadSkin(newSkin)) { /* The Reset() or SetString() below will cause recursion, so the m_confirmSkinChange boolean is set so as to not prompt the user as to whether they want to keep the current skin. */ if (confirm && m_confirmSkinChange) { if (HELPERS::ShowYesNoDialogText(CVariant{13123}, CVariant{13111}, CVariant{""}, CVariant{""}, 10000) != DialogResponse::YES) { m_confirmSkinChange = false; m_ServiceManager->GetSettings().SetString(CSettings::SETTING_LOOKANDFEEL_SKIN, oldSkin); } } } else { // skin failed to load - we revert to the default only if we didn't fail loading the default std::string defaultSkin = std::static_pointer_cast<CSettingString>(m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_SKIN))->GetDefault(); if (newSkin != defaultSkin) { m_confirmSkinChange = false; m_ServiceManager->GetSettings().GetSetting(CSettings::SETTING_LOOKANDFEEL_SKIN)->Reset(); CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(24102), g_localizeStrings.Get(24103)); } } m_confirmSkinChange = true; } bool CApplication::Load(const TiXmlNode *settings) { if (settings == NULL) return false; const TiXmlElement *audioElement = settings->FirstChildElement("audio"); if (audioElement != NULL) { XMLUtils::GetBoolean(audioElement, "mute", m_muted); if (!XMLUtils::GetFloat(audioElement, "fvolumelevel", m_volumeLevel, VOLUME_MINIMUM, VOLUME_MAXIMUM)) m_volumeLevel = VOLUME_MAXIMUM; } return true; } bool CApplication::Save(TiXmlNode *settings) const { if (settings == NULL) return false; TiXmlElement volumeNode("audio"); TiXmlNode *audioNode = settings->InsertEndChild(volumeNode); if (audioNode == NULL) return false; XMLUtils::SetBoolean(audioNode, "mute", m_muted); XMLUtils::SetFloat(audioNode, "fvolumelevel", m_volumeLevel); return true; } bool CApplication::LoadSkin(const std::string& skinID) { SkinPtr skin; { AddonPtr addon; if (!CAddonMgr::GetInstance().GetAddon(skinID, addon, ADDON_SKIN)) return false; skin = std::static_pointer_cast<ADDON::CSkinInfo>(addon); } // store player and rendering state bool bPreviousPlayingState = false; bool bPreviousRenderingState = false; if (m_pPlayer->IsPlayingVideo()) { bPreviousPlayingState = !m_pPlayer->IsPausedPlayback(); if (bPreviousPlayingState) m_pPlayer->Pause(); m_pPlayer->FlushRenderer(); if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO) { g_windowManager.ActivateWindow(WINDOW_HOME); bPreviousRenderingState = true; } } CSingleLock lock(g_graphicsContext); // store current active window with its focused control int currentWindowID = g_windowManager.GetActiveWindow(); int currentFocusedControlID = -1; if (currentWindowID != WINDOW_INVALID) { CGUIWindow* pWindow = g_windowManager.GetWindow(currentWindowID); if (pWindow) currentFocusedControlID = pWindow->GetFocusedControlID(); } UnloadSkin(); skin->Start(); // migrate any skin-specific settings that are still stored in guisettings.xml CSkinSettings::GetInstance().MigrateSettings(skin); // check if the skin has been properly loaded and if it has a Home.xml if (!skin->HasSkinFile("Home.xml")) { CLog::Log(LOGERROR, "failed to load requested skin '%s'", skin->ID().c_str()); return false; } CLog::Log(LOGNOTICE, " load skin from: %s (version: %s)", skin->Path().c_str(), skin->Version().asString().c_str()); g_SkinInfo = skin; CLog::Log(LOGINFO, " load fonts for skin..."); g_graphicsContext.SetMediaDir(skin->Path()); g_directoryCache.ClearSubPaths(skin->Path()); g_colorManager.Load(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_SKINCOLORS)); g_SkinInfo->LoadIncludes(); g_fontManager.LoadFonts(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOOKANDFEEL_FONT)); // load in the skin strings std::string langPath = URIUtils::AddFileToFolder(skin->Path(), "language"); URIUtils::AddSlashAtEnd(langPath); g_localizeStrings.LoadSkinStrings(langPath, m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOCALE_LANGUAGE)); int64_t start; start = CurrentHostCounter(); CLog::Log(LOGINFO, " load new skin..."); // Load custom windows LoadCustomWindows(); int64_t end, freq; end = CurrentHostCounter(); freq = CurrentHostFrequency(); CLog::Log(LOGDEBUG,"Load Skin XML: %.2fms", 1000.f * (end - start) / freq); CLog::Log(LOGINFO, " initialize new skin..."); g_windowManager.AddMsgTarget(this); g_windowManager.AddMsgTarget(&g_playlistPlayer); g_windowManager.AddMsgTarget(&g_infoManager); g_windowManager.AddMsgTarget(&g_fontManager); g_windowManager.AddMsgTarget(&CStereoscopicsManager::GetInstance()); g_windowManager.SetCallback(*this); g_windowManager.Initialize(); CTextureCache::GetInstance().Initialize(); g_audioManager.Enable(true); g_audioManager.Load(); if (g_SkinInfo->HasSkinFile("DialogFullScreenInfo.xml")) g_windowManager.Add(new CGUIDialogFullScreenInfo); CLog::Log(LOGINFO, " skin loaded..."); // leave the graphics lock lock.Leave(); // restore active window if (currentWindowID != WINDOW_INVALID) { g_windowManager.ActivateWindow(currentWindowID); if (currentFocusedControlID != -1) { CGUIWindow *pWindow = g_windowManager.GetWindow(currentWindowID); if (pWindow && pWindow->HasSaveLastControl()) { CGUIMessage msg(GUI_MSG_SETFOCUS, currentWindowID, currentFocusedControlID, 0); pWindow->OnMessage(msg); } } } // restore player and rendering state if (m_pPlayer->IsPlayingVideo()) { if (bPreviousPlayingState) m_pPlayer->Pause(); if (bPreviousRenderingState) g_windowManager.ActivateWindow(WINDOW_FULLSCREEN_VIDEO); } return true; } void CApplication::UnloadSkin(bool forReload /* = false */) { CLog::Log(LOGINFO, "Unloading old skin %s...", forReload ? "for reload " : ""); if (g_SkinInfo != nullptr && m_saveSkinOnUnloading) g_SkinInfo->SaveSettings(); else if (!m_saveSkinOnUnloading) m_saveSkinOnUnloading = true; g_audioManager.Enable(false); g_windowManager.DeInitialize(); CTextureCache::GetInstance().Deinitialize(); // remove the skin-dependent window g_windowManager.Delete(WINDOW_DIALOG_FULLSCREEN_INFO); g_TextureManager.Cleanup(); g_largeTextureManager.CleanupUnusedImages(true); g_fontManager.Clear(); g_colorManager.Clear(); g_infoManager.Clear(); // The g_SkinInfo shared_ptr ought to be reset here // but there are too many places it's used without checking for NULL // and as a result a race condition on exit can cause a crash. } bool CApplication::LoadCustomWindows() { // Start from wherever home.xml is std::vector<std::string> vecSkinPath; g_SkinInfo->GetSkinPaths(vecSkinPath); for (const auto &skinPath : vecSkinPath) { CLog::Log(LOGINFO, "Loading custom window XMLs from skin path %s", skinPath.c_str()); CFileItemList items; if (CDirectory::GetDirectory(skinPath, items, ".xml", DIR_FLAG_NO_FILE_DIRS)) { for (const auto &item : items.GetList()) { if (item->m_bIsFolder) continue; std::string skinFile = URIUtils::GetFileName(item->GetPath()); if (StringUtils::StartsWithNoCase(skinFile, "custom")) { CXBMCTinyXML xmlDoc; if (!xmlDoc.LoadFile(item->GetPath())) { CLog::Log(LOGERROR, "Unable to load custom window XML %s. Line %d\n%s", item->GetPath().c_str(), xmlDoc.ErrorRow(), xmlDoc.ErrorDesc()); continue; } // Root element should be <window> TiXmlElement* pRootElement = xmlDoc.RootElement(); std::string strValue = pRootElement->Value(); if (!StringUtils::EqualsNoCase(strValue, "window")) { CLog::Log(LOGERROR, "No <window> root element found for custom window in %s", skinFile.c_str()); continue; } int id = WINDOW_INVALID; // Read the type attribute or element to get the window type to create // If no type is specified, create a CGUIWindow as default std::string strType; if (pRootElement->Attribute("type")) strType = pRootElement->Attribute("type"); else { const TiXmlNode *pType = pRootElement->FirstChild("type"); if (pType && pType->FirstChild()) strType = pType->FirstChild()->Value(); } // Read the id attribute or element to get the window id if (!pRootElement->Attribute("id", &id)) { const TiXmlNode *pType = pRootElement->FirstChild("id"); if (pType && pType->FirstChild()) id = atol(pType->FirstChild()->Value()); } int windowId = id + WINDOW_HOME; if (id == WINDOW_INVALID || g_windowManager.GetWindow(windowId)) { // No id specified or id already in use CLog::Log(LOGERROR, "No id specified or id already in use for custom window in %s", skinFile.c_str()); continue; } CGUIWindow* pWindow = NULL; bool hasVisibleCondition = false; if (StringUtils::EqualsNoCase(strType, "dialog")) { hasVisibleCondition = pRootElement->FirstChildElement("visible"); pWindow = new CGUIDialog(windowId, skinFile); } else if (StringUtils::EqualsNoCase(strType, "submenu")) { pWindow = new CGUIDialogSubMenu(windowId, skinFile); } else if (StringUtils::EqualsNoCase(strType, "buttonmenu")) { pWindow = new CGUIDialogButtonMenu(windowId, skinFile); } else { pWindow = new CGUIWindow(windowId, skinFile); } if (!pWindow) { CLog::Log(LOGERROR, "Failed to create custom window from %s", skinFile.c_str()); continue; } pWindow->SetCustom(true); // Determining whether our custom dialog is modeless (visible condition is present) // will be done on load. Therefore we need to initialize the custom dialog on gui init. pWindow->SetLoadType(hasVisibleCondition ? CGUIWindow::LOAD_ON_GUI_INIT : CGUIWindow::KEEP_IN_MEMORY); g_windowManager.AddCustomWindow(pWindow); } } } } return true; } void CApplication::Render() { // do not render if we are stopped or in background if (m_bStop) return; bool hasRendered = false; // Whether externalplayer is playing and we're unfocused bool extPlayerActive = m_pPlayer->IsExternalPlaying() && !m_AppFocused; if (!extPlayerActive && g_graphicsContext.IsFullScreenVideo() && !m_pPlayer->IsPausedPlayback()) { ResetScreenSaver(); } if(!g_Windowing.BeginRender()) return; // render gui layer if (!m_skipGuiRender) { if (g_graphicsContext.GetStereoMode()) { g_graphicsContext.SetStereoView(RENDER_STEREO_VIEW_LEFT); hasRendered |= g_windowManager.Render(); if (g_graphicsContext.GetStereoMode() != RENDER_STEREO_MODE_MONO) { g_graphicsContext.SetStereoView(RENDER_STEREO_VIEW_RIGHT); hasRendered |= g_windowManager.Render(); } g_graphicsContext.SetStereoView(RENDER_STEREO_VIEW_OFF); } else { hasRendered |= g_windowManager.Render(); } // execute post rendering actions (finalize window closing) g_windowManager.AfterRender(); m_lastRenderTime = XbmcThreads::SystemClockMillis(); } // render video layer g_windowManager.RenderEx(); g_Windowing.EndRender(); // reset our info cache - we do this at the end of Render so that it is // fresh for the next process(), or after a windowclose animation (where process() // isn't called) g_infoManager.ResetCache(); if (hasRendered) { g_infoManager.UpdateFPS(); } g_graphicsContext.Flip(hasRendered, m_pPlayer->IsRenderingVideoLayer()); CTimeUtils::UpdateFrameTime(hasRendered); } void CApplication::SetStandAlone(bool value) { g_advancedSettings.m_handleMounting = m_bStandalone = value; } // OnAppCommand is called in response to a XBMC_APPCOMMAND event. // This needs to return true if it processed the appcommand or false if it didn't bool CApplication::OnAppCommand(const CAction &action) { // Reset the screen saver ResetScreenSaver(); // If we were currently in the screen saver wake up and don't process the appcommand if (WakeUpScreenSaverAndDPMS()) return true; // The action ID is the APPCOMMAND code. We need to retrieve the action // associated with this appcommand from the mapping table. uint32_t appcmd = action.GetID(); CKey key(appcmd | KEY_APPCOMMAND, (unsigned int) 0); int iWin = g_windowManager.GetActiveWindow() & WINDOW_ID_MASK; CAction appcmdaction = CButtonTranslator::GetInstance().GetAction(iWin, key); // If we couldn't find an action return false to indicate we have not // handled this appcommand if (!appcmdaction.GetID()) { CLog::LogF(LOGDEBUG, "unknown appcommand %d", appcmd); return false; } // Process the appcommand CLog::LogF(LOGDEBUG, "appcommand %d, trying action %s", appcmd, appcmdaction.GetName().c_str()); OnAction(appcmdaction); // Always return true regardless of whether the action succeeded or not. // This stops Windows handling the appcommand itself. return true; } bool CApplication::OnAction(const CAction &action) { // special case for switching between GUI & fullscreen mode. if (action.GetID() == ACTION_SHOW_GUI) { // Switch to fullscreen mode if we can if (SwitchToFullScreen()) { m_navigationTimer.StartZero(); return true; } } if (action.GetID() == ACTION_TOGGLE_FULLSCREEN) { g_graphicsContext.ToggleFullScreen(); m_pPlayer->TriggerUpdateResolution(); return true; } if (action.IsMouse()) CInputManager::GetInstance().SetMouseActive(true); if (action.GetID() == ACTION_CREATE_EPISODE_BOOKMARK) { CGUIDialogVideoBookmarks::OnAddEpisodeBookmark(); } if (action.GetID() == ACTION_CREATE_BOOKMARK) { CGUIDialogVideoBookmarks::OnAddBookmark(); } // The action PLAYPAUSE behaves as ACTION_PAUSE if we are currently // playing or ACTION_PLAYER_PLAY if we are seeking (FF/RW) or not playing. if (action.GetID() == ACTION_PLAYER_PLAYPAUSE) { if (m_pPlayer->IsPlaying() && m_pPlayer->GetPlaySpeed() == 1) return OnAction(CAction(ACTION_PAUSE)); else return OnAction(CAction(ACTION_PLAYER_PLAY)); } //if the action would start or stop inertial scrolling //by gesture - bypass the normal OnAction handler of current window if( !m_pInertialScrollingHandler->CheckForInertialScrolling(&action) ) { // in normal case // just pass the action to the current window and let it handle it if (g_windowManager.OnAction(action)) { m_navigationTimer.StartZero(); return true; } } // handle extra global presses // notify action listeners if (NotifyActionListeners(action)) return true; // screenshot : take a screenshot :) if (action.GetID() == ACTION_TAKE_SCREENSHOT) { CScreenShot::TakeScreenshot(); return true; } // built in functions : execute the built-in if (action.GetID() == ACTION_BUILT_IN_FUNCTION) { if (!CBuiltins::GetInstance().IsSystemPowerdownCommand(action.GetName()) || CServiceBroker::GetPVRManager().CanSystemPowerdown()) { CBuiltins::GetInstance().Execute(action.GetName()); m_navigationTimer.StartZero(); } return true; } // reload keymaps if (action.GetID() == ACTION_RELOAD_KEYMAPS) { CButtonTranslator::GetInstance().Clear(); CButtonTranslator::GetInstance().Load(); } // show info : Shows the current video or song information if (action.GetID() == ACTION_SHOW_INFO) { g_infoManager.ToggleShowInfo(); return true; } if ((action.GetID() == ACTION_INCREASE_RATING || action.GetID() == ACTION_DECREASE_RATING) && m_pPlayer->IsPlayingAudio()) { const CMusicInfoTag *tag = g_infoManager.GetCurrentSongTag(); if (tag) { *m_itemCurrentFile->GetMusicInfoTag() = *tag; int userrating = tag->GetUserrating(); bool needsUpdate(false); if (userrating > 0 && action.GetID() == ACTION_DECREASE_RATING) { m_itemCurrentFile->GetMusicInfoTag()->SetUserrating(userrating - 1); needsUpdate = true; } else if (userrating < 10 && action.GetID() == ACTION_INCREASE_RATING) { m_itemCurrentFile->GetMusicInfoTag()->SetUserrating(userrating + 1); needsUpdate = true; } if (needsUpdate) { CMusicDatabase db; if (db.Open()) // OpenForWrite() ? { db.SetSongUserrating(m_itemCurrentFile->GetPath(), m_itemCurrentFile->GetMusicInfoTag()->GetUserrating()); db.Close(); } // send a message to all windows to tell them to update the fileitem (eg playlistplayer, media windows) CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_ITEM, 0, m_itemCurrentFile); g_windowManager.SendMessage(msg); } } return true; } else if ((action.GetID() == ACTION_INCREASE_RATING || action.GetID() == ACTION_DECREASE_RATING) && m_pPlayer->IsPlayingVideo()) { const CVideoInfoTag *tag = g_infoManager.GetCurrentMovieTag(); if (tag) { *m_itemCurrentFile->GetVideoInfoTag() = *tag; int rating = tag->m_iUserRating; bool needsUpdate(false); if (rating > 1 && action.GetID() == ACTION_DECREASE_RATING) { m_itemCurrentFile->GetVideoInfoTag()->m_iUserRating = rating - 1; needsUpdate = true; } else if (rating < 10 && action.GetID() == ACTION_INCREASE_RATING) { m_itemCurrentFile->GetVideoInfoTag()->m_iUserRating = rating + 1; needsUpdate = true; } if (needsUpdate) { CVideoDatabase db; if (db.Open()) { db.SetVideoUserRating(m_itemCurrentFile->GetVideoInfoTag()->m_iDbId, m_itemCurrentFile->GetVideoInfoTag()->m_iUserRating, m_itemCurrentFile->GetVideoInfoTag()->m_type); db.Close(); } // send a message to all windows to tell them to update the fileitem (eg playlistplayer, media windows) CGUIMessage msg(GUI_MSG_NOTIFY_ALL, 0, 0, GUI_MSG_UPDATE_ITEM, 0, m_itemCurrentFile); g_windowManager.SendMessage(msg); } } return true; } // Now check with the playlist player if action can be handled. // In case of the action PREV_ITEM, we only allow the playlist player to take it if we're less than 3 seconds into playback. if (!(action.GetID() == ACTION_PREV_ITEM && m_pPlayer->CanSeek() && GetTime() > 3) ) { if (g_playlistPlayer.OnAction(action)) return true; } // Now check with the player if action can be handled. bool bIsPlayingPVRChannel = (CServiceBroker::GetPVRManager().IsStarted() && g_application.CurrentFileItem().IsPVRChannel()); if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO || (g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION && bIsPlayingPVRChannel) || ((g_windowManager.GetActiveWindow() == WINDOW_DIALOG_VIDEO_OSD || (g_windowManager.GetActiveWindow() == WINDOW_DIALOG_MUSIC_OSD && bIsPlayingPVRChannel)) && (action.GetID() == ACTION_NEXT_ITEM || action.GetID() == ACTION_PREV_ITEM || action.GetID() == ACTION_CHANNEL_UP || action.GetID() == ACTION_CHANNEL_DOWN)) || action.GetID() == ACTION_STOP) { if (m_pPlayer->OnAction(action)) return true; // Player ignored action; popup the OSD if ((action.GetID() == ACTION_MOUSE_MOVE && (action.GetAmount(2) || action.GetAmount(3))) // filter "false" mouse move from touch || action.GetID() == ACTION_MOUSE_LEFT_CLICK) { CApplicationMessenger::GetInstance().PostMsg(TMSG_GUI_ACTION, WINDOW_INVALID, -1, static_cast<void*>(new CAction(ACTION_TRIGGER_OSD))); } } // stop : stops playing current audio song if (action.GetID() == ACTION_STOP) { StopPlaying(); return true; } // In case the playlist player nor the player didn't handle PREV_ITEM, because we are past the 3 secs limit. // If so, we just jump to the start of the track. if (action.GetID() == ACTION_PREV_ITEM && m_pPlayer->CanSeek()) { SeekTime(0); m_pPlayer->SetPlaySpeed(1); return true; } // forward action to graphic context and see if it can handle it if (CStereoscopicsManager::GetInstance().OnAction(action)) return true; if (m_pPlayer->IsPlaying()) { // forward channel switches to the player - he knows what to do if (action.GetID() == ACTION_CHANNEL_UP || action.GetID() == ACTION_CHANNEL_DOWN) { m_pPlayer->OnAction(action); return true; } // pause : toggle pause action if (action.GetID() == ACTION_PAUSE) { m_pPlayer->Pause(); // go back to normal play speed on unpause if (!m_pPlayer->IsPaused() && m_pPlayer->GetPlaySpeed() != 1) m_pPlayer->SetPlaySpeed(1); g_audioManager.Enable(m_pPlayer->IsPaused()); return true; } // play: unpause or set playspeed back to normal if (action.GetID() == ACTION_PLAYER_PLAY) { // if currently paused - unpause if (m_pPlayer->IsPaused()) return OnAction(CAction(ACTION_PAUSE)); // if we do a FF/RW then go back to normal speed if (m_pPlayer->GetPlaySpeed() != 1) m_pPlayer->SetPlaySpeed(1); return true; } if (!m_pPlayer->IsPaused()) { if (action.GetID() == ACTION_PLAYER_FORWARD || action.GetID() == ACTION_PLAYER_REWIND) { float playSpeed = m_pPlayer->GetPlaySpeed(); if (playSpeed >= 0.75 && playSpeed <= 1.55) playSpeed = 1; if (action.GetID() == ACTION_PLAYER_REWIND && (playSpeed == 1)) // Enables Rewinding playSpeed *= -2; else if (action.GetID() == ACTION_PLAYER_REWIND && playSpeed > 1) //goes down a notch if you're FFing playSpeed /= 2; else if (action.GetID() == ACTION_PLAYER_FORWARD && playSpeed < 1) //goes up a notch if you're RWing playSpeed /= 2; else playSpeed *= 2; if (action.GetID() == ACTION_PLAYER_FORWARD && playSpeed == -1) //sets iSpeed back to 1 if -1 (didn't plan for a -1) playSpeed = 1; if (playSpeed > 32 || playSpeed < -32) playSpeed = 1; m_pPlayer->SetPlaySpeed(playSpeed); return true; } else if ((action.GetAmount() || m_pPlayer->GetPlaySpeed() != 1) && (action.GetID() == ACTION_ANALOG_REWIND || action.GetID() == ACTION_ANALOG_FORWARD)) { // calculate the speed based on the amount the button is held down int iPower = (int)(action.GetAmount() * MAX_FFWD_SPEED + 0.5f); // amount can be negative, for example rewind and forward share the same axis iPower = std::abs(iPower); // returns 0 -> MAX_FFWD_SPEED int iSpeed = 1 << iPower; if (iSpeed != 1 && action.GetID() == ACTION_ANALOG_REWIND) iSpeed = -iSpeed; g_application.m_pPlayer->SetPlaySpeed(static_cast<float>(iSpeed)); if (iSpeed == 1) CLog::Log(LOGDEBUG,"Resetting playspeed"); return true; } } // allow play to unpause else { if (action.GetID() == ACTION_PLAYER_PLAY) { // unpause, and set the playspeed back to normal m_pPlayer->Pause(); g_audioManager.Enable(m_pPlayer->IsPaused()); g_application.m_pPlayer->SetPlaySpeed(1); return true; } } // record current file if (action.GetID() == ACTION_RECORD) { if (m_pPlayer->CanRecord()) m_pPlayer->Record(!m_pPlayer->IsRecording()); } } if (action.GetID() == ACTION_SWITCH_PLAYER) { if(m_pPlayer->IsPlaying()) { std::vector<std::string> players; CFileItem item(*m_itemCurrentFile.get()); CPlayerCoreFactory::GetInstance().GetPlayers(item, players); std::string player = CPlayerCoreFactory::GetInstance().SelectPlayerDialog(players); if (!player.empty()) { item.m_lStartOffset = (int)(GetTime() * 75); PlayFile(std::move(item), player, true); } } else { std::vector<std::string> players; CPlayerCoreFactory::GetInstance().GetRemotePlayers(players); std::string player = CPlayerCoreFactory::GetInstance().SelectPlayerDialog(players); if (!player.empty()) { PlayFile(CFileItem(), player, false); } } } if (CServiceBroker::GetPeripherals().OnAction(action)) return true; if (action.GetID() == ACTION_MUTE) { ToggleMute(); ShowVolumeBar(&action); return true; } if (action.GetID() == ACTION_TOGGLE_DIGITAL_ANALOG) { bool passthrough = m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_AUDIOOUTPUT_PASSTHROUGH); m_ServiceManager->GetSettings().SetBool(CSettings::SETTING_AUDIOOUTPUT_PASSTHROUGH, !passthrough); if (g_windowManager.GetActiveWindow() == WINDOW_SETTINGS_SYSTEM) { CGUIMessage msg(GUI_MSG_WINDOW_INIT, 0,0,WINDOW_INVALID,g_windowManager.GetActiveWindow()); g_windowManager.SendMessage(msg); } return true; } // Check for global volume control if ((action.GetAmount() && (action.GetID() == ACTION_VOLUME_UP || action.GetID() == ACTION_VOLUME_DOWN)) || action.GetID() == ACTION_VOLUME_SET) { if (!m_pPlayer->IsPassthrough()) { if (m_muted) UnMute(); float volume = m_volumeLevel; int volumesteps = m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_AUDIOOUTPUT_VOLUMESTEPS); // sanity check if (volumesteps == 0) volumesteps = 90; // Android has steps based on the max available volume level #if defined(TARGET_ANDROID) float step = (VOLUME_MAXIMUM - VOLUME_MINIMUM) / CXBMCApp::GetMaxSystemVolume(); #else float step = (VOLUME_MAXIMUM - VOLUME_MINIMUM) / volumesteps; if (action.GetRepeat()) step *= action.GetRepeat() * 50; // 50 fps #endif if (action.GetID() == ACTION_VOLUME_UP) volume += (float)(action.GetAmount() * action.GetAmount() * step); else if (action.GetID() == ACTION_VOLUME_DOWN) volume -= (float)(action.GetAmount() * action.GetAmount() * step); else volume = action.GetAmount() * step; if (volume != m_volumeLevel) SetVolume(volume, false); } // show visual feedback of volume or passthrough indicator ShowVolumeBar(&action); return true; } if (action.GetID() == ACTION_GUIPROFILE_BEGIN) { CGUIControlProfiler::Instance().SetOutputFile(CSpecialProtocol::TranslatePath("special://home/guiprofiler.xml")); CGUIControlProfiler::Instance().Start(); return true; } if (action.GetID() == ACTION_SHOW_PLAYLIST) { int iPlaylist = g_playlistPlayer.GetCurrentPlaylist(); if (iPlaylist == PLAYLIST_VIDEO && g_windowManager.GetActiveWindow() != WINDOW_VIDEO_PLAYLIST) g_windowManager.ActivateWindow(WINDOW_VIDEO_PLAYLIST); else if (iPlaylist == PLAYLIST_MUSIC && g_windowManager.GetActiveWindow() != WINDOW_MUSIC_PLAYLIST) g_windowManager.ActivateWindow(WINDOW_MUSIC_PLAYLIST); return true; } return false; } int CApplication::GetMessageMask() { return TMSG_MASK_APPLICATION; } void CApplication::OnApplicationMessage(ThreadMessage* pMsg) { switch (pMsg->dwMessage) { case TMSG_POWERDOWN: Stop(EXITCODE_POWERDOWN); g_powerManager.Powerdown(); break; case TMSG_QUIT: Stop(EXITCODE_QUIT); break; case TMSG_SHUTDOWN: HandleShutdownMessage(); break; case TMSG_RENDERER_FLUSH: m_pPlayer->FlushRenderer(); break; case TMSG_HIBERNATE: g_powerManager.Hibernate(); break; case TMSG_SUSPEND: g_powerManager.Suspend(); break; case TMSG_RESTART: case TMSG_RESET: Stop(EXITCODE_REBOOT); g_powerManager.Reboot(); break; case TMSG_RESTARTAPP: #if defined(TARGET_WINDOWS) || defined(TARGET_LINUX) Stop(EXITCODE_RESTARTAPP); #endif break; case TMSG_INHIBITIDLESHUTDOWN: InhibitIdleShutdown(pMsg->param1 != 0); break; case TMSG_ACTIVATESCREENSAVER: ActivateScreenSaver(); break; case TMSG_VOLUME_SHOW: { CAction action(pMsg->param1); ShowVolumeBar(&action); } break; #ifdef TARGET_ANDROID case TMSG_DISPLAY_SETUP: // We might come from a refresh rate switch destroying the native window; use the context resolution *static_cast<bool*>(pMsg->lpVoid) = InitWindow(g_graphicsContext.GetVideoResolution()); SetRenderGUI(true); break; case TMSG_DISPLAY_DESTROY: *static_cast<bool*>(pMsg->lpVoid) = DestroyWindow(); SetRenderGUI(false); break; #endif case TMSG_START_ANDROID_ACTIVITY: { #if defined(TARGET_ANDROID) if (pMsg->params.size()) { CXBMCApp::StartActivity(pMsg->params[0], pMsg->params.size() > 1 ? pMsg->params[1] : "", pMsg->params.size() > 2 ? pMsg->params[2] : "", pMsg->params.size() > 3 ? pMsg->params[3] : ""); } #endif } break; case TMSG_NETWORKMESSAGE: getNetwork().NetworkMessage((CNetwork::EMESSAGE)pMsg->param1, pMsg->param2); break; case TMSG_SETLANGUAGE: SetLanguage(pMsg->strParam); break; case TMSG_SWITCHTOFULLSCREEN: if (g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO) SwitchToFullScreen(true); break; case TMSG_VIDEORESIZE: { XBMC_Event newEvent; memset(&newEvent, 0, sizeof(newEvent)); newEvent.type = XBMC_VIDEORESIZE; newEvent.resize.w = pMsg->param1; newEvent.resize.h = pMsg->param2; OnEvent(newEvent); g_windowManager.MarkDirty(); } break; case TMSG_SETVIDEORESOLUTION: g_graphicsContext.SetVideoResolution(static_cast<RESOLUTION>(pMsg->param1), pMsg->param2 == 1); break; case TMSG_TOGGLEFULLSCREEN: g_graphicsContext.ToggleFullScreen(); m_pPlayer->TriggerUpdateResolution(); break; case TMSG_MINIMIZE: Minimize(); break; case TMSG_EXECUTE_OS: /* Suspend AE temporarily so exclusive or hog-mode sinks */ /* don't block external player's access to audio device */ if (!m_ServiceManager->GetActiveAE().Suspend()) { CLog::Log(LOGNOTICE, "%s: Failed to suspend AudioEngine before launching external program", __FUNCTION__); } #if defined( TARGET_POSIX) && !defined(TARGET_DARWIN) CUtil::RunCommandLine(pMsg->strParam.c_str(), (pMsg->param1 == 1)); #elif defined(TARGET_WINDOWS) CWIN32Util::XBMCShellExecute(pMsg->strParam.c_str(), (pMsg->param1 == 1)); #endif /* Resume AE processing of XBMC native audio */ if (!m_ServiceManager->GetActiveAE().Resume()) { CLog::Log(LOGFATAL, "%s: Failed to restart AudioEngine after return from external player", __FUNCTION__); } break; case TMSG_EXECUTE_SCRIPT: CScriptInvocationManager::GetInstance().ExecuteAsync(pMsg->strParam); break; case TMSG_EXECUTE_BUILT_IN: CBuiltins::GetInstance().Execute(pMsg->strParam.c_str()); break; case TMSG_PICTURE_SHOW: { CGUIWindowSlideShow *pSlideShow = g_windowManager.GetWindow<CGUIWindowSlideShow>(WINDOW_SLIDESHOW); if (!pSlideShow) return; // stop playing file if (g_application.m_pPlayer->IsPlayingVideo()) g_application.StopPlaying(); if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO) g_windowManager.PreviousWindow(); g_application.ResetScreenSaver(); g_application.WakeUpScreenSaverAndDPMS(); g_graphicsContext.Lock(); if (g_windowManager.GetActiveWindow() != WINDOW_SLIDESHOW) g_windowManager.ActivateWindow(WINDOW_SLIDESHOW); if (URIUtils::IsZIP(pMsg->strParam) || URIUtils::IsRAR(pMsg->strParam)) // actually a cbz/cbr { CFileItemList items; CURL pathToUrl; if (URIUtils::IsZIP(pMsg->strParam)) pathToUrl = URIUtils::CreateArchivePath("zip", CURL(pMsg->strParam), ""); else pathToUrl = URIUtils::CreateArchivePath("rar", CURL(pMsg->strParam), ""); CUtil::GetRecursiveListing(pathToUrl.Get(), items, g_advancedSettings.GetPictureExtensions(), XFILE::DIR_FLAG_NO_FILE_DIRS); if (items.Size() > 0) { pSlideShow->Reset(); for (int i = 0; i<items.Size(); ++i) { pSlideShow->Add(items[i].get()); } pSlideShow->Select(items[0]->GetPath()); } } else { CFileItem item(pMsg->strParam, false); pSlideShow->Reset(); pSlideShow->Add(&item); pSlideShow->Select(pMsg->strParam); } g_graphicsContext.Unlock(); } break; case TMSG_PICTURE_SLIDESHOW: { CGUIWindowSlideShow *pSlideShow = g_windowManager.GetWindow<CGUIWindowSlideShow>(WINDOW_SLIDESHOW); if (!pSlideShow) return; if (g_application.m_pPlayer->IsPlayingVideo()) g_application.StopPlaying(); g_graphicsContext.Lock(); pSlideShow->Reset(); CFileItemList items; std::string strPath = pMsg->strParam; std::string extensions = g_advancedSettings.GetPictureExtensions(); if (pMsg->param1) extensions += "|.tbn"; CUtil::GetRecursiveListing(strPath, items, extensions); if (items.Size() > 0) { for (int i = 0; i<items.Size(); ++i) pSlideShow->Add(items[i].get()); pSlideShow->StartSlideShow(); //Start the slideshow! } if (g_windowManager.GetActiveWindow() != WINDOW_SLIDESHOW) { if (items.Size() == 0) { m_ServiceManager->GetSettings().SetString(CSettings::SETTING_SCREENSAVER_MODE, "screensaver.xbmc.builtin.dim"); g_application.ActivateScreenSaver(); } else g_windowManager.ActivateWindow(WINDOW_SLIDESHOW); } g_graphicsContext.Unlock(); } break; case TMSG_LOADPROFILE: CGUIWindowLoginScreen::LoadProfile(pMsg->param1); break; default: CLog::Log(LOGERROR, "%s: Unhandled threadmessage sent, %u", __FUNCTION__, pMsg->dwMessage); break; } } void CApplication::HandleShutdownMessage() { switch (m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_POWERMANAGEMENT_SHUTDOWNSTATE)) { case POWERSTATE_SHUTDOWN: CApplicationMessenger::GetInstance().PostMsg(TMSG_POWERDOWN); break; case POWERSTATE_SUSPEND: CApplicationMessenger::GetInstance().PostMsg(TMSG_SUSPEND); break; case POWERSTATE_HIBERNATE: CApplicationMessenger::GetInstance().PostMsg(TMSG_HIBERNATE); break; case POWERSTATE_QUIT: CApplicationMessenger::GetInstance().PostMsg(TMSG_QUIT); break; case POWERSTATE_MINIMIZE: CApplicationMessenger::GetInstance().PostMsg(TMSG_MINIMIZE); break; default: CLog::Log(LOGERROR, "%s: No valid shutdownstate matched", __FUNCTION__); break; } } void CApplication::LockFrameMoveGuard() { ++m_WaitingExternalCalls; m_frameMoveGuard.lock(); ++m_ProcessedExternalCalls; g_graphicsContext.Lock(); }; void CApplication::UnlockFrameMoveGuard() { --m_WaitingExternalCalls; g_graphicsContext.Unlock(); m_frameMoveGuard.unlock(); }; void CApplication::FrameMove(bool processEvents, bool processGUI) { MEASURE_FUNCTION; if (processEvents) { // currently we calculate the repeat time (ie time from last similar keypress) just global as fps float frameTime = m_frameTime.GetElapsedSeconds(); m_frameTime.StartZero(); // never set a frametime less than 2 fps to avoid problems when debugging and on breaks if( frameTime > 0.5 ) frameTime = 0.5; if (processGUI && m_renderGUI) { g_graphicsContext.Lock(); // check if there are notifications to display CGUIDialogKaiToast *toast = g_windowManager.GetWindow<CGUIDialogKaiToast>(WINDOW_DIALOG_KAI_TOAST); if (toast && toast->DoWork()) { if (!toast->IsDialogRunning()) { toast->Open(); } } g_graphicsContext.Unlock(); } CWinEvents::MessagePump(); CInputManager::GetInstance().Process(g_windowManager.GetActiveWindowID(), frameTime); if (processGUI && m_renderGUI) { m_pInertialScrollingHandler->ProcessInertialScroll(frameTime); CSeekHandler::GetInstance().FrameMove(); } // Open the door for external calls e.g python exactly here. // Window size can be between 2 and 10ms and depends on number of continuous requests if (m_WaitingExternalCalls) { CSingleExit ex(g_graphicsContext); m_frameMoveGuard.unlock(); // Calculate a window size between 2 and 10ms, 4 continuous requests let the window grow by 1ms // WHen not playing video we allow it to increase to 80ms unsigned int max_sleep = m_pPlayer->IsPlayingVideo() && !m_pPlayer->IsPausedPlayback() ? 10 : 80; unsigned int sleepTime = std::max(static_cast<unsigned int>(2), std::min(m_ProcessedExternalCalls >> 2, max_sleep)); Sleep(sleepTime); m_frameMoveGuard.lock(); m_ProcessedExternalDecay = 5; } if (m_ProcessedExternalDecay && --m_ProcessedExternalDecay == 0) m_ProcessedExternalCalls = 0; } if (processGUI && m_renderGUI) { m_skipGuiRender = false; int fps = 0; #if defined(TARGET_RASPBERRY_PI) || defined(HAS_IMXVPU) // This code reduces rendering fps of the GUI layer when playing videos in fullscreen mode // it makes only sense on architectures with multiple layers if (g_graphicsContext.IsFullScreenVideo() && !m_pPlayer->IsPausedPlayback() && m_pPlayer->IsRenderingVideoLayer()) fps = m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_VIDEOPLAYER_LIMITGUIUPDATE); #endif unsigned int now = XbmcThreads::SystemClockMillis(); unsigned int frameTime = now - m_lastRenderTime; if (fps > 0 && frameTime * fps < 1000) m_skipGuiRender = true; if (!m_bStop) { if (!m_skipGuiRender) g_windowManager.Process(CTimeUtils::GetFrameTime()); } g_windowManager.FrameMove(); } m_pPlayer->FrameMove(); } bool CApplication::Cleanup() { try { CLog::Log(LOGNOTICE, "unload skin"); UnloadSkin(); // stop all remaining scripts; must be done after skin has been unloaded, // not before some windows still need it when deinitializing during skin // unloading CScriptInvocationManager::GetInstance().Uninitialize(); g_Windowing.DestroyRenderSystem(); g_Windowing.DestroyWindow(); g_Windowing.DestroyWindowSystem(); g_windowManager.DestroyWindows(); CLog::Log(LOGNOTICE, "unload sections"); #ifdef HAS_PERFORMANCE_SAMPLE CLog::Log(LOGNOTICE, "performance statistics"); m_perfStats.DumpStats(); #endif // Shutdown as much as possible of the // application, to reduce the leaks dumped // to the vc output window before calling // _CrtDumpMemoryLeaks(). Most of the leaks // shown are no real leaks, as parts of the app // are still allocated. g_localizeStrings.Clear(); g_LangCodeExpander.Clear(); g_charsetConverter.clear(); g_directoryCache.Clear(); CButtonTranslator::GetInstance().Clear(); #ifdef HAS_EVENT_SERVER CEventServer::RemoveInstance(); #endif DllLoaderContainer::Clear(); g_playlistPlayer.Clear(); m_ServiceManager->GetSettings().Uninitialize(); g_advancedSettings.Clear(); #ifdef TARGET_POSIX CXHandle::DumpObjectTracker(); #ifdef HAS_DVD_DRIVE CLibcdio::ReleaseInstance(); #endif #endif #ifdef _CRTDBG_MAP_ALLOC _CrtDumpMemoryLeaks(); while(1); // execution ends #endif delete m_network; m_network = NULL; // Cleanup was called more than once on exit during my tests if (m_ServiceManager) { m_ServiceManager->Deinit(); m_ServiceManager.reset(); } return true; } catch (...) { CLog::Log(LOGERROR, "Exception in CApplication::Cleanup()"); return false; } } void CApplication::Stop(int exitCode) { try { m_frameMoveGuard.unlock(); CVariant vExitCode(CVariant::VariantTypeObject); vExitCode["exitcode"] = exitCode; CAnnouncementManager::GetInstance().Announce(System, "xbmc", "OnQuit", vExitCode); // Abort any active screensaver WakeUpScreenSaverAndDPMS(); SaveFileState(true); g_alarmClock.StopThread(); if( m_bSystemScreenSaverEnable ) g_Windowing.EnableSystemScreenSaver(true); CLog::Log(LOGNOTICE, "Storing total System Uptime"); g_sysinfo.SetTotalUptime(g_sysinfo.GetTotalUptime() + (int)(CTimeUtils::GetFrameTime() / 60000)); // Update the settings information (volume, uptime etc. need saving) if (CFile::Exists(CProfilesManager::GetInstance().GetSettingsFile())) { CLog::Log(LOGNOTICE, "Saving settings"); m_ServiceManager->GetSettings().Save(); } else CLog::Log(LOGNOTICE, "Not saving settings (settings.xml is not present)"); // kodi may crash or deadlock during exit (shutdown / reboot) due to // either a bug in core or misbehaving addons. so try saving // skin settings early CLog::Log(LOGNOTICE, "Saving skin settings"); if (g_SkinInfo != nullptr) g_SkinInfo->SaveSettings(); m_bStop = true; // Add this here to keep the same ordering behaviour for now // Needs cleaning up CApplicationMessenger::GetInstance().Stop(); m_AppFocused = false; m_ExitCode = exitCode; CLog::Log(LOGNOTICE, "stop all"); // cancel any jobs from the jobmanager CJobManager::GetInstance().CancelJobs(); // stop scanning before we kill the network and so on if (m_musicInfoScanner->IsScanning()) m_musicInfoScanner->Stop(true); if (CVideoLibraryQueue::GetInstance().IsRunning()) CVideoLibraryQueue::GetInstance().CancelAllJobs(); CApplicationMessenger::GetInstance().Cleanup(); CLog::Log(LOGNOTICE, "stop player"); m_pPlayer->ClosePlayer(); StopServices(); #ifdef HAS_ZEROCONF if(CZeroconfBrowser::IsInstantiated()) { CLog::Log(LOGNOTICE, "stop zeroconf browser"); CZeroconfBrowser::GetInstance()->Stop(); CZeroconfBrowser::ReleaseInstance(); } #endif #ifdef HAS_FILESYSTEM_SFTP CSFTPSessionManager::DisconnectAllSessions(); #endif VECADDONS addons; CServiceBroker::GetBinaryAddonCache().GetAddons(addons, ADDON_VFS); for (auto& it : addons) { AddonPtr addon = CServiceBroker::GetBinaryAddonCache().GetAddonInstance(it->ID(), ADDON_VFS); VFSEntryPtr vfs = std::static_pointer_cast<CVFSEntry>(addon); vfs->DisconnectAll(); } #if defined(TARGET_POSIX) && defined(HAS_FILESYSTEM_SMB) smb.Deinit(); #endif #if defined(TARGET_DARWIN_OSX) if (XBMCHelper::GetInstance().IsAlwaysOn() == false) XBMCHelper::GetInstance().Stop(); #endif g_mediaManager.Stop(); // Stop services before unloading Python CAddonMgr::GetInstance().StopServices(false); // unregister action listeners UnregisterActionListener(&CSeekHandler::GetInstance()); UnregisterActionListener(&CPlayerController::GetInstance()); g_audioManager.DeInitialize(); // shutdown the AudioEngine m_ServiceManager->DestroyAudioEngine(); CLog::Log(LOGNOTICE, "closing down remote control service"); CInputManager::GetInstance().DisableRemoteControl(); // unregister ffmpeg lock manager call back av_lockmgr_register(NULL); CLog::Log(LOGNOTICE, "stopped"); } catch (...) { CLog::Log(LOGERROR, "Exception in CApplication::Stop()"); } cleanup_emu_environ(); Sleep(200); } bool CApplication::PlayMedia(const CFileItem& item, const std::string &player, int iPlaylist) { //If item is a plugin, expand out now and run ourselves again if (item.IsPlugin()) { CFileItem item_new(item); if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new)) return PlayMedia(item_new, player, iPlaylist); return false; } if (item.IsSmartPlayList()) { CFileItemList items; CUtil::GetRecursiveListing(item.GetPath(), items, "", DIR_FLAG_NO_FILE_DIRS); if (items.Size()) { CSmartPlaylist smartpl; //get name and type of smartplaylist, this will always succeed as GetDirectory also did this. smartpl.OpenAndReadName(item.GetURL()); CPlayList playlist; playlist.Add(items); return ProcessAndStartPlaylist(smartpl.GetName(), playlist, (smartpl.GetType() == "songs" || smartpl.GetType() == "albums") ? PLAYLIST_MUSIC:PLAYLIST_VIDEO); } } else if (item.IsPlayList() || item.IsInternetStream()) { CGUIDialogCache* dlgCache = new CGUIDialogCache(5000, g_localizeStrings.Get(10214), item.GetLabel()); //is or could be a playlist std::unique_ptr<CPlayList> pPlayList (CPlayListFactory::Create(item)); bool gotPlayList = (pPlayList.get() && pPlayList->Load(item.GetPath())); if (dlgCache) { dlgCache->Close(); if (dlgCache->IsCanceled()) return true; } if (gotPlayList) { if (iPlaylist != PLAYLIST_NONE) { int track=0; if (item.HasProperty("playlist_starting_track")) track = (int)item.GetProperty("playlist_starting_track").asInteger(); return ProcessAndStartPlaylist(item.GetPath(), *pPlayList, iPlaylist, track); } else { CLog::Log(LOGWARNING, "CApplication::PlayMedia called to play a playlist %s but no idea which playlist to use, playing first item", item.GetPath().c_str()); if(pPlayList->size()) return PlayFile(*(*pPlayList)[0], "", false) == PLAYBACK_OK; } } } else if (item.IsPVR()) { return CServiceBroker::GetPVRManager().GUIActions()->PlayMedia(CFileItemPtr(new CFileItem(item))); } CURL path(item.GetPath()); if (path.GetProtocol() == "game") { AddonPtr addon; if (CAddonMgr::GetInstance().GetAddon(path.GetHostName(), addon, ADDON_GAMEDLL)) { CFileItem addonItem(addon); return PlayFile(addonItem, player, false) == PLAYBACK_OK; } } //nothing special just play return PlayFile(item, player, false) == PLAYBACK_OK; } // PlayStack() // For playing a multi-file video. Particularly inefficient // on startup, as we are required to calculate the length // of each video, so we open + close each one in turn. // A faster calculation of video time would improve this // substantially. // return value: same with PlayFile() PlayBackRet CApplication::PlayStack(const CFileItem& item, bool bRestart) { if (!item.IsStack()) return PLAYBACK_FAIL; CVideoDatabase dbs; // case 1: stacked ISOs if (CFileItem(CStackDirectory::GetFirstStackedFile(item.GetPath()),false).IsDiscImage()) { CStackDirectory dir; CFileItemList movieList; if (!dir.GetDirectory(item.GetURL(), movieList) || movieList.IsEmpty()) return PLAYBACK_FAIL; // first assume values passed to the stack int selectedFile = item.m_lStartPartNumber; int startoffset = item.m_lStartOffset; // check if we instructed the stack to resume from default if (startoffset == STARTOFFSET_RESUME) // selected file is not specified, pick the 'last' resume point { if (dbs.Open()) { CBookmark bookmark; std::string path = item.GetPath(); if (item.HasProperty("original_listitem_url") && URIUtils::IsPlugin(item.GetProperty("original_listitem_url").asString())) path = item.GetProperty("original_listitem_url").asString(); if( dbs.GetResumeBookMark(path, bookmark) ) { startoffset = (int)(bookmark.timeInSeconds*75); selectedFile = bookmark.partNumber; } dbs.Close(); } else CLog::LogF(LOGERROR, "Cannot open VideoDatabase"); } // make sure that the selected part is within the boundaries if (selectedFile <= 0) { CLog::LogF(LOGWARNING, "Selected part %d out of range, playing part 1", selectedFile); selectedFile = 1; } else if (selectedFile > movieList.Size()) { CLog::LogF(LOGWARNING, "Selected part %d out of range, playing part %d", selectedFile, movieList.Size()); selectedFile = movieList.Size(); } // set startoffset in movieitem, track stack item for updating purposes, and finally play disc part movieList[selectedFile - 1]->m_lStartOffset = startoffset > 0 ? STARTOFFSET_RESUME : 0; movieList[selectedFile - 1]->SetProperty("stackFileItemToUpdate", true); *m_stackFileItemToUpdate = item; return PlayFile(*(movieList[selectedFile - 1]), ""); } // case 2: all other stacks else { LoadVideoSettings(item); // see if we have the info in the database //! @todo If user changes the time speed (FPS via framerate conversion stuff) //! then these times will be wrong. //! Also, this is really just a hack for the slow load up times we have //! A much better solution is a fast reader of FPS and fileLength //! that we can use on a file to get it's time. std::vector<int> times; bool haveTimes(false); CVideoDatabase dbs; if (dbs.Open()) { haveTimes = dbs.GetStackTimes(item.GetPath(), times); dbs.Close(); } // calculate the total time of the stack CStackDirectory dir; if (!dir.GetDirectory(item.GetURL(), *m_currentStack) || m_currentStack->IsEmpty()) return PLAYBACK_FAIL; long totalTime = 0; for (int i = 0; i < m_currentStack->Size(); i++) { if (haveTimes) (*m_currentStack)[i]->m_lEndOffset = times[i]; else { int duration; if (!CDVDFileInfo::GetFileDuration((*m_currentStack)[i]->GetPath(), duration)) { m_currentStack->Clear(); return PLAYBACK_FAIL; } totalTime += duration / 1000; (*m_currentStack)[i]->m_lEndOffset = totalTime; times.push_back(totalTime); } } double seconds = item.m_lStartOffset / 75.0; if (!haveTimes || item.m_lStartOffset == STARTOFFSET_RESUME ) { // have our times now, so update the dB if (dbs.Open()) { if (!haveTimes && !times.empty()) dbs.SetStackTimes(item.GetPath(), times); if (item.m_lStartOffset == STARTOFFSET_RESUME) { // can only resume seek here, not dvdstate CBookmark bookmark; std::string path = item.GetPath(); if (item.HasProperty("original_listitem_url") && URIUtils::IsPlugin(item.GetProperty("original_listitem_url").asString())) path = item.GetProperty("original_listitem_url").asString(); if (dbs.GetResumeBookMark(path, bookmark)) seconds = bookmark.timeInSeconds; else seconds = 0.0f; } dbs.Close(); } } m_itemCurrentFile.reset(new CFileItem(item)); m_currentStackPosition = 0; if (seconds > 0) { // work out where to seek to for (int i = 0; i < m_currentStack->Size(); i++) { if (seconds < (*m_currentStack)[i]->m_lEndOffset) { CFileItem item(*(*m_currentStack)[i]); long start = (i > 0) ? (*m_currentStack)[i-1]->m_lEndOffset : 0; item.m_lStartOffset = (long)(seconds - start) * 75; m_currentStackPosition = i; return PlayFile(item, "", true); } } } return PlayFile(*(*m_currentStack)[0], "", true); } return PLAYBACK_FAIL; } PlayBackRet CApplication::PlayFile(CFileItem item, const std::string& player, bool bRestart) { // Ensure the MIME type has been retrieved for http:// and shout:// streams if (item.GetMimeType().empty()) item.FillInMimeType(); if (!bRestart) { SaveFileState(true); // Switch to default options CMediaSettings::GetInstance().GetCurrentVideoSettings() = CMediaSettings::GetInstance().GetDefaultVideoSettings(); CMediaSettings::GetInstance().GetCurrentAudioSettings() = CMediaSettings::GetInstance().GetDefaultAudioSettings(); // see if we have saved options in the database m_pPlayer->SetPlaySpeed(1); m_itemCurrentFile.reset(new CFileItem(item)); m_nextPlaylistItem = -1; m_currentStackPosition = 0; m_currentStack->Clear(); if (item.IsVideo()) CUtil::ClearSubtitles(); } if (item.IsDiscStub()) { #ifdef HAS_DVD_DRIVE // Display the Play Eject dialog if there is any optical disc drive if (g_mediaManager.HasOpticalDrive()) { if (CGUIDialogPlayEject::ShowAndGetInput(item)) // PlayDiscAskResume takes path to disc. No parameter means default DVD drive. // Can't do better as CGUIDialogPlayEject calls CMediaManager::IsDiscInDrive, which assumes default DVD drive anyway return MEDIA_DETECT::CAutorun::PlayDiscAskResume() ? PLAYBACK_OK : PLAYBACK_FAIL; } else #endif CGUIDialogOK::ShowAndGetInput(CVariant{435}, CVariant{436}); return PLAYBACK_OK; } if (item.IsPlayList()) return PLAYBACK_FAIL; if (item.IsPlugin()) { // we modify the item so that it becomes a real URL CFileItem item_new(item); if (XFILE::CPluginDirectory::GetPluginResult(item.GetPath(), item_new)) return PlayFile(std::move(item_new), player, false); return PLAYBACK_FAIL; } // a disc image might be Blu-Ray disc if (item.IsBDFile() || item.IsDiscImage()) { //check if we must show the simplified bd menu if (!CGUIDialogSimpleMenu::ShowPlaySelection(const_cast<CFileItem&>(item))) return PLAYBACK_CANCELED; } #ifdef HAS_UPNP if (URIUtils::IsUPnP(item.GetPath())) { CFileItem item_new(item); if (XFILE::CUPnPDirectory::GetResource(item.GetURL(), item_new)) return PlayFile(std::move(item_new), player, false); return PLAYBACK_FAIL; } #endif // if we have a stacked set of files, we need to setup our stack routines for // "seamless" seeking and total time of the movie etc. // will recall with restart set to true if (item.IsStack()) return PlayStack(item, bRestart); CPlayerOptions options; if( item.HasProperty("StartPercent") ) { double fallback = 0.0f; if(item.GetProperty("StartPercent").isString()) fallback = (double)atof(item.GetProperty("StartPercent").asString().c_str()); options.startpercent = item.GetProperty("StartPercent").asDouble(fallback); } if (bRestart) { // have to be set here due to playstack using this for starting the file options.starttime = item.m_lStartOffset / 75.0; if (item.HasVideoInfoTag()) options.state = item.GetVideoInfoTag()->GetResumePoint().playerState; if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0 && m_itemCurrentFile->m_lStartOffset != 0) m_itemCurrentFile->m_lStartOffset = STARTOFFSET_RESUME; // to force fullscreen switching } else { options.starttime = item.m_lStartOffset / 75.0; LoadVideoSettings(item); if (item.IsVideo()) { // open the d/b and retrieve the bookmarks for the current movie CVideoDatabase dbs; dbs.Open(); if( item.m_lStartOffset == STARTOFFSET_RESUME ) { options.starttime = 0.0f; if (item.IsResumePointSet()) { options.starttime = item.GetCurrentResumeTime(); if (item.HasVideoInfoTag()) options.state = item.GetVideoInfoTag()->GetResumePoint().playerState; } else { CBookmark bookmark; std::string path = item.GetPath(); if (item.HasVideoInfoTag() && StringUtils::StartsWith(item.GetVideoInfoTag()->m_strFileNameAndPath, "removable://")) path = item.GetVideoInfoTag()->m_strFileNameAndPath; else if (item.HasProperty("original_listitem_url") && URIUtils::IsPlugin(item.GetProperty("original_listitem_url").asString())) path = item.GetProperty("original_listitem_url").asString(); if (dbs.GetResumeBookMark(path, bookmark)) { options.starttime = bookmark.timeInSeconds; options.state = bookmark.playerState; } } if (options.starttime == 0.0f && item.HasVideoInfoTag()) { // No resume point is set, but check if this item is part of a multi-episode file const CVideoInfoTag *tag = item.GetVideoInfoTag(); if (tag->m_iBookmarkId > 0) { CBookmark bookmark; dbs.GetBookMarkForEpisode(*tag, bookmark); options.starttime = bookmark.timeInSeconds; options.state = bookmark.playerState; } } } else if (item.HasVideoInfoTag()) { const CVideoInfoTag *tag = item.GetVideoInfoTag(); if (tag->m_iBookmarkId > 0) { CBookmark bookmark; dbs.GetBookMarkForEpisode(*tag, bookmark); options.starttime = bookmark.timeInSeconds; options.state = bookmark.playerState; } } dbs.Close(); } } // this really aught to be inside !bRestart, but since PlayStack // uses that to init playback, we have to keep it outside int playlist = g_playlistPlayer.GetCurrentPlaylist(); if (item.IsVideo() && playlist == PLAYLIST_VIDEO && g_playlistPlayer.GetPlaylist(playlist).size() > 1) { // playing from a playlist by the looks // don't switch to fullscreen if we are not playing the first item... options.fullscreen = !g_playlistPlayer.HasPlayedFirstFile() && g_advancedSettings.m_fullScreenOnMovieStart && !CMediaSettings::GetInstance().DoesVideoStartWindowed(); } else if(m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) { //! @todo - this will fail if user seeks back to first file in stack if(m_currentStackPosition == 0 || m_itemCurrentFile->m_lStartOffset == STARTOFFSET_RESUME) options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !CMediaSettings::GetInstance().DoesVideoStartWindowed(); else options.fullscreen = false; // reset this so we don't think we are resuming on seek m_itemCurrentFile->m_lStartOffset = 0; } else options.fullscreen = g_advancedSettings.m_fullScreenOnMovieStart && !CMediaSettings::GetInstance().DoesVideoStartWindowed(); // reset VideoStartWindowed as it's a temp setting CMediaSettings::GetInstance().SetVideoStartWindowed(false); { CSingleLock lock(m_playStateMutex); // tell system we are starting a file m_bPlaybackStarting = true; // for playing a new item, previous playing item's callback may already // pushed some delay message into the threadmessage list, they are not // expected be processed after or during the new item playback starting. // so we clean up previous playing item's playback callback delay messages here. int previousMsgsIgnoredByNewPlaying[] = { GUI_MSG_PLAYBACK_STARTED, GUI_MSG_PLAYBACK_ENDED, GUI_MSG_PLAYBACK_STOPPED, GUI_MSG_PLAYLIST_CHANGED, GUI_MSG_PLAYLISTPLAYER_STOPPED, GUI_MSG_PLAYLISTPLAYER_STARTED, GUI_MSG_PLAYLISTPLAYER_CHANGED, GUI_MSG_QUEUE_NEXT_ITEM, 0 }; int dMsgCount = g_windowManager.RemoveThreadMessageByMessageIds(&previousMsgsIgnoredByNewPlaying[0]); if (dMsgCount > 0) CLog::LogF(LOGDEBUG,"Ignored %d playback thread messages", dMsgCount); } std::string newPlayer; if (!player.empty()) newPlayer = player; else if (bRestart && !m_pPlayer->GetCurrentPlayer().empty()) newPlayer = m_pPlayer->GetCurrentPlayer(); else newPlayer = CPlayerCoreFactory::GetInstance().GetDefaultPlayer(item); // We should restart the player, unless the previous and next tracks are using // one of the players that allows gapless playback (paplayer, VideoPlayer) m_pPlayer->ClosePlayerGapless(newPlayer); // now reset play state to starting, since we already stopped the previous playing item if there is. // and from now there should be no playback callback from previous playing item be called. m_ePlayState = PLAY_STATE_STARTING; m_pPlayer->CreatePlayer(newPlayer, *this); PlayBackRet iResult; if (m_pPlayer->HasPlayer()) { /* When playing video pause any low priority jobs, they will be unpaused when playback stops. * This should speed up player startup for files on internet filesystems (eg. webdav) and * increase performance on low powered systems (Atom/ARM). */ if (item.IsVideo() || item.IsGame()) { CJobManager::GetInstance().PauseJobs(); } // don't hold graphicscontext here since player // may wait on another thread, that requires gfx CSingleExit ex(g_graphicsContext); iResult = m_pPlayer->OpenFile(item, options); } else { CLog::Log(LOGERROR, "Error creating player for item %s (File doesn't exist?)", item.GetPath().c_str()); iResult = PLAYBACK_FAIL; } if (iResult == PLAYBACK_OK) { m_pPlayer->SetVolume(m_volumeLevel); m_pPlayer->SetMute(m_muted); if(m_pPlayer->IsPlayingAudio()) { if (g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO) g_windowManager.ActivateWindow(WINDOW_VISUALISATION); } #ifdef HAS_VIDEO_PLAYBACK else if(m_pPlayer->IsPlayingVideo()) { // if player didn't manage to switch to fullscreen by itself do it here if (options.fullscreen && m_pPlayer->IsRenderingVideo() && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO ) SwitchToFullScreen(true); } #endif else { if (g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION || g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO) g_windowManager.PreviousWindow(); } #if !defined(TARGET_POSIX) g_audioManager.Enable(false); #endif if (item.HasPVRChannelInfoTag()) g_playlistPlayer.SetCurrentPlaylist(PLAYLIST_NONE); } CSingleLock lock(m_playStateMutex); m_bPlaybackStarting = false; if (iResult == PLAYBACK_OK) { // play state: none, starting; playing; stopped; ended. // last 3 states are set by playback callback, they are all ignored during starting, // but we recorded the state, here we can make up the callback for the state. CLog::LogF(LOGDEBUG,"OpenFile succeed, play state %d", m_ePlayState); switch (m_ePlayState) { case PLAY_STATE_PLAYING: OnPlayBackStarted(); break; // FIXME: it seems no meaning to callback started here if there was an started callback // before this stopped/ended callback we recorded. if we callback started here // first, it will delay send OnPlay announce, but then we callback stopped/ended // which will send OnStop announce at once, so currently, just call stopped/ended. case PLAY_STATE_ENDED: OnPlayBackEnded(); break; case PLAY_STATE_STOPPED: OnPlayBackStopped(); break; case PLAY_STATE_STARTING: // neither started nor stopped/ended callback be called, that means the item still // not started, we need not make up any callback, just leave this and // let the player callback do its work. break; default: break; } } else if (iResult == PLAYBACK_FAIL) { // we send this if it isn't playlistplayer that is doing this int next = g_playlistPlayer.GetNextSong(); int size = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist()).size(); if(next < 0 || next >= size) OnPlayBackStopped(); m_ePlayState = PLAY_STATE_NONE; } return iResult; } void CApplication::OnPlayBackEnded() { CSingleLock lock(m_playStateMutex); CLog::LogF(LOGDEBUG,"play state was %d, starting %d", m_ePlayState, m_bPlaybackStarting); m_ePlayState = PLAY_STATE_ENDED; if(m_bPlaybackStarting) return; // informs python script currently running playback has ended // (does nothing if python is not loaded) #ifdef HAS_PYTHON g_pythonParser.OnPlayBackEnded(); #endif #ifdef TARGET_ANDROID CXBMCApp::OnPlayBackEnded(); #elif defined(TARGET_DARWIN_IOS) CDarwinUtils::EnableOSScreenSaver(true); #endif CVariant data(CVariant::VariantTypeObject); data["end"] = true; CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnStop", m_itemCurrentFile, data); CGUIMessage msg(GUI_MSG_PLAYBACK_ENDED, 0, 0); g_windowManager.SendThreadMessage(msg); } void CApplication::OnPlayBackStarted() { CSingleLock lock(m_playStateMutex); CLog::LogF(LOGDEBUG,"play state was %d, starting %d", m_ePlayState, m_bPlaybackStarting); m_ePlayState = PLAY_STATE_PLAYING; if(m_bPlaybackStarting) return; #ifdef HAS_PYTHON // informs python script currently running playback has started // (does nothing if python is not loaded) g_pythonParser.OnPlayBackStarted(); #endif #ifdef TARGET_ANDROID CXBMCApp::OnPlayBackStarted(); #elif defined(TARGET_DARWIN_IOS) if (m_pPlayer->IsPlayingVideo()) CDarwinUtils::EnableOSScreenSaver(false); #endif CGUIMessage msg(GUI_MSG_PLAYBACK_STARTED, 0, 0); g_windowManager.SendThreadMessage(msg); } void CApplication::OnQueueNextItem() { CSingleLock lock(m_playStateMutex); CLog::LogF(LOGDEBUG,"play state was %d, starting %d", m_ePlayState, m_bPlaybackStarting); if(m_bPlaybackStarting) return; // informs python script currently running that we are requesting the next track // (does nothing if python is not loaded) #ifdef HAS_PYTHON g_pythonParser.OnQueueNextItem(); // currently unimplemented #endif CGUIMessage msg(GUI_MSG_QUEUE_NEXT_ITEM, 0, 0); g_windowManager.SendThreadMessage(msg); } void CApplication::OnPlayBackStopped() { CSingleLock lock(m_playStateMutex); CLog::LogF(LOGDEBUG, "play state was %d, starting %d", m_ePlayState, m_bPlaybackStarting); m_ePlayState = PLAY_STATE_STOPPED; if(m_bPlaybackStarting) return; // informs python script currently running playback has ended // (does nothing if python is not loaded) #ifdef HAS_PYTHON g_pythonParser.OnPlayBackStopped(); #endif #ifdef TARGET_ANDROID CXBMCApp::OnPlayBackStopped(); #elif defined(TARGET_DARWIN_IOS) CDarwinUtils::EnableOSScreenSaver(true); #endif CVariant data(CVariant::VariantTypeObject); data["end"] = false; CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnStop", m_itemCurrentFile, data); CGUIMessage msg( GUI_MSG_PLAYBACK_STOPPED, 0, 0 ); g_windowManager.SendThreadMessage(msg); } void CApplication::OnPlayBackPaused() { #ifdef HAS_PYTHON g_pythonParser.OnPlayBackPaused(); #endif #ifdef TARGET_ANDROID CXBMCApp::OnPlayBackPaused(); #elif defined(TARGET_DARWIN_IOS) CDarwinUtils::EnableOSScreenSaver(true); #endif CVariant param; param["player"]["speed"] = 0; param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist(); CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnPause", m_itemCurrentFile, param); } void CApplication::OnPlayBackResumed() { #ifdef HAS_PYTHON g_pythonParser.OnPlayBackResumed(); #endif #ifdef TARGET_ANDROID CXBMCApp::OnPlayBackResumed(); #elif defined(TARGET_DARWIN_IOS) if (m_pPlayer->IsPlayingVideo()) CDarwinUtils::EnableOSScreenSaver(false); #endif CVariant param; param["player"]["speed"] = 1; param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist(); CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param); } void CApplication::OnPlayBackSpeedChanged(int iSpeed) { #ifdef HAS_PYTHON g_pythonParser.OnPlayBackSpeedChanged(iSpeed); #endif CVariant param; param["player"]["speed"] = iSpeed; param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist(); CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnSpeedChanged", m_itemCurrentFile, param); } void CApplication::OnPlayBackSeek(int64_t iTime, int64_t seekOffset) { #ifdef HAS_PYTHON g_pythonParser.OnPlayBackSeek(static_cast<int>(iTime), static_cast<int>(seekOffset)); #endif CVariant param; CJSONUtils::MillisecondsToTimeObject(iTime, param["player"]["time"]); CJSONUtils::MillisecondsToTimeObject(seekOffset, param["player"]["seekoffset"]); param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist(); param["player"]["speed"] = (int)m_pPlayer->GetPlaySpeed(); CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnSeek", m_itemCurrentFile, param); g_infoManager.SetDisplayAfterSeek(2500, static_cast<int>(seekOffset)); } void CApplication::OnPlayBackSeekChapter(int iChapter) { #ifdef HAS_PYTHON g_pythonParser.OnPlayBackSeekChapter(iChapter); #endif } bool CApplication::IsPlayingFullScreenVideo() const { return m_pPlayer->IsPlayingVideo() && g_graphicsContext.IsFullScreenVideo(); } bool CApplication::IsFullScreen() { return IsPlayingFullScreenVideo() || (g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION) || g_windowManager.GetActiveWindow() == WINDOW_SLIDESHOW; } void CApplication::SaveFileState(bool bForeground /* = false */) { if (!CProfilesManager::GetInstance().GetCurrentProfile().canWriteDatabases()) return; CJob* job = new CSaveFileStateJob(*m_progressTrackingItem, *m_stackFileItemToUpdate, m_progressTrackingVideoResumeBookmark, m_progressTrackingPlayCountUpdate, CMediaSettings::GetInstance().GetCurrentVideoSettings(), CMediaSettings::GetInstance().GetCurrentAudioSettings()); if (bForeground) { // Run job in the foreground to make sure it finishes job->DoWork(); delete job; } else CJobManager::GetInstance().AddJob(job, NULL, CJob::PRIORITY_NORMAL); } void CApplication::UpdateFileState() { // Did the file change? if (m_progressTrackingItem->GetPath() != "" && m_progressTrackingItem->GetPath() != CurrentFile()) { // Ignore for PVR channels, PerformChannelSwitch takes care of this. // Also ignore video playlists containing multiple items: video settings have already been saved in PlayFile() // and we'd overwrite them with settings for the *previous* item. //! @todo these "exceptions" should be removed and the whole logic of saving settings be revisited and //! possibly moved out of CApplication. See PRs 5842, 5958, http://trac.kodi.tv/ticket/15704#comment:3 int playlist = g_playlistPlayer.GetCurrentPlaylist(); if (!m_progressTrackingItem->IsPVRChannel() && !(playlist == PLAYLIST_VIDEO && g_playlistPlayer.GetPlaylist(playlist).size() > 1)) SaveFileState(); // Reset tracking item m_progressTrackingItem->Reset(); } else { if (m_pPlayer->IsPlaying()) { if (m_progressTrackingItem->GetPath() == "") { // Init some stuff *m_progressTrackingItem = CurrentFileItem(); m_progressTrackingPlayCountUpdate = false; } if ((m_progressTrackingItem->IsAudio() && g_advancedSettings.m_audioPlayCountMinimumPercent > 0 && GetPercentage() >= g_advancedSettings.m_audioPlayCountMinimumPercent) || (m_progressTrackingItem->IsVideo() && g_advancedSettings.m_videoPlayCountMinimumPercent > 0 && GetPercentage() >= g_advancedSettings.m_videoPlayCountMinimumPercent)) { m_progressTrackingPlayCountUpdate = true; } // Check whether we're *really* playing video else we may race when getting eg. stream details if (m_pPlayer->IsPlayingVideo() && !m_pPlayer->IsPlayingGame()) { /* Always update streamdetails, except for DVDs where we only update streamdetails if total duration > 15m (Should yield more correct info) */ if (!(m_progressTrackingItem->IsDiscImage() || m_progressTrackingItem->IsDVDFile()) || m_pPlayer->GetTotalTime() > 15*60*1000) { CStreamDetails details; // Update with stream details from player, if any if (m_pPlayer->GetStreamDetails(details)) m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails = details; if (m_progressTrackingItem->IsStack()) m_progressTrackingItem->GetVideoInfoTag()->m_streamDetails.SetVideoDuration(0, (int)GetTotalTime()); // Overwrite with CApp's totaltime as it takes into account total stack time } // Update bookmark for save m_progressTrackingVideoResumeBookmark.player = m_pPlayer->GetCurrentPlayer(); m_progressTrackingVideoResumeBookmark.playerState = m_pPlayer->GetPlayerState(); m_progressTrackingVideoResumeBookmark.thumbNailImage.clear(); if (g_advancedSettings.m_videoIgnorePercentAtEnd > 0 && GetTotalTime() - GetTime() < 0.01f * g_advancedSettings.m_videoIgnorePercentAtEnd * GetTotalTime()) { // Delete the bookmark m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f; } else if (GetTime() > g_advancedSettings.m_videoIgnoreSecondsAtStart) { // Update the bookmark m_progressTrackingVideoResumeBookmark.timeInSeconds = GetTime(); m_progressTrackingVideoResumeBookmark.totalTimeInSeconds = GetTotalTime(); } else { // Do nothing m_progressTrackingVideoResumeBookmark.timeInSeconds = 0.0f; } } if (m_pPlayer->IsPlayingAudio() && !m_pPlayer->IsPlayingGame()) { if (m_progressTrackingItem->IsAudioBook()) m_progressTrackingVideoResumeBookmark.timeInSeconds = GetTime(); } } } } void CApplication::LoadVideoSettings(const CFileItem& item) { CVideoDatabase dbs; if (dbs.Open()) { CLog::Log(LOGDEBUG, "Loading settings for %s", CURL::GetRedacted(item.GetPath()).c_str()); // Load stored settings if they exist, otherwise use default if (!dbs.GetVideoSettings(item, CMediaSettings::GetInstance().GetCurrentVideoSettings())) CMediaSettings::GetInstance().GetCurrentVideoSettings() = CMediaSettings::GetInstance().GetDefaultVideoSettings(); dbs.Close(); } } void CApplication::StopPlaying() { int iWin = g_windowManager.GetActiveWindow(); if ( m_pPlayer->IsPlaying() ) { m_pPlayer->CloseFile(); // turn off visualisation window when stopping if ((iWin == WINDOW_VISUALISATION || iWin == WINDOW_FULLSCREEN_VIDEO) && !m_bStop) g_windowManager.PreviousWindow(); g_partyModeManager.Disable(); } } void CApplication::ResetSystemIdleTimer() { // reset system idle timer m_idleTimer.StartZero(); #if defined(TARGET_DARWIN_IOS) CDarwinUtils::ResetSystemIdleTimer(); #endif } void CApplication::ResetScreenSaver() { // reset our timers m_shutdownTimer.StartZero(); // screen saver timer is reset only if we're not already in screensaver or // DPMS mode if ((!m_screensaverActive && m_iScreenSaveLock == 0) && !m_dpmsIsActive) ResetScreenSaverTimer(); } void CApplication::ResetScreenSaverTimer() { m_screenSaverTimer.StartZero(); } void CApplication::StopScreenSaverTimer() { m_screenSaverTimer.Stop(); } bool CApplication::ToggleDPMS(bool manual) { if (manual || (m_dpmsIsManual == manual)) { if (m_dpmsIsActive) { m_dpmsIsActive = false; m_dpmsIsManual = false; SetRenderGUI(true); CAnnouncementManager::GetInstance().Announce(GUI, "xbmc", "OnDPMSDeactivated"); return m_dpms->DisablePowerSaving(); } else { if (m_dpms->EnablePowerSaving(m_dpms->GetSupportedModes()[0])) { m_dpmsIsActive = true; m_dpmsIsManual = manual; SetRenderGUI(false); CAnnouncementManager::GetInstance().Announce(GUI, "xbmc", "OnDPMSActivated"); return true; } } } return false; } bool CApplication::WakeUpScreenSaverAndDPMS(bool bPowerOffKeyPressed /* = false */) { bool result = false; // First reset DPMS, if active if (m_dpmsIsActive) { if (m_dpmsIsManual) return false; //! @todo if screensaver lock is specified but screensaver is not active //! (DPMS came first), activate screensaver now. ToggleDPMS(false); ResetScreenSaverTimer(); result = !m_screensaverActive || WakeUpScreenSaver(bPowerOffKeyPressed); } else if (m_screensaverActive) result = WakeUpScreenSaver(bPowerOffKeyPressed); if(result) { // allow listeners to ignore the deactivation if it precedes a powerdown/suspend etc CVariant data(CVariant::VariantTypeObject); data["shuttingdown"] = bPowerOffKeyPressed; CAnnouncementManager::GetInstance().Announce(GUI, "xbmc", "OnScreensaverDeactivated", data); #ifdef TARGET_ANDROID // Screensaver deactivated -> acquire wake lock CXBMCApp::EnableWakeLock(true); #endif } return result; } bool CApplication::WakeUpScreenSaver(bool bPowerOffKeyPressed /* = false */) { if (m_iScreenSaveLock == 2) return false; // if Screen saver is active if (m_screensaverActive && !m_screensaverIdInUse.empty()) { if (m_iScreenSaveLock == 0) if (CProfilesManager::GetInstance().GetMasterProfile().getLockMode() != LOCK_MODE_EVERYONE && (CProfilesManager::GetInstance().UsingLoginScreen() || m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MASTERLOCK_STARTUPLOCK)) && CProfilesManager::GetInstance().GetCurrentProfile().getLockMode() != LOCK_MODE_EVERYONE && m_screensaverIdInUse != "screensaver.xbmc.builtin.dim" && m_screensaverIdInUse != "screensaver.xbmc.builtin.black" && m_screensaverIdInUse != "visualization") { m_iScreenSaveLock = 2; CGUIMessage msg(GUI_MSG_CHECK_LOCK,0,0); CGUIWindow* pWindow = g_windowManager.GetWindow(WINDOW_SCREENSAVER); if (pWindow) pWindow->OnMessage(msg); } if (m_iScreenSaveLock == -1) { m_iScreenSaveLock = 0; return true; } // disable screensaver m_screensaverActive = false; m_iScreenSaveLock = 0; ResetScreenSaverTimer(); if (m_screensaverIdInUse == "visualization") { // we can just continue as usual from vis mode return false; } else if (m_screensaverIdInUse == "screensaver.xbmc.builtin.dim" || m_screensaverIdInUse == "screensaver.xbmc.builtin.black" || m_screensaverIdInUse.empty()) { return true; } else if (!m_screensaverIdInUse.empty()) { // we're in screensaver window if (m_pythonScreenSaver) { // What sound does a python screensaver make? #define SCRIPT_ALARM "sssssscreensaver" #define SCRIPT_TIMEOUT 15 // seconds /* FIXME: This is a hack but a proper fix is non-trivial. Basically this code * makes sure the addon gets terminated after we've moved out of the screensaver window. * If we don't do this, we may simply lockup. */ g_alarmClock.Start(SCRIPT_ALARM, SCRIPT_TIMEOUT, "StopScript(" + m_pythonScreenSaver->LibPath() + ")", true, false); m_pythonScreenSaver.reset(); } if (g_windowManager.GetActiveWindow() == WINDOW_SCREENSAVER) g_windowManager.PreviousWindow(); // show the previous window else if (g_windowManager.GetActiveWindow() == WINDOW_SLIDESHOW) CApplicationMessenger::GetInstance().SendMsg(TMSG_GUI_ACTION, WINDOW_SLIDESHOW, -1, static_cast<void*>(new CAction(ACTION_STOP))); } return true; } else return false; } void CApplication::CheckScreenSaverAndDPMS() { if (!m_dpmsIsActive) g_Windowing.ResetOSScreensaver(); bool maybeScreensaver = !m_dpmsIsActive && !m_screensaverActive && !m_ServiceManager->GetSettings().GetString(CSettings::SETTING_SCREENSAVER_MODE).empty(); bool maybeDPMS = !m_dpmsIsActive && m_dpms->IsSupported() && m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_POWERMANAGEMENT_DISPLAYSOFF) > 0; // Has the screen saver window become active? if (maybeScreensaver && g_windowManager.IsWindowActive(WINDOW_SCREENSAVER)) { m_screensaverActive = true; maybeScreensaver = false; } if (m_screensaverActive && m_pPlayer->IsPlayingVideo() && !m_pPlayer->IsPaused()) { WakeUpScreenSaverAndDPMS(); return; } if (!maybeScreensaver && !maybeDPMS) return; // Nothing to do. // See if we need to reset timer. // * Are we playing a video and it is not paused? if ((m_pPlayer->IsPlayingVideo() && !m_pPlayer->IsPaused()) // * Are we playing some music in fullscreen vis? || (m_pPlayer->IsPlayingAudio() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION && !m_ServiceManager->GetSettings().GetString(CSettings::SETTING_MUSICPLAYER_VISUALISATION).empty())) { ResetScreenSaverTimer(); return; } float elapsed = m_screenSaverTimer.IsRunning() ? m_screenSaverTimer.GetElapsedSeconds() : 0.f; // DPMS has priority (it makes the screensaver not needed) if (maybeDPMS && elapsed > m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_POWERMANAGEMENT_DISPLAYSOFF) * 60) { ToggleDPMS(false); WakeUpScreenSaver(); } else if (maybeScreensaver && elapsed > m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_SCREENSAVER_TIME) * 60) { ActivateScreenSaver(); } } // activate the screensaver. // if forceType is true, we ignore the various conditions that can alter // the type of screensaver displayed void CApplication::ActivateScreenSaver(bool forceType /*= false */) { if (m_pPlayer->IsPlayingAudio() && m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_SCREENSAVER_USEMUSICVISINSTEAD) && !m_ServiceManager->GetSettings().GetString(CSettings::SETTING_MUSICPLAYER_VISUALISATION).empty()) { // just activate the visualisation if user toggled the usemusicvisinstead option g_windowManager.ActivateWindow(WINDOW_VISUALISATION); return; } m_screensaverActive = true; // disable screensaver lock from the login screen m_iScreenSaveLock = g_windowManager.GetActiveWindow() == WINDOW_LOGIN_SCREEN ? 1 : 0; // set to Dim in the case of a dialog on screen or playing video if (!forceType && (g_windowManager.HasModalDialog() || (m_pPlayer->IsPlayingVideo() && m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_SCREENSAVER_USEDIMONPAUSE)) || CServiceBroker::GetPVRManager().GUIActions()->IsRunningChannelScan())) m_screensaverIdInUse = "screensaver.xbmc.builtin.dim"; else // Get Screensaver Mode m_screensaverIdInUse = m_ServiceManager->GetSettings().GetString(CSettings::SETTING_SCREENSAVER_MODE); if (m_screensaverIdInUse == "screensaver.xbmc.builtin.dim" || m_screensaverIdInUse == "screensaver.xbmc.builtin.black") { #ifdef TARGET_ANDROID // Default screensaver activated -> release wake lock CXBMCApp::EnableWakeLock(false); #endif return; } else if (m_screensaverIdInUse.empty()) return; else if (CAddonMgr::GetInstance().GetAddon(m_screensaverIdInUse, m_pythonScreenSaver, ADDON_SCREENSAVER)) { std::string libPath = m_pythonScreenSaver->LibPath(); if (CScriptInvocationManager::GetInstance().HasLanguageInvoker(libPath)) { CLog::Log(LOGDEBUG, "using python screensaver add-on %s", m_screensaverIdInUse.c_str()); // Don't allow a previously-scheduled alarm to kill our new screensaver g_alarmClock.Stop(SCRIPT_ALARM, true); if (!CScriptInvocationManager::GetInstance().Stop(libPath)) CScriptInvocationManager::GetInstance().ExecuteAsync(libPath, AddonPtr(new CAddon(dynamic_cast<ADDON::CAddon&>(*m_pythonScreenSaver)))); return; } m_pythonScreenSaver.reset(); } g_windowManager.ActivateWindow(WINDOW_SCREENSAVER); } void CApplication::CheckShutdown() { // first check if we should reset the timer if (m_bInhibitIdleShutdown || m_pPlayer->IsPlaying() || m_pPlayer->IsPausedPlayback() // is something playing? || m_musicInfoScanner->IsScanning() || CVideoLibraryQueue::GetInstance().IsRunning() || g_windowManager.IsWindowActive(WINDOW_DIALOG_PROGRESS) // progress dialog is onscreen || !CServiceBroker::GetPVRManager().CanSystemPowerdown(false)) { m_shutdownTimer.StartZero(); return; } float elapsed = m_shutdownTimer.IsRunning() ? m_shutdownTimer.GetElapsedSeconds() : 0.f; if ( elapsed > m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_POWERMANAGEMENT_SHUTDOWNTIME) * 60 ) { // Since it is a sleep instead of a shutdown, let's set everything to reset when we wake up. m_shutdownTimer.Stop(); // Sleep the box CApplicationMessenger::GetInstance().PostMsg(TMSG_SHUTDOWN); } } void CApplication::InhibitIdleShutdown(bool inhibit) { m_bInhibitIdleShutdown = inhibit; } bool CApplication::IsIdleShutdownInhibited() const { return m_bInhibitIdleShutdown; } bool CApplication::OnMessage(CGUIMessage& message) { switch ( message.GetMessage() ) { case GUI_MSG_NOTIFY_ALL: { if (message.GetParam1()==GUI_MSG_REMOVED_MEDIA) { // Update general playlist: Remove DVD playlist items int nRemoved = g_playlistPlayer.RemoveDVDItems(); if ( nRemoved > 0 ) { CGUIMessage msg( GUI_MSG_PLAYLIST_CHANGED, 0, 0 ); g_windowManager.SendMessage( msg ); } // stop the file if it's on dvd (will set the resume point etc) if (m_itemCurrentFile->IsOnDVD()) StopPlaying(); } else if (message.GetParam1() == GUI_MSG_UI_READY) { // remove splash window g_windowManager.Delete(WINDOW_SPLASH); // show the volumebar if the volume is muted if (IsMuted() || GetVolume(false) <= VOLUME_MINIMUM) ShowVolumeBar(); if (m_fallbackLanguageLoaded) CGUIDialogOK::ShowAndGetInput(CVariant{24133}, CVariant{24134}); if (!m_incompatibleAddons.empty()) { auto addonList = StringUtils::Join(m_incompatibleAddons, ", "); auto msg = StringUtils::Format(g_localizeStrings.Get(24149).c_str(), addonList.c_str()); CGUIDialogOK::ShowAndGetInput(CVariant{24148}, CVariant{std::move(msg)}); m_incompatibleAddons.clear(); } // show info dialog about moved configuration files if needed ShowAppMigrationMessage(); m_bInitializing = false; } } break; case GUI_MSG_PLAYBACK_STARTED: { #ifdef TARGET_DARWIN_IOS CDarwinUtils::SetScheduling(message.GetMessage()); #endif CPlayList playList = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist()); // Update our infoManager with the new details etc. if (m_nextPlaylistItem >= 0) { // playing an item which is not in the list - player might be stopped already // so do nothing if (playList.size() <= m_nextPlaylistItem) return true; // we've started a previously queued item CFileItemPtr item = playList[m_nextPlaylistItem]; // update the playlist manager int currentSong = g_playlistPlayer.GetCurrentSong(); int param = ((currentSong & 0xffff) << 16) | (m_nextPlaylistItem & 0xffff); CGUIMessage msg(GUI_MSG_PLAYLISTPLAYER_CHANGED, 0, 0, g_playlistPlayer.GetCurrentPlaylist(), param, item); g_windowManager.SendThreadMessage(msg); g_playlistPlayer.SetCurrentSong(m_nextPlaylistItem); m_itemCurrentFile.reset(new CFileItem(*item)); } g_infoManager.SetCurrentItem(m_itemCurrentFile); g_partyModeManager.OnSongChange(true); CVariant param; param["player"]["speed"] = 1; param["player"]["playerid"] = g_playlistPlayer.GetCurrentPlaylist(); CAnnouncementManager::GetInstance().Announce(Player, "xbmc", "OnPlay", m_itemCurrentFile, param); return true; } break; case GUI_MSG_QUEUE_NEXT_ITEM: { // Check to see if our playlist player has a new item for us, // and if so, we check whether our current player wants the file int iNext = g_playlistPlayer.GetNextSong(); CPlayList& playlist = g_playlistPlayer.GetPlaylist(g_playlistPlayer.GetCurrentPlaylist()); if (iNext < 0 || iNext >= playlist.size()) { m_pPlayer->OnNothingToQueueNotify(); return true; // nothing to do } // ok, grab the next song CFileItem file(*playlist[iNext]); // handle plugin:// CURL url(file.GetPath()); if (url.IsProtocol("plugin")) XFILE::CPluginDirectory::GetPluginResult(url.Get(), file); // Don't queue if next media type is different from current one if ((!file.IsVideo() && m_pPlayer->IsPlayingVideo()) || ((!file.IsAudio() || file.IsVideo()) && m_pPlayer->IsPlayingAudio())) { m_pPlayer->OnNothingToQueueNotify(); return true; } #ifdef HAS_UPNP if (URIUtils::IsUPnP(file.GetPath())) { if (!XFILE::CUPnPDirectory::GetResource(file.GetURL(), file)) return true; } #endif // ok - send the file to the player, if it accepts it if (m_pPlayer->QueueNextFile(file)) { // player accepted the next file m_nextPlaylistItem = iNext; } else { /* Player didn't accept next file: *ALWAYS* advance playlist in this case so the player can queue the next (if it wants to) and it doesn't keep looping on this song */ g_playlistPlayer.SetCurrentSong(iNext); } return true; } break; case GUI_MSG_PLAYBACK_STOPPED: case GUI_MSG_PLAYBACK_ENDED: case GUI_MSG_PLAYLISTPLAYER_STOPPED: { #ifdef TARGET_DARWIN_IOS CDarwinUtils::SetScheduling(message.GetMessage()); #endif // first check if we still have items in the stack to play if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED) { if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0 && m_currentStackPosition < m_currentStack->Size() - 1) { // just play the next item in the stack PlayFile(*(*m_currentStack)[++m_currentStackPosition], "", true); return true; } } // In case playback ended due to user eg. skipping over the end, clear // our resume bookmark here if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED && m_progressTrackingPlayCountUpdate && g_advancedSettings.m_videoIgnorePercentAtEnd > 0) { // Delete the bookmark m_progressTrackingVideoResumeBookmark.timeInSeconds = -1.0f; } // reset the current playing file m_itemCurrentFile->Reset(); g_infoManager.ResetCurrentItem(); m_currentStack->Clear(); if (message.GetMessage() == GUI_MSG_PLAYBACK_ENDED) { g_playlistPlayer.PlayNext(1, true); } else { m_pPlayer->ClosePlayer(); } if (!m_pPlayer->IsPlaying()) { g_audioManager.Enable(true); } if (!m_pPlayer->IsPlayingVideo()) { if(g_windowManager.GetActiveWindow() == WINDOW_FULLSCREEN_VIDEO) { g_windowManager.PreviousWindow(); } else { CSingleLock lock(g_graphicsContext); // resets to res_desktop or look&feel resolution (including refreshrate) g_graphicsContext.SetFullScreenVideo(false); } } if (!m_pPlayer->IsPlayingAudio() && g_playlistPlayer.GetCurrentPlaylist() == PLAYLIST_NONE && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION) { m_ServiceManager->GetSettings().Save(); // save vis settings WakeUpScreenSaverAndDPMS(); g_windowManager.PreviousWindow(); } // DVD ejected while playing in vis ? if (!m_pPlayer->IsPlayingAudio() && (m_itemCurrentFile->IsCDDA() || m_itemCurrentFile->IsOnDVD()) && !g_mediaManager.IsDiscInDrive() && g_windowManager.GetActiveWindow() == WINDOW_VISUALISATION) { // yes, disable vis m_ServiceManager->GetSettings().Save(); // save vis settings WakeUpScreenSaverAndDPMS(); g_windowManager.PreviousWindow(); } if (IsEnableTestMode()) CApplicationMessenger::GetInstance().PostMsg(TMSG_QUIT); return true; } break; case GUI_MSG_PLAYLISTPLAYER_STARTED: case GUI_MSG_PLAYLISTPLAYER_CHANGED: { return true; } break; case GUI_MSG_FULLSCREEN: { // Switch to fullscreen, if we can SwitchToFullScreen(); return true; } break; case GUI_MSG_EXECUTE: if (message.GetNumStringParams()) return ExecuteXBMCAction(message.GetStringParam(), message.GetItem()); break; } return false; } bool CApplication::ExecuteXBMCAction(std::string actionStr, const CGUIListItemPtr &item /* = NULL */) { // see if it is a user set string //We don't know if there is unsecure information in this yet, so we //postpone any logging const std::string in_actionStr(actionStr); if (item) actionStr = CGUIInfoLabel::GetItemLabel(actionStr, item.get()); else actionStr = CGUIInfoLabel::GetLabel(actionStr); // user has asked for something to be executed if (CBuiltins::GetInstance().HasCommand(actionStr)) { if (!CBuiltins::GetInstance().IsSystemPowerdownCommand(actionStr) || CServiceBroker::GetPVRManager().CanSystemPowerdown()) CBuiltins::GetInstance().Execute(actionStr); } else { // try translating the action from our ButtonTranslator int actionID; if (CButtonTranslator::TranslateActionString(actionStr.c_str(), actionID)) { OnAction(CAction(actionID)); return true; } CFileItem item(actionStr, false); #ifdef HAS_PYTHON if (item.IsPythonScript()) { // a python script CScriptInvocationManager::GetInstance().ExecuteAsync(item.GetPath()); } else #endif if (item.IsAudio() || item.IsVideo() || item.IsGame()) { // an audio or video file PlayFile(item, ""); } else { //At this point we have given up to translate, so even though //there may be insecure information, we log it. CLog::LogF(LOGDEBUG,"Tried translating, but failed to understand %s", in_actionStr.c_str()); return false; } } return true; } // inform the user that the configuration data has moved from old XBMC location // to new Kodi location - if applicable void CApplication::ShowAppMigrationMessage() { // .kodi_migration_complete will be created from the installer/packaging // once an old XBMC configuration was moved to the new Kodi location // if this is the case show the migration info to the user once which // tells him to have a look into the wiki where the move of configuration // is further explained. if (CFile::Exists("special://home/.kodi_data_was_migrated") && !CFile::Exists("special://home/.kodi_migration_info_shown")) { CGUIDialogOK::ShowAndGetInput(CVariant{24128}, CVariant{24129}); CFile tmpFile; // create the file which will prevent this dialog from appearing in the future tmpFile.OpenForWrite("special://home/.kodi_migration_info_shown"); tmpFile.Close(); } } void CApplication::Process() { MEASURE_FUNCTION; // dispatch the messages generated by python or other threads to the current window g_windowManager.DispatchThreadMessages(); // process messages which have to be send to the gui // (this can only be done after g_windowManager.Render()) CApplicationMessenger::GetInstance().ProcessWindowMessages(); if (m_autoExecScriptExecuted) { m_autoExecScriptExecuted = false; // autoexec.py - profile std::string strAutoExecPy = CSpecialProtocol::TranslatePath("special://profile/autoexec.py"); if (XFILE::CFile::Exists(strAutoExecPy)) CScriptInvocationManager::GetInstance().ExecuteAsync(strAutoExecPy); else CLog::Log(LOGDEBUG, "no profile autoexec.py (%s) found, skipping", strAutoExecPy.c_str()); } // handle any active scripts { // Allow processing of script threads to let them shut down properly. CSingleExit ex(g_graphicsContext); m_frameMoveGuard.unlock(); CScriptInvocationManager::GetInstance().Process(); m_frameMoveGuard.lock(); } // process messages, even if a movie is playing CApplicationMessenger::GetInstance().ProcessMessages(); if (g_application.m_bStop) return; //we're done, everything has been unloaded // update sound m_pPlayer->DoAudioWork(); // do any processing that isn't needed on each run if( m_slowTimer.GetElapsedMilliseconds() > 500 ) { m_slowTimer.Reset(); ProcessSlow(); } #if !defined(TARGET_DARWIN) g_cpuInfo.getUsedPercentage(); // must call it to recalculate pct values #endif } // We get called every 500ms void CApplication::ProcessSlow() { g_powerManager.ProcessEvents(); #if defined(TARGET_DARWIN_OSX) // There is an issue on OS X that several system services ask the cursor to become visible // during their startup routines. Given that we can't control this, we hack it in by // forcing the if (g_Windowing.IsFullScreen()) { // SDL thinks it's hidden Cocoa_HideMouse(); } #endif // Temporarily pause pausable jobs when viewing video/picture int currentWindow = g_windowManager.GetActiveWindow(); if (CurrentFileItem().IsVideo() || CurrentFileItem().IsPicture() || currentWindow == WINDOW_FULLSCREEN_VIDEO || currentWindow == WINDOW_SLIDESHOW) { CJobManager::GetInstance().PauseJobs(); } else { CJobManager::GetInstance().UnPauseJobs(); } // Store our file state for use on close() UpdateFileState(); // Check if we need to activate the screensaver / DPMS. CheckScreenSaverAndDPMS(); // Check if we need to shutdown (if enabled). #if defined(TARGET_DARWIN) if (m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_POWERMANAGEMENT_SHUTDOWNTIME) && g_advancedSettings.m_fullScreen) #else if (m_ServiceManager->GetSettings().GetInt(CSettings::SETTING_POWERMANAGEMENT_SHUTDOWNTIME)) #endif { CheckShutdown(); } // check if we should restart the player CheckDelayedPlayerRestart(); // check if we can unload any unreferenced dlls or sections if (!m_pPlayer->IsPlayingVideo()) CSectionLoader::UnloadDelayed(); // check for any idle curl connections g_curlInterface.CheckIdle(); g_largeTextureManager.CleanupUnusedImages(); g_TextureManager.FreeUnusedTextures(5000); #ifdef HAS_DVD_DRIVE // checks whats in the DVD drive and tries to autostart the content (xbox games, dvd, cdda, avi files...) if (!m_pPlayer->IsPlayingVideo()) m_Autorun->HandleAutorun(); #endif // update upnp server/renderer states #ifdef HAS_UPNP if(UPNP::CUPnP::IsInstantiated()) UPNP::CUPnP::GetInstance()->UpdateState(); #endif #if defined(TARGET_POSIX) && defined(HAS_FILESYSTEM_SMB) smb.CheckIfIdle(); #endif #ifdef HAS_FILESYSTEM_NFS gNfsConnection.CheckIfIdle(); #endif #ifdef HAS_FILESYSTEM_SFTP CSFTPSessionManager::ClearOutIdleSessions(); #endif VECADDONS addons; CServiceBroker::GetBinaryAddonCache().GetAddons(addons, ADDON_VFS); for (auto& it : addons) { AddonPtr addon = CServiceBroker::GetBinaryAddonCache().GetAddonInstance(it->ID(), ADDON_VFS); VFSEntryPtr vfs = std::static_pointer_cast<CVFSEntry>(addon); vfs->ClearOutIdle(); } g_mediaManager.ProcessEvents(); m_ServiceManager->GetActiveAE().GarbageCollect(); g_windowManager.SendMessage(GUI_MSG_REFRESH_TIMER,0,0); // if we don't render the gui there's no reason to start the screensaver. // that way the screensaver won't kick in if we maximize the XBMC window // after the screensaver start time. if(!m_renderGUI) ResetScreenSaverTimer(); } // Global Idle Time in Seconds // idle time will be reset if on any OnKey() // int return: system Idle time in seconds! 0 is no idle! int CApplication::GlobalIdleTime() { if(!m_idleTimer.IsRunning()) m_idleTimer.StartZero(); return (int)m_idleTimer.GetElapsedSeconds(); } float CApplication::NavigationIdleTime() { if (!m_navigationTimer.IsRunning()) m_navigationTimer.StartZero(); return m_navigationTimer.GetElapsedSeconds(); } void CApplication::DelayedPlayerRestart() { m_restartPlayerTimer.StartZero(); } void CApplication::CheckDelayedPlayerRestart() { if (m_restartPlayerTimer.GetElapsedSeconds() > 3) { m_restartPlayerTimer.Stop(); m_restartPlayerTimer.Reset(); Restart(true); } } void CApplication::Restart(bool bSamePosition) { // this function gets called when the user changes a setting (like noninterleaved) // and which means we gotta close & reopen the current playing file // first check if we're playing a file if ( !m_pPlayer->IsPlayingVideo() && !m_pPlayer->IsPlayingAudio()) return ; if( !m_pPlayer->HasPlayer() ) return ; SaveFileState(); // do we want to return to the current position in the file if (false == bSamePosition) { // no, then just reopen the file and start at the beginning PlayFile(*m_itemCurrentFile, "", true); return ; } // else get current position double time = GetTime(); // get player state, needed for dvd's std::string state = m_pPlayer->GetPlayerState(); // set the requested starttime m_itemCurrentFile->m_lStartOffset = (long)(time * 75.0); // reopen the file if ( PlayFile(*m_itemCurrentFile, "", true) == PLAYBACK_OK ) m_pPlayer->SetPlayerState(state); } const std::string& CApplication::CurrentFile() { return m_itemCurrentFile->GetPath(); } std::shared_ptr<CFileItem> CApplication::CurrentFileItemPtr() { return m_itemCurrentFile; } CFileItem& CApplication::CurrentFileItem() { return *m_itemCurrentFile; } void CApplication::SetCurrentFileItem(const CFileItem& item) { m_itemCurrentFile.reset(new CFileItem(item)); } CFileItem& CApplication::CurrentUnstackedItem() { if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) return *(*m_currentStack)[m_currentStackPosition]; else return *m_itemCurrentFile; } void CApplication::ShowVolumeBar(const CAction *action) { CGUIDialog *volumeBar = g_windowManager.GetDialog(WINDOW_DIALOG_VOLUME_BAR); if (volumeBar) { volumeBar->Open(); if (action) volumeBar->OnAction(*action); } } bool CApplication::IsMuted() const { if (CServiceBroker::GetPeripherals().IsMuted()) return true; return m_ServiceManager->GetActiveAE().IsMuted(); } void CApplication::ToggleMute(void) { if (m_muted) UnMute(); else Mute(); } void CApplication::SetMute(bool mute) { if (m_muted != mute) { ToggleMute(); m_muted = mute; } } void CApplication::Mute() { if (CServiceBroker::GetPeripherals().Mute()) return; m_ServiceManager->GetActiveAE().SetMute(true); m_muted = true; VolumeChanged(); } void CApplication::UnMute() { if (CServiceBroker::GetPeripherals().UnMute()) return; m_ServiceManager->GetActiveAE().SetMute(false); m_muted = false; VolumeChanged(); } void CApplication::SetVolume(float iValue, bool isPercentage/*=true*/) { float hardwareVolume = iValue; if(isPercentage) hardwareVolume /= 100.0f; SetHardwareVolume(hardwareVolume); VolumeChanged(); } void CApplication::SetHardwareVolume(float hardwareVolume) { hardwareVolume = std::max(VOLUME_MINIMUM, std::min(VOLUME_MAXIMUM, hardwareVolume)); m_volumeLevel = hardwareVolume; m_ServiceManager->GetActiveAE().SetVolume(hardwareVolume); } float CApplication::GetVolume(bool percentage /* = true */) const { if (percentage) { // converts the hardware volume to a percentage return m_volumeLevel * 100.0f; } return m_volumeLevel; } void CApplication::VolumeChanged() const { CVariant data(CVariant::VariantTypeObject); data["volume"] = GetVolume(); data["muted"] = m_muted; CAnnouncementManager::GetInstance().Announce(Application, "xbmc", "OnVolumeChanged", data); // if player has volume control, set it. m_pPlayer->SetVolume(m_volumeLevel); m_pPlayer->SetMute(m_muted); } int CApplication::GetSubtitleDelay() const { // converts subtitle delay to a percentage return int(((float)(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_SubtitleDelay + g_advancedSettings.m_videoSubsDelayRange)) / (2 * g_advancedSettings.m_videoSubsDelayRange)*100.0f + 0.5f); } int CApplication::GetAudioDelay() const { // converts audio delay to a percentage return int(((float)(CMediaSettings::GetInstance().GetCurrentVideoSettings().m_AudioDelay + g_advancedSettings.m_videoAudioDelayRange)) / (2 * g_advancedSettings.m_videoAudioDelayRange)*100.0f + 0.5f); } // Returns the total time in seconds of the current media. Fractional // portions of a second are possible - but not necessarily supported by the // player class. This returns a double to be consistent with GetTime() and // SeekTime(). double CApplication::GetTotalTime() const { double rc = 0.0; if (m_pPlayer->IsPlaying()) { if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) rc = (*m_currentStack)[m_currentStack->Size() - 1]->m_lEndOffset; else rc = static_cast<double>(m_pPlayer->GetTotalTime() * 0.001f); } return rc; } void CApplication::StopShutdownTimer() { m_shutdownTimer.Stop(); } void CApplication::ResetShutdownTimers() { // reset system shutdown timer m_shutdownTimer.StartZero(); // delete custom shutdown timer if (g_alarmClock.HasAlarm("shutdowntimer")) g_alarmClock.Stop("shutdowntimer", true); } // Returns the current time in seconds of the currently playing media. // Fractional portions of a second are possible. This returns a double to // be consistent with GetTotalTime() and SeekTime(). double CApplication::GetTime() const { double rc = 0.0; if (m_pPlayer->IsPlaying()) { if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) { long startOfCurrentFile = (m_currentStackPosition > 0) ? (*m_currentStack)[m_currentStackPosition-1]->m_lEndOffset : 0; rc = (double)startOfCurrentFile + m_pPlayer->GetTime() * 0.001; } else rc = static_cast<double>(m_pPlayer->GetTime() * 0.001f); } return rc; } // Sets the current position of the currently playing media to the specified // time in seconds. Fractional portions of a second are valid. The passed // time is the time offset from the beginning of the file as opposed to a // delta from the current position. This method accepts a double to be // consistent with GetTime() and GetTotalTime(). void CApplication::SeekTime( double dTime ) { if (m_pPlayer->IsPlaying() && (dTime >= 0.0)) { if (!m_pPlayer->CanSeek()) return; if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) { // find the item in the stack we are seeking to, and load the new // file if necessary, and calculate the correct seek within the new // file. Otherwise, just fall through to the usual routine if the // time is higher than our total time. for (int i = 0; i < m_currentStack->Size(); i++) { if ((*m_currentStack)[i]->m_lEndOffset > dTime) { long startOfNewFile = (i > 0) ? (*m_currentStack)[i-1]->m_lEndOffset : 0; if (m_currentStackPosition == i) m_pPlayer->SeekTime((int64_t)((dTime - startOfNewFile) * 1000.0)); else { // seeking to a new file m_currentStackPosition = i; CFileItem *item = new CFileItem(*(*m_currentStack)[i]); item->m_lStartOffset = static_cast<long>((dTime - startOfNewFile) * 75.0); // don't just call "PlayFile" here, as we are quite likely called from the // player thread, so we won't be able to delete ourselves. CApplicationMessenger::GetInstance().PostMsg(TMSG_MEDIA_PLAY, 1, 0, static_cast<void*>(item)); } return; } } } // convert to milliseconds and perform seek m_pPlayer->SeekTime( static_cast<int64_t>( dTime * 1000.0 ) ); } } float CApplication::GetPercentage() const { if (m_pPlayer->IsPlaying()) { if (m_pPlayer->GetTotalTime() == 0 && m_pPlayer->IsPlayingAudio() && m_itemCurrentFile->HasMusicInfoTag()) { const CMusicInfoTag& tag = *m_itemCurrentFile->GetMusicInfoTag(); if (tag.GetDuration() > 0) return (float)(GetTime() / tag.GetDuration() * 100); } if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) { double totalTime = GetTotalTime(); if (totalTime > 0.0f) return (float)(GetTime() / totalTime * 100); } else return m_pPlayer->GetPercentage(); } return 0.0f; } float CApplication::GetCachePercentage() const { if (m_pPlayer->IsPlaying()) { // Note that the player returns a relative cache percentage and we want an absolute percentage if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) { float stackedTotalTime = (float) GetTotalTime(); // We need to take into account the stack's total time vs. currently playing file's total time if (stackedTotalTime > 0.0f) return std::min( 100.0f, GetPercentage() + (m_pPlayer->GetCachePercentage() * m_pPlayer->GetTotalTime() * 0.001f / stackedTotalTime ) ); } else return std::min( 100.0f, m_pPlayer->GetPercentage() + m_pPlayer->GetCachePercentage() ); } return 0.0f; } void CApplication::SeekPercentage(float percent) { if (m_pPlayer->IsPlaying() && (percent >= 0.0)) { if (!m_pPlayer->CanSeek()) return; if (m_itemCurrentFile->IsStack() && m_currentStack->Size() > 0) SeekTime(percent * 0.01 * GetTotalTime()); else m_pPlayer->SeekPercentage(percent); } } // SwitchToFullScreen() returns true if a switch is made, else returns false bool CApplication::SwitchToFullScreen(bool force /* = false */) { // don't switch if the slideshow is active if (g_windowManager.GetFocusedWindow() == WINDOW_SLIDESHOW) return false; // if playing from the video info window, close it first! if (g_windowManager.HasModalDialog() && g_windowManager.GetTopMostModalDialogID() == WINDOW_DIALOG_VIDEO_INFO) { CGUIDialogVideoInfo* pDialog = g_windowManager.GetWindow<CGUIDialogVideoInfo>(WINDOW_DIALOG_VIDEO_INFO); if (pDialog) pDialog->Close(true); } int windowID = WINDOW_INVALID; // See if we're playing a video, and are in GUI mode if (m_pPlayer->IsPlayingVideo() && g_windowManager.GetActiveWindow() != WINDOW_FULLSCREEN_VIDEO) windowID = WINDOW_FULLSCREEN_VIDEO; // special case for switching between GUI & visualisation mode. (only if we're playing an audio song) if (m_pPlayer->IsPlayingAudio() && g_windowManager.GetActiveWindow() != WINDOW_VISUALISATION) windowID = WINDOW_VISUALISATION; if (windowID != WINDOW_INVALID) { if (force) g_windowManager.ForceActivateWindow(windowID); else g_windowManager.ActivateWindow(windowID); return true; } return false; } void CApplication::Minimize() { g_Windowing.Minimize(); } std::string CApplication::GetCurrentPlayer() { return m_pPlayer->GetCurrentPlayer(); } void CApplication::UpdateLibraries() { if (m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_VIDEOLIBRARY_UPDATEONSTARTUP)) { CLog::LogF(LOGNOTICE, "Starting video library startup scan"); StartVideoScan("", !m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_VIDEOLIBRARY_BACKGROUNDUPDATE)); } if (m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MUSICLIBRARY_UPDATEONSTARTUP)) { CLog::LogF(LOGNOTICE, "Starting music library startup scan"); StartMusicScan("", !m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MUSICLIBRARY_BACKGROUNDUPDATE)); } } bool CApplication::IsVideoScanning() const { return CVideoLibraryQueue::GetInstance().IsScanningLibrary(); } bool CApplication::IsMusicScanning() const { return m_musicInfoScanner->IsScanning(); } void CApplication::StopVideoScan() { CVideoLibraryQueue::GetInstance().StopLibraryScanning(); } void CApplication::StopMusicScan() { if (m_musicInfoScanner->IsScanning()) m_musicInfoScanner->Stop(); } void CApplication::StartVideoCleanup(bool userInitiated /* = true */) { if (userInitiated && CVideoLibraryQueue::GetInstance().IsRunning()) return; std::set<int> paths; if (userInitiated) CVideoLibraryQueue::GetInstance().CleanLibraryModal(paths); else CVideoLibraryQueue::GetInstance().CleanLibrary(paths, true); } void CApplication::StartVideoScan(const std::string &strDirectory, bool userInitiated /* = true */, bool scanAll /* = false */) { CVideoLibraryQueue::GetInstance().ScanLibrary(strDirectory, scanAll, userInitiated); } void CApplication::StartMusicCleanup(bool userInitiated /* = true */) { if (m_musicInfoScanner->IsScanning()) return; if (userInitiated) m_musicInfoScanner->CleanDatabase(true); else { m_musicInfoScanner->ShowDialog(false); m_musicInfoScanner->StartCleanDatabase(); } } void CApplication::StartMusicScan(const std::string &strDirectory, bool userInitiated /* = true */, int flags /* = 0 */) { if (m_musicInfoScanner->IsScanning()) return; if (!flags) { // setup default flags if (m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MUSICLIBRARY_DOWNLOADINFO)) flags |= CMusicInfoScanner::SCAN_ONLINE; if (!userInitiated || m_ServiceManager->GetSettings().GetBool(CSettings::SETTING_MUSICLIBRARY_BACKGROUNDUPDATE)) flags |= CMusicInfoScanner::SCAN_BACKGROUND; // Ask for full rescan of music files //! @todo replace with a music library setting in UI if (g_advancedSettings.m_bMusicLibraryPromptFullTagScan) if (CGUIDialogYesNo::ShowAndGetInput(CVariant{ 799 }, CVariant{ 38062 })) flags |= CMusicInfoScanner::SCAN_RESCAN; } if (!(flags & CMusicInfoScanner::SCAN_BACKGROUND)) m_musicInfoScanner->ShowDialog(true); m_musicInfoScanner->Start(strDirectory, flags); } void CApplication::StartMusicAlbumScan(const std::string& strDirectory, bool refresh) { if (m_musicInfoScanner->IsScanning()) return; m_musicInfoScanner->ShowDialog(true); m_musicInfoScanner->FetchAlbumInfo(strDirectory,refresh); } void CApplication::StartMusicArtistScan(const std::string& strDirectory, bool refresh) { if (m_musicInfoScanner->IsScanning()) return; m_musicInfoScanner->ShowDialog(true); m_musicInfoScanner->FetchArtistInfo(strDirectory,refresh); } bool CApplication::ProcessAndStartPlaylist(const std::string& strPlayList, CPlayList& playlist, int iPlaylist, int track) { CLog::Log(LOGDEBUG,"CApplication::ProcessAndStartPlaylist(%s, %i)",strPlayList.c_str(), iPlaylist); // initial exit conditions // no songs in playlist just return if (playlist.size() == 0) return false; // illegal playlist if (iPlaylist < PLAYLIST_MUSIC || iPlaylist > PLAYLIST_VIDEO) return false; // setup correct playlist g_playlistPlayer.ClearPlaylist(iPlaylist); // if the playlist contains an internet stream, this file will be used // to generate a thumbnail for musicplayer.cover g_application.m_strPlayListFile = strPlayList; // add the items to the playlist player g_playlistPlayer.Add(iPlaylist, playlist); // if we have a playlist if (g_playlistPlayer.GetPlaylist(iPlaylist).size()) { // start playing it g_playlistPlayer.SetCurrentPlaylist(iPlaylist); g_playlistPlayer.Reset(); g_playlistPlayer.Play(track, ""); return true; } return false; } bool CApplication::IsCurrentThread() const { return CThread::IsCurrentThread(m_threadID); } void CApplication::SetRenderGUI(bool renderGUI) { if (renderGUI && ! m_renderGUI) g_windowManager.MarkDirty(); m_renderGUI = renderGUI; } CNetwork& CApplication::getNetwork() { return *m_network; } #ifdef HAS_PERFORMANCE_SAMPLE CPerformanceStats &CApplication::GetPerformanceStats() { return m_perfStats; } #endif bool CApplication::SetLanguage(const std::string &strLanguage) { // nothing to be done if the language hasn't changed if (strLanguage == m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOCALE_LANGUAGE)) return true; return m_ServiceManager->GetSettings().SetString(CSettings::SETTING_LOCALE_LANGUAGE, strLanguage); } bool CApplication::LoadLanguage(bool reload) { // load the configured langauge if (!g_langInfo.SetLanguage(m_fallbackLanguageLoaded, "", reload)) return false; // set the proper audio and subtitle languages g_langInfo.SetAudioLanguage(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOCALE_AUDIOLANGUAGE)); g_langInfo.SetSubtitleLanguage(m_ServiceManager->GetSettings().GetString(CSettings::SETTING_LOCALE_SUBTITLELANGUAGE)); return true; } void CApplication::SetLoggingIn(bool switchingProfiles) { // don't save skin settings on unloading when logging into another profile // because in that case we have already loaded the new profile and // would therefore write the previous skin's settings into the new profile // instead of into the previous one m_saveSkinOnUnloading = !switchingProfiles; // make sure that the autoexec.py script is executed after logging in m_autoExecScriptExecuted = true; } void CApplication::CloseNetworkShares() { CLog::Log(LOGDEBUG,"CApplication::CloseNetworkShares: Closing all network shares"); #if defined(HAS_FILESYSTEM_SMB) && !defined(TARGET_WINDOWS) smb.Deinit(); #endif #ifdef HAS_FILESYSTEM_NFS gNfsConnection.Deinit(); #endif #ifdef HAS_FILESYSTEM_SFTP CSFTPSessionManager::DisconnectAllSessions(); #endif VECADDONS addons; CServiceBroker::GetBinaryAddonCache().GetAddons(addons, ADDON_VFS); for (auto& it : addons) { AddonPtr addon = CServiceBroker::GetBinaryAddonCache().GetAddonInstance(it->ID(), ADDON_VFS); VFSEntryPtr vfs = std::static_pointer_cast<CVFSEntry>(addon); vfs->DisconnectAll(); } } void CApplication::RegisterActionListener(IActionListener *listener) { CSingleLock lock(m_critSection); std::vector<IActionListener *>::iterator it = std::find(m_actionListeners.begin(), m_actionListeners.end(), listener); if (it == m_actionListeners.end()) m_actionListeners.push_back(listener); } void CApplication::UnregisterActionListener(IActionListener *listener) { CSingleLock lock(m_critSection); std::vector<IActionListener *>::iterator it = std::find(m_actionListeners.begin(), m_actionListeners.end(), listener); if (it != m_actionListeners.end()) m_actionListeners.erase(it); } bool CApplication::NotifyActionListeners(const CAction &action) const { CSingleLock lock(m_critSection); for (std::vector<IActionListener *>::const_iterator it = m_actionListeners.begin(); it != m_actionListeners.end(); ++it) { if ((*it)->OnAction(action)) return true; } return false; }
gpl-2.0
SunPowered/python-workshop-2015
code/session3/matplotlib_package.py
3980
# -*- coding: utf-8 -*- """ matplotlib_package.py - 3 Data Analysis The dominant plotting library in Python was constructed to emulate the standard MATLAB plotting syntax and functionality, hence the name 'matplotlib'. There are several ways to interface with matplotlib. One can plot interactively, which is useful for on the fly visualization. One can subclass or wrap consistent and repetitive functionality to customize plots. Plotting options can be defined on the local operating system, if desired. It is important to configure the plotting backend for your system, this is done in Spyder in the iPython settings->Graphics. For this module, inline plotting is recommended. Resources: http://matplotlib.org/examples/pylab_examples/ """ import os import numpy as np np.random.seed(12345) plot_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, 'plots')) SAVE_FIGS = False N_FIG = 1 DEBUG = False def more(): global SAVE_FIGS, N_FIG, plot_dir, DEBUG if SAVE_FIGS: plot_name = os.path.join(plot_dir, "plot{}.png".format(N_FIG)) plt.savefig(plot_name) N_FIG += 1 plt.show() if not DEBUG: print raw_input("More...") print """ Interactive Plotting By utilizing the matplotlib module pyplot, one easily has access to all the standard plotting and customization mechanisms """ from matplotlib import pyplot as plt print print "Plot 1" time = np.linspace(0, 6 * np.pi) data = 2 * np.sin(time) + 3 * np.cos(time) plt.plot(time, data) plt.title('A title') plt.xlabel('Time') plt.ylabel('Data') plt.savefig(os.path.join(plot_dir, 'plot_example.png')) """ Multiple series can be plotted at once, with the following argument a flag for linestyle and colour. Important to note that each plot is made up of a figure, and axes, and plots. if we keep plotting and changing options, the same axes on the same figure will be modified in place. Plots amend the current figure, use the 'figure' function to start a new figure. Alternatively, we can use the 'show' function to force the current figure to be rendered. """ more() print print 'Plot 2' #plt.figure() sin_data = np.sin(time) cos_data = np.cos(time) plt.plot(time, cos_data, '-b', time, sin_data, '*r') plt.title('Sin/Cos') plt.xlabel('Time') plt.ylabel('Data') plt.legend(['Cosine', 'Sine']) """ Some more advanced figures include multiple axes on one figure. These are called 'subplots', and can be created and modified as follows. """ more() print print "Plot 3" ax = plt.subplot(2, 1, 1) # 2 rows, 1 col, current plot 1 plt.plot(time, sin_data, "--k") plt.title("Damped/Undamped Oscillator") plt.ylabel("Sin") plt.xlabel('Time') damped_sin = np.sin(time) * np.exp(-time / 5) plt.subplot(2, 1, 2) # This go to the next subplot axes plt.plot(time, damped_sin, '-g') plt.ylabel("Damped Sin") plt.xlabel("Time") """ There are many other types of plots that are available """ more() print print "Plot 4" hist_data = np.random.randn(2000) plt.hist(hist_data, color="g", bins=50) plt.title("Normally Distributed Data") more() """ With some careful manupulation, some advanced plottypes are also possible, such as a heatmap """ import matplotlib.mlab as mlab # Matlab compatible names import matplotlib.cm as cm # Colour maps print print "Plot 5" delta = 0.025 x = y = np.arange(-3.0, 3.0, delta) X, Y = np.meshgrid(x, y) Z1 = mlab.bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0) Z2 = mlab.bivariate_normal(X, Y, 1.5, 0.5, 1, 1) Z = Z2 - Z1 # difference of Gaussians im = plt.imshow(Z, interpolation='bilinear', cmap=cm.RdYlGn, origin='lower', extent=[-3, 3, -3, 3], vmax=abs(Z).max(), vmin=-abs(Z).max()) plt.title("Heatmaps!") plt.xlabel("X (mm)") plt.ylabel("Y (mm)") more()
gpl-2.0
gorkemgok/Tick4J
src/main/java/com/gorkemgok/tick4j/backtest/Positions.java
628
package com.gorkemgok.tick4j.backtest; import java.util.ArrayList; /** * Created by gorkemgok on 20/01/15. */ public class Positions { private ArrayList<Position> positions = new ArrayList<Position>(); private int openPositionCount = 0; public void addPosition(Position position){ positions.add(position); position.setParent(this); openPositionCount++; } public ArrayList<Position> getPositions(){ return positions; } public void closeOnePosition(){ openPositionCount--; } public int getOpenPositionCount() { return openPositionCount; } }
gpl-2.0
caco13/acheipinheiros
administrator/components/com_gmapfp/views/gmapfp/tmpl/upload_form.php
1655
<?php /* * GMapFP Component Google Map for Joomla! 1.7.x * Version 10.0pro * Creation date: Août 2011 * Author: Fabrice4821 - www.gmapfp.org * Author email: webmaster@gmapfp.org * License GNU/GPL */ defined('_JEXEC') or die('Restricted access'); ?> <script language="javascript" type="text/javascript"> function control() { var form = document.adminForm; // do field validation if (form.image1.value == ""){ alert( "<?php echo JText::_('GMAPFP_UPLOAD_ERREUR'); ?>" ); } else { return true; } return false; } </script> <style> .upload {font-family: Geneva, Arial, Helvetica, sans-serif;font-weight: bold;font-size: 12px;color: #3D5EA0;margin: 5px 0;text-align: left;} .inputbox {font-size: 11px;} </style> <form action='index.php?option=comgmapfp&controller=gmapfp&task=upload_image&tmpl=component' method='post' id='adminForm' name='adminForm' enctype='multipart/form-data' onsubmit='return control();'> <table width='100%' border='0' cellpadding='4' cellspacing='2' class='adminForm'> <div class="upload"><?php echo JText::_('GMAPFP_TELECHARGER_IMAGE') ;?> <tr align='left' valign='middle'> <td class='upload' align='left' valign='top'> <input type='hidden' name='option' value='com_gmapfp' /> <input class='inputbox' type='file' name='image1' /><br /> <input type='hidden' name='no_html' value='no_html' /> <input class='upload' type='submit' style="background:#55ff55; height:21px; cursor:pointer;" value='<?php echo JText::_('GMAPFP_BP_UPLOAD') ;?>' /> </td></tr></form></table></div> </table></table>
gpl-2.0
Crashthatch/PatternRecogniserPublic
src/main/java/processors/SplitEndsToColumns.java
2116
package processors; import com.google.common.collect.TreeBasedTable; import com.google.common.collect.Table; import database.TransformationService; import database.TransformationServiceReversible; import java.util.ArrayList; public class SplitEndsToColumns extends TransformationServiceReversible { private int splitIdx; private int endSplitIdx; public SplitEndsToColumns(int splitIdx, int endSplitIdx) { colsIn = 1; colsOut = 3; rowsIn = 1; rowsOut = 1; this.splitIdx = splitIdx; this.endSplitIdx = endSplitIdx; } public Table<Integer, Integer, String> doWork(Table<Integer, Integer, String> input) { Table<Integer, Integer, String> outTable = TreeBasedTable.create(); String stringin = input.get(0,0); int index = 0; //If they passed in -ve indexes, count from the end of the string. int useSplitIdx = splitIdx; int useEndSplitIdx = endSplitIdx; if( splitIdx < 0 ){ useSplitIdx = stringin.length()+splitIdx; } if( endSplitIdx < 0 ){ useEndSplitIdx = stringin.length()+endSplitIdx; } ArrayList<String> strings = new ArrayList<>(); strings.add(stringin.substring(0, useSplitIdx)); strings.add(stringin.substring(useSplitIdx, useEndSplitIdx)); strings.add(stringin.substring(useEndSplitIdx)); for (String string : strings) { outTable.put(0, index, string ); index++; } return outTable; } @Override public TransformationService getReverseTransformer() { return new concatenateAll(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + splitIdx; result = prime * result + endSplitIdx; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SplitEndsToColumns other = (SplitEndsToColumns) obj; if (splitIdx != other.splitIdx || endSplitIdx != other.endSplitIdx) return false; return true; } }
gpl-2.0
spidasoftware/webhooks-tool
tests/unit/controllers/users-test.js
317
import { moduleFor, test } from 'ember-qunit'; moduleFor('controller:users', { // Specify the other units that are required for this test. // needs: ['controller:foo'] }); // Replace this with your real tests. test('it exists', function(assert) { var controller = this.subject(); assert.ok(controller); });
gpl-2.0
aaronsilber/aaronsilber.me
site/routes/views/contact.js
326
var keystone = require('keystone'); exports = module.exports = function(req, res) { var view = new keystone.View(req, res), locals = res.locals; // locals.section is used to set the currently selected // item in the header navigation. locals.section = 'contact'; // Render the view view.render('contact'); };
gpl-2.0
yassine-khachlek/laravel-benchmark
src/App/Console/Commands/Benchmark.php
1944
<?php namespace Yk\LaravelBenchmark\App\Console\Commands; use Illuminate\Console\Command; use Artisan; class Benchmark extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'benchmark {artisan_command}'; /** * The console command description. * * @var string */ protected $description = 'Command description'; public $report = []; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $command = $this->argument('artisan_command'); $this->report['COMMAND_NAME'] = $command; $this->report['PHP_VERSION'] = phpversion(); $this->report['PLATFORM'] = php_uname('s').' '.php_uname('m').' '.php_uname('r'); $this->report['START'] = microtime(true); $memory_get_usage = memory_get_usage(); $exitCode = Artisan::call($command, [ ]); $this->report['END'] = microtime(true); $this->report['TIME'] = ceil(($this->report['END'] - $this->report['START']) * pow(10, 2)) / pow(10, 2)." Seconds"; $this->report['MEMORY_PEAK_USAGE'] = round((memory_get_peak_usage() - $memory_get_usage)/pow(10, 6), 2, PHP_ROUND_HALF_UP).' Megabytes'; $this->report['START'] = date('Y-m-d H:i:s', $this->report['START']); $this->report['END'] = date('Y-m-d H:i:s', $this->report['END']); $this->report['OUTPUT_LENGTH'] = strlen(Artisan::output()); foreach (array_keys($this->report) as $key) { $title = $key; while (strlen($title)<20) { $title .= " "; } $this->info($title.': '.$this->report[$key]); } } }
gpl-2.0
aecreative/bill
themes/bridge/framework/admin/options/20.logo/map.php
2019
<?php $logoPage = new QodeAdminPage("1", "Logo"); $qodeFramework->qodeOptions->addAdminPage("logo",$logoPage); $panel1 = new QodePanel("Logo", "logo"); $logoPage->addChild("panel1",$panel1); $logo_image = new QodeField("image","logo_image",QODE_ROOT."/img/logo.png","Logo Image - normal","Choose a default logo image to display "); $panel1->addChild("logo_image",$logo_image); $logo_image_light = new QodeField("image","logo_image_light",QODE_ROOT."/img/logo_white.png","Logo Image - Light",'Choose a logo image to display for "Light" header skin'); $panel1->addChild("logo_image_light",$logo_image_light); $logo_image_dark = new QodeField("image","logo_image_dark",QODE_ROOT."/img/logo_black.png","Logo Image - Dark",'Choose a logo image to display for "Dark" header skin'); $panel1->addChild("logo_image_dark",$logo_image_dark); $logo_image_sticky = new QodeField("image","logo_image_sticky",QODE_ROOT."/img/logo_black.png","Logo Image - Sticky Header",'Choose a logo image to display for "Sticky" header type'); $panel1->addChild("logo_image_sticky",$logo_image_sticky); $logo_image_fixed_hidden = new QodeField("image","logo_image_fixed_hidden","","Logo Image - Fixed Advanced Header",'Choose a logo image to display for "Fixed Advanced" header type'); $panel1->addChild("logo_image_fixed_hidden",$logo_image_fixed_hidden); $logo_image_mobile = new QodeField("image","logo_image_mobile","","Logo Image - Mobile Header",'Choose a logo image to display for "Mobile" header type'); $panel1->addChild("logo_image_mobile",$logo_image_mobile); $logo_mobile_header_height = new QodeField("text","logo_mobile_header_height","","Logo Height For Mobile Header (px)","Define logo height for mobile header"); $panel1->addChild("logo_mobile_header_height",$logo_mobile_header_height); $logo_mobile_height = new QodeField("text","logo_mobile_height","","Logo Height For Mobile Devices (px)","Define logo height for mobile devices"); $panel1->addChild("logo_mobile_height",$logo_mobile_height);
gpl-2.0
kenyaehrs/ipd
omod/src/main/java/org/openmrs/module/ipd/web/controller/global/IpdSingleton.java
1631
/** * Copyright 2010 Society for Health Information Systems Programmes, India (HISP India) * * This file is part of IPD module. * * IPD module 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. * IPD module 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 IPD module. If not, see <http://www.gnu.org/licenses/>. * **/ package org.openmrs.module.ipd.web.controller.global; import java.util.HashMap; /** * <p> Class: SubStoreSingleton </p> * <p> Package: org.openmrs.module.inventory.web.controller.substore </p> * <p> Author: Nguyen manh chuyen </p> * <p> Update by: Nguyen manh chuyen </p> * <p> Version: $1.0 </p> * <p> Create date: Dec 28, 2010 10:11:47 PM </p> * <p> Update date: Dec 28, 2010 10:11:47 PM </p> **/ public class IpdSingleton { private static IpdSingleton instance = null; public static final IpdSingleton getInstance(){ if (instance == null) { instance = new IpdSingleton(); } return instance; } private static HashMap<String, Object> hash; public static HashMap<String, Object> getHash() { if( hash == null ) hash = new HashMap<String, Object>(); return hash; } }
gpl-2.0
redrock9/NClassForLinux
src/CSharp/CSharpEvent.cs
7327
// NClass - Free class diagram editor // Copyright (C) 2006-2009 Balazs Tihanyi // // 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, write to the Free Software Foundation, Inc., // 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Text; using System.Text.RegularExpressions; using NClass.Core; using NClass.Translations; namespace NClass.CSharp { internal sealed class CSharpEvent : Event { // [<access>] [<modifiers>] event <type> <name> const string EventPattern = @"^\s*" + CSharpLanguage.AccessPattern + CSharpLanguage.OperationModifiersPattern + @"event\s+" + @"(?<type>" + CSharpLanguage.GenericTypePattern2 + @")\s+" + @"(?<name>" + CSharpLanguage.GenericOperationNamePattern + ")" + CSharpLanguage.DeclarationEnding; const string EventNamePattern = @"^\s*(?<name>" + CSharpLanguage.GenericOperationNamePattern + @")\s*$"; static Regex eventRegex = new Regex(EventPattern, RegexOptions.ExplicitCapture); static Regex nameRegex = new Regex(EventNamePattern, RegexOptions.ExplicitCapture); bool isExplicitImplementation = false; /// <exception cref="ArgumentNullException"> /// <paramref name="parent"/> is null. /// </exception> internal CSharpEvent(CompositeType parent) : this("NewEvent", parent) { } /// <exception cref="BadSyntaxException"> /// The <paramref name="name"/> does not fit to the syntax. /// </exception> /// <exception cref="ArgumentException"> /// The language of <paramref name="parent"/> does not equal. /// </exception> /// <exception cref="ArgumentNullException"> /// <paramref name="parent"/> is null. /// </exception> internal CSharpEvent(string name, CompositeType parent) : base(name, parent) { } /// <exception cref="BadSyntaxException"> /// The <paramref name="value"/> does not fit to the syntax. /// </exception> public override string Name { get { return base.Name; } set { Match match = nameRegex.Match(value); if (match.Success) { try { RaiseChangedEvent = false; ValidName = match.Groups["name"].Value; IsExplicitImplementation = match.Groups["namedot"].Success; } finally { RaiseChangedEvent = true; } } else { throw new BadSyntaxException(Strings.ErrorInvalidName); } } } protected override string DefaultType { get { return "EventHandler"; } } /// <exception cref="BadSyntaxException"> /// Cannot set access visibility. /// </exception> public override AccessModifier AccessModifier { get { return base.AccessModifier; } set { if (value != AccessModifier.Default && IsExplicitImplementation) { throw new BadSyntaxException( Strings.ErrorExplicitImplementationAccess); } if (value != AccessModifier.Default && Parent is InterfaceType) { throw new BadSyntaxException( Strings.ErrorInterfaceMemberAccess); } base.AccessModifier = value; } } public override bool IsAccessModifiable { get { return (base.IsAccessModifiable && !IsExplicitImplementation); } } public bool IsExplicitImplementation { get { return isExplicitImplementation; } private set { if (isExplicitImplementation != value) { try { RaiseChangedEvent = false; if (value) AccessModifier = AccessModifier.Default; isExplicitImplementation = value; Changed(); } finally { RaiseChangedEvent = true; } } } } public override bool HasBody { get { return IsExplicitImplementation; } } public override Language Language { get { return CSharpLanguage.Instance; } } /// <exception cref="BadSyntaxException"> /// The <paramref name="declaration"/> does not fit to the syntax. /// </exception> public override void InitFromString(string declaration) { Match match = eventRegex.Match(declaration); RaiseChangedEvent = false; try { if (match.Success) { ClearModifiers(); Group nameGroup = match.Groups["name"]; Group typeGroup = match.Groups["type"]; Group accessGroup = match.Groups["access"]; Group modifierGroup = match.Groups["modifier"]; Group nameDotGroup = match.Groups["namedot"]; if (CSharpLanguage.Instance.IsForbiddenName(nameGroup.Value)) throw new BadSyntaxException(Strings.ErrorInvalidName); if (CSharpLanguage.Instance.IsForbiddenTypeName(typeGroup.Value)) throw new BadSyntaxException(Strings.ErrorInvalidTypeName); ValidName = nameGroup.Value; ValidType = typeGroup.Value; IsExplicitImplementation = nameDotGroup.Success; AccessModifier = Language.TryParseAccessModifier(accessGroup.Value); foreach (Capture modifierCapture in modifierGroup.Captures) { if (modifierCapture.Value == "static") IsStatic = true; if (modifierCapture.Value == "virtual") IsVirtual = true; if (modifierCapture.Value == "abstract") IsAbstract = true; if (modifierCapture.Value == "override") IsOverride = true; if (modifierCapture.Value == "sealed") IsSealed = true; if (modifierCapture.Value == "new") IsHider = true; } } else { throw new BadSyntaxException(Strings.ErrorInvalidDeclaration); } } finally { RaiseChangedEvent = true; } } public override string GetDeclaration() { bool needsSemicolon = !IsExplicitImplementation; return GetDeclarationLine(needsSemicolon); } public string GetDeclarationLine(bool withSemicolon) { StringBuilder builder = new StringBuilder(50); if (AccessModifier != AccessModifier.Default) { builder.Append(Language.GetAccessString(AccessModifier, true)); builder.Append(" "); } if (IsHider) builder.Append("new "); if (IsStatic) builder.Append("static "); if (IsVirtual) builder.Append("virtual "); if (IsAbstract) builder.Append("abstract "); if (IsSealed) builder.Append("sealed "); if (IsOverride) builder.Append("override "); builder.AppendFormat("event {0} {1}", Type, Name); if (withSemicolon && !HasBody) builder.Append(";"); return builder.ToString(); } public override Operation Clone(CompositeType newParent) { CSharpEvent newEvent = new CSharpEvent(newParent); newEvent.CopyFrom(this); return newEvent; } public override string ToString() { return GetDeclarationLine(false); } } }
gpl-2.0
tomasz-orynski/BlueBit.CarsEvidence
BlueBit.CarsEvidence.GUI.Desktop/View/Panels/ListPanelView.xaml.cs
596
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BlueBit.CarsEvidence.GUI.Desktop.View.Panels { public partial class ListPanelView : UserControl { public ListPanelView() { InitializeComponent(); } } }
gpl-2.0
jrbranaa/pitchperspectives
wp-content/themes/brickyard-premium/category.php
766
<?php /** * The category archive template file. * @package BrickYard * @since BrickYard 1.0.0 */ get_header(); ?> <div class="entry-content"> <div class="entry-content-inner"> <?php if ( have_posts() ) : ?> <div class="content-headline"> <h1 class="entry-headline"><span class="entry-headline-text"><?php single_cat_title(); ?></span></h1> </div> <?php if ( category_description() ) : ?> <div class="archive-meta"><?php echo category_description(); ?></div> <?php endif; ?> <?php while (have_posts()) : the_post(); ?> <?php get_template_part( 'content', 'archives' ); ?> <?php endwhile; endif; ?> <?php brickyard_content_nav( 'nav-below' ); ?> </div> </div> </div> <!-- end of content --> <?php get_sidebar(); ?> <?php get_footer(); ?>
gpl-2.0
SergeyVorobiev/SK
SK35/src/com/vorobiev/myDialogs/DialogSlave.java
4656
package com.vorobiev.myDialogs; import android.annotation.SuppressLint; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.vorobiev.data.Player; import com.vorobiev.gameInterface.Sound; import com.vorobiev.gameclass.Assets; import com.vorobiev.objects.RightPanel; import com.vorobiev.sk.GameLayout; import com.vorobiev.sk.MyTouchListener; import com.vorobiev.sk.MyTouchListener.MyDownButtonAction; public class DialogSlave extends MyDialog { private Button button_up; private View dialogSlaveView; private TextView textCost; private TextView textLevel; private TextView textSize; private TextView textZa; public DialogSlave(Context paramContext) { super(paramContext); } @SuppressLint({"InflateParams"}) protected void create(AlertDialog paramAlertDialog) { this.dialogSlaveView = LayoutInflater.from(this.activity).inflate(2130903048, null); this.textLevel = ((TextView)this.dialogSlaveView.findViewById(2131361906)); this.textSize = ((TextView)this.dialogSlaveView.findViewById(2131361907)); this.textCost = ((TextView)this.dialogSlaveView.findViewById(2131361910)); this.button_up = ((Button)this.dialogSlaveView.findViewById(2131361908)); this.textZa = ((TextView)this.dialogSlaveView.findViewById(2131361909)); MyTouchListener localMyTouchListener = new MyTouchListener(2130837533, 2130837534, new MyTouchListener.MyDownButtonAction() { public void actionOnClick(View paramAnonymousView) { if ((Player.resource[15] >= Player.costBirth) && (Player.levelBirth < 20)) { Assets.money.play(1.0F); paramAnonymousView = Player.resource; paramAnonymousView[15] -= Player.costBirth; Player.costBirth *= 2L; double d = 1.0D / Player.levelBirth; Player.multiplePeople = (float)(Player.multiplePeople * Math.pow(2.0D, d)); Player.levelBirth += 1; DialogSlave.this.textLevel.setText("Уровень " + String.valueOf(Player.levelBirth)); int i = (int)(Player.multiplePeople / Player.koefPeopleTwo * Player.numPeople * 365.0F); DialogSlave.this.textSize.setText(String.valueOf(i)); DialogSlave.this.textCost.setText(String.valueOf(Player.costBirth)); GameLayout.rightPanel.updateMoney(); } for (;;) { if (Player.levelBirth == 20) { DialogSlave.this.textLevel.setText("МАКСИМУМ"); DialogSlave.this.textCost.setVisibility(4); DialogSlave.this.textZa.setVisibility(4); DialogSlave.this.button_up.setVisibility(4); } return; Assets.no.play(1.0F); } } }); this.button_up.setOnTouchListener(localMyTouchListener); prepare(paramAlertDialog); paramAlertDialog.setView(this.dialogSlaveView); paramAlertDialog.setButton(-1, "Хорошо", new DialogInterface.OnClickListener() { public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt) { paramAnonymousDialogInterface.cancel(); } }); paramAlertDialog.setCancelable(false); } protected void prepare(AlertDialog paramAlertDialog) { if (Player.resource[16] <= 100000L) { Player.koefPeopleTwo = 1.0F; } if (Player.resource[16] > 100000L) { Player.koefPeopleTwo = 4.0F; } if (Player.resource[16] > 1000000L) { Player.koefPeopleTwo = 6.0F; } if (Player.resource[16] > 2000000L) { Player.koefPeopleTwo = 9.0F; } if (Player.levelBirth == 20) { this.textLevel.setText("МАКСИМУМ"); this.textCost.setVisibility(4); this.textZa.setVisibility(4); this.button_up.setVisibility(4); } for (;;) { int i = (int)(Player.multiplePeople / Player.koefPeopleTwo * Player.numPeople * 365.0F); this.textSize.setText(String.valueOf(i)); return; this.textLevel.setText("Уровень " + String.valueOf(Player.levelBirth)); this.textCost.setText(String.valueOf(Player.costBirth)); } } } /* Location: C:\Users\Сергей\Desktop\SK35-dex2jar.jar!\com\vorobiev\myDialogs\DialogSlave.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
gpl-2.0
Habbie/pdns
pdns/syncres.cc
182640
/* * This file is part of PowerDNS or dnsdist. * Copyright -- PowerDNS.COM B.V. and its contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * In addition, for the avoidance of any doubt, permission is granted to * link this program with OpenSSL and to (re)distribute the binaries * produced as the result of such linking. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "arguments.hh" #include "aggressive_nsec.hh" #include "cachecleaner.hh" #include "dns_random.hh" #include "dnsparser.hh" #include "dnsrecords.hh" #include "ednssubnet.hh" #include "logger.hh" #include "lua-recursor4.hh" #include "rec-lua-conf.hh" #include "syncres.hh" #include "dnsseckeeper.hh" #include "validate-recursor.hh" thread_local SyncRes::ThreadLocalStorage SyncRes::t_sstorage; thread_local std::unique_ptr<addrringbuf_t> t_timeouts; std::unique_ptr<NetmaskGroup> SyncRes::s_dontQuery{nullptr}; NetmaskGroup SyncRes::s_ednslocalsubnets; NetmaskGroup SyncRes::s_ednsremotesubnets; SuffixMatchNode SyncRes::s_ednsdomains; EDNSSubnetOpts SyncRes::s_ecsScopeZero; string SyncRes::s_serverID; SyncRes::LogMode SyncRes::s_lm; const std::unordered_set<QType> SyncRes::s_redirectionQTypes = {QType::CNAME, QType::DNAME}; unsigned int SyncRes::s_maxnegttl; unsigned int SyncRes::s_maxbogusttl; unsigned int SyncRes::s_maxcachettl; unsigned int SyncRes::s_maxqperq; unsigned int SyncRes::s_maxnsaddressqperq; unsigned int SyncRes::s_maxtotusec; unsigned int SyncRes::s_maxdepth; unsigned int SyncRes::s_minimumTTL; unsigned int SyncRes::s_minimumECSTTL; unsigned int SyncRes::s_packetcachettl; unsigned int SyncRes::s_packetcacheservfailttl; unsigned int SyncRes::s_serverdownmaxfails; unsigned int SyncRes::s_serverdownthrottletime; unsigned int SyncRes::s_nonresolvingnsmaxfails; unsigned int SyncRes::s_nonresolvingnsthrottletime; unsigned int SyncRes::s_ecscachelimitttl; std::atomic<uint64_t> SyncRes::s_authzonequeries; std::atomic<uint64_t> SyncRes::s_queries; std::atomic<uint64_t> SyncRes::s_outgoingtimeouts; std::atomic<uint64_t> SyncRes::s_outgoing4timeouts; std::atomic<uint64_t> SyncRes::s_outgoing6timeouts; std::atomic<uint64_t> SyncRes::s_outqueries; std::atomic<uint64_t> SyncRes::s_tcpoutqueries; std::atomic<uint64_t> SyncRes::s_dotoutqueries; std::atomic<uint64_t> SyncRes::s_throttledqueries; std::atomic<uint64_t> SyncRes::s_dontqueries; std::atomic<uint64_t> SyncRes::s_qnameminfallbacksuccess; std::atomic<uint64_t> SyncRes::s_unreachables; std::atomic<uint64_t> SyncRes::s_ecsqueries; std::atomic<uint64_t> SyncRes::s_ecsresponses; std::map<uint8_t, std::atomic<uint64_t>> SyncRes::s_ecsResponsesBySubnetSize4; std::map<uint8_t, std::atomic<uint64_t>> SyncRes::s_ecsResponsesBySubnetSize6; uint8_t SyncRes::s_ecsipv4limit; uint8_t SyncRes::s_ecsipv6limit; uint8_t SyncRes::s_ecsipv4cachelimit; uint8_t SyncRes::s_ecsipv6cachelimit; bool SyncRes::s_ecsipv4nevercache; bool SyncRes::s_ecsipv6nevercache; bool SyncRes::s_doIPv4; bool SyncRes::s_doIPv6; bool SyncRes::s_nopacketcache; bool SyncRes::s_rootNXTrust; bool SyncRes::s_noEDNS; bool SyncRes::s_qnameminimization; SyncRes::HardenNXD SyncRes::s_hardenNXD; unsigned int SyncRes::s_refresh_ttlperc; int SyncRes::s_tcp_fast_open; bool SyncRes::s_tcp_fast_open_connect; bool SyncRes::s_dot_to_port_853; #define LOG(x) if(d_lm == Log) { g_log <<Logger::Warning << x; } else if(d_lm == Store) { d_trace << x; } static inline void accountAuthLatency(uint64_t usec, int family) { if (family == AF_INET) { g_stats.auth4Answers(usec); g_stats.cumulativeAuth4Answers(usec); } else { g_stats.auth6Answers(usec); g_stats.cumulativeAuth6Answers(usec); } } SyncRes::SyncRes(const struct timeval& now) : d_authzonequeries(0), d_outqueries(0), d_tcpoutqueries(0), d_dotoutqueries(0), d_throttledqueries(0), d_timeouts(0), d_unreachables(0), d_totUsec(0), d_now(now), d_cacheonly(false), d_doDNSSEC(false), d_doEDNS0(false), d_qNameMinimization(s_qnameminimization), d_lm(s_lm) { } /** everything begins here - this is the entry point just after receiving a packet */ int SyncRes::beginResolve(const DNSName &qname, const QType qtype, QClass qclass, vector<DNSRecord>&ret, unsigned int depth) { vState state = vState::Indeterminate; s_queries++; d_wasVariable=false; d_wasOutOfBand=false; d_cutStates.clear(); if (doSpecialNamesResolve(qname, qtype, qclass, ret)) { d_queryValidationState = vState::Insecure; // this could fool our stats into thinking a validation took place return 0; // so do check before updating counters (we do now) } auto qtypeCode = qtype.getCode(); /* rfc6895 section 3.1 */ if (qtypeCode == 0 || (qtypeCode >= 128 && qtypeCode <= 254) || qtypeCode == QType::RRSIG || qtypeCode == QType::NSEC3 || qtypeCode == QType::OPT || qtypeCode == 65535) { return -1; } if(qclass==QClass::ANY) qclass=QClass::IN; else if(qclass!=QClass::IN) return -1; if (qtype == QType::DS) { d_externalDSQuery = qname; } else { d_externalDSQuery.clear(); } set<GetBestNSAnswer> beenthere; int res=doResolve(qname, qtype, ret, depth, beenthere, state); d_queryValidationState = state; if (shouldValidate()) { if (d_queryValidationState != vState::Indeterminate) { g_stats.dnssecValidations++; } auto xdnssec = g_xdnssec.getLocal(); if (xdnssec->check(qname)) { increaseXDNSSECStateCounter(d_queryValidationState); } else { increaseDNSSECStateCounter(d_queryValidationState); } } return res; } /*! Handles all special, built-in names * Fills ret with an answer and returns true if it handled the query. * * Handles the following queries (and their ANY variants): * * - localhost. IN A * - localhost. IN AAAA * - 1.0.0.127.in-addr.arpa. IN PTR * - 1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa. IN PTR * - version.bind. CH TXT * - version.pdns. CH TXT * - id.server. CH TXT * - trustanchor.server CH TXT * - negativetrustanchor.server CH TXT */ bool SyncRes::doSpecialNamesResolve(const DNSName &qname, const QType qtype, const QClass qclass, vector<DNSRecord> &ret) { static const DNSName arpa("1.0.0.127.in-addr.arpa."), ip6_arpa("1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.ip6.arpa."), localhost("localhost."), versionbind("version.bind."), idserver("id.server."), versionpdns("version.pdns."), trustanchorserver("trustanchor.server."), negativetrustanchorserver("negativetrustanchor.server."); bool handled = false; vector<pair<QType::typeenum, string> > answers; if ((qname == arpa || qname == ip6_arpa) && qclass == QClass::IN) { handled = true; if (qtype == QType::PTR || qtype == QType::ANY) answers.push_back({QType::PTR, "localhost."}); } if (qname.isPartOf(localhost) && qclass == QClass::IN) { handled = true; if (qtype == QType::A || qtype == QType::ANY) answers.push_back({QType::A, "127.0.0.1"}); if (qtype == QType::AAAA || qtype == QType::ANY) answers.push_back({QType::AAAA, "::1"}); } if ((qname == versionbind || qname == idserver || qname == versionpdns) && qclass == QClass::CHAOS) { handled = true; if (qtype == QType::TXT || qtype == QType::ANY) { if(qname == versionbind || qname == versionpdns) answers.push_back({QType::TXT, "\""+::arg()["version-string"]+"\""}); else if (s_serverID != "disabled") answers.push_back({QType::TXT, "\""+s_serverID+"\""}); } } if (qname == trustanchorserver && qclass == QClass::CHAOS && ::arg().mustDo("allow-trust-anchor-query")) { handled = true; if (qtype == QType::TXT || qtype == QType::ANY) { auto luaLocal = g_luaconfs.getLocal(); for (auto const &dsAnchor : luaLocal->dsAnchors) { ostringstream ans; ans<<"\""; ans<<dsAnchor.first.toString(); // Explicit toString to have a trailing dot for (auto const &dsRecord : dsAnchor.second) { ans<<" "; ans<<dsRecord.d_tag; } ans << "\""; answers.push_back({QType::TXT, ans.str()}); } } } if (qname == negativetrustanchorserver && qclass == QClass::CHAOS && ::arg().mustDo("allow-trust-anchor-query")) { handled = true; if (qtype == QType::TXT || qtype == QType::ANY) { auto luaLocal = g_luaconfs.getLocal(); for (auto const &negAnchor : luaLocal->negAnchors) { ostringstream ans; ans<<"\""; ans<<negAnchor.first.toString(); // Explicit toString to have a trailing dot if (negAnchor.second.length()) ans<<" "<<negAnchor.second; ans << "\""; answers.push_back({QType::TXT, ans.str()}); } } } if (handled && !answers.empty()) { ret.clear(); d_wasOutOfBand=true; DNSRecord dr; dr.d_name = qname; dr.d_place = DNSResourceRecord::ANSWER; dr.d_class = qclass; dr.d_ttl = 86400; for (const auto& ans : answers) { dr.d_type = ans.first; dr.d_content = DNSRecordContent::mastermake(ans.first, qclass, ans.second); ret.push_back(dr); } } return handled; } //! This is the 'out of band resolver', in other words, the authoritative server void SyncRes::AuthDomain::addSOA(std::vector<DNSRecord>& records) const { SyncRes::AuthDomain::records_t::const_iterator ziter = d_records.find(boost::make_tuple(getName(), QType::SOA)); if (ziter != d_records.end()) { DNSRecord dr = *ziter; dr.d_place = DNSResourceRecord::AUTHORITY; records.push_back(dr); } else { // cerr<<qname<<": can't find SOA record '"<<getName()<<"' in our zone!"<<endl; } } int SyncRes::AuthDomain::getRecords(const DNSName& qname, const QType qtype, std::vector<DNSRecord>& records) const { int result = RCode::NoError; records.clear(); // partial lookup std::pair<records_t::const_iterator,records_t::const_iterator> range = d_records.equal_range(tie(qname)); SyncRes::AuthDomain::records_t::const_iterator ziter; bool somedata = false; for(ziter = range.first; ziter != range.second; ++ziter) { somedata = true; if(qtype == QType::ANY || ziter->d_type == qtype || ziter->d_type == QType::CNAME) { // let rest of nameserver do the legwork on this one records.push_back(*ziter); } else if (ziter->d_type == QType::NS && ziter->d_name.countLabels() > getName().countLabels()) { // we hit a delegation point! DNSRecord dr = *ziter; dr.d_place=DNSResourceRecord::AUTHORITY; records.push_back(dr); } } if (!records.empty()) { /* We have found an exact match, we're done */ // cerr<<qname<<": exact match in zone '"<<getName()<<"'"<<endl; return result; } if (somedata) { /* We have records for that name, but not of the wanted qtype */ // cerr<<qname<<": found record in '"<<getName()<<"', but nothing of the right type, sending SOA"<<endl; addSOA(records); return result; } // cerr<<qname<<": nothing found so far in '"<<getName()<<"', trying wildcards"<<endl; DNSName wcarddomain(qname); while(wcarddomain != getName() && wcarddomain.chopOff()) { // cerr<<qname<<": trying '*."<<wcarddomain<<"' in "<<getName()<<endl; range = d_records.equal_range(boost::make_tuple(g_wildcarddnsname + wcarddomain)); if (range.first==range.second) continue; for(ziter = range.first; ziter != range.second; ++ziter) { DNSRecord dr = *ziter; // if we hit a CNAME, just answer that - rest of recursor will do the needful & follow if(dr.d_type == qtype || qtype == QType::ANY || dr.d_type == QType::CNAME) { dr.d_name = qname; dr.d_place = DNSResourceRecord::ANSWER; records.push_back(dr); } } if (records.empty()) { addSOA(records); } // cerr<<qname<<": in '"<<getName()<<"', had wildcard match on '*."<<wcarddomain<<"'"<<endl; return result; } /* Nothing for this name, no wildcard, let's see if there is some NS */ DNSName nsdomain(qname); while (nsdomain.chopOff() && nsdomain != getName()) { range = d_records.equal_range(boost::make_tuple(nsdomain,QType::NS)); if(range.first == range.second) continue; for(ziter = range.first; ziter != range.second; ++ziter) { DNSRecord dr = *ziter; dr.d_place = DNSResourceRecord::AUTHORITY; records.push_back(dr); } } if(records.empty()) { // cerr<<qname<<": no NS match in zone '"<<getName()<<"' either, handing out SOA"<<endl; addSOA(records); result = RCode::NXDomain; } return result; } bool SyncRes::doOOBResolve(const AuthDomain& domain, const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, int& res) { d_authzonequeries++; s_authzonequeries++; res = domain.getRecords(qname, qtype, ret); return true; } bool SyncRes::doOOBResolve(const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, int& res) { string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } DNSName authdomain(qname); domainmap_t::const_iterator iter=getBestAuthZone(&authdomain); if(iter==t_sstorage.domainmap->end() || !iter->second.isAuth()) { LOG(prefix<<qname<<": auth storage has no zone for this query!"<<endl); return false; } LOG(prefix<<qname<<": auth storage has data, zone='"<<authdomain<<"'"<<endl); return doOOBResolve(iter->second, qname, qtype, ret, res); } bool SyncRes::isRecursiveForwardOrAuth(const DNSName &qname) const { DNSName authname(qname); domainmap_t::const_iterator iter = getBestAuthZone(&authname); return iter != t_sstorage.domainmap->end() && (iter->second.isAuth() || iter->second.shouldRecurse()); } bool SyncRes::isForwardOrAuth(const DNSName &qname) const { DNSName authname(qname); domainmap_t::const_iterator iter = getBestAuthZone(&authname); return iter != t_sstorage.domainmap->end() && (iter->second.isAuth() || !iter->second.shouldRecurse()); } uint64_t SyncRes::doEDNSDump(int fd) { int newfd = dup(fd); if (newfd == -1) { return 0; } auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose); if (!fp) { close(newfd); return 0; } uint64_t count = 0; fprintf(fp.get(),"; edns from thread follows\n;\n"); for(const auto& eds : t_sstorage.ednsstatus) { count++; char tmp[26]; fprintf(fp.get(), "%s\t%d\t%s", eds.address.toString().c_str(), (int)eds.mode, ctime_r(&eds.modeSetAt, tmp)); } return count; } uint64_t SyncRes::doDumpNSSpeeds(int fd) { int newfd = dup(fd); if (newfd == -1) { return 0; } auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose); if (!fp) { close(newfd); return 0; } fprintf(fp.get(), "; nsspeed dump from thread follows\n;\n"); uint64_t count=0; for(const auto& i : t_sstorage.nsSpeeds) { count++; // an <empty> can appear hear in case of authoritative (hosted) zones fprintf(fp.get(), "%s -> ", i.first.toLogString().c_str()); for(const auto& j : i.second.d_collection) { // typedef vector<pair<ComboAddress, DecayingEwma> > collection_t; fprintf(fp.get(), "%s/%f ", j.first.toString().c_str(), j.second.peek()); } fprintf(fp.get(), "\n"); } return count; } uint64_t SyncRes::doDumpThrottleMap(int fd) { int newfd = dup(fd); if (newfd == -1) { return 0; } auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose); if (!fp) { close(newfd); return 0; } fprintf(fp.get(), "; throttle map dump follows\n"); fprintf(fp.get(), "; remote IP\tqname\tqtype\tcount\tttd\n"); uint64_t count=0; const auto& throttleMap = t_sstorage.throttle.getThrottleMap(); for(const auto& i : throttleMap) { count++; char tmp[26]; // remote IP, dns name, qtype, count, ttd fprintf(fp.get(), "%s\t%s\t%d\t%u\t%s", i.thing.get<0>().toString().c_str(), i.thing.get<1>().toLogString().c_str(), i.thing.get<2>(), i.count, ctime_r(&i.ttd, tmp)); } return count; } uint64_t SyncRes::doDumpFailedServers(int fd) { int newfd = dup(fd); if (newfd == -1) { return 0; } auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose); if (!fp) { close(newfd); return 0; } fprintf(fp.get(), "; failed servers dump follows\n"); fprintf(fp.get(), "; remote IP\tcount\ttimestamp\n"); uint64_t count=0; for(const auto& i : t_sstorage.fails.getMap()) { count++; char tmp[26]; ctime_r(&i.last, tmp); fprintf(fp.get(), "%s\t%llu\t%s", i.key.toString().c_str(), i.value, tmp); } return count; } uint64_t SyncRes::doDumpNonResolvingNS(int fd) { int newfd = dup(fd); if (newfd == -1) { return 0; } auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fdopen(newfd, "w"), fclose); if (!fp) { close(newfd); return 0; } fprintf(fp.get(), "; non-resolving nameserver dump follows\n"); fprintf(fp.get(), "; name\tcount\ttimestamp\n"); uint64_t count=0; for(const auto& i : t_sstorage.nonresolving.getMap()) { count++; char tmp[26]; ctime_r(&i.last, tmp); fprintf(fp.get(), "%s\t%llu\t%s", i.key.toString().c_str(), i.value, tmp); } return count; } /* so here is the story. First we complete the full resolution process for a domain name. And only THEN do we decide to also do DNSSEC validation, which leads to new queries. To make this simple, we *always* ask for DNSSEC records so that if there are RRSIGs for a name, we'll have them. However, some hosts simply can't answer questions which ask for DNSSEC. This can manifest itself as: * No answer * FormErr * Nonsense answer The cause of "No answer" may be fragmentation, and it is tempting to probe if smaller answers would get through. Another cause of "No answer" may simply be a network condition. Nonsense answers are a clearer indication this host won't be able to do DNSSEC evah. Previous implementations have suffered from turning off DNSSEC questions for an authoritative server based on timeouts. A clever idea is to only turn off DNSSEC if we know a domain isn't signed anyhow. The problem with that really clever idea however is that at this point in PowerDNS, we may simply not know that yet. All the DNSSEC thinking happens elsewhere. It may not have happened yet. For now this means we can't be clever, but will turn off DNSSEC if you reply with FormError or gibberish. */ LWResult::Result SyncRes::asyncresolveWrapper(const ComboAddress& ip, bool ednsMANDATORY, const DNSName& domain, const DNSName& auth, int type, bool doTCP, bool sendRDQuery, struct timeval* now, boost::optional<Netmask>& srcmask, LWResult* res, bool* chained) const { /* what is your QUEST? the goal is to get as many remotes as possible on the highest level of EDNS support The levels are: 0) UNKNOWN Unknown state 1) EDNS: Honors EDNS0 2) EDNSIGNORANT: Ignores EDNS0, gives replies without EDNS0 3) NOEDNS: Generates FORMERR on EDNS queries Everybody starts out assumed to be '0'. If '0', send out EDNS0 If you FORMERR us, go to '3', If no EDNS in response, go to '2' If '1', send out EDNS0 If FORMERR, downgrade to 3 If '2', keep on including EDNS0, see what happens Same behaviour as 0 If '3', send bare queries */ auto ednsstatus = t_sstorage.ednsstatus.insert(ip).first; // does this include port? YES auto &ind = t_sstorage.ednsstatus.get<ComboAddress>(); if (ednsstatus->modeSetAt && ednsstatus->modeSetAt + 3600 < d_now.tv_sec) { t_sstorage.ednsstatus.reset(ind, ednsstatus); // cerr<<"Resetting EDNS Status for "<<ip.toString()<<endl); } const SyncRes::EDNSStatus::EDNSMode *mode = &ednsstatus->mode; const SyncRes::EDNSStatus::EDNSMode oldmode = *mode; int EDNSLevel = 0; auto luaconfsLocal = g_luaconfs.getLocal(); ResolveContext ctx; ctx.d_initialRequestId = d_initialRequestId; #ifdef HAVE_FSTRM ctx.d_auth = auth; #endif LWResult::Result ret; for(int tries = 0; tries < 3; ++tries) { // cerr<<"Remote '"<<ip.toString()<<"' currently in mode "<<mode<<endl; if (*mode == EDNSStatus::NOEDNS) { g_stats.noEdnsOutQueries++; EDNSLevel = 0; // level != mode } else if (ednsMANDATORY || *mode == EDNSStatus::UNKNOWN || *mode == EDNSStatus::EDNSOK || *mode == EDNSStatus::EDNSIGNORANT) EDNSLevel = 1; DNSName sendQname(domain); if (g_lowercaseOutgoing) sendQname.makeUsLowerCase(); if (d_asyncResolve) { ret = d_asyncResolve(ip, sendQname, type, doTCP, sendRDQuery, EDNSLevel, now, srcmask, ctx, res, chained); } else { ret = asyncresolve(ip, sendQname, type, doTCP, sendRDQuery, EDNSLevel, now, srcmask, ctx, d_outgoingProtobufServers, d_frameStreamServers, luaconfsLocal->outgoingProtobufExportConfig.exportTypes, res, chained); } // ednsstatus might be cleared, so do a new lookup ednsstatus = t_sstorage.ednsstatus.insert(ip).first; mode = &ednsstatus->mode; if (ret == LWResult::Result::PermanentError || ret == LWResult::Result::OSLimitError || ret == LWResult::Result::Spoofed) { return ret; // transport error, nothing to learn here } if (ret == LWResult::Result::Timeout) { // timeout, not doing anything with it now return ret; } else if (*mode == EDNSStatus::UNKNOWN || *mode == EDNSStatus::EDNSOK || *mode == EDNSStatus::EDNSIGNORANT ) { if(res->d_validpacket && !res->d_haveEDNS && res->d_rcode == RCode::FormErr) { // cerr<<"Downgrading to NOEDNS because of "<<RCode::to_s(res->d_rcode)<<" for query to "<<ip.toString()<<" for '"<<domain<<"'"<<endl; t_sstorage.ednsstatus.setMode(ind, ednsstatus, EDNSStatus::NOEDNS); continue; } else if(!res->d_haveEDNS) { if (*mode != EDNSStatus::EDNSIGNORANT) { t_sstorage.ednsstatus.setMode(ind, ednsstatus, EDNSStatus::EDNSIGNORANT); // cerr<<"We find that "<<ip.toString()<<" is an EDNS-ignorer for '"<<domain<<"', moving to mode 2"<<endl; } } else { t_sstorage.ednsstatus.setMode(ind, ednsstatus, EDNSStatus::EDNSOK); // cerr<<"We find that "<<ip.toString()<<" is EDNS OK!"<<endl; } } if (oldmode != *mode || !ednsstatus->modeSetAt) { t_sstorage.ednsstatus.setTS(ind, ednsstatus, d_now.tv_sec); } // cerr<<"Result: ret="<<ret<<", EDNS-level: "<<EDNSLevel<<", haveEDNS: "<<res->d_haveEDNS<<", new mode: "<<mode<<endl; return LWResult::Result::Success; } return ret; } #define QLOG(x) LOG(prefix << " child=" << child << ": " << x << endl) int SyncRes::doResolve(const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state) { string prefix = d_prefix; prefix.append(depth, ' '); auto luaconfsLocal = g_luaconfs.getLocal(); /* Apply qname (including CNAME chain) filtering policies */ if (d_wantsRPZ && !d_appliedPolicy.wasHit()) { if (luaconfsLocal->dfe.getQueryPolicy(qname, d_discardedPolicies, d_appliedPolicy)) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); bool done = false; int rcode = RCode::NoError; handlePolicyHit(prefix, qname, qtype, ret, done, rcode, depth); if (done) { return rcode; } } } initZoneCutsFromTA(qname); // In the auth or recursive forward case, it does not make sense to do qname-minimization if (!getQNameMinimization() || isRecursiveForwardOrAuth(qname)) { return doResolveNoQNameMinimization(qname, qtype, ret, depth, beenthere, state); } // The qname minimization algorithm is a simplified version of the one in RFC 7816 (bis). // It could be simplified because the cache maintenance (both positive and negative) // is already done by doResolveNoQNameMinimization(). // // Sketch of algorithm: // Check cache // If result found: done // Otherwise determine closes ancestor from cache data // Repeat querying A, adding more labels of the original qname // If we get a delegation continue at ancestor determination // Until we have the full name. // // The algorithm starts with adding a single label per iteration, and // moves to three labels per iteration after three iterations. DNSName child; prefix.append(string("QM ") + qname.toString() + "|" + qtype.toString()); QLOG("doResolve"); // Look in cache only vector<DNSRecord> retq; bool old = setCacheOnly(true); bool fromCache = false; // For cache peeking, we tell doResolveNoQNameMinimization not to consider the (non-recursive) forward case. // Otherwise all queries in a forward domain will be forwarded, while we want to consult the cache. // The out-of-band cases for doResolveNoQNameMinimization() should be reconsidered and redone some day. int res = doResolveNoQNameMinimization(qname, qtype, retq, depth, beenthere, state, &fromCache, nullptr, false); setCacheOnly(old); if (fromCache) { QLOG("Step0 Found in cache"); if (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None && (d_appliedPolicy.d_kind == DNSFilterEngine::PolicyKind::NXDOMAIN || d_appliedPolicy.d_kind == DNSFilterEngine::PolicyKind::NODATA)) { ret.clear(); } ret.insert(ret.end(), retq.begin(), retq.end()); return res; } QLOG("Step0 Not cached"); const unsigned int qnamelen = qname.countLabels(); DNSName fwdomain(qname); const bool forwarded = getBestAuthZone(&fwdomain) != t_sstorage.domainmap->end(); if (forwarded) { QLOG("Step0 qname is in a forwarded domain " << fwdomain); } for (unsigned int i = 0; i <= qnamelen; ) { // Step 1 vector<DNSRecord> bestns; DNSName nsdomain(qname); if (qtype == QType::DS) { nsdomain.chopOff(); } // the two retries allow getBestNSFromCache&co to reprime the root // hints, in case they ever go missing for (int tries = 0; tries < 2 && bestns.empty(); ++tries) { bool flawedNSSet = false; set<GetBestNSAnswer> beenthereIgnored; getBestNSFromCache(nsdomain, qtype, bestns, &flawedNSSet, depth, beenthereIgnored, boost::make_optional(forwarded, fwdomain)); if (forwarded) { break; } } if (bestns.size() == 0) { if (!forwarded) { // Something terrible is wrong QLOG("Step1 No ancestor found return ServFail"); return RCode::ServFail; } child = fwdomain; } else { QLOG("Step1 Ancestor from cache is " << bestns[0].d_name); if (forwarded) { child = bestns[0].d_name.isPartOf(fwdomain) ? bestns[0].d_name : fwdomain; QLOG("Step1 Final Ancestor (using forwarding info) is " << child); } else { child = bestns[0].d_name; } } unsigned int targetlen = std::min(child.countLabels() + (i > 3 ? 3 : 1), qnamelen); for (; i <= qnamelen; i++) { // Step 2 while (child.countLabels() < targetlen) { child.prependRawLabel(qname.getRawLabel(qnamelen - child.countLabels() - 1)); } targetlen += i > 3 ? 3 : 1; targetlen = std::min(targetlen, qnamelen); QLOG("Step2 New child"); // Step 3 resolve if (child == qname) { QLOG("Step3 Going to do final resolve"); res = doResolveNoQNameMinimization(qname, qtype, ret, depth, beenthere, state); QLOG("Step3 Final resolve: " << RCode::to_s(res) << "/" << ret.size()); return res; } // Step 4 QLOG("Step4 Resolve A for child"); bool oldFollowCNAME = d_followCNAME; d_followCNAME = false; retq.resize(0); StopAtDelegation stopAtDelegation = Stop; res = doResolveNoQNameMinimization(child, QType::A, retq, depth, beenthere, state, nullptr, &stopAtDelegation); d_followCNAME = oldFollowCNAME; QLOG("Step4 Resolve A result is " << RCode::to_s(res) << "/" << retq.size() << "/" << stopAtDelegation); if (stopAtDelegation == Stopped) { QLOG("Delegation seen, continue at step 1"); break; } if (res != RCode::NoError) { // Case 5: unexpected answer QLOG("Step5: other rcode, last effort final resolve"); setQNameMinimization(false); // We might have hit a depth level check, but we still want to allow some recursion levels in the fallback // no-qname-minimization case. This has the effect that a qname minimization fallback case might reach 150% of // maxdepth. res = doResolveNoQNameMinimization(qname, qtype, ret, depth/2, beenthere, state); if(res == RCode::NoError) { s_qnameminfallbacksuccess++; } QLOG("Step5 End resolve: " << RCode::to_s(res) << "/" << ret.size()); return res; } } } // Should not be reached QLOG("Max iterations reached, return ServFail"); return RCode::ServFail; } /*! This function will check the cache and go out to the internet if the answer is not in cache * * \param qname The name we need an answer for * \param qtype * \param ret The vector of DNSRecords we need to fill with the answers * \param depth The recursion depth we are in * \param beenthere * \param fromCache tells the caller the result came from the cache, may be nullptr * \param stopAtDelegation if non-nullptr and pointed-to value is Stop requests the callee to stop at a delegation, if so pointed-to value is set to Stopped * \return DNS RCODE or -1 (Error) */ int SyncRes::doResolveNoQNameMinimization(const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>& beenthere, vState& state, bool *fromCache, StopAtDelegation *stopAtDelegation, bool considerforwards) { string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } LOG(prefix<<qname<<": Wants "<< (d_doDNSSEC ? "" : "NO ") << "DNSSEC processing, "<<(d_requireAuthData ? "" : "NO ")<<"auth data in query for "<<qtype<<endl); if (s_maxdepth && depth > s_maxdepth) { string msg = "More than " + std::to_string(s_maxdepth) + " (max-recursion-depth) levels of recursion needed while resolving " + qname.toLogString(); LOG(prefix << qname << ": " << msg << endl); throw ImmediateServFailException(msg); } int res=0; // This is a difficult way of expressing "this is a normal query", i.e. not getRootNS. if(!(d_updatingRootNS && qtype.getCode()==QType::NS && qname.isRoot())) { if(d_cacheonly) { // very limited OOB support LWResult lwr; LOG(prefix<<qname<<": Recursion not requested for '"<<qname<<"|"<<qtype<<"', peeking at auth/forward zones"<<endl); DNSName authname(qname); domainmap_t::const_iterator iter=getBestAuthZone(&authname); if(iter != t_sstorage.domainmap->end()) { if(iter->second.isAuth()) { ret.clear(); d_wasOutOfBand = doOOBResolve(qname, qtype, ret, depth, res); if (fromCache) *fromCache = d_wasOutOfBand; return res; } else if (considerforwards) { const vector<ComboAddress>& servers = iter->second.d_servers; const ComboAddress remoteIP = servers.front(); LOG(prefix<<qname<<": forwarding query to hardcoded nameserver '"<< remoteIP.toStringWithPort()<<"' for zone '"<<authname<<"'"<<endl); boost::optional<Netmask> nm; bool chained = false; auto resolveRet = asyncresolveWrapper(remoteIP, d_doDNSSEC, qname, authname, qtype.getCode(), false, false, &d_now, nm, &lwr, &chained); d_totUsec += lwr.d_usec; accountAuthLatency(lwr.d_usec, remoteIP.sin4.sin_family); if (fromCache) *fromCache = true; // filter out the good stuff from lwr.result() if (resolveRet == LWResult::Result::Success) { for(const auto& rec : lwr.d_records) { if(rec.d_place == DNSResourceRecord::ANSWER) ret.push_back(rec); } return 0; } else { return RCode::ServFail; } } } } DNSName authname(qname); bool wasForwardedOrAuthZone = false; bool wasAuthZone = false; bool wasForwardRecurse = false; domainmap_t::const_iterator iter = getBestAuthZone(&authname); if(iter != t_sstorage.domainmap->end()) { const auto& domain = iter->second; wasForwardedOrAuthZone = true; if (domain.isAuth()) { wasAuthZone = true; } else if (domain.shouldRecurse()) { wasForwardRecurse = true; } } /* When we are looking for a DS, we want to the non-CNAME cache check first because we can actually have a DS (from the parent zone) AND a CNAME (from the child zone), and what we really want is the DS */ if (qtype != QType::DS && doCNAMECacheCheck(qname, qtype, ret, depth, res, state, wasAuthZone, wasForwardRecurse)) { // will reroute us if needed d_wasOutOfBand = wasAuthZone; // Here we have an issue. If we were prevented from going out to the network (cache-only was set, possibly because we // are in QM Step0) we might have a CNAME but not the corresponding target. // It means that we will sometimes go to the next steps when we are in fact done, but that's fine since // we will get the records from the cache, resulting in a small overhead. // This might be a real problem if we had a RPZ hit, though, because we do not want the processing to continue, since // RPZ rules will not be evaluated anymore (we already matched). const bool stoppedByPolicyHit = d_appliedPolicy.wasHit(); if (fromCache && (!d_cacheonly || stoppedByPolicyHit)) { *fromCache = true; } /* Apply Post filtering policies */ if (d_wantsRPZ && !stoppedByPolicyHit) { auto luaLocal = g_luaconfs.getLocal(); if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); bool done = false; handlePolicyHit(prefix, qname, qtype, ret, done, res, depth); if (done && fromCache) { *fromCache = true; } } } return res; } if (doCacheCheck(qname, authname, wasForwardedOrAuthZone, wasAuthZone, wasForwardRecurse, qtype, ret, depth, res, state)) { // we done d_wasOutOfBand = wasAuthZone; if (fromCache) { *fromCache = true; } if (d_wantsRPZ && !d_appliedPolicy.wasHit()) { auto luaLocal = g_luaconfs.getLocal(); if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); bool done = false; handlePolicyHit(prefix, qname, qtype, ret, done, res, depth); } } return res; } /* if we have not found a cached DS (or denial of), now is the time to look for a CNAME */ if (qtype == QType::DS && doCNAMECacheCheck(qname, qtype, ret, depth, res, state, wasAuthZone, wasForwardRecurse)) { // will reroute us if needed d_wasOutOfBand = wasAuthZone; // Here we have an issue. If we were prevented from going out to the network (cache-only was set, possibly because we // are in QM Step0) we might have a CNAME but not the corresponding target. // It means that we will sometimes go to the next steps when we are in fact done, but that's fine since // we will get the records from the cache, resulting in a small overhead. // This might be a real problem if we had a RPZ hit, though, because we do not want the processing to continue, since // RPZ rules will not be evaluated anymore (we already matched). const bool stoppedByPolicyHit = d_appliedPolicy.wasHit(); if (fromCache && (!d_cacheonly || stoppedByPolicyHit)) { *fromCache = true; } /* Apply Post filtering policies */ if (d_wantsRPZ && !stoppedByPolicyHit) { auto luaLocal = g_luaconfs.getLocal(); if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); bool done = false; handlePolicyHit(prefix, qname, qtype, ret, done, res, depth); if (done && fromCache) { *fromCache = true; } } } return res; } } if (d_cacheonly) { return 0; } LOG(prefix<<qname<<": No cache hit for '"<<qname<<"|"<<qtype<<"', trying to find an appropriate NS record"<<endl); DNSName subdomain(qname); if (qtype == QType::DS) subdomain.chopOff(); NsSet nsset; bool flawedNSSet=false; // the two retries allow getBestNSNamesFromCache&co to reprime the root // hints, in case they ever go missing for(int tries=0;tries<2 && nsset.empty();++tries) { subdomain=getBestNSNamesFromCache(subdomain, qtype, nsset, &flawedNSSet, depth, beenthere); // pass beenthere to both occasions } res = doResolveAt(nsset, subdomain, flawedNSSet, qname, qtype, ret, depth, beenthere, state, stopAtDelegation); /* Apply Post filtering policies */ if (d_wantsRPZ && !d_appliedPolicy.wasHit()) { auto luaLocal = g_luaconfs.getLocal(); if (luaLocal->dfe.getPostPolicy(ret, d_discardedPolicies, d_appliedPolicy)) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); bool done = false; handlePolicyHit(prefix, qname, qtype, ret, done, res, depth); } } if (!res) { return 0; } LOG(prefix<<qname<<": failed (res="<<res<<")"<<endl); return res<0 ? RCode::ServFail : res; } #if 0 // for testing purposes static bool ipv6First(const ComboAddress& a, const ComboAddress& b) { return !(a.sin4.sin_family < a.sin4.sin_family); } #endif struct speedOrderCA { speedOrderCA(std::map<ComboAddress,float>& speeds): d_speeds(speeds) {} bool operator()(const ComboAddress& a, const ComboAddress& b) const { return d_speeds[a] < d_speeds[b]; } std::map<ComboAddress, float>& d_speeds; }; /** This function explicitly goes out for A or AAAA addresses */ vector<ComboAddress> SyncRes::getAddrs(const DNSName &qname, unsigned int depth, set<GetBestNSAnswer>& beenthere, bool cacheOnly, unsigned int& addressQueriesForNS) { typedef vector<DNSRecord> res_t; typedef vector<ComboAddress> ret_t; ret_t ret; bool oldCacheOnly = setCacheOnly(cacheOnly); bool oldRequireAuthData = d_requireAuthData; bool oldValidationRequested = d_DNSSECValidationRequested; bool oldFollowCNAME = d_followCNAME; const unsigned int startqueries = d_outqueries; d_requireAuthData = false; d_DNSSECValidationRequested = false; d_followCNAME = true; try { // First look for both A and AAAA in the cache and be satisfied if we find anything res_t cset; if (s_doIPv4 && g_recCache->get(d_now.tv_sec, qname, QType::A, false, &cset, d_cacheRemote, d_refresh, d_routingTag) > 0) { for (const auto &i : cset) { if (auto rec = getRR<ARecordContent>(i)) { ret.push_back(rec->getCA(53)); } } } if (s_doIPv6 && g_recCache->get(d_now.tv_sec, qname, QType::AAAA, false, &cset, d_cacheRemote, d_refresh, d_routingTag) > 0) { for (const auto &i : cset) { if (auto rec = getRR<AAAARecordContent>(i)) { ret.push_back(rec->getCA(53)); } } } if (ret.empty()) { // Nothing in the cache... vState newState = vState::Indeterminate; cset.clear(); if (s_doIPv4 && doResolve(qname, QType::A, cset, depth+1, beenthere, newState) == 0) { // this consults cache, OR goes out for (auto const &i : cset) { if (i.d_type == QType::A) { if (auto rec = getRR<ARecordContent>(i)) { ret.push_back(rec->getCA(53)); } } } } if (s_doIPv6) { // s_doIPv6 **IMPLIES** pdns::isQueryLocalAddressFamilyEnabled(AF_INET6) returned true if (ret.empty()) { // We only go out to find IPv6 records if we did not find any IPv4 ones. // Once IPv6 adoption matters, this needs to be revisited newState = vState::Indeterminate; cset.clear(); if (doResolve(qname, QType::AAAA, cset, depth+1, beenthere, newState) == 0) { // this consults cache, OR goes out for (const auto &i : cset) { if (i.d_type == QType::AAAA) { if (auto rec = getRR<AAAARecordContent>(i)) ret.push_back(rec->getCA(53)); } } } } else { // We have some IPv4 records, don't bother with going out to get IPv6, but do consult the cache, we might have // encountered some IPv6 glue cset.clear(); if (g_recCache->get(d_now.tv_sec, qname, QType::AAAA, false, &cset, d_cacheRemote, d_refresh, d_routingTag) > 0) { for (const auto &i : cset) { if (auto rec = getRR<AAAARecordContent>(i)) { ret.push_back(rec->getCA(53)); } } } } } } } catch (const PolicyHitException& e) { /* we ignore a policy hit while trying to retrieve the addresses of a NS and keep processing the current query */ } if (ret.empty() && d_outqueries > startqueries) { // We did 1 or more outgoing queries to resolve this NS name but returned empty handed addressQueriesForNS++; } d_requireAuthData = oldRequireAuthData; d_DNSSECValidationRequested = oldValidationRequested; setCacheOnly(oldCacheOnly); d_followCNAME = oldFollowCNAME; /* we need to remove from the nsSpeeds collection the existing IPs for this nameserver that are no longer in the set, even if there is only one or none at all in the current set. */ map<ComboAddress, float> speeds; auto& collection = t_sstorage.nsSpeeds[qname]; float factor = collection.getFactor(d_now); for(const auto& val: ret) { speeds[val] = collection.d_collection[val].get(factor); } t_sstorage.nsSpeeds[qname].purge(speeds); if (ret.size() > 1) { shuffle(ret.begin(), ret.end(), pdns::dns_random_engine()); speedOrderCA so(speeds); stable_sort(ret.begin(), ret.end(), so); } if(doLog()) { string prefix=d_prefix; prefix.append(depth, ' '); LOG(prefix<<"Nameserver "<<qname<<" IPs: "); bool first = true; for(const auto& addr : ret) { if (first) { first = false; } else { LOG(", "); } LOG((addr.toString())<<"(" << (boost::format("%0.2f") % (speeds[addr]/1000.0)).str() <<"ms)"); } LOG(endl); } return ret; } void SyncRes::getBestNSFromCache(const DNSName &qname, const QType qtype, vector<DNSRecord>& bestns, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>& beenthere, const boost::optional<DNSName>& cutOffDomain) { string prefix; DNSName subdomain(qname); if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } bestns.clear(); bool brokeloop; do { if (cutOffDomain && (subdomain == *cutOffDomain || !subdomain.isPartOf(*cutOffDomain))) { break; } brokeloop=false; LOG(prefix<<qname<<": Checking if we have NS in cache for '"<<subdomain<<"'"<<endl); vector<DNSRecord> ns; *flawedNSSet = false; if(g_recCache->get(d_now.tv_sec, subdomain, QType::NS, false, &ns, d_cacheRemote, d_refresh, d_routingTag) > 0) { bestns.reserve(ns.size()); for(auto k=ns.cbegin();k!=ns.cend(); ++k) { if(k->d_ttl > (unsigned int)d_now.tv_sec ) { vector<DNSRecord> aset; QType nsqt{QType::ADDR}; if (s_doIPv4 && !s_doIPv6) { nsqt = QType::A; } else if (!s_doIPv4 && s_doIPv6) { nsqt = QType::AAAA; } const DNSRecord& dr=*k; auto nrr = getRR<NSRecordContent>(dr); if(nrr && (!nrr->getNS().isPartOf(subdomain) || g_recCache->get(d_now.tv_sec, nrr->getNS(), nsqt, false, doLog() ? &aset : 0, d_cacheRemote, d_refresh, d_routingTag) > 5)) { bestns.push_back(dr); LOG(prefix<<qname<<": NS (with ip, or non-glue) in cache for '"<<subdomain<<"' -> '"<<nrr->getNS()<<"'"<<endl); LOG(prefix<<qname<<": within bailiwick: "<< nrr->getNS().isPartOf(subdomain)); if(!aset.empty()) { LOG(", in cache, ttl="<<(unsigned int)(((time_t)aset.begin()->d_ttl- d_now.tv_sec ))<<endl); } else { LOG(", not in cache / did not look at cache"<<endl); } } else { *flawedNSSet=true; LOG(prefix<<qname<<": NS in cache for '"<<subdomain<<"', but needs glue ("<<nrr->getNS()<<") which we miss or is expired"<<endl); } } } if(!bestns.empty()) { GetBestNSAnswer answer; answer.qname=qname; answer.qtype=qtype.getCode(); for(const auto& dr : bestns) { if (auto nsContent = getRR<NSRecordContent>(dr)) { answer.bestns.insert(make_pair(dr.d_name, nsContent->getNS())); } } auto insertionPair = beenthere.insert(std::move(answer)); if(!insertionPair.second) { brokeloop=true; LOG(prefix<<qname<<": We have NS in cache for '"<<subdomain<<"' but part of LOOP (already seen "<<answer.qname<<")! Trying less specific NS"<<endl); ; if(doLog()) for( set<GetBestNSAnswer>::const_iterator j=beenthere.begin();j!=beenthere.end();++j) { bool neo = (j == insertionPair.first); LOG(prefix<<qname<<": beenthere"<<(neo?"*":"")<<": "<<j->qname<<"|"<<DNSRecordContent::NumberToType(j->qtype)<<" ("<<(unsigned int)j->bestns.size()<<")"<<endl); } bestns.clear(); } else { LOG(prefix<<qname<<": We have NS in cache for '"<<subdomain<<"' (flawedNSSet="<<*flawedNSSet<<")"<<endl); return; } } } LOG(prefix<<qname<<": no valid/useful NS in cache for '"<<subdomain<<"'"<<endl); if(subdomain.isRoot() && !brokeloop) { // We lost the root NS records primeHints(); LOG(prefix<<qname<<": reprimed the root"<<endl); /* let's prevent an infinite loop */ if (!d_updatingRootNS) { primeRootNSZones(g_dnssecmode != DNSSECMode::Off, depth); getRootNS(d_now, d_asyncResolve, depth); } } } while(subdomain.chopOff()); } SyncRes::domainmap_t::const_iterator SyncRes::getBestAuthZone(DNSName* qname) const { if (t_sstorage.domainmap->empty()) { return t_sstorage.domainmap->end(); } SyncRes::domainmap_t::const_iterator ret; do { ret=t_sstorage.domainmap->find(*qname); if(ret!=t_sstorage.domainmap->end()) break; }while(qname->chopOff()); return ret; } /** doesn't actually do the work, leaves that to getBestNSFromCache */ DNSName SyncRes::getBestNSNamesFromCache(const DNSName &qname, const QType qtype, NsSet& nsset, bool* flawedNSSet, unsigned int depth, set<GetBestNSAnswer>&beenthere) { string prefix; if (doLog()) { prefix = d_prefix; prefix.append(depth, ' '); } DNSName authOrForwDomain(qname); domainmap_t::const_iterator iter = getBestAuthZone(&authOrForwDomain); // We have an auth, forwarder of forwarder-recurse if (iter != t_sstorage.domainmap->end()) { if (iter->second.isAuth()) { // this gets picked up in doResolveAt, the empty DNSName, combined with the // empty vector means 'we are auth for this zone' nsset.insert({DNSName(), {{}, false}}); return authOrForwDomain; } else { if (iter->second.shouldRecurse()) { // Again, picked up in doResolveAt. An empty DNSName, combined with a // non-empty vector of ComboAddresses means 'this is a forwarded domain' // This is actually picked up in retrieveAddressesForNS called from doResolveAt. nsset.insert({DNSName(), {iter->second.d_servers, true }}); return authOrForwDomain; } } } // We might have a (non-recursive) forwarder, but maybe the cache already contains // a better NS vector<DNSRecord> bestns; DNSName nsFromCacheDomain(g_rootdnsname); getBestNSFromCache(qname, qtype, bestns, flawedNSSet, depth, beenthere); // Pick up the auth domain for (const auto& k : bestns) { const auto nsContent = getRR<NSRecordContent>(k); if (nsContent) { nsFromCacheDomain = k.d_name; break; } } if (iter != t_sstorage.domainmap->end()) { if (doLog()) { LOG(prefix << qname << " authOrForwDomain: " << authOrForwDomain << " nsFromCacheDomain: " << nsFromCacheDomain << " isPartof: " << authOrForwDomain.isPartOf(nsFromCacheDomain) << endl); } // If the forwarder is better or equal to what's found in the cache, use forwarder. Note that name.isPartOf(name). // So queries that get NS for authOrForwDomain itself go to the forwarder if (authOrForwDomain.isPartOf(nsFromCacheDomain)) { if (doLog()) { LOG(prefix << qname << ": using forwarder as NS" << endl); } nsset.insert({DNSName(), {iter->second.d_servers, false }}); return authOrForwDomain; } else { if (doLog()) { LOG(prefix << qname << ": using NS from cache" << endl); } } } for (auto k = bestns.cbegin(); k != bestns.cend(); ++k) { // The actual resolver code will not even look at the ComboAddress or bool const auto nsContent = getRR<NSRecordContent>(*k); if (nsContent) { nsset.insert({nsContent->getNS(), {{}, false}}); } } return nsFromCacheDomain; } void SyncRes::updateValidationStatusInCache(const DNSName &qname, const QType qt, bool aa, vState newState) const { if (qt == QType::ANY || qt == QType::ADDR) { // not doing that return; } if (vStateIsBogus(newState)) { g_recCache->updateValidationStatus(d_now.tv_sec, qname, qt, d_cacheRemote, d_routingTag, aa, newState, s_maxbogusttl + d_now.tv_sec); } else { g_recCache->updateValidationStatus(d_now.tv_sec, qname, qt, d_cacheRemote, d_routingTag, aa, newState, boost::none); } } static bool scanForCNAMELoop(const DNSName& name, const vector<DNSRecord>& records) { for (const auto& record: records) { if (record.d_type == QType::CNAME && record.d_place == DNSResourceRecord::ANSWER) { if (name == record.d_name) { return true; } } } return false; } bool SyncRes::doCNAMECacheCheck(const DNSName &qname, const QType qtype, vector<DNSRecord>& ret, unsigned int depth, int &res, vState& state, bool wasAuthZone, bool wasForwardRecurse) { string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } if((depth>9 && d_outqueries>10 && d_throttledqueries>5) || depth > 15) { LOG(prefix<<qname<<": recursing (CNAME or other indirection) too deep, depth="<<depth<<endl); res=RCode::ServFail; return true; } vector<DNSRecord> cset; vector<std::shared_ptr<RRSIGRecordContent>> signatures; vector<std::shared_ptr<DNSRecord>> authorityRecs; bool wasAuth; uint32_t capTTL = std::numeric_limits<uint32_t>::max(); DNSName foundName; DNSName authZone; QType foundQT = QType::ENT; /* we don't require auth data for forward-recurse lookups */ if (g_recCache->get(d_now.tv_sec, qname, QType::CNAME, !wasForwardRecurse && d_requireAuthData, &cset, d_cacheRemote, d_refresh, d_routingTag, d_doDNSSEC ? &signatures : nullptr, d_doDNSSEC ? &authorityRecs : nullptr, &d_wasVariable, &state, &wasAuth, &authZone) > 0) { foundName = qname; foundQT = QType::CNAME; } if (foundName.empty() && qname != g_rootdnsname) { // look for a DNAME cache hit auto labels = qname.getRawLabels(); DNSName dnameName(g_rootdnsname); do { dnameName.prependRawLabel(labels.back()); labels.pop_back(); if (dnameName == qname && qtype != QType::DNAME) { // The client does not want a DNAME, but we've reached the QNAME already. So there is no match break; } if (g_recCache->get(d_now.tv_sec, dnameName, QType::DNAME, !wasForwardRecurse && d_requireAuthData, &cset, d_cacheRemote, d_refresh, d_routingTag, d_doDNSSEC ? &signatures : nullptr, d_doDNSSEC ? &authorityRecs : nullptr, &d_wasVariable, &state, &wasAuth, &authZone) > 0) { foundName = dnameName; foundQT = QType::DNAME; break; } } while(!labels.empty()); } if (foundName.empty()) { return false; } if (qtype == QType::DS && authZone == qname) { /* CNAME at APEX of the child zone, we can't use that to prove that there is no DS */ LOG(prefix<<qname<<": Found a "<<foundQT.toString()<<" cache hit of '"<< qname <<"' from "<<authZone<<", but such a record at the apex of the child zone does not prove that there is no DS in the parent zone"<<endl); return false; } for(auto const &record : cset) { if (record.d_class != QClass::IN) { continue; } if(record.d_ttl > (unsigned int) d_now.tv_sec) { if (!wasAuthZone && shouldValidate() && (wasAuth || wasForwardRecurse) && state == vState::Indeterminate && d_requireAuthData) { /* This means we couldn't figure out the state when this entry was cached */ vState recordState = getValidationStatus(foundName, !signatures.empty(), qtype == QType::DS, depth); if (recordState == vState::Secure) { LOG(prefix<<qname<<": got vState::Indeterminate state from the "<<foundQT.toString()<<" cache, validating.."<<endl); state = SyncRes::validateRecordsWithSigs(depth, qname, qtype, foundName, foundQT, cset, signatures); if (state != vState::Indeterminate) { LOG(prefix<<qname<<": got vState::Indeterminate state from the "<<foundQT.toString()<<" cache, new validation result is "<<state<<endl); if (vStateIsBogus(state)) { capTTL = s_maxbogusttl; } updateValidationStatusInCache(foundName, foundQT, wasAuth, state); } } } LOG(prefix<<qname<<": Found cache "<<foundQT.toString()<<" hit for '"<< foundName << "|"<<foundQT.toString()<<"' to '"<<record.d_content->getZoneRepresentation()<<"', validation state is "<<state<<endl); DNSRecord dr = record; dr.d_ttl -= d_now.tv_sec; dr.d_ttl = std::min(dr.d_ttl, capTTL); const uint32_t ttl = dr.d_ttl; ret.reserve(ret.size() + 2 + signatures.size() + authorityRecs.size()); ret.push_back(dr); for(const auto& signature : signatures) { DNSRecord sigdr; sigdr.d_type=QType::RRSIG; sigdr.d_name=foundName; sigdr.d_ttl=ttl; sigdr.d_content=signature; sigdr.d_place=DNSResourceRecord::ANSWER; sigdr.d_class=QClass::IN; ret.push_back(sigdr); } for(const auto& rec : authorityRecs) { DNSRecord authDR(*rec); authDR.d_ttl=ttl; ret.push_back(authDR); } DNSName newTarget; if (foundQT == QType::DNAME) { if (qtype == QType::DNAME && qname == foundName) { // client wanted the DNAME, no need to synthesize a CNAME res = RCode::NoError; return true; } // Synthesize a CNAME auto dnameRR = getRR<DNAMERecordContent>(record); if (dnameRR == nullptr) { throw ImmediateServFailException("Unable to get record content for "+foundName.toLogString()+"|DNAME cache entry"); } const auto& dnameSuffix = dnameRR->getTarget(); DNSName targetPrefix = qname.makeRelative(foundName); try { dr.d_type = QType::CNAME; dr.d_name = targetPrefix + foundName; newTarget = targetPrefix + dnameSuffix; dr.d_content = std::make_shared<CNAMERecordContent>(CNAMERecordContent(newTarget)); ret.push_back(dr); } catch (const std::exception &e) { // We should probably catch an std::range_error here and set the rcode to YXDOMAIN (RFC 6672, section 2.2) // But this is consistent with processRecords throw ImmediateServFailException("Unable to perform DNAME substitution(DNAME owner: '" + foundName.toLogString() + "', DNAME target: '" + dnameSuffix.toLogString() + "', substituted name: '" + targetPrefix.toLogString() + "." + dnameSuffix.toLogString() + "' : " + e.what()); } LOG(prefix<<qname<<": Synthesized "<<dr.d_name<<"|CNAME "<<newTarget<<endl); } if(qtype == QType::CNAME) { // perhaps they really wanted a CNAME! res = RCode::NoError; return true; } if (qtype == QType::DS || qtype == QType::DNSKEY) { res = RCode::NoError; return true; } // We have a DNAME _or_ CNAME cache hit and the client wants something else than those two. // Let's find the answer! if (foundQT == QType::CNAME) { const auto cnameContent = getRR<CNAMERecordContent>(record); if (cnameContent == nullptr) { throw ImmediateServFailException("Unable to get record content for "+foundName.toLogString()+"|CNAME cache entry"); } newTarget = cnameContent->getTarget(); } if (qname == newTarget) { string msg = "got a CNAME referral (from cache) to self"; LOG(prefix<<qname<<": "<<msg<<endl); throw ImmediateServFailException(msg); } if (newTarget.isPartOf(qname)) { // a.b.c. CNAME x.a.b.c will go to great depths with QM on string msg = "got a CNAME referral (from cache) to child, disabling QM"; LOG(prefix<<qname<<": "<<msg<<endl); setQNameMinimization(false); } if (!d_followCNAME) { res = RCode::NoError; return true; } // Check to see if we already have seen the new target as a previous target if (scanForCNAMELoop(newTarget, ret)) { string msg = "got a CNAME referral (from cache) that causes a loop"; LOG(prefix<<qname<<": status="<<msg<<endl); throw ImmediateServFailException(msg); } set<GetBestNSAnswer>beenthere; vState cnameState = vState::Indeterminate; // Be aware that going out on the network might be disabled (cache-only), for example because we are in QM Step0, // so you can't trust that a real lookup will have been made. res = doResolve(newTarget, qtype, ret, depth+1, beenthere, cnameState); LOG(prefix<<qname<<": updating validation state for response to "<<qname<<" from "<<state<<" with the state from the DNAME/CNAME quest: "<<cnameState<<endl); updateValidationState(state, cnameState); return true; } } throw ImmediateServFailException("Could not determine whether or not there was a CNAME or DNAME in cache for '" + qname.toLogString() + "'"); } namespace { struct CacheEntry { vector<DNSRecord> records; vector<shared_ptr<RRSIGRecordContent>> signatures; uint32_t signaturesTTL{std::numeric_limits<uint32_t>::max()}; }; struct CacheKey { DNSName name; QType type; DNSResourceRecord::Place place; bool operator<(const CacheKey& rhs) const { return tie(type, place, name) < tie(rhs.type, rhs.place, rhs.name); } }; typedef map<CacheKey, CacheEntry> tcache_t; } static void reapRecordsFromNegCacheEntryForValidation(tcache_t& tcache, const vector<DNSRecord>& records) { for (const auto& rec : records) { if (rec.d_type == QType::RRSIG) { auto rrsig = getRR<RRSIGRecordContent>(rec); if (rrsig) { tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signatures.push_back(rrsig); } } else { tcache[{rec.d_name,rec.d_type,rec.d_place}].records.push_back(rec); } } } static bool negativeCacheEntryHasSOA(const NegCache::NegCacheEntry& ne) { return !ne.authoritySOA.records.empty(); } static void reapRecordsForValidation(std::map<QType, CacheEntry>& entries, const vector<DNSRecord>& records) { for (const auto& rec : records) { entries[rec.d_type].records.push_back(rec); } } static void reapSignaturesForValidation(std::map<QType, CacheEntry>& entries, const vector<std::shared_ptr<RRSIGRecordContent>>& signatures) { for (const auto& sig : signatures) { entries[sig->d_type].signatures.push_back(sig); } } /*! * Convenience function to push the records from records into ret with a new TTL * * \param records DNSRecords that need to go into ret * \param ttl The new TTL for these records * \param ret The vector of DNSRecords that should contain the records with the modified TTL */ static void addTTLModifiedRecords(vector<DNSRecord>& records, const uint32_t ttl, vector<DNSRecord>& ret) { for (auto& rec : records) { rec.d_ttl = ttl; ret.push_back(std::move(rec)); } } void SyncRes::computeNegCacheValidationStatus(const NegCache::NegCacheEntry& ne, const DNSName& qname, const QType qtype, const int res, vState& state, unsigned int depth) { tcache_t tcache; reapRecordsFromNegCacheEntryForValidation(tcache, ne.authoritySOA.records); reapRecordsFromNegCacheEntryForValidation(tcache, ne.authoritySOA.signatures); reapRecordsFromNegCacheEntryForValidation(tcache, ne.DNSSECRecords.records); reapRecordsFromNegCacheEntryForValidation(tcache, ne.DNSSECRecords.signatures); for (const auto& entry : tcache) { // this happens when we did store signatures, but passed on the records themselves if (entry.second.records.empty()) { continue; } const DNSName& owner = entry.first.name; vState recordState = getValidationStatus(owner, !entry.second.signatures.empty(), qtype == QType::DS, depth); if (state == vState::Indeterminate) { state = recordState; } if (recordState == vState::Secure) { recordState = SyncRes::validateRecordsWithSigs(depth, qname, qtype, owner, QType(entry.first.type), entry.second.records, entry.second.signatures); } if (recordState != vState::Indeterminate && recordState != state) { updateValidationState(state, recordState); if (state != vState::Secure) { break; } } } if (state == vState::Secure) { vState neValidationState = ne.d_validationState; dState expectedState = res == RCode::NXDomain ? dState::NXDOMAIN : dState::NXQTYPE; dState denialState = getDenialValidationState(ne, expectedState, false); updateDenialValidationState(neValidationState, ne.d_name, state, denialState, expectedState, qtype == QType::DS, depth); } if (state != vState::Indeterminate) { /* validation succeeded, let's update the cache entry so we don't have to validate again */ boost::optional<time_t> capTTD = boost::none; if (vStateIsBogus(state)) { capTTD = d_now.tv_sec + s_maxbogusttl; } g_negCache->updateValidationStatus(ne.d_name, ne.d_qtype, state, capTTD); } } bool SyncRes::doCacheCheck(const DNSName &qname, const DNSName& authname, bool wasForwardedOrAuthZone, bool wasAuthZone, bool wasForwardRecurse, QType qtype, vector<DNSRecord>&ret, unsigned int depth, int &res, vState& state) { bool giveNegative=false; string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } // sqname and sqtype are used contain 'higher' names if we have them (e.g. powerdns.com|SOA when we find a negative entry for doesnotexist.powerdns.com|A) DNSName sqname(qname); QType sqt(qtype); uint32_t sttl=0; // cout<<"Lookup for '"<<qname<<"|"<<qtype.toString()<<"' -> "<<getLastLabel(qname)<<endl; vState cachedState; NegCache::NegCacheEntry ne; if(s_rootNXTrust && g_negCache->getRootNXTrust(qname, d_now, ne) && ne.d_auth.isRoot() && !(wasForwardedOrAuthZone && !authname.isRoot())) { // when forwarding, the root may only neg-cache if it was forwarded to. sttl = ne.d_ttd - d_now.tv_sec; LOG(prefix<<qname<<": Entire name '"<<qname<<"', is negatively cached via '"<<ne.d_auth<<"' & '"<<ne.d_name<<"' for another "<<sttl<<" seconds"<<endl); res = RCode::NXDomain; giveNegative = true; cachedState = ne.d_validationState; } else if (g_negCache->get(qname, qtype, d_now, ne)) { /* If we are looking for a DS, discard NXD if auth == qname and ask for a specific denial instead */ if (qtype != QType::DS || ne.d_qtype.getCode() || ne.d_auth != qname || g_negCache->get(qname, qtype, d_now, ne, true)) { /* Careful! If the client is asking for a DS that does not exist, we need to provide the SOA along with the NSEC(3) proof and we might not have it if we picked up the proof from a delegation, in which case we need to keep on to do the actual DS query. */ if (qtype == QType::DS && ne.d_qtype.getCode() && !d_externalDSQuery.empty() && qname == d_externalDSQuery && !negativeCacheEntryHasSOA(ne)) { giveNegative = false; } else { res = RCode::NXDomain; sttl = ne.d_ttd - d_now.tv_sec; giveNegative = true; cachedState = ne.d_validationState; if (ne.d_qtype.getCode()) { LOG(prefix<<qname<<": "<<qtype<<" is negatively cached via '"<<ne.d_auth<<"' for another "<<sttl<<" seconds"<<endl); res = RCode::NoError; } else { LOG(prefix<<qname<<": Entire name '"<<qname<<"' is negatively cached via '"<<ne.d_auth<<"' for another "<<sttl<<" seconds"<<endl); } } } } else if (s_hardenNXD != HardenNXD::No && !qname.isRoot() && !wasForwardedOrAuthZone) { auto labels = qname.getRawLabels(); DNSName negCacheName(g_rootdnsname); negCacheName.prependRawLabel(labels.back()); labels.pop_back(); while(!labels.empty()) { if (g_negCache->get(negCacheName, QType::ENT, d_now, ne, true)) { if (ne.d_validationState == vState::Indeterminate && validationEnabled()) { // LOG(prefix << negCacheName << " negatively cached and vState::Indeterminate, trying to validate NXDOMAIN" << endl); // ... // And get the updated ne struct //t_sstorage.negcache.get(negCacheName, QType(0), d_now, ne, true); } if ((s_hardenNXD == HardenNXD::Yes && !vStateIsBogus(ne.d_validationState)) || ne.d_validationState == vState::Secure) { res = RCode::NXDomain; sttl = ne.d_ttd - d_now.tv_sec; giveNegative = true; cachedState = ne.d_validationState; LOG(prefix<<qname<<": Name '"<<negCacheName<<"' and below, is negatively cached via '"<<ne.d_auth<<"' for another "<<sttl<<" seconds"<<endl); break; } } negCacheName.prependRawLabel(labels.back()); labels.pop_back(); } } if (giveNegative) { state = cachedState; if (!wasAuthZone && shouldValidate() && state == vState::Indeterminate) { LOG(prefix<<qname<<": got vState::Indeterminate state for records retrieved from the negative cache, validating.."<<endl); computeNegCacheValidationStatus(ne, qname, qtype, res, state, depth); if (state != cachedState && vStateIsBogus(state)) { sttl = std::min(sttl, s_maxbogusttl); } } // Transplant SOA to the returned packet addTTLModifiedRecords(ne.authoritySOA.records, sttl, ret); if(d_doDNSSEC) { addTTLModifiedRecords(ne.authoritySOA.signatures, sttl, ret); addTTLModifiedRecords(ne.DNSSECRecords.records, sttl, ret); addTTLModifiedRecords(ne.DNSSECRecords.signatures, sttl, ret); } LOG(prefix<<qname<<": updating validation state with negative cache content for "<<qname<<" to "<<state<<endl); return true; } vector<DNSRecord> cset; bool found=false, expired=false; vector<std::shared_ptr<RRSIGRecordContent>> signatures; vector<std::shared_ptr<DNSRecord>> authorityRecs; uint32_t ttl=0; uint32_t capTTL = std::numeric_limits<uint32_t>::max(); bool wasCachedAuth; if(g_recCache->get(d_now.tv_sec, sqname, sqt, !wasForwardRecurse && d_requireAuthData, &cset, d_cacheRemote, d_refresh, d_routingTag, d_doDNSSEC ? &signatures : nullptr, d_doDNSSEC ? &authorityRecs : nullptr, &d_wasVariable, &cachedState, &wasCachedAuth) > 0) { LOG(prefix<<sqname<<": Found cache hit for "<<sqt.toString()<<": "); if (!wasAuthZone && shouldValidate() && (wasCachedAuth || wasForwardRecurse) && cachedState == vState::Indeterminate && d_requireAuthData) { /* This means we couldn't figure out the state when this entry was cached */ vState recordState = getValidationStatus(qname, !signatures.empty(), qtype == QType::DS, depth); if (recordState == vState::Secure) { LOG(prefix<<sqname<<": got vState::Indeterminate state from the cache, validating.."<<endl); if (sqt == QType::DNSKEY && sqname == getSigner(signatures)) { cachedState = validateDNSKeys(sqname, cset, signatures, depth); } else { if (sqt == QType::ANY) { std::map<QType, CacheEntry> types; reapRecordsForValidation(types, cset); reapSignaturesForValidation(types, signatures); for (const auto& type : types) { vState cachedRecordState; if (type.first == QType::DNSKEY && sqname == getSigner(type.second.signatures)) { cachedRecordState = validateDNSKeys(sqname, type.second.records, type.second.signatures, depth); } else { cachedRecordState = SyncRes::validateRecordsWithSigs(depth, qname, qtype, sqname, type.first, type.second.records, type.second.signatures); } updateDNSSECValidationState(cachedState, cachedRecordState); } } else { cachedState = SyncRes::validateRecordsWithSigs(depth, qname, qtype, sqname, sqt, cset, signatures); } } } else { cachedState = recordState; } if (cachedState != vState::Indeterminate) { LOG(prefix<<qname<<": got vState::Indeterminate state from the cache, validation result is "<<cachedState<<endl); if (vStateIsBogus(cachedState)) { capTTL = s_maxbogusttl; } if (sqt != QType::ANY && sqt != QType::ADDR) { updateValidationStatusInCache(sqname, sqt, wasCachedAuth, cachedState); } } } for(auto j=cset.cbegin() ; j != cset.cend() ; ++j) { LOG(j->d_content->getZoneRepresentation()); if (j->d_class != QClass::IN) { continue; } if(j->d_ttl>(unsigned int) d_now.tv_sec) { DNSRecord dr=*j; dr.d_ttl -= d_now.tv_sec; dr.d_ttl = std::min(dr.d_ttl, capTTL); ttl = dr.d_ttl; ret.push_back(dr); LOG("[ttl="<<dr.d_ttl<<"] "); found=true; } else { LOG("[expired] "); expired=true; } } ret.reserve(ret.size() + signatures.size() + authorityRecs.size()); for(const auto& signature : signatures) { DNSRecord dr; dr.d_type=QType::RRSIG; dr.d_name=sqname; dr.d_ttl=ttl; dr.d_content=signature; dr.d_place = DNSResourceRecord::ANSWER; dr.d_class=QClass::IN; ret.push_back(dr); } for(const auto& rec : authorityRecs) { DNSRecord dr(*rec); dr.d_ttl=ttl; ret.push_back(dr); } LOG(endl); if(found && !expired) { if (!giveNegative) res=0; LOG(prefix<<qname<<": updating validation state with cache content for "<<qname<<" to "<<cachedState<<endl); state = cachedState; return true; } else LOG(prefix<<qname<<": cache had only stale entries"<<endl); } /* let's check if we have a NSEC covering that record */ if (g_aggressiveNSECCache && !wasForwardedOrAuthZone) { if (g_aggressiveNSECCache->getDenial(d_now.tv_sec, qname, qtype, ret, res, d_cacheRemote, d_routingTag, d_doDNSSEC)) { state = vState::Secure; return true; } } return false; } bool SyncRes::moreSpecificThan(const DNSName& a, const DNSName &b) const { return (a.isPartOf(b) && a.countLabels() > b.countLabels()); } struct speedOrder { bool operator()(const std::pair<DNSName, float> &a, const std::pair<DNSName, float> &b) const { return a.second < b.second; } }; inline std::vector<std::pair<DNSName, float>> SyncRes::shuffleInSpeedOrder(NsSet &tnameservers, const string &prefix) { std::vector<std::pair<DNSName, float>> rnameservers; rnameservers.reserve(tnameservers.size()); for(const auto& tns: tnameservers) { float speed = t_sstorage.nsSpeeds[tns.first].get(d_now); rnameservers.push_back({tns.first, speed}); if(tns.first.empty()) // this was an authoritative OOB zone, don't pollute the nsSpeeds with that return rnameservers; } shuffle(rnameservers.begin(),rnameservers.end(), pdns::dns_random_engine()); speedOrder so; stable_sort(rnameservers.begin(),rnameservers.end(), so); if(doLog()) { LOG(prefix<<"Nameservers: "); for(auto i=rnameservers.begin();i!=rnameservers.end();++i) { if(i!=rnameservers.begin()) { LOG(", "); if(!((i-rnameservers.begin())%3)) { LOG(endl<<prefix<<" "); } } LOG(i->first.toLogString()<<"(" << (boost::format("%0.2f") % (i->second/1000.0)).str() <<"ms)"); } LOG(endl); } return rnameservers; } inline vector<ComboAddress> SyncRes::shuffleForwardSpeed(const vector<ComboAddress> &rnameservers, const string &prefix, const bool wasRd) { vector<ComboAddress> nameservers = rnameservers; map<ComboAddress, float> speeds; for(const auto& val: nameservers) { float speed; DNSName nsName = DNSName(val.toStringWithPort()); speed=t_sstorage.nsSpeeds[nsName].get(d_now); speeds[val]=speed; } shuffle(nameservers.begin(),nameservers.end(), pdns::dns_random_engine()); speedOrderCA so(speeds); stable_sort(nameservers.begin(),nameservers.end(), so); if(doLog()) { LOG(prefix<<"Nameservers: "); for(vector<ComboAddress>::const_iterator i=nameservers.cbegin();i!=nameservers.cend();++i) { if(i!=nameservers.cbegin()) { LOG(", "); if(!((i-nameservers.cbegin())%3)) { LOG(endl<<prefix<<" "); } } LOG((wasRd ? string("+") : string("-")) << i->toStringWithPort() <<"(" << (boost::format("%0.2f") % (speeds[*i]/1000.0)).str() <<"ms)"); } LOG(endl); } return nameservers; } static uint32_t getRRSIGTTL(const time_t now, const std::shared_ptr<RRSIGRecordContent>& rrsig) { uint32_t res = 0; if (now < rrsig->d_sigexpire) { res = static_cast<uint32_t>(rrsig->d_sigexpire) - now; } return res; } static const set<QType> nsecTypes = {QType::NSEC, QType::NSEC3}; /* Fills the authoritySOA and DNSSECRecords fields from ne with those found in the records * * \param records The records to parse for the authority SOA and NSEC(3) records * \param ne The NegCacheEntry to be filled out (will not be cleared, only appended to */ static void harvestNXRecords(const vector<DNSRecord>& records, NegCache::NegCacheEntry& ne, const time_t now, uint32_t* lowestTTL) { for (const auto& rec : records) { if (rec.d_place != DNSResourceRecord::AUTHORITY) { // RFC 4035 section 3.1.3. indicates that NSEC records MUST be placed in // the AUTHORITY section. Section 3.1.1 indicates that that RRSIGs for // records MUST be in the same section as the records they cover. // Hence, we ignore all records outside of the AUTHORITY section. continue; } if (rec.d_type == QType::RRSIG) { auto rrsig = getRR<RRSIGRecordContent>(rec); if (rrsig) { if (rrsig->d_type == QType::SOA) { ne.authoritySOA.signatures.push_back(rec); if (lowestTTL && isRRSIGNotExpired(now, rrsig)) { *lowestTTL = min(*lowestTTL, rec.d_ttl); *lowestTTL = min(*lowestTTL, getRRSIGTTL(now, rrsig)); } } if (nsecTypes.count(rrsig->d_type)) { ne.DNSSECRecords.signatures.push_back(rec); if (lowestTTL && isRRSIGNotExpired(now, rrsig)) { *lowestTTL = min(*lowestTTL, rec.d_ttl); *lowestTTL = min(*lowestTTL, getRRSIGTTL(now, rrsig)); } } } continue; } if (rec.d_type == QType::SOA) { ne.authoritySOA.records.push_back(rec); if (lowestTTL) { *lowestTTL = min(*lowestTTL, rec.d_ttl); } continue; } if (nsecTypes.count(rec.d_type)) { ne.DNSSECRecords.records.push_back(rec); if (lowestTTL) { *lowestTTL = min(*lowestTTL, rec.d_ttl); } continue; } } } static cspmap_t harvestCSPFromNE(const NegCache::NegCacheEntry& ne) { cspmap_t cspmap; for(const auto& rec : ne.DNSSECRecords.signatures) { if(rec.d_type == QType::RRSIG) { auto rrc = getRR<RRSIGRecordContent>(rec); if (rrc) { cspmap[{rec.d_name,rrc->d_type}].signatures.push_back(rrc); } } } for(const auto& rec : ne.DNSSECRecords.records) { cspmap[{rec.d_name, rec.d_type}].records.insert(rec.d_content); } return cspmap; } // TODO remove after processRecords is fixed! // Adds the RRSIG for the SOA and the NSEC(3) + RRSIGs to ret static void addNXNSECS(vector<DNSRecord>&ret, const vector<DNSRecord>& records) { NegCache::NegCacheEntry ne; harvestNXRecords(records, ne, 0, nullptr); ret.insert(ret.end(), ne.authoritySOA.signatures.begin(), ne.authoritySOA.signatures.end()); ret.insert(ret.end(), ne.DNSSECRecords.records.begin(), ne.DNSSECRecords.records.end()); ret.insert(ret.end(), ne.DNSSECRecords.signatures.begin(), ne.DNSSECRecords.signatures.end()); } static bool rpzHitShouldReplaceContent(const DNSName& qname, const QType qtype, const std::vector<DNSRecord>& records) { if (qtype == QType::CNAME) { return true; } for (const auto& record : records) { if (record.d_type == QType::CNAME) { if (auto content = getRR<CNAMERecordContent>(record)) { if (qname == content->getTarget()) { /* we have a CNAME whose target matches the entry we are about to generate, so it will complete the current records, not replace them */ return false; } } } } return true; } static void removeConflictingRecord(std::vector<DNSRecord>& records, const DNSName& name, const QType dtype) { for (auto it = records.begin(); it != records.end(); ) { bool remove = false; if (it->d_class == QClass::IN && (it->d_type == QType::CNAME || dtype == QType::CNAME || it->d_type == dtype) && it->d_name == name) { remove = true; } else if (it->d_class == QClass::IN && it->d_type == QType::RRSIG && it->d_name == name) { if (auto rrc = getRR<RRSIGRecordContent>(*it)) { if (rrc->d_type == QType::CNAME || rrc->d_type == dtype) { /* also remove any RRSIG that could conflict */ remove = true; } } } if (remove) { it = records.erase(it); } else { ++it; } } } void SyncRes::handlePolicyHit(const std::string& prefix, const DNSName& qname, const QType qtype, std::vector<DNSRecord>& ret, bool& done, int& rcode, unsigned int depth) { if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) { /* reset to no match */ d_appliedPolicy = DNSFilterEngine::Policy(); return; } /* don't account truncate actions for TCP queries, since they are not applied */ if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::Truncate || !d_queryReceivedOverTCP) { ++g_stats.policyResults[d_appliedPolicy.d_kind]; ++(g_stats.policyHits.lock()->operator[](d_appliedPolicy.getName())); } if (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) { LOG(prefix << qname << "|" << qtype << d_appliedPolicy.getLogString() << endl); } switch (d_appliedPolicy.d_kind) { case DNSFilterEngine::PolicyKind::NoAction: return; case DNSFilterEngine::PolicyKind::Drop: ++g_stats.policyDrops; throw ImmediateQueryDropException(); case DNSFilterEngine::PolicyKind::NXDOMAIN: ret.clear(); rcode = RCode::NXDomain; done = true; return; case DNSFilterEngine::PolicyKind::NODATA: ret.clear(); rcode = RCode::NoError; done = true; return; case DNSFilterEngine::PolicyKind::Truncate: if (!d_queryReceivedOverTCP) { ret.clear(); rcode = RCode::NoError; throw SendTruncatedAnswerException(); } return; case DNSFilterEngine::PolicyKind::Custom: { if (rpzHitShouldReplaceContent(qname, qtype, ret)) { ret.clear(); } rcode = RCode::NoError; done = true; auto spoofed = d_appliedPolicy.getCustomRecords(qname, qtype.getCode()); for (auto& dr : spoofed) { removeConflictingRecord(ret, dr.d_name, dr.d_type); } for (auto& dr : spoofed) { ret.push_back(dr); if (dr.d_name == qname && dr.d_type == QType::CNAME && qtype != QType::CNAME) { if (auto content = getRR<CNAMERecordContent>(dr)) { vState newTargetState = vState::Indeterminate; handleNewTarget(prefix, qname, content->getTarget(), qtype.getCode(), ret, rcode, depth, {}, newTargetState); } } } } } } bool SyncRes::nameserversBlockedByRPZ(const DNSFilterEngine& dfe, const NsSet& nameservers) { /* we skip RPZ processing if: - it was disabled (d_wantsRPZ is false) ; - we already got a RPZ hit (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) since the only way we can get back here is that it was a 'pass-thru' (NoAction) meaning that we should not process any further RPZ rules. Except that we need to process rules of higher priority.. */ if (d_wantsRPZ && !d_appliedPolicy.wasHit()) { for (auto const &ns : nameservers) { bool match = dfe.getProcessingPolicy(ns.first, d_discardedPolicies, d_appliedPolicy); if (match) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { // client query needs an RPZ response LOG(", however nameserver "<<ns.first<<" was blocked by RPZ policy '"<<d_appliedPolicy.getName()<<"'"<<endl); return true; } } // Traverse all IP addresses for this NS to see if they have an RPN NSIP policy for (auto const &address : ns.second.first) { match = dfe.getProcessingPolicy(address, d_discardedPolicies, d_appliedPolicy); if (match) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { // client query needs an RPZ response LOG(", however nameserver "<<ns.first<<" IP address "<<address.toString()<<" was blocked by RPZ policy '"<<d_appliedPolicy.getName()<<"'"<<endl); return true; } } } } } return false; } bool SyncRes::nameserverIPBlockedByRPZ(const DNSFilterEngine& dfe, const ComboAddress& remoteIP) { /* we skip RPZ processing if: - it was disabled (d_wantsRPZ is false) ; - we already got a RPZ hit (d_appliedPolicy.d_type != DNSFilterEngine::PolicyType::None) since the only way we can get back here is that it was a 'pass-thru' (NoAction) meaning that we should not process any further RPZ rules. Except that we need to process rules of higher priority.. */ if (d_wantsRPZ && !d_appliedPolicy.wasHit()) { bool match = dfe.getProcessingPolicy(remoteIP, d_discardedPolicies, d_appliedPolicy); if (match) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { LOG(" (blocked by RPZ policy '" + d_appliedPolicy.getName() + "')"); return true; } } } return false; } vector<ComboAddress> SyncRes::retrieveAddressesForNS(const std::string& prefix, const DNSName& qname, std::vector<std::pair<DNSName, float>>::const_iterator& tns, const unsigned int depth, set<GetBestNSAnswer>& beenthere, const vector<std::pair<DNSName, float>>& rnameservers, NsSet& nameservers, bool& sendRDQuery, bool& pierceDontQuery, bool& flawedNSSet, bool cacheOnly, unsigned int &nretrieveAddressesForNS) { vector<ComboAddress> result; size_t nonresolvingfails = 0; if (!tns->first.empty()) { if (s_nonresolvingnsmaxfails > 0) { nonresolvingfails = t_sstorage.nonresolving.value(tns->first); if (nonresolvingfails >= s_nonresolvingnsmaxfails) { LOG(prefix<<qname<<": NS "<<tns->first<< " in non-resolving map, skipping"<<endl); return result; } } LOG(prefix<<qname<<": Trying to resolve NS '"<<tns->first<< "' ("<<1+tns-rnameservers.begin()<<"/"<<(unsigned int)rnameservers.size()<<")"<<endl); const unsigned int oldOutQueries = d_outqueries; try { result = getAddrs(tns->first, depth, beenthere, cacheOnly, nretrieveAddressesForNS); } // Other exceptions should likely not throttle... catch (const ImmediateServFailException& ex) { if (s_nonresolvingnsmaxfails > 0 && d_outqueries > oldOutQueries) { auto dontThrottleNames = g_dontThrottleNames.getLocal(); if (!dontThrottleNames->check(tns->first)) { t_sstorage.nonresolving.incr(tns->first, d_now); } } throw ex; } if (s_nonresolvingnsmaxfails > 0 && d_outqueries > oldOutQueries) { if (result.empty()) { auto dontThrottleNames = g_dontThrottleNames.getLocal(); if (!dontThrottleNames->check(tns->first)) { t_sstorage.nonresolving.incr(tns->first, d_now); } } else if (nonresolvingfails > 0) { // Succeeding resolve, clear memory of recent failures t_sstorage.nonresolving.clear(tns->first); } } pierceDontQuery=false; } else { LOG(prefix<<qname<<": Domain has hardcoded nameserver"); if(nameservers[tns->first].first.size() > 1) { LOG("s"); } LOG(endl); sendRDQuery = nameservers[tns->first].second; result = shuffleForwardSpeed(nameservers[tns->first].first, doLog() ? (prefix+qname.toString()+": ") : string(), sendRDQuery); pierceDontQuery=true; } return result; } bool SyncRes::throttledOrBlocked(const std::string& prefix, const ComboAddress& remoteIP, const DNSName& qname, const QType qtype, bool pierceDontQuery) { if(t_sstorage.throttle.shouldThrottle(d_now.tv_sec, boost::make_tuple(remoteIP, "", 0))) { LOG(prefix<<qname<<": server throttled "<<endl); s_throttledqueries++; d_throttledqueries++; return true; } else if(t_sstorage.throttle.shouldThrottle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()))) { LOG(prefix<<qname<<": query throttled "<<remoteIP.toString()<<", "<<qname<<"; "<<qtype<<endl); s_throttledqueries++; d_throttledqueries++; return true; } else if(!pierceDontQuery && s_dontQuery && s_dontQuery->match(&remoteIP)) { // We could have retrieved an NS from the cache in a forwarding domain // Even in the case of !pierceDontQuery we still want to allow that NS DNSName forwardCandidate(qname); auto it = getBestAuthZone(&forwardCandidate); if (it == t_sstorage.domainmap->end()) { LOG(prefix<<qname<<": not sending query to " << remoteIP.toString() << ", blocked by 'dont-query' setting" << endl); s_dontqueries++; return true; } else { // The name (from the cache) is forwarded, but is it forwarded to an IP in known forwarders? const auto& ips = it->second.d_servers; if (std::find(ips.cbegin(), ips.cend(), remoteIP) == ips.cend()) { LOG(prefix<<qname<<": not sending query to " << remoteIP.toString() << ", blocked by 'dont-query' setting" << endl); s_dontqueries++; return true; } else { LOG(prefix<<qname<<": sending query to " << remoteIP.toString() << ", blocked by 'dont-query' but a forwarding/auth case" << endl); } } } return false; } bool SyncRes::validationEnabled() const { return g_dnssecmode != DNSSECMode::Off && g_dnssecmode != DNSSECMode::ProcessNoValidate; } uint32_t SyncRes::computeLowestTTD(const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, uint32_t signaturesTTL, const std::vector<std::shared_ptr<DNSRecord>>& authorityRecs) const { uint32_t lowestTTD = std::numeric_limits<uint32_t>::max(); for (const auto& record : records) { lowestTTD = min(lowestTTD, record.d_ttl); } /* even if it was not requested for that request (Process, and neither AD nor DO set), it might be requested at a later time so we need to be careful with the TTL. */ if (validationEnabled() && !signatures.empty()) { /* if we are validating, we don't want to cache records after their signatures expire. */ /* records TTL are now TTD, let's add 'now' to the signatures lowest TTL */ lowestTTD = min(lowestTTD, static_cast<uint32_t>(signaturesTTL + d_now.tv_sec)); for(const auto& sig : signatures) { if (isRRSIGNotExpired(d_now.tv_sec, sig)) { // we don't decrement d_sigexpire by 'now' because we actually want a TTD, not a TTL */ lowestTTD = min(lowestTTD, static_cast<uint32_t>(sig->d_sigexpire)); } } } for (const auto& entry : authorityRecs) { /* be careful, this is still a TTL here */ lowestTTD = min(lowestTTD, static_cast<uint32_t>(entry->d_ttl + d_now.tv_sec)); if (entry->d_type == QType::RRSIG && validationEnabled()) { auto rrsig = getRR<RRSIGRecordContent>(*entry); if (rrsig) { if (isRRSIGNotExpired(d_now.tv_sec, rrsig)) { // we don't decrement d_sigexpire by 'now' because we actually want a TTD, not a TTL */ lowestTTD = min(lowestTTD, static_cast<uint32_t>(rrsig->d_sigexpire)); } } } } return lowestTTD; } void SyncRes::updateValidationState(vState& state, const vState stateUpdate) { LOG(d_prefix<<"validation state was "<<state<<", state update is "<<stateUpdate); updateDNSSECValidationState(state, stateUpdate); LOG(", validation state is now "<<state<<endl); } vState SyncRes::getTA(const DNSName& zone, dsmap_t& ds) { auto luaLocal = g_luaconfs.getLocal(); if (luaLocal->dsAnchors.empty()) { LOG(d_prefix<<": No trust anchors configured, everything is Insecure"<<endl); /* We have no TA, everything is insecure */ return vState::Insecure; } std::string reason; if (haveNegativeTrustAnchor(luaLocal->negAnchors, zone, reason)) { LOG(d_prefix<<": got NTA for '"<<zone<<"'"<<endl); return vState::NTA; } if (getTrustAnchor(luaLocal->dsAnchors, zone, ds)) { LOG(d_prefix<<": got TA for '"<<zone<<"'"<<endl); return vState::TA; } else { LOG(d_prefix<<": no TA found for '"<<zone<<"' among "<< luaLocal->dsAnchors.size()<<endl); } if (zone.isRoot()) { /* No TA for the root */ return vState::Insecure; } return vState::Indeterminate; } static size_t countSupportedDS(const dsmap_t& dsmap) { size_t count = 0; for (const auto& ds : dsmap) { if (isSupportedDS(ds)) { count++; } } return count; } void SyncRes::initZoneCutsFromTA(const DNSName& from) { DNSName zone(from); do { dsmap_t ds; vState result = getTA(zone, ds); if (result != vState::Indeterminate) { if (result == vState::TA) { if (countSupportedDS(ds) == 0) { ds.clear(); result = vState::Insecure; } else { result = vState::Secure; } } else if (result == vState::NTA) { result = vState::Insecure; } d_cutStates[zone] = result; } } while (zone.chopOff()); } vState SyncRes::getDSRecords(const DNSName& zone, dsmap_t& ds, bool taOnly, unsigned int depth, bool bogusOnNXD, bool* foundCut) { vState result = getTA(zone, ds); if (result != vState::Indeterminate || taOnly) { if (foundCut) { *foundCut = (result != vState::Indeterminate); } if (result == vState::TA) { if (countSupportedDS(ds) == 0) { ds.clear(); result = vState::Insecure; } else { result = vState::Secure; } } else if (result == vState::NTA) { result = vState::Insecure; } return result; } std::set<GetBestNSAnswer> beenthere; std::vector<DNSRecord> dsrecords; vState state = vState::Indeterminate; const bool oldCacheOnly = setCacheOnly(false); int rcode = doResolve(zone, QType::DS, dsrecords, depth + 1, beenthere, state); setCacheOnly(oldCacheOnly); if (rcode == RCode::ServFail) { throw ImmediateServFailException("Server Failure while retrieving DS records for " + zone.toLogString()); } if (rcode == RCode::NoError || (rcode == RCode::NXDomain && !bogusOnNXD)) { uint8_t bestDigestType = 0; bool gotCNAME = false; for (const auto& record : dsrecords) { if (record.d_type == QType::DS) { const auto dscontent = getRR<DSRecordContent>(record); if (dscontent && isSupportedDS(*dscontent)) { // Make GOST a lower prio than SHA256 if (dscontent->d_digesttype == DNSSECKeeper::DIGEST_GOST && bestDigestType == DNSSECKeeper::DIGEST_SHA256) { continue; } if (dscontent->d_digesttype > bestDigestType || (bestDigestType == DNSSECKeeper::DIGEST_GOST && dscontent->d_digesttype == DNSSECKeeper::DIGEST_SHA256)) { bestDigestType = dscontent->d_digesttype; } ds.insert(*dscontent); } } else if (record.d_type == QType::CNAME && record.d_name == zone) { gotCNAME = true; } } /* RFC 4509 section 3: "Validator implementations SHOULD ignore DS RRs containing SHA-1 * digests if DS RRs with SHA-256 digests are present in the DS RRset." * As SHA348 is specified as well, the spirit of the this line is "use the best algorithm". */ for (auto dsrec = ds.begin(); dsrec != ds.end(); ) { if (dsrec->d_digesttype != bestDigestType) { dsrec = ds.erase(dsrec); } else { ++dsrec; } } if (rcode == RCode::NoError) { if (ds.empty()) { /* we have no DS, it's either: - a delegation to a non-DNSSEC signed zone - no delegation, we stay in the same zone */ if (gotCNAME || denialProvesNoDelegation(zone, dsrecords)) { /* we are still inside the same zone */ if (foundCut) { *foundCut = false; } return state; } d_cutStates[zone] = state == vState::Secure ? vState::Insecure : state; /* delegation with no DS, might be Secure -> Insecure */ if (foundCut) { *foundCut = true; } /* a delegation with no DS is either: - a signed zone (Secure) to an unsigned one (Insecure) - an unsigned zone to another unsigned one (Insecure stays Insecure, Bogus stays Bogus) */ return state == vState::Secure ? vState::Insecure : state; } else { /* we have a DS */ d_cutStates[zone] = state; if (foundCut) { *foundCut = true; } } } return state; } LOG(d_prefix<<": returning Bogus state from "<<__func__<<"("<<zone<<")"<<endl); return vState::BogusUnableToGetDSs; } vState SyncRes::getValidationStatus(const DNSName& name, bool wouldBeValid, bool typeIsDS, unsigned int depth) { vState result = vState::Indeterminate; if (!shouldValidate()) { return result; } DNSName subdomain(name); if (typeIsDS) { subdomain.chopOff(); } { const auto& it = d_cutStates.find(subdomain); if (it != d_cutStates.cend()) { LOG(d_prefix<<": got status "<<it->second<<" for name "<<subdomain<<endl); return it->second; } } /* look for the best match we have */ DNSName best(subdomain); while (best.chopOff()) { const auto& it = d_cutStates.find(best); if (it != d_cutStates.cend()) { result = it->second; if (vStateIsBogus(result) || result == vState::Insecure) { LOG(d_prefix<<": got status "<<result<<" for name "<<best<<endl); return result; } break; } } /* by now we have the best match, it's likely Secure (otherwise we would not be there) but we don't know if we missed a cut (or several). We could see if we have DS (or denial of) in cache but let's not worry for now, we will if we don't have a signature, or if the signer doesn't match what we expect */ if (!wouldBeValid && best != subdomain) { /* no signatures or Bogus, we likely missed a cut, let's try to find it */ LOG(d_prefix<<": no or invalid signature/proof for "<<name<<", we likely missed a cut between "<<best<<" and "<<subdomain<<", looking for it"<<endl); DNSName ds(best); std::vector<string> labelsToAdd = subdomain.makeRelative(ds).getRawLabels(); while (!labelsToAdd.empty()) { ds.prependRawLabel(labelsToAdd.back()); labelsToAdd.pop_back(); LOG(d_prefix<<": - Looking for a DS at "<<ds<<endl); bool foundCut = false; dsmap_t results; vState dsState = getDSRecords(ds, results, false, depth, false, &foundCut); if (foundCut) { LOG(d_prefix<<": - Found cut at "<<ds<<endl); LOG(d_prefix<<": New state for "<<ds<<" is "<<dsState<<endl); d_cutStates[ds] = dsState; if (dsState != vState::Secure) { return dsState; } } } /* we did not miss a cut, good luck */ return result; } #if 0 /* we don't need this, we actually do the right thing later */ DNSName signer = getSigner(signatures); if (!signer.empty() && name.isPartOf(signer)) { if (signer == best) { return result; } /* the zone cut is not the one we expected, this is fine because we will retrieve the needed DNSKEYs and DSs later, and even go Insecure if we missed a cut to Insecure (no DS) and the signatures do not validate (we should not go Bogus in that case) */ } /* something is not right, but let's not worry about that for now.. */ #endif return result; } vState SyncRes::validateDNSKeys(const DNSName& zone, const std::vector<DNSRecord>& dnskeys, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures, unsigned int depth) { dsmap_t ds; if (signatures.empty()) { LOG(d_prefix<<": we have "<<std::to_string(dnskeys.size())<<" DNSKEYs but no signature, going Bogus!"<<endl); return vState::BogusNoRRSIG; } DNSName signer = getSigner(signatures); if (!signer.empty() && zone.isPartOf(signer)) { vState state = getDSRecords(signer, ds, false, depth); if (state != vState::Secure) { return state; } } else { LOG(d_prefix<<": we have "<<std::to_string(dnskeys.size())<<" DNSKEYs but the zone ("<<zone<<") is not part of the signer ("<<signer<<"), check that we did not miss a zone cut"<<endl); /* try again to get the missed cuts, harder this time */ auto zState = getValidationStatus(zone, false, false, depth); if (zState == vState::Secure) { /* too bad */ LOG(d_prefix<<": after checking the zone cuts again, we still have "<<std::to_string(dnskeys.size())<<" DNSKEYs and the zone ("<<zone<<") is still not part of the signer ("<<signer<<"), going Bogus!"<<endl); return vState::BogusNoValidRRSIG; } else { return zState; } } skeyset_t tentativeKeys; sortedRecords_t toSign; for (const auto& dnskey : dnskeys) { if (dnskey.d_type == QType::DNSKEY) { auto content = getRR<DNSKEYRecordContent>(dnskey); if (content) { tentativeKeys.insert(content); toSign.insert(content); } } } LOG(d_prefix<<": trying to validate "<<std::to_string(tentativeKeys.size())<<" DNSKEYs with "<<std::to_string(ds.size())<<" DS"<<endl); skeyset_t validatedKeys; auto state = validateDNSKeysAgainstDS(d_now.tv_sec, zone, ds, tentativeKeys, toSign, signatures, validatedKeys); LOG(d_prefix<<": we now have "<<std::to_string(validatedKeys.size())<<" DNSKEYs"<<endl); /* if we found at least one valid RRSIG covering the set, all tentative keys are validated keys. Otherwise it means we haven't found at least one DNSKEY and a matching RRSIG covering this set, this looks Bogus. */ if (validatedKeys.size() != tentativeKeys.size()) { LOG(d_prefix<<": let's check whether we missed a zone cut before returning a Bogus state from "<<__func__<<"("<<zone<<")"<<endl); /* try again to get the missed cuts, harder this time */ auto zState = getValidationStatus(zone, false, false, depth); if (zState == vState::Secure) { /* too bad */ LOG(d_prefix<<": after checking the zone cuts we are still in a Secure zone, returning Bogus state from "<<__func__<<"("<<zone<<")"<<endl); return state; } else { return zState; } } return state; } vState SyncRes::getDNSKeys(const DNSName& signer, skeyset_t& keys, unsigned int depth) { std::vector<DNSRecord> records; std::set<GetBestNSAnswer> beenthere; LOG(d_prefix<<"Retrieving DNSKeys for "<<signer<<endl); vState state = vState::Indeterminate; const bool oldCacheOnly = setCacheOnly(false); int rcode = doResolve(signer, QType::DNSKEY, records, depth + 1, beenthere, state); setCacheOnly(oldCacheOnly); if (rcode == RCode::ServFail) { throw ImmediateServFailException("Server Failure while retrieving DNSKEY records for " + signer.toLogString()); } if (rcode == RCode::NoError) { if (state == vState::Secure) { for (const auto& key : records) { if (key.d_type == QType::DNSKEY) { auto content = getRR<DNSKEYRecordContent>(key); if (content) { keys.insert(content); } } } } LOG(d_prefix<<"Retrieved "<<keys.size()<<" DNSKeys for "<<signer<<", state is "<<state<<endl); return state; } if (state == vState::Insecure) { return state; } LOG(d_prefix<<"Returning Bogus state from "<<__func__<<"("<<signer<<")"<<endl); return vState::BogusUnableToGetDNSKEYs; } vState SyncRes::validateRecordsWithSigs(unsigned int depth, const DNSName& qname, const QType qtype, const DNSName& name, const QType type, const std::vector<DNSRecord>& records, const std::vector<std::shared_ptr<RRSIGRecordContent> >& signatures) { skeyset_t keys; if (signatures.empty()) { LOG(d_prefix<<"Bogus!"<<endl); return vState::BogusNoRRSIG; } const DNSName signer = getSigner(signatures); bool dsFailed = false; if (!signer.empty() && name.isPartOf(signer)) { vState state = vState::Secure; if ((qtype == QType::DNSKEY || qtype == QType::DS) && signer == qname) { /* we are already retrieving those keys, sorry */ if (type == QType::DS && signer == name && !signer.isRoot()) { /* Unless we are getting the DS of the root zone, we should never see a DS (or a denial of a DS) signed by the DS itself, since we should be requesting it from the parent zone. Something is very wrong */ LOG(d_prefix<<"The DS for "<<qname<<" is signed by itself"<<endl); state = vState::BogusSelfSignedDS; dsFailed = true; } else if (qtype == QType::DS && signer == qname && !signer.isRoot() && (type == QType::SOA || type == QType::NSEC || type == QType::NSEC3)) { /* if we are trying to validate the DS or more likely NSEC(3)s proving that it does not exist, we have a problem. In that case let's go Bogus (we will check later if we missed a cut) */ state = vState::BogusSelfSignedDS; dsFailed = true; } else if (qtype == QType::DNSKEY && signer == qname) { /* that actually does happen when a server returns NS records in authority along with the DNSKEY, leading us to trying to validate the RRSIGs for the NS with the DNSKEY that we are about to process. */ if ((name == signer && type == QType::NSEC) || type == QType::NSEC3) { /* if we are trying to validate the DNSKEY (should not happen here), or more likely NSEC(3)s proving that it does not exist, we have a problem. In that case let's see if the DS does exist, and if it does let's go Bogus */ dsmap_t results; vState dsState = getDSRecords(signer, results, false, depth, true); if (vStateIsBogus(dsState) || dsState == vState::Insecure) { state = dsState; if (vStateIsBogus(dsState)) { dsFailed = true; } } else { LOG(d_prefix<<"Unable to get the DS for "<<signer<<endl); state = vState::BogusUnableToGetDNSKEYs; dsFailed = true; } } else { /* return immediately since looking at the cuts is not going to change the fact that we are looking at a signature done with the key we are trying to obtain */ LOG(d_prefix<<"we are looking at a signature done with the key we are trying to obtain "<<signer<<endl); return vState::Indeterminate; } } } if (state == vState::Secure) { LOG(d_prefix<<"retrieving the DNSKEYs for "<<signer<<endl); state = getDNSKeys(signer, keys, depth); } if (state != vState::Secure) { if (!vStateIsBogus(state)) { return state; } /* try again to get the missed cuts, harder this time */ LOG(d_prefix<<"checking whether we missed a zone cut for "<<signer<<" before returning a Bogus state for "<<name<<"|"<<type.toString()<<endl); auto zState = getValidationStatus(signer, false, dsFailed, depth); if (zState == vState::Secure) { /* too bad */ LOG(d_prefix<<"we are still in a Secure zone, returning "<<vStateToString(state)<<endl); return state; } else { return zState; } } } sortedRecords_t recordcontents; for (const auto& record : records) { recordcontents.insert(record.d_content); } LOG(d_prefix<<"Going to validate "<<recordcontents.size()<< " record contents with "<<signatures.size()<<" sigs and "<<keys.size()<<" keys for "<<name<<"|"<<type.toString()<<endl); vState state = validateWithKeySet(d_now.tv_sec, name, recordcontents, signatures, keys, false); if (state == vState::Secure) { LOG(d_prefix<<"Secure!"<<endl); return vState::Secure; } LOG(d_prefix<<vStateToString(state)<<"!"<<endl); /* try again to get the missed cuts, harder this time */ auto zState = getValidationStatus(name, false, type == QType::DS, depth); LOG(d_prefix<<"checking whether we missed a zone cut before returning a Bogus state"<<endl); if (zState == vState::Secure) { /* too bad */ LOG(d_prefix<<"we are still in a Secure zone, returning "<<vStateToString(state)<<endl); return state; } else { return zState; } } /* This function will check whether the answer should have the AA bit set, and will set if it should be set and isn't. This is unfortunately needed to deal with very crappy so-called DNS servers */ void SyncRes::fixupAnswer(const std::string& prefix, LWResult& lwr, const DNSName& qname, const QType qtype, const DNSName& auth, bool wasForwarded, bool rdQuery) { const bool wasForwardRecurse = wasForwarded && rdQuery; if (wasForwardRecurse || lwr.d_aabit) { /* easy */ return; } for (const auto& rec : lwr.d_records) { if (rec.d_type == QType::OPT) { continue; } if (rec.d_class != QClass::IN) { continue; } if (rec.d_type == QType::ANY) { continue; } if (rec.d_place == DNSResourceRecord::ANSWER && (rec.d_type == qtype || rec.d_type == QType::CNAME || qtype == QType::ANY) && rec.d_name == qname && rec.d_name.isPartOf(auth)) { /* This is clearly an answer to the question we were asking, from an authoritative server that is allowed to send it. We are going to assume this server is broken and does not know it should set the AA bit, even though it is DNS 101 */ LOG(prefix<<"Received a record for "<<rec.d_name<<"|"<<DNSRecordContent::NumberToType(rec.d_type)<<" in the answer section from "<<auth<<", without the AA bit set. Assuming this server is clueless and setting the AA bit."<<endl); lwr.d_aabit = true; return; } if (rec.d_place != DNSResourceRecord::ANSWER) { /* we have scanned all the records in the answer section, if any, we are done */ return; } } } static bool allowAdditionalEntry(std::unordered_set<DNSName>& allowedAdditionals, const DNSRecord& rec) { switch(rec.d_type) { case QType::MX: { if (auto mxContent = getRR<MXRecordContent>(rec)) { allowedAdditionals.insert(mxContent->d_mxname); } return true; } case QType::NS: { if (auto nsContent = getRR<NSRecordContent>(rec)) { allowedAdditionals.insert(nsContent->getNS()); } return true; } case QType::SRV: { if (auto srvContent = getRR<SRVRecordContent>(rec)) { allowedAdditionals.insert(srvContent->d_target); } return true; } default: return false; } } void SyncRes::sanitizeRecords(const std::string& prefix, LWResult& lwr, const DNSName& qname, const QType qtype, const DNSName& auth, bool wasForwarded, bool rdQuery) { const bool wasForwardRecurse = wasForwarded && rdQuery; /* list of names for which we will allow A and AAAA records in the additional section to remain */ std::unordered_set<DNSName> allowedAdditionals = { qname }; bool haveAnswers = false; bool isNXDomain = false; bool isNXQType = false; for(auto rec = lwr.d_records.begin(); rec != lwr.d_records.end(); ) { if (rec->d_type == QType::OPT) { ++rec; continue; } if (rec->d_class != QClass::IN) { LOG(prefix<<"Removing non internet-classed data received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_type == QType::ANY) { LOG(prefix<<"Removing 'ANY'-typed data received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (!rec->d_name.isPartOf(auth)) { LOG(prefix<<"Removing record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } /* dealing with the records in answer */ if (!(lwr.d_aabit || wasForwardRecurse) && rec->d_place == DNSResourceRecord::ANSWER) { /* for now we allow a CNAME for the exact qname in ANSWER with AA=0, because Amazon DNS servers are sending such responses */ if (!(rec->d_type == QType::CNAME && qname == rec->d_name)) { LOG(prefix<<"Removing record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the answer section without the AA bit set received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } } if (rec->d_type == QType::DNAME && (rec->d_place != DNSResourceRecord::ANSWER || !qname.isPartOf(rec->d_name))) { LOG(prefix<<"Removing invalid DNAME record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_place == DNSResourceRecord::ANSWER && (qtype != QType::ANY && rec->d_type != qtype.getCode() && s_redirectionQTypes.count(rec->d_type) == 0 && rec->d_type != QType::SOA && rec->d_type != QType::RRSIG)) { LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the ANSWER section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_place == DNSResourceRecord::ANSWER && !haveAnswers) { haveAnswers = true; } if (rec->d_place == DNSResourceRecord::ANSWER) { allowAdditionalEntry(allowedAdditionals, *rec); } /* dealing with the records in authority */ if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type != QType::NS && rec->d_type != QType::DS && rec->d_type != QType::SOA && rec->d_type != QType::RRSIG && rec->d_type != QType::NSEC && rec->d_type != QType::NSEC3) { LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the AUTHORITY section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::SOA) { if (!qname.isPartOf(rec->d_name)) { LOG(prefix<<"Removing irrelevant SOA record '"<<rec->d_name<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the AUTHORITY section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (!(lwr.d_aabit || wasForwardRecurse)) { LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the AUTHORITY section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (!haveAnswers) { if (lwr.d_rcode == RCode::NXDomain) { isNXDomain = true; } else if (lwr.d_rcode == RCode::NoError) { isNXQType = true; } } } if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::NS && (isNXDomain || isNXQType)) { /* * We don't want to pick up NS records in AUTHORITY and their ADDITIONAL sections of NXDomain answers * because they are somewhat easy to insert into a large, fragmented UDP response * for an off-path attacker by injecting spoofed UDP fragments. So do not add these to allowedAdditionals. */ LOG(prefix<<"Removing NS record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section of a "<<(isNXDomain ? "NXD" : "NXQTYPE")<<" response received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::NS && !d_updatingRootNS && rec->d_name == g_rootdnsname) { /* * We don't want to pick up root NS records in AUTHORITY and their associated ADDITIONAL sections of random queries. * So don't add them to allowedAdditionals. */ LOG(prefix<<"Removing NS record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the "<<(int)rec->d_place<<" section of a response received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_place == DNSResourceRecord::AUTHORITY && rec->d_type == QType::NS) { allowAdditionalEntry(allowedAdditionals, *rec); } /* dealing with the records in additional */ if (rec->d_place == DNSResourceRecord::ADDITIONAL && rec->d_type != QType::A && rec->d_type != QType::AAAA && rec->d_type != QType::RRSIG) { LOG(prefix<<"Removing irrelevant record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the ADDITIONAL section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } if (rec->d_place == DNSResourceRecord::ADDITIONAL && allowedAdditionals.count(rec->d_name) == 0) { LOG(prefix<<"Removing irrelevant additional record '"<<rec->d_name<<"|"<<DNSRecordContent::NumberToType(rec->d_type)<<"|"<<rec->d_content->getZoneRepresentation()<<"' in the ADDITIONAL section received from "<<auth<<endl); rec = lwr.d_records.erase(rec); continue; } ++rec; } } RCode::rcodes_ SyncRes::updateCacheFromRecords(unsigned int depth, LWResult& lwr, const DNSName& qname, const QType qtype, const DNSName& auth, bool wasForwarded, const boost::optional<Netmask> ednsmask, vState& state, bool& needWildcardProof, bool& gatherWildcardProof, unsigned int& wildcardLabelsCount, bool rdQuery, const ComboAddress& remoteIP) { bool wasForwardRecurse = wasForwarded && rdQuery; tcache_t tcache; string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } fixupAnswer(prefix, lwr, qname, qtype, auth, wasForwarded, rdQuery); sanitizeRecords(prefix, lwr, qname, qtype, auth, wasForwarded, rdQuery); std::vector<std::shared_ptr<DNSRecord>> authorityRecs; const unsigned int labelCount = qname.countLabels(); bool isCNAMEAnswer = false; bool isDNAMEAnswer = false; DNSName seenAuth; for (auto& rec : lwr.d_records) { if (rec.d_type == QType::OPT || rec.d_class != QClass::IN) { continue; } rec.d_ttl = min(s_maxcachettl, rec.d_ttl); if (!isCNAMEAnswer && rec.d_place == DNSResourceRecord::ANSWER && rec.d_type == QType::CNAME && (!(qtype==QType::CNAME)) && rec.d_name == qname && !isDNAMEAnswer) { isCNAMEAnswer = true; } if (!isDNAMEAnswer && rec.d_place == DNSResourceRecord::ANSWER && rec.d_type == QType::DNAME && qtype != QType::DNAME && qname.isPartOf(rec.d_name)) { isDNAMEAnswer = true; isCNAMEAnswer = false; } if (rec.d_type == QType::SOA && rec.d_place == DNSResourceRecord::AUTHORITY && qname.isPartOf(rec.d_name)) { seenAuth = rec.d_name; } if (rec.d_type == QType::RRSIG) { auto rrsig = getRR<RRSIGRecordContent>(rec); if (rrsig) { /* As illustrated in rfc4035's Appendix B.6, the RRSIG label count can be lower than the name's label count if it was synthesized from the wildcard. Note that the difference might be > 1. */ if (rec.d_name == qname && isWildcardExpanded(labelCount, rrsig)) { gatherWildcardProof = true; if (!isWildcardExpandedOntoItself(rec.d_name, labelCount, rrsig)) { /* if we have a wildcard expanded onto itself, we don't need to prove that the exact name doesn't exist because it actually does. We still want to gather the corresponding NSEC/NSEC3 records to pass them to our client in case it wants to validate by itself. */ LOG(prefix<<qname<<": RRSIG indicates the name was synthesized from a wildcard, we need a wildcard proof"<<endl); needWildcardProof = true; } else { LOG(prefix<<qname<<": RRSIG indicates the name was synthesized from a wildcard expanded onto itself, we need to gather wildcard proof"<<endl); } wildcardLabelsCount = rrsig->d_labels; } // cerr<<"Got an RRSIG for "<<DNSRecordContent::NumberToType(rrsig->d_type)<<" with name '"<<rec.d_name<<"' and place "<<rec.d_place<<endl; tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signatures.push_back(rrsig); tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signaturesTTL = std::min(tcache[{rec.d_name, rrsig->d_type, rec.d_place}].signaturesTTL, rec.d_ttl); } } } /* if we have a positive answer synthesized from a wildcard, we need to store the corresponding NSEC/NSEC3 records proving that the exact name did not exist in the negative cache */ if (gatherWildcardProof) { for (const auto& rec : lwr.d_records) { if (rec.d_type == QType::OPT || rec.d_class != QClass::IN) { continue; } if (nsecTypes.count(rec.d_type)) { authorityRecs.push_back(std::make_shared<DNSRecord>(rec)); } else if (rec.d_type == QType::RRSIG) { auto rrsig = getRR<RRSIGRecordContent>(rec); if (rrsig && nsecTypes.count(rrsig->d_type)) { authorityRecs.push_back(std::make_shared<DNSRecord>(rec)); } } } } // reap all answers from this packet that are acceptable for (auto& rec : lwr.d_records) { if(rec.d_type == QType::OPT) { LOG(prefix<<qname<<": OPT answer '"<<rec.d_name<<"' from '"<<auth<<"' nameservers" <<endl); continue; } LOG(prefix<<qname<<": accept answer '"<<rec.d_name<<"|"<<DNSRecordContent::NumberToType(rec.d_type)<<"|"<<rec.d_content->getZoneRepresentation()<<"' from '"<<auth<<"' nameservers? ttl="<<rec.d_ttl<<", place="<<(int)rec.d_place<<" "); // We called sanitizeRecords before, so all ANY, non-IN and non-aa/non-forwardrecurse answer records are already removed if(rec.d_name.isPartOf(auth)) { if (rec.d_type == QType::RRSIG) { LOG("RRSIG - separate"<<endl); } else if (rec.d_type == QType::DS && rec.d_name == auth) { LOG("NO - DS provided by child zone"<<endl); } else { bool haveLogged = false; if (isDNAMEAnswer && rec.d_type == QType::CNAME) { LOG("NO - we already have a DNAME answer for this domain"<<endl); continue; } if (!t_sstorage.domainmap->empty()) { // Check if we are authoritative for a zone in this answer DNSName tmp_qname(rec.d_name); // We may be auth for domain example.com, but the DS record needs to come from the parent (.com) nameserver if (rec.d_type == QType::DS) { tmp_qname.chopOff(); } auto auth_domain_iter=getBestAuthZone(&tmp_qname); if(auth_domain_iter!=t_sstorage.domainmap->end() && auth.countLabels() <= auth_domain_iter->first.countLabels()) { if (auth_domain_iter->first != auth) { LOG("NO! - we are authoritative for the zone "<<auth_domain_iter->first<<endl); continue; } else { LOG("YES! - This answer was "); if (!wasForwarded) { LOG("retrieved from the local auth store."); } else { LOG("received from a server we forward to."); } haveLogged = true; LOG(endl); } } } if (!haveLogged) { LOG("YES!"<<endl); } rec.d_ttl=min(s_maxcachettl, rec.d_ttl); DNSRecord dr(rec); dr.d_ttl += d_now.tv_sec; dr.d_place=DNSResourceRecord::ANSWER; tcache[{rec.d_name,rec.d_type,rec.d_place}].records.push_back(dr); } } else LOG("NO!"<<endl); } // supplant for (auto& entry : tcache) { if ((entry.second.records.size() + entry.second.signatures.size() + authorityRecs.size()) > 1) { // need to group the ttl to be the minimum of the RRSET (RFC 2181, 5.2) uint32_t lowestTTD = computeLowestTTD(entry.second.records, entry.second.signatures, entry.second.signaturesTTL, authorityRecs); for (auto& record : entry.second.records) { record.d_ttl = lowestTTD; // boom } } // cout<<"Have "<<i->second.records.size()<<" records and "<<i->second.signatures.size()<<" signatures for "<<i->first.name; // cout<<'|'<<DNSRecordContent::NumberToType(i->first.type)<<endl; } for(tcache_t::iterator i = tcache.begin(); i != tcache.end(); ++i) { if (i->second.records.empty()) // this happens when we did store signatures, but passed on the records themselves continue; /* Even if the AA bit is set, additional data cannot be considered as authoritative. This is especially important during validation because keeping records in the additional section is allowed even if the corresponding RRSIGs are not included, without setting the TC bit, as stated in rfc4035's section 3.1.1. Including RRSIG RRs in a Response: "When placing a signed RRset in the Additional section, the name server MUST also place its RRSIG RRs in the Additional section. If space does not permit inclusion of both the RRset and its associated RRSIG RRs, the name server MAY retain the RRset while dropping the RRSIG RRs. If this happens, the name server MUST NOT set the TC bit solely because these RRSIG RRs didn't fit." */ bool isAA = lwr.d_aabit && i->first.place != DNSResourceRecord::ADDITIONAL; /* if we forwarded the query to a recursor, we can expect the answer to be signed, even if the answer is not AA. Of course that's not only true inside a Secure zone, but we check that below. */ bool expectSignature = i->first.place == DNSResourceRecord::ANSWER || ((lwr.d_aabit || wasForwardRecurse) && i->first.place != DNSResourceRecord::ADDITIONAL); /* in a non authoritative answer, we only care about the DS record (or lack of) */ if (!isAA && (i->first.type == QType::DS || i->first.type == QType::NSEC || i->first.type == QType::NSEC3) && i->first.place == DNSResourceRecord::AUTHORITY) { expectSignature = true; } if (isCNAMEAnswer && (i->first.place != DNSResourceRecord::ANSWER || i->first.type != QType::CNAME || i->first.name != qname)) { /* rfc2181 states: Note that the answer section of an authoritative answer normally contains only authoritative data. However when the name sought is an alias (see section 10.1.1) only the record describing that alias is necessarily authoritative. Clients should assume that other records may have come from the server's cache. Where authoritative answers are required, the client should query again, using the canonical name associated with the alias. */ isAA = false; expectSignature = false; } if (isCNAMEAnswer && i->first.place == DNSResourceRecord::AUTHORITY && i->first.type == QType::NS && auth == i->first.name) { /* These NS can't be authoritative since we have a CNAME answer for which (see above) only the record describing that alias is necessarily authoritative. But if we allow the current auth, which might be serving the child zone, to raise the TTL of non-authoritative NS in the cache, they might be able to keep a "ghost" zone alive forever, even after the delegation is gone from the parent. So let's just do nothing with them, we can fetch them directly if we need them. */ LOG(d_prefix<<": skipping authority NS from '"<<auth<<"' nameservers in CNAME answer "<<i->first.name<<"|"<<DNSRecordContent::NumberToType(i->first.type)<<endl); continue; } /* * RFC 6672 section 5.3.1 * In any response, a signed DNAME RR indicates a non-terminal * redirection of the query. There might or might not be a server- * synthesized CNAME in the answer section; if there is, the CNAME will * never be signed. For a DNSSEC validator, verification of the DNAME * RR and then that the CNAME was properly synthesized is sufficient * proof. * * We do the synthesis check in processRecords, here we make sure we * don't validate the CNAME. */ if (isDNAMEAnswer && i->first.type == QType::CNAME) { expectSignature = false; } vState recordState = vState::Indeterminate; if (expectSignature && shouldValidate()) { vState initialState = getValidationStatus(i->first.name, !i->second.signatures.empty(), i->first.type == QType::DS, depth); LOG(d_prefix<<": got initial zone status "<<initialState<<" for record "<<i->first.name<<"|"<<DNSRecordContent::NumberToType(i->first.type)<<endl); if (initialState == vState::Secure) { if (i->first.type == QType::DNSKEY && i->first.place == DNSResourceRecord::ANSWER && i->first.name == getSigner(i->second.signatures)) { LOG(d_prefix<<"Validating DNSKEY for "<<i->first.name<<endl); recordState = validateDNSKeys(i->first.name, i->second.records, i->second.signatures, depth); } else { LOG(d_prefix<<"Validating non-additional "<<QType(i->first.type).toString()<<" record for "<<i->first.name<<endl); recordState = validateRecordsWithSigs(depth, qname, qtype, i->first.name, QType(i->first.type), i->second.records, i->second.signatures); } } else { recordState = initialState; LOG(d_prefix<<"Skipping validation because the current state is "<<recordState<<endl); } LOG(d_prefix<<"Validation result is "<<recordState<<", current state is "<<state<<endl); if (state != recordState) { updateValidationState(state, recordState); } } if (vStateIsBogus(recordState)) { /* this is a TTD by now, be careful */ for(auto& record : i->second.records) { record.d_ttl = std::min(record.d_ttl, static_cast<uint32_t>(s_maxbogusttl + d_now.tv_sec)); } } /* We don't need to store NSEC3 records in the positive cache because: - we don't allow direct NSEC3 queries - denial of existence proofs in wildcard expanded positive responses are stored in authorityRecs - denial of existence proofs for negative responses are stored in the negative cache We also don't want to cache non-authoritative data except for: - records coming from non forward-recurse servers (those will never be AA) - DS (special case) - NS, A and AAAA (used for infra queries) */ if (i->first.type != QType::NSEC3 && (i->first.type == QType::DS || i->first.type == QType::NS || i->first.type == QType::A || i->first.type == QType::AAAA || isAA || wasForwardRecurse)) { bool doCache = true; if (i->first.place == DNSResourceRecord::ANSWER && ednsmask) { const bool isv4 = ednsmask->isIPv4(); if ((isv4 && s_ecsipv4nevercache) || (!isv4 && s_ecsipv6nevercache)) { doCache = false; } // If ednsmask is relevant, we do not want to cache if the scope prefix length is large and TTL is small if (doCache && s_ecscachelimitttl > 0) { bool manyMaskBits = (isv4 && ednsmask->getBits() > s_ecsipv4cachelimit) || (!isv4 && ednsmask->getBits() > s_ecsipv6cachelimit); if (manyMaskBits) { uint32_t minttl = UINT32_MAX; for (const auto &it : i->second.records) { if (it.d_ttl < minttl) minttl = it.d_ttl; } bool ttlIsSmall = minttl < s_ecscachelimitttl + d_now.tv_sec; if (ttlIsSmall) { // Case: many bits and ttlIsSmall doCache = false; } } } } if (doCache) { g_recCache->replace(d_now.tv_sec, i->first.name, i->first.type, i->second.records, i->second.signatures, authorityRecs, i->first.type == QType::DS ? true : isAA, auth, i->first.place == DNSResourceRecord::ANSWER ? ednsmask : boost::none, d_routingTag, recordState, remoteIP); if (g_aggressiveNSECCache && needWildcardProof && recordState == vState::Secure && i->first.place == DNSResourceRecord::ANSWER && i->first.name == qname && !i->second.signatures.empty() && !d_routingTag && !ednsmask) { /* we have an answer synthesized from a wildcard and aggressive NSEC is enabled, we need to store the wildcard in its non-expanded form in the cache to be able to synthesize wildcard answers later */ const auto& rrsig = i->second.signatures.at(0); if (isWildcardExpanded(labelCount, rrsig) && !isWildcardExpandedOntoItself(i->first.name, labelCount, rrsig)) { DNSName realOwner = getNSECOwnerName(i->first.name, i->second.signatures); std::vector<DNSRecord> content; content.reserve(i->second.records.size()); for (const auto& record : i->second.records) { DNSRecord nonExpandedRecord(record); nonExpandedRecord.d_name = realOwner; content.push_back(std::move(nonExpandedRecord)); } g_recCache->replace(d_now.tv_sec, realOwner, QType(i->first.type), content, i->second.signatures, /* no additional records in that case */ {}, i->first.type == QType::DS ? true : isAA, auth, boost::none, boost::none, recordState, remoteIP); } } } } if (seenAuth.empty() && !i->second.signatures.empty()) { seenAuth = getSigner(i->second.signatures); } if (g_aggressiveNSECCache && (i->first.type == QType::NSEC || i->first.type == QType::NSEC3) && recordState == vState::Secure && !seenAuth.empty()) { // Good candidate for NSEC{,3} caching g_aggressiveNSECCache->insertNSEC(seenAuth, i->first.name, i->second.records.at(0), i->second.signatures, i->first.type == QType::NSEC3); } if (i->first.place == DNSResourceRecord::ANSWER && ednsmask) { d_wasVariable=true; } } return RCode::NoError; } void SyncRes::updateDenialValidationState(vState& neValidationState, const DNSName& neName, vState& state, const dState denialState, const dState expectedState, bool isDS, unsigned int depth) { if (denialState == expectedState) { neValidationState = vState::Secure; } else { if (denialState == dState::OPTOUT) { LOG(d_prefix<<"OPT-out denial found for "<<neName<<endl); /* rfc5155 states: "The AD bit, as defined by [RFC4035], MUST NOT be set when returning a response containing a closest (provable) encloser proof in which the NSEC3 RR that covers the "next closer" name has the Opt-Out bit set. This rule is based on what this closest encloser proof actually proves: names that would be covered by the Opt-Out NSEC3 RR may or may not exist as insecure delegations. As such, not all the data in responses containing such closest encloser proofs will have been cryptographically verified, so the AD bit cannot be set." At best the Opt-Out NSEC3 RR proves that there is no signed DS (so no secure delegation). */ neValidationState = vState::Insecure; } else if (denialState == dState::INSECURE) { LOG(d_prefix<<"Insecure denial found for "<<neName<<", returning Insecure"<<endl); neValidationState = vState::Insecure; } else { LOG(d_prefix<<"Invalid denial found for "<<neName<<", res="<<denialState<<", expectedState="<<expectedState<<", checking whether we have missed a zone cut before returning a Bogus state"<<endl); /* try again to get the missed cuts, harder this time */ auto zState = getValidationStatus(neName, false, isDS, depth); if (zState != vState::Secure) { neValidationState = zState; } else { LOG(d_prefix<<"Still in a secure zone with an invalid denial for "<<neName<<", returning "<<vStateToString(vState::BogusInvalidDenial)<<endl); neValidationState = vState::BogusInvalidDenial; } } } updateValidationState(state, neValidationState); } dState SyncRes::getDenialValidationState(const NegCache::NegCacheEntry& ne, const dState expectedState, bool referralToUnsigned) { cspmap_t csp = harvestCSPFromNE(ne); return getDenial(csp, ne.d_name, ne.d_qtype.getCode(), referralToUnsigned, expectedState == dState::NXQTYPE); } bool SyncRes::processRecords(const std::string& prefix, const DNSName& qname, const QType qtype, const DNSName& auth, LWResult& lwr, const bool sendRDQuery, vector<DNSRecord>& ret, set<DNSName>& nsset, DNSName& newtarget, DNSName& newauth, bool& realreferral, bool& negindic, vState& state, const bool needWildcardProof, const bool gatherWildcardProof, const unsigned int wildcardLabelsCount, int& rcode, bool& negIndicHasSignatures, unsigned int depth) { bool done = false; DNSName dnameTarget, dnameOwner; uint32_t dnameTTL = 0; bool referralOnDS = false; for (auto& rec : lwr.d_records) { if (rec.d_type != QType::OPT && rec.d_class != QClass::IN) { continue; } if (rec.d_place == DNSResourceRecord::ANSWER && !(lwr.d_aabit || sendRDQuery)) { /* for now we allow a CNAME for the exact qname in ANSWER with AA=0, because Amazon DNS servers are sending such responses */ if (!(rec.d_type == QType::CNAME && rec.d_name == qname)) { continue; } } const bool negCacheIndiction = rec.d_place == DNSResourceRecord::AUTHORITY && rec.d_type == QType::SOA && lwr.d_rcode == RCode::NXDomain && qname.isPartOf(rec.d_name) && rec.d_name.isPartOf(auth); bool putInNegCache = true; if (negCacheIndiction && qtype == QType::DS && isForwardOrAuth(qname)) { // #10189, a NXDOMAIN to a DS query for a forwarded or auth domain should not NXDOMAIN the whole domain putInNegCache = false; } if (negCacheIndiction) { LOG(prefix<<qname<<": got negative caching indication for name '"<<qname<<"' (accept="<<rec.d_name.isPartOf(auth)<<"), newtarget='"<<newtarget<<"'"<<endl); rec.d_ttl = min(rec.d_ttl, s_maxnegttl); // only add a SOA if we're not going anywhere after this if (newtarget.empty()) { ret.push_back(rec); } NegCache::NegCacheEntry ne; uint32_t lowestTTL = rec.d_ttl; /* if we get an NXDomain answer with a CNAME, the name does exist but the target does not */ ne.d_name = newtarget.empty() ? qname : newtarget; ne.d_qtype = QType::ENT; // this encodes 'whole record' ne.d_auth = rec.d_name; harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL); if (vStateIsBogus(state)) { ne.d_validationState = state; } else { /* here we need to get the validation status of the zone telling us that the domain does not exist, ie the owner of the SOA */ auto recordState = getValidationStatus(rec.d_name, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), false, depth); if (recordState == vState::Secure) { dState denialState = getDenialValidationState(ne, dState::NXDOMAIN, false); updateDenialValidationState(ne.d_validationState, ne.d_name, state, denialState, dState::NXDOMAIN, false, depth); } else { ne.d_validationState = recordState; updateValidationState(state, ne.d_validationState); } } if (vStateIsBogus(ne.d_validationState)) { lowestTTL = min(lowestTTL, s_maxbogusttl); } ne.d_ttd = d_now.tv_sec + lowestTTL; /* if we get an NXDomain answer with a CNAME, let's not cache the target, even the server was authoritative for it, and do an additional query for the CNAME target. We have a regression test making sure we do exactly that. */ if (!wasVariable() && newtarget.empty() && putInNegCache) { g_negCache->add(ne); if (s_rootNXTrust && ne.d_auth.isRoot() && auth.isRoot() && lwr.d_aabit) { ne.d_name = ne.d_name.getLastLabel(); g_negCache->add(ne); } } negIndicHasSignatures = !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(); negindic = true; } else if (rec.d_place == DNSResourceRecord::ANSWER && s_redirectionQTypes.count(rec.d_type) > 0 && // CNAME or DNAME answer s_redirectionQTypes.count(qtype.getCode()) == 0) { // But not in response to a CNAME or DNAME query if (rec.d_type == QType::CNAME && rec.d_name == qname) { if (!dnameOwner.empty()) { // We synthesize ourselves continue; } ret.push_back(rec); if (auto content = getRR<CNAMERecordContent>(rec)) { newtarget = DNSName(content->getTarget()); } } else if (rec.d_type == QType::DNAME && qname.isPartOf(rec.d_name)) { // DNAME ret.push_back(rec); if (auto content = getRR<DNAMERecordContent>(rec)) { dnameOwner = rec.d_name; dnameTarget = content->getTarget(); dnameTTL = rec.d_ttl; if (!newtarget.empty()) { // We had a CNAME before, remove it from ret so we don't cache it ret.erase(std::remove_if( ret.begin(), ret.end(), [&qname](DNSRecord& rr) { return (rr.d_place == DNSResourceRecord::ANSWER && rr.d_type == QType::CNAME && rr.d_name == qname); }), ret.end()); } try { newtarget = qname.makeRelative(dnameOwner) + dnameTarget; } catch (const std::exception &e) { // We should probably catch an std::range_error here and set the rcode to YXDOMAIN (RFC 6672, section 2.2) // But there is no way to set the RCODE from this function throw ImmediateServFailException("Unable to perform DNAME substitution(DNAME owner: '" + dnameOwner.toLogString() + "', DNAME target: '" + dnameTarget.toLogString() + "', substituted name: '" + qname.makeRelative(dnameOwner).toLogString() + "." + dnameTarget.toLogString() + "' : " + e.what()); } } } } /* if we have a positive answer synthesized from a wildcard, we need to return the corresponding NSEC/NSEC3 records from the AUTHORITY section proving that the exact name did not exist. Except if this is a NODATA answer because then we will gather the NXNSEC records later */ else if (gatherWildcardProof && !negindic && (rec.d_type == QType::RRSIG || rec.d_type == QType::NSEC || rec.d_type == QType::NSEC3) && rec.d_place == DNSResourceRecord::AUTHORITY) { ret.push_back(rec); // enjoy your DNSSEC } // for ANY answers we *must* have an authoritative answer, unless we are forwarding recursively else if (rec.d_place == DNSResourceRecord::ANSWER && rec.d_name == qname && ( rec.d_type == qtype.getCode() || ((lwr.d_aabit || sendRDQuery) && qtype == QType::ANY) ) ) { LOG(prefix<<qname<<": answer is in: resolved to '"<< rec.d_content->getZoneRepresentation()<<"|"<<DNSRecordContent::NumberToType(rec.d_type)<<"'"<<endl); done = true; rcode = RCode::NoError; if (needWildcardProof) { /* positive answer synthesized from a wildcard */ NegCache::NegCacheEntry ne; ne.d_name = qname; ne.d_qtype = QType::ENT; // this encodes 'whole record' uint32_t lowestTTL = rec.d_ttl; harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL); if (vStateIsBogus(state)) { ne.d_validationState = state; } else { auto recordState = getValidationStatus(qname, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), false, depth); if (recordState == vState::Secure) { /* We have a positive answer synthesized from a wildcard, we need to check that we have proof that the exact name doesn't exist so the wildcard can be used, as described in section 5.3.4 of RFC 4035 and 5.3 of RFC 7129. */ cspmap_t csp = harvestCSPFromNE(ne); dState res = getDenial(csp, qname, ne.d_qtype.getCode(), false, false, false, wildcardLabelsCount); if (res != dState::NXDOMAIN) { vState st = vState::BogusInvalidDenial; if (res == dState::INSECURE || res == dState::OPTOUT) { /* Some part could not be validated, for example a NSEC3 record with a too large number of iterations, this is not enough to warrant a Bogus, but go Insecure. */ st = vState::Insecure; LOG(d_prefix<<"Unable to validate denial in wildcard expanded positive response found for "<<qname<<", returning Insecure, res="<<res<<endl); } else { LOG(d_prefix<<"Invalid denial in wildcard expanded positive response found for "<<qname<<", returning Bogus, res="<<res<<endl); rec.d_ttl = std::min(rec.d_ttl, s_maxbogusttl); } updateValidationState(state, st); /* we already stored the record with a different validation status, let's fix it */ updateValidationStatusInCache(qname, qtype, lwr.d_aabit, st); } } } } ret.push_back(rec); } else if ((rec.d_type == QType::RRSIG || rec.d_type == QType::NSEC || rec.d_type == QType::NSEC3) && rec.d_place == DNSResourceRecord::ANSWER) { if (rec.d_type != QType::RRSIG || rec.d_name == qname) { ret.push_back(rec); // enjoy your DNSSEC } else if (rec.d_type == QType::RRSIG && qname.isPartOf(rec.d_name)) { auto rrsig = getRR<RRSIGRecordContent>(rec); if (rrsig != nullptr && rrsig->d_type == QType::DNAME) { ret.push_back(rec); } } } else if (rec.d_place == DNSResourceRecord::AUTHORITY && rec.d_type == QType::NS && qname.isPartOf(rec.d_name)) { if (moreSpecificThan(rec.d_name,auth)) { newauth = rec.d_name; LOG(prefix<<qname<<": got NS record '"<<rec.d_name<<"' -> '"<<rec.d_content->getZoneRepresentation()<<"'"<<endl); /* check if we have a referral from the parent zone to a child zone for a DS query, which is not right */ if (qtype == QType::DS && (newauth.isPartOf(qname) || qname == newauth)) { /* just got a referral from the parent zone when asking for a DS, looks like this server did not get the DNSSEC memo.. */ referralOnDS = true; } else { realreferral = true; if (auto content = getRR<NSRecordContent>(rec)) { nsset.insert(content->getNS()); } } } else { LOG(prefix<<qname<<": got upwards/level NS record '"<<rec.d_name<<"' -> '"<<rec.d_content->getZoneRepresentation()<<"', had '"<<auth<<"'"<<endl); if (auto content = getRR<NSRecordContent>(rec)) { nsset.insert(content->getNS()); } } } else if (rec.d_place==DNSResourceRecord::AUTHORITY && rec.d_type==QType::DS && qname.isPartOf(rec.d_name)) { LOG(prefix<<qname<<": got DS record '"<<rec.d_name<<"' -> '"<<rec.d_content->getZoneRepresentation()<<"'"<<endl); } else if (realreferral && rec.d_place == DNSResourceRecord::AUTHORITY && (rec.d_type == QType::NSEC || rec.d_type == QType::NSEC3) && newauth.isPartOf(auth)) { /* we might have received a denial of the DS, let's check */ NegCache::NegCacheEntry ne; uint32_t lowestTTL = rec.d_ttl; harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL); if (!vStateIsBogus(state)) { auto recordState = getValidationStatus(newauth, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), true, depth); if (recordState == vState::Secure) { ne.d_auth = auth; ne.d_name = newauth; ne.d_qtype = QType::DS; rec.d_ttl = min(s_maxnegttl, rec.d_ttl); dState denialState = getDenialValidationState(ne, dState::NXQTYPE, true); if (denialState == dState::NXQTYPE || denialState == dState::OPTOUT || denialState == dState::INSECURE) { ne.d_ttd = lowestTTL + d_now.tv_sec; ne.d_validationState = vState::Secure; if (denialState == dState::OPTOUT) { ne.d_validationState = vState::Insecure; } LOG(prefix<<qname<<": got negative indication of DS record for '"<<newauth<<"'"<<endl); if (!wasVariable()) { g_negCache->add(ne); } /* Careful! If the client is asking for a DS that does not exist, we need to provide the SOA along with the NSEC(3) proof and we might not have it if we picked up the proof from a delegation, in which case we need to keep on to do the actual DS query. */ if (qtype == QType::DS && qname == newauth && (d_externalDSQuery.empty() || qname != d_externalDSQuery)) { /* we are actually done! */ negindic = true; negIndicHasSignatures = !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(); nsset.clear(); } } } } } else if (!done && rec.d_place == DNSResourceRecord::AUTHORITY && rec.d_type == QType::SOA && lwr.d_rcode == RCode::NoError && qname.isPartOf(rec.d_name)) { LOG(prefix<<qname<<": got negative caching indication for '"<< qname<<"|"<<qtype<<"'"<<endl); if (!newtarget.empty()) { LOG(prefix<<qname<<": Hang on! Got a redirect to '"<<newtarget<<"' already"<<endl); } else { rec.d_ttl = min(s_maxnegttl, rec.d_ttl); NegCache::NegCacheEntry ne; ne.d_auth = rec.d_name; uint32_t lowestTTL = rec.d_ttl; ne.d_name = qname; ne.d_qtype = qtype; harvestNXRecords(lwr.d_records, ne, d_now.tv_sec, &lowestTTL); if (vStateIsBogus(state)) { ne.d_validationState = state; } else { auto recordState = getValidationStatus(qname, !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(), qtype == QType::DS, depth); if (recordState == vState::Secure) { dState denialState = getDenialValidationState(ne, dState::NXQTYPE, false); updateDenialValidationState(ne.d_validationState, ne.d_name, state, denialState, dState::NXQTYPE, qtype == QType::DS, depth); } else { ne.d_validationState = recordState; updateValidationState(state, ne.d_validationState); } } if (vStateIsBogus(ne.d_validationState)) { lowestTTL = min(lowestTTL, s_maxbogusttl); rec.d_ttl = min(rec.d_ttl, s_maxbogusttl); } ne.d_ttd = d_now.tv_sec + lowestTTL; if (!wasVariable()) { if (qtype.getCode()) { // prevents us from NXDOMAIN'ing a whole domain g_negCache->add(ne); } } ret.push_back(rec); negindic = true; negIndicHasSignatures = !ne.authoritySOA.signatures.empty() || !ne.DNSSECRecords.signatures.empty(); } } } if (!dnameTarget.empty()) { // Synthesize a CNAME auto cnamerec = DNSRecord(); cnamerec.d_name = qname; cnamerec.d_type = QType::CNAME; cnamerec.d_ttl = dnameTTL; cnamerec.d_content = std::make_shared<CNAMERecordContent>(CNAMERecordContent(newtarget)); ret.push_back(std::move(cnamerec)); } /* If we have seen a proper denial, let's forget that we also had a referral for a DS query. Otherwise we need to deal with it. */ if (referralOnDS && !negindic) { LOG(prefix<<qname<<": got a referral to the child zone for a DS query without a negative indication (missing SOA in authority), treating that as a NODATA"<<endl); if (!vStateIsBogus(state)) { auto recordState = getValidationStatus(qname, false, true, depth); if (recordState == vState::Secure) { /* we are in a secure zone, got a referral to the child zone on a DS query, no denial, that's wrong */ LOG(prefix<<qname<<": NODATA without a negative indication (missing SOA in authority) in a DNSSEC secure zone, going Bogus"<<endl); updateValidationState(state, vState::BogusMissingNegativeIndication); } } negindic = true; negIndicHasSignatures = false; } return done; } bool SyncRes::doResolveAtThisIP(const std::string& prefix, const DNSName& qname, const QType qtype, LWResult& lwr, boost::optional<Netmask>& ednsmask, const DNSName& auth, bool const sendRDQuery, const bool wasForwarded, const DNSName& nsName, const ComboAddress& remoteIP, bool doTCP, bool doDoT, bool& truncated, bool& spoofed) { bool chained = false; LWResult::Result resolveret = LWResult::Result::Success; s_outqueries++; d_outqueries++; if(d_outqueries + d_throttledqueries > s_maxqperq) { throw ImmediateServFailException("more than "+std::to_string(s_maxqperq)+" (max-qperq) queries sent while resolving "+qname.toLogString()); } if(s_maxtotusec && d_totUsec > s_maxtotusec) { throw ImmediateServFailException("Too much time waiting for "+qname.toLogString()+"|"+qtype.toString()+", timeouts: "+std::to_string(d_timeouts) +", throttles: "+std::to_string(d_throttledqueries) + ", queries: "+std::to_string(d_outqueries)+", "+std::to_string(d_totUsec/1000)+"msec"); } if(doTCP) { if (doDoT) { LOG(prefix<<qname<<": using DoT with "<< remoteIP.toStringWithPort() <<endl); s_dotoutqueries++; d_dotoutqueries++; } else { LOG(prefix<<qname<<": using TCP with "<< remoteIP.toStringWithPort() <<endl); s_tcpoutqueries++; d_tcpoutqueries++; } } int preOutQueryRet = RCode::NoError; if(d_pdl && d_pdl->preoutquery(remoteIP, d_requestor, qname, qtype, doTCP, lwr.d_records, preOutQueryRet)) { LOG(prefix<<qname<<": query handled by Lua"<<endl); } else { ednsmask=getEDNSSubnetMask(qname, remoteIP); if(ednsmask) { LOG(prefix<<qname<<": Adding EDNS Client Subnet Mask "<<ednsmask->toString()<<" to query"<<endl); s_ecsqueries++; } resolveret = asyncresolveWrapper(remoteIP, d_doDNSSEC, qname, auth, qtype.getCode(), doTCP, sendRDQuery, &d_now, ednsmask, &lwr, &chained); // <- we go out on the wire! if(ednsmask) { s_ecsresponses++; LOG(prefix<<qname<<": Received EDNS Client Subnet Mask "<<ednsmask->toString()<<" on response"<<endl); if (ednsmask->getBits() > 0) { if (ednsmask->isIPv4()) { ++SyncRes::s_ecsResponsesBySubnetSize4.at(ednsmask->getBits()-1); } else { ++SyncRes::s_ecsResponsesBySubnetSize6.at(ednsmask->getBits()-1); } } } } /* preoutquery killed the query by setting dq.rcode to -3 */ if (preOutQueryRet == -3) { throw ImmediateServFailException("Query killed by policy"); } d_totUsec += lwr.d_usec; accountAuthLatency(lwr.d_usec, remoteIP.sin4.sin_family); bool dontThrottle = false; { auto dontThrottleNames = g_dontThrottleNames.getLocal(); auto dontThrottleNetmasks = g_dontThrottleNetmasks.getLocal(); dontThrottle = dontThrottleNames->check(nsName) || dontThrottleNetmasks->match(remoteIP); } if (resolveret != LWResult::Result::Success) { /* Error while resolving */ if (resolveret == LWResult::Result::Timeout) { /* Time out */ LOG(prefix<<qname<<": timeout resolving after "<<lwr.d_usec/1000.0<<"msec "<< (doTCP ? "over TCP" : "")<<endl); d_timeouts++; s_outgoingtimeouts++; if(remoteIP.sin4.sin_family == AF_INET) s_outgoing4timeouts++; else s_outgoing6timeouts++; if(t_timeouts) t_timeouts->push_back(remoteIP); } else if (resolveret == LWResult::Result::OSLimitError) { /* OS resource limit reached */ LOG(prefix<<qname<<": hit a local resource limit resolving"<< (doTCP ? " over TCP" : "")<<", probable error: "<<stringerror()<<endl); g_stats.resourceLimits++; } else if (resolveret == LWResult::Result::Spoofed) { spoofed = true; } else { /* -1 means server unreachable */ s_unreachables++; d_unreachables++; // XXX questionable use of errno LOG(prefix<<qname<<": error resolving from "<<remoteIP.toString()<< (doTCP ? " over TCP" : "") <<", possible error: "<<stringerror()<< endl); } if (resolveret != LWResult::Result::OSLimitError && !chained && !dontThrottle) { // don't account for resource limits, they are our own fault // And don't throttle when the IP address is on the dontThrottleNetmasks list or the name is part of dontThrottleNames t_sstorage.nsSpeeds[nsName.empty()? DNSName(remoteIP.toStringWithPort()) : nsName].submit(remoteIP, 1000000, d_now); // 1 sec // code below makes sure we don't filter COM or the root if (s_serverdownmaxfails > 0 && (auth != g_rootdnsname) && t_sstorage.fails.incr(remoteIP, d_now) >= s_serverdownmaxfails) { LOG(prefix<<qname<<": Max fails reached resolving on "<< remoteIP.toString() <<". Going full throttle for "<< s_serverdownthrottletime <<" seconds" <<endl); // mark server as down t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, "", 0), s_serverdownthrottletime, 10000); } else if (resolveret == LWResult::Result::Timeout) { // unreachable, 1 minute or 100 queries t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()), 60, 100); } else { // timeout, 10 seconds or 5 queries t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()), 10, 5); } } return false; } if (lwr.d_validpacket == false) { LOG(prefix<<qname<<": "<<nsName<<" ("<<remoteIP.toString()<<") returned a packet we could not parse over " << (doTCP ? "TCP" : "UDP") << ", trying sibling IP or NS"<<endl); if (!chained && !dontThrottle) { // let's make sure we prefer a different server for some time, if there is one available t_sstorage.nsSpeeds[nsName.empty()? DNSName(remoteIP.toStringWithPort()) : nsName].submit(remoteIP, 1000000, d_now); // 1 sec if (doTCP) { // we can be more heavy-handed over TCP t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()), 60, 10); } else { t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()), 10, 2); } } return false; } else { /* we got an answer */ if (lwr.d_rcode != RCode::NoError && lwr.d_rcode != RCode::NXDomain) { LOG(prefix<<qname<<": "<<nsName<<" ("<<remoteIP.toString()<<") returned a "<< RCode::to_s(lwr.d_rcode) << ", trying sibling IP or NS"<<endl); if (!chained && !dontThrottle) { if (wasForwarded && lwr.d_rcode == RCode::ServFail) { // rather than throttling what could be the only server we have for this destination, let's make sure we try a different one if there is one available // on the other hand, we might keep hammering a server under attack if there is no other alternative, or the alternative is overwhelmed as well, but // at the very least we will detect that if our packets stop being answered t_sstorage.nsSpeeds[nsName.empty()? DNSName(remoteIP.toStringWithPort()) : nsName].submit(remoteIP, 1000000, d_now); // 1 sec } else { t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()), 60, 3); } } return false; } } /* this server sent a valid answer, mark it backup up if it was down */ if(s_serverdownmaxfails > 0) { t_sstorage.fails.clear(remoteIP); } if (lwr.d_tcbit) { truncated = true; if (doTCP) { LOG(prefix<<qname<<": truncated bit set, over TCP?"<<endl); if (!dontThrottle) { /* let's treat that as a ServFail answer from this server */ t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(remoteIP, qname, qtype.getCode()), 60, 3); } return false; } LOG(prefix<<qname<<": truncated bit set, over UDP"<<endl); return true; } return true; } void SyncRes::handleNewTarget(const std::string& prefix, const DNSName& qname, const DNSName& newtarget, const QType qtype, std::vector<DNSRecord>& ret, int& rcode, int depth, const std::vector<DNSRecord>& recordsFromAnswer, vState& state) { if (newtarget == qname) { LOG(prefix<<qname<<": status=got a CNAME referral to self, returning SERVFAIL"<<endl); ret.clear(); rcode = RCode::ServFail; return; } if (newtarget.isPartOf(qname)) { // a.b.c. CNAME x.a.b.c will go to great depths with QM on LOG(prefix<<qname<<": status=got a CNAME referral to child, disabling QM"<<endl); setQNameMinimization(false); } if (depth > 10) { LOG(prefix<<qname<<": status=got a CNAME referral, but recursing too deep, returning SERVFAIL"<<endl); rcode = RCode::ServFail; return; } if (!d_followCNAME) { rcode = RCode::NoError; return; } // Check to see if we already have seen the new target as a previous target if (scanForCNAMELoop(newtarget, ret)) { LOG(prefix<<qname<<": status=got a CNAME referral that causes a loop, returning SERVFAIL"<<endl); ret.clear(); rcode = RCode::ServFail; return; } if (qtype == QType::DS || qtype == QType::DNSKEY) { LOG(prefix<<qname<<": status=got a CNAME referral, but we are looking for a DS or DNSKEY"<<endl); if (d_doDNSSEC) { addNXNSECS(ret, recordsFromAnswer); } rcode = RCode::NoError; return; } LOG(prefix<<qname<<": status=got a CNAME referral, starting over with "<<newtarget<<endl); set<GetBestNSAnswer> beenthere; vState cnameState = vState::Indeterminate; rcode = doResolve(newtarget, qtype, ret, depth + 1, beenthere, cnameState); LOG(prefix<<qname<<": updating validation state for response to "<<qname<<" from "<<state<<" with the state from the CNAME quest: "<<cnameState<<endl); updateValidationState(state, cnameState); } bool SyncRes::processAnswer(unsigned int depth, LWResult& lwr, const DNSName& qname, const QType qtype, DNSName& auth, bool wasForwarded, const boost::optional<Netmask> ednsmask, bool sendRDQuery, NsSet &nameservers, std::vector<DNSRecord>& ret, const DNSFilterEngine& dfe, bool* gotNewServers, int* rcode, vState& state, const ComboAddress& remoteIP) { string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } if(s_minimumTTL) { for(auto& rec : lwr.d_records) { rec.d_ttl = max(rec.d_ttl, s_minimumTTL); } } /* if the answer is ECS-specific, a minimum TTL is set for this kind of answers and it's higher than the global minimum TTL */ if (ednsmask && s_minimumECSTTL > 0 && (s_minimumTTL == 0 || s_minimumECSTTL > s_minimumTTL)) { for(auto& rec : lwr.d_records) { if (rec.d_place == DNSResourceRecord::ANSWER) { rec.d_ttl = max(rec.d_ttl, s_minimumECSTTL); } } } bool needWildcardProof = false; bool gatherWildcardProof = false; unsigned int wildcardLabelsCount; *rcode = updateCacheFromRecords(depth, lwr, qname, qtype, auth, wasForwarded, ednsmask, state, needWildcardProof, gatherWildcardProof, wildcardLabelsCount, sendRDQuery, remoteIP); if (*rcode != RCode::NoError) { return true; } LOG(prefix<<qname<<": determining status after receiving this packet"<<endl); set<DNSName> nsset; bool realreferral = false; bool negindic = false; bool negIndicHasSignatures = false; DNSName newauth; DNSName newtarget; bool done = processRecords(prefix, qname, qtype, auth, lwr, sendRDQuery, ret, nsset, newtarget, newauth, realreferral, negindic, state, needWildcardProof, gatherWildcardProof, wildcardLabelsCount, *rcode, negIndicHasSignatures, depth); if (done){ LOG(prefix<<qname<<": status=got results, this level of recursion done"<<endl); LOG(prefix<<qname<<": validation status is "<<state<<endl); return true; } if (!newtarget.empty()) { handleNewTarget(prefix, qname, newtarget, qtype.getCode(), ret, *rcode, depth, lwr.d_records, state); return true; } if (lwr.d_rcode == RCode::NXDomain) { LOG(prefix<<qname<<": status=NXDOMAIN, we are done "<<(negindic ? "(have negative SOA)" : "")<<endl); auto tempState = getValidationStatus(qname, negIndicHasSignatures, qtype == QType::DS, depth); if (tempState == vState::Secure && (lwr.d_aabit || sendRDQuery) && !negindic) { LOG(prefix<<qname<<": NXDOMAIN without a negative indication (missing SOA in authority) in a DNSSEC secure zone, going Bogus"<<endl); updateValidationState(state, vState::BogusMissingNegativeIndication); } else if (state == vState::Indeterminate) { /* we might not have validated any record, because we did get a NXDOMAIN without any SOA from an insecure zone, for example */ updateValidationState(state, tempState); } if (d_doDNSSEC) { addNXNSECS(ret, lwr.d_records); } *rcode = RCode::NXDomain; return true; } if (nsset.empty() && !lwr.d_rcode && (negindic || lwr.d_aabit || sendRDQuery)) { LOG(prefix<<qname<<": status=noerror, other types may exist, but we are done "<<(negindic ? "(have negative SOA) " : "")<<(lwr.d_aabit ? "(have aa bit) " : "")<<endl); auto tempState = getValidationStatus(qname, negIndicHasSignatures, qtype == QType::DS, depth); if (tempState == vState::Secure && (lwr.d_aabit || sendRDQuery) && !negindic) { LOG(prefix<<qname<<": NODATA without a negative indication (missing SOA in authority) in a DNSSEC secure zone, going Bogus"<<endl); updateValidationState(state, vState::BogusMissingNegativeIndication); } else if (state == vState::Indeterminate) { /* we might not have validated any record, because we did get a NODATA without any SOA from an insecure zone, for example */ updateValidationState(state, tempState); } if (d_doDNSSEC) { addNXNSECS(ret, lwr.d_records); } *rcode = RCode::NoError; return true; } if(realreferral) { LOG(prefix<<qname<<": status=did not resolve, got "<<(unsigned int)nsset.size()<<" NS, "); nameservers.clear(); for (auto const &nameserver : nsset) { if (d_wantsRPZ && !d_appliedPolicy.wasHit()) { bool match = dfe.getProcessingPolicy(nameserver, d_discardedPolicies, d_appliedPolicy); if (match) { mergePolicyTags(d_policyTags, d_appliedPolicy.getTags()); if (d_appliedPolicy.d_kind != DNSFilterEngine::PolicyKind::NoAction) { // client query needs an RPZ response if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) { /* reset to no match */ d_appliedPolicy = DNSFilterEngine::Policy(); } else { LOG("however "<<nameserver<<" was blocked by RPZ policy '"<<d_appliedPolicy.getName()<<"'"<<endl); throw PolicyHitException(); } } } } nameservers.insert({nameserver, {{}, false}}); } LOG("looping to them"<<endl); *gotNewServers = true; auth=newauth; return false; } return false; } bool SyncRes::doDoTtoAuth(const DNSName& ns) const { return g_DoTToAuthNames.getLocal()->check(ns); } /** returns: * -1 in case of no results * rcode otherwise */ int SyncRes::doResolveAt(NsSet &nameservers, DNSName auth, bool flawedNSSet, const DNSName &qname, const QType qtype, vector<DNSRecord>&ret, unsigned int depth, set<GetBestNSAnswer>&beenthere, vState& state, StopAtDelegation* stopAtDelegation) { auto luaconfsLocal = g_luaconfs.getLocal(); string prefix; if(doLog()) { prefix=d_prefix; prefix.append(depth, ' '); } LOG(prefix<<qname<<": Cache consultations done, have "<<(unsigned int)nameservers.size()<<" NS to contact"); if (nameserversBlockedByRPZ(luaconfsLocal->dfe, nameservers)) { /* RPZ hit */ if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) { /* reset to no match */ d_appliedPolicy = DNSFilterEngine::Policy(); } else { throw PolicyHitException(); } } LOG(endl); unsigned int addressQueriesForNS = 0; for(;;) { // we may get more specific nameservers auto rnameservers = shuffleInSpeedOrder(nameservers, doLog() ? (prefix+qname.toString()+": ") : string() ); // We allow s_maxnsaddressqperq (default 10) queries with empty responses when resolving NS names. // If a zone publishes many (more than s_maxnsaddressqperq) NS records, we allow less. // This is to "punish" zones that publish many non-resolving NS names. // We always allow 5 NS name resolving attempts with empty results. unsigned int nsLimit = s_maxnsaddressqperq; if (rnameservers.size() > nsLimit) { int newLimit = static_cast<int>(nsLimit) - (rnameservers.size() - nsLimit); nsLimit = std::max(5, newLimit); } for(auto tns=rnameservers.cbegin();;++tns) { if (addressQueriesForNS >= nsLimit) { throw ImmediateServFailException(std::to_string(nsLimit)+" (adjusted max-ns-address-qperq) or more queries with empty results for NS addresses sent resolving "+qname.toLogString()); } if(tns==rnameservers.cend()) { LOG(prefix<<qname<<": Failed to resolve via any of the "<<(unsigned int)rnameservers.size()<<" offered NS at level '"<<auth<<"'"<<endl); if(!auth.isRoot() && flawedNSSet) { LOG(prefix<<qname<<": Ageing nameservers for level '"<<auth<<"', next query might succeed"<<endl); if(g_recCache->doAgeCache(d_now.tv_sec, auth, QType::NS, 10)) g_stats.nsSetInvalidations++; } return -1; } bool cacheOnly = false; // this line needs to identify the 'self-resolving' behaviour if(qname == tns->first && (qtype.getCode() == QType::A || qtype.getCode() == QType::AAAA)) { /* we might have a glue entry in cache so let's try this NS but only if we have enough in the cache to know how to reach it */ LOG(prefix<<qname<<": Using NS to resolve itself, but only using what we have in cache ("<<(1+tns-rnameservers.cbegin())<<"/"<<rnameservers.size()<<")"<<endl); cacheOnly = true; } typedef vector<ComboAddress> remoteIPs_t; remoteIPs_t remoteIPs; remoteIPs_t::iterator remoteIP; bool pierceDontQuery=false; bool sendRDQuery=false; boost::optional<Netmask> ednsmask; LWResult lwr; const bool wasForwarded = tns->first.empty() && (!nameservers[tns->first].first.empty()); int rcode = RCode::NoError; bool gotNewServers = false; if (tns->first.empty() && !wasForwarded) { static ComboAddress const s_oobRemote("255.255.255.255"); LOG(prefix<<qname<<": Domain is out-of-band"<<endl); /* setting state to indeterminate since validation is disabled for local auth zone, and Insecure would be misleading. */ state = vState::Indeterminate; d_wasOutOfBand = doOOBResolve(qname, qtype, lwr.d_records, depth, lwr.d_rcode); lwr.d_tcbit=false; lwr.d_aabit=true; /* we have received an answer, are we done ? */ bool done = processAnswer(depth, lwr, qname, qtype, auth, false, ednsmask, sendRDQuery, nameservers, ret, luaconfsLocal->dfe, &gotNewServers, &rcode, state, s_oobRemote); if (done) { return rcode; } if (gotNewServers) { if (stopAtDelegation && *stopAtDelegation == Stop) { *stopAtDelegation = Stopped; return rcode; } break; } } else { /* if tns is empty, retrieveAddressesForNS() knows we have hardcoded servers (i.e. "forwards") */ remoteIPs = retrieveAddressesForNS(prefix, qname, tns, depth, beenthere, rnameservers, nameservers, sendRDQuery, pierceDontQuery, flawedNSSet, cacheOnly, addressQueriesForNS); if(remoteIPs.empty()) { LOG(prefix<<qname<<": Failed to get IP for NS "<<tns->first<<", trying next if available"<<endl); flawedNSSet=true; continue; } else { bool hitPolicy{false}; LOG(prefix<<qname<<": Resolved '"<<auth<<"' NS "<<tns->first<<" to: "); for(remoteIP = remoteIPs.begin(); remoteIP != remoteIPs.end(); ++remoteIP) { if(remoteIP != remoteIPs.begin()) { LOG(", "); } LOG(remoteIP->toString()); if(nameserverIPBlockedByRPZ(luaconfsLocal->dfe, *remoteIP)) { hitPolicy = true; } } LOG(endl); if (hitPolicy) { //implies d_wantsRPZ /* RPZ hit */ if (d_pdl && d_pdl->policyHitEventFilter(d_requestor, qname, qtype, d_queryReceivedOverTCP, d_appliedPolicy, d_policyTags, d_discardedPolicies)) { /* reset to no match */ d_appliedPolicy = DNSFilterEngine::Policy(); } else { throw PolicyHitException(); } } } for(remoteIP = remoteIPs.begin(); remoteIP != remoteIPs.end(); ++remoteIP) { LOG(prefix<<qname<<": Trying IP "<< remoteIP->toStringWithPort() <<", asking '"<<qname<<"|"<<qtype<<"'"<<endl); if (throttledOrBlocked(prefix, *remoteIP, qname, qtype, pierceDontQuery)) { continue; } bool truncated = false; bool spoofed = false; bool gotAnswer = false; bool doDoT = false; if (doDoTtoAuth(tns->first)) { remoteIP->setPort(853); doDoT = true; } if (SyncRes::s_dot_to_port_853 && remoteIP->getPort() == 853) { doDoT = true; } bool forceTCP = doDoT; if (!forceTCP) { gotAnswer = doResolveAtThisIP(prefix, qname, qtype, lwr, ednsmask, auth, sendRDQuery, wasForwarded, tns->first, *remoteIP, false, false, truncated, spoofed); } if (forceTCP || (spoofed || (gotAnswer && truncated))) { /* retry, over TCP this time */ gotAnswer = doResolveAtThisIP(prefix, qname, qtype, lwr, ednsmask, auth, sendRDQuery, wasForwarded, tns->first, *remoteIP, true, doDoT, truncated, spoofed); } if (!gotAnswer) { continue; } LOG(prefix<<qname<<": Got "<<(unsigned int)lwr.d_records.size()<<" answers from "<<tns->first<<" ("<< remoteIP->toString() <<"), rcode="<<lwr.d_rcode<<" ("<<RCode::to_s(lwr.d_rcode)<<"), aa="<<lwr.d_aabit<<", in "<<lwr.d_usec/1000<<"ms"<<endl); /* // for you IPv6 fanatics :-) if(remoteIP->sin4.sin_family==AF_INET6) lwr.d_usec/=3; */ // cout<<"msec: "<<lwr.d_usec/1000.0<<", "<<g_avgLatency/1000.0<<'\n'; t_sstorage.nsSpeeds[tns->first.empty()? DNSName(remoteIP->toStringWithPort()) : tns->first].submit(*remoteIP, lwr.d_usec, d_now); /* we have received an answer, are we done ? */ bool done = processAnswer(depth, lwr, qname, qtype, auth, wasForwarded, ednsmask, sendRDQuery, nameservers, ret, luaconfsLocal->dfe, &gotNewServers, &rcode, state, *remoteIP); if (done) { return rcode; } if (gotNewServers) { if (stopAtDelegation && *stopAtDelegation == Stop) { *stopAtDelegation = Stopped; return rcode; } break; } /* was lame */ t_sstorage.throttle.throttle(d_now.tv_sec, boost::make_tuple(*remoteIP, qname, qtype.getCode()), 60, 100); } if (gotNewServers) { break; } if(remoteIP == remoteIPs.cend()) // we tried all IP addresses, none worked continue; } } } return -1; } void SyncRes::setQuerySource(const ComboAddress& requestor, boost::optional<const EDNSSubnetOpts&> incomingECS) { d_requestor = requestor; if (incomingECS && incomingECS->source.getBits() > 0) { d_cacheRemote = incomingECS->source.getMaskedNetwork(); uint8_t bits = std::min(incomingECS->source.getBits(), (incomingECS->source.isIPv4() ? s_ecsipv4limit : s_ecsipv6limit)); ComboAddress trunc = incomingECS->source.getNetwork(); trunc.truncate(bits); d_outgoingECSNetwork = boost::optional<Netmask>(Netmask(trunc, bits)); } else { d_cacheRemote = d_requestor; if(!incomingECS && s_ednslocalsubnets.match(d_requestor)) { ComboAddress trunc = d_requestor; uint8_t bits = d_requestor.isIPv4() ? 32 : 128; bits = std::min(bits, (trunc.isIPv4() ? s_ecsipv4limit : s_ecsipv6limit)); trunc.truncate(bits); d_outgoingECSNetwork = boost::optional<Netmask>(Netmask(trunc, bits)); } else if (s_ecsScopeZero.source.getBits() > 0) { /* RFC7871 says we MUST NOT send any ECS if the source scope is 0. But using an empty ECS in that case would mean inserting a non ECS-specific entry into the cache, preventing any further ECS-specific query to be sent. So instead we use the trick described in section 7.1.2: "The subsequent Recursive Resolver query to the Authoritative Nameserver will then either not include an ECS option or MAY optionally include its own address information, which is what the Authoritative Nameserver will almost certainly use to generate any Tailored Response in lieu of an option. This allows the answer to be handled by the same caching mechanism as other queries, with an explicit indicator of the applicable scope. Subsequent Stub Resolver queries for /0 can then be answered from this cached response. */ d_outgoingECSNetwork = boost::optional<Netmask>(s_ecsScopeZero.source.getMaskedNetwork()); d_cacheRemote = s_ecsScopeZero.source.getNetwork(); } else { // ECS disabled because no scope-zero address could be derived. d_outgoingECSNetwork = boost::none; } } } boost::optional<Netmask> SyncRes::getEDNSSubnetMask(const DNSName& dn, const ComboAddress& rem) { if(d_outgoingECSNetwork && (s_ednsdomains.check(dn) || s_ednsremotesubnets.match(rem))) { return d_outgoingECSNetwork; } return boost::none; } void SyncRes::parseEDNSSubnetAllowlist(const std::string& alist) { vector<string> parts; stringtok(parts, alist, ",; "); for(const auto& a : parts) { try { s_ednsremotesubnets.addMask(Netmask(a)); } catch(...) { s_ednsdomains.add(DNSName(a)); } } } void SyncRes::parseEDNSSubnetAddFor(const std::string& subnetlist) { vector<string> parts; stringtok(parts, subnetlist, ",; "); for(const auto& a : parts) { s_ednslocalsubnets.addMask(a); } } // used by PowerDNSLua - note that this neglects to add the packet count & statistics back to pdns_recursor.cc int directResolve(const DNSName& qname, const QType qtype, const QClass qclass, vector<DNSRecord>& ret) { return directResolve(qname, qtype, qclass, ret, SyncRes::s_qnameminimization); } int directResolve(const DNSName& qname, const QType qtype, const QClass qclass, vector<DNSRecord>& ret, bool qm) { struct timeval now; gettimeofday(&now, 0); SyncRes sr(now); sr.setQNameMinimization(qm); int res = -1; try { res = sr.beginResolve(qname, qtype, qclass, ret, 0); } catch(const PDNSException& e) { g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got pdns exception: "<<e.reason<<endl; ret.clear(); } catch(const ImmediateServFailException& e) { g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got ImmediateServFailException: "<<e.reason<<endl; ret.clear(); } catch(const PolicyHitException& e) { g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got a policy hit"<<endl; ret.clear(); } catch(const std::exception& e) { g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got STL error: "<<e.what()<<endl; ret.clear(); } catch(...) { g_log<<Logger::Error<<"Failed to resolve "<<qname<<", got an exception"<<endl; ret.clear(); } return res; } int SyncRes::getRootNS(struct timeval now, asyncresolve_t asyncCallback, unsigned int depth) { SyncRes sr(now); sr.setDoEDNS0(true); sr.setUpdatingRootNS(); sr.setDoDNSSEC(g_dnssecmode != DNSSECMode::Off); sr.setDNSSECValidationRequested(g_dnssecmode != DNSSECMode::Off && g_dnssecmode != DNSSECMode::ProcessNoValidate); sr.setAsyncCallback(asyncCallback); vector<DNSRecord> ret; int res=-1; try { res=sr.beginResolve(g_rootdnsname, QType::NS, 1, ret, depth + 1); if (g_dnssecmode != DNSSECMode::Off && g_dnssecmode != DNSSECMode::ProcessNoValidate) { auto state = sr.getValidationState(); if (vStateIsBogus(state)) { throw PDNSException("Got Bogus validation result for .|NS"); } } } catch(const PDNSException& e) { g_log<<Logger::Error<<"Failed to update . records, got an exception: "<<e.reason<<endl; } catch(const ImmediateServFailException& e) { g_log<<Logger::Error<<"Failed to update . records, got an exception: "<<e.reason<<endl; } catch(const PolicyHitException& e) { g_log<<Logger::Error<<"Failed to update . records, got a policy hit"<<endl; ret.clear(); } catch(const std::exception& e) { g_log<<Logger::Error<<"Failed to update . records, got an exception: "<<e.what()<<endl; } catch(...) { g_log<<Logger::Error<<"Failed to update . records, got an exception"<<endl; } if(!res) { g_log<<Logger::Notice<<"Refreshed . records"<<endl; } else g_log<<Logger::Warning<<"Failed to update . records, RCODE="<<res<<endl; return res; }
gpl-2.0
hijoy/VSL_ERS
WebUI/MasterPage.master.cs
7077
using System; using System.Data; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using BusinessObjects; using BusinessObjects.AuthorizationDSTableAdapters; public partial class MasterPage : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { Response.Cache.SetCacheability(HttpCacheability.NoCache); //lwy, migrate from mainpage if (Session["StuffUser"] == null) { this.NavigateMenu.Visible = false; return; } if (!IsPostBack) { AuthorizationDS.StuffUserRow stuffUser = (AuthorizationDS.StuffUserRow)Session["StuffUser"]; if (Session["ProxyStuffUserId"] != null) { this.Session["Position"] = new OUTreeBLL().GetPositionById((int)Session["PositionId"]); this.Session["StuffUser"] = new StuffUserBLL().GetStuffUserById((int)Session["StuffUserId"])[0]; List<string> useRootItems = new List<string>(); useRootItems.Add(" ÉêÇëÓ뱨Ïú"); //useRootItems.Add("¸öÈË·ÑÓñ¨ÏúÉêÇë"); //useRootItems.Add("³ö²îÉêÇë"); //useRootItems.Add("³ö²î±¨ÏúÉêÇë"); this.CustomizeNavigateMenu(); List<MenuItem> noUseRootItems = new List<MenuItem>(); foreach (MenuItem rootItem in this.NavigateMenu.Items) { if (!useRootItems.Contains(rootItem.Text)) { noUseRootItems.Add(rootItem); } } foreach (MenuItem noUseRootItem in noUseRootItems) { this.NavigateMenu.Items.Remove(noUseRootItem); } this.CustomizeNavigateMenu(); } else { AuthorizationBLL bll = new AuthorizationBLL(); AuthorizationDS.PositionDataTable positions = bll.GetPositionByStuffUser(stuffUser.StuffUserId); if (positions.Count == 0) { PageUtility.ShowModelDlg(this.Page, "ûÓÐÉèÖÃÖ°Îñ,ÇëÁªÏµÏµÍ³¹ÜÀíÔ±"); this.Response.Redirect("~/ErrorPage/NoPositionErrorPage.aspx"); return; } this.PositionSelectCtl.Items.Clear(); foreach (AuthorizationDS.PositionRow position in positions) { this.PositionSelectCtl.Items.Add(new ListItem(position.PositionName, position.PositionId.ToString())); } if (positions.Count > 0) { this.PositionSelectCtl.Visible = true; this.PositionSelectLabel.Visible = true; } if (this.Session["SelectedPosition"] == null) { int currentPositionId = int.Parse(this.PositionSelectCtl.SelectedValue); Session["Position"] = new OUTreeBLL().GetPositionById(currentPositionId); } else { Session["Position"] = Session["SelectedPosition"]; this.PositionSelectCtl.SelectedValue = ((AuthorizationDS.PositionRow)Session["Position"]).PositionId.ToString(); } if (Session["Position"] == null) { int currentPositionId = int.Parse(this.PositionSelectCtl.SelectedValue); Session["Position"] = new OUTreeBLL().GetPositionById(currentPositionId); } else { this.PositionSelectCtl.SelectedValue = ((AuthorizationDS.PositionRow)Session["Position"]).PositionId.ToString(); } } AuthorizationDS.StuffUserRow user = (AuthorizationDS.StuffUserRow)Session["StuffUser"]; this.StuffNameCtl.Text = user.StuffName; this.LastLogInTimeCtl.Text = user.IsLaterLogInTimeNull() ? "" : user.LaterLogInTime.ToShortDateString(); } this.CustomizeNavigateMenu(); } protected void Page_Error(Object sender, EventArgs args) { Exception e = Server.GetLastError(); this.ModelDlgContentLiteral.Text = e.Message; this.ModelDlg.Style["display"] = "none"; this.ModelDlgUpdatePanel.Update(); Server.ClearError(); } protected void ScriptManager1_AsyncPostBackError(object sender, AsyncPostBackErrorEventArgs e) { throw e.Exception; } ///lwy, migrate from main page private void CustomizeNavigateMenu() { List<MenuItem> rootItems = new List<MenuItem>(); foreach (MenuItem rootItem in this.NavigateMenu.Items) { rootItems.Add(rootItem); } List<string> uiEntryCodes = new List<string>(); uiEntryCodes.AddRange(new AuthorizationBLL().GetEnabledUIEntryCode(((AuthorizationDS.PositionRow)this.Session["Position"]).PositionId)); foreach (MenuItem item in rootItems) { this.CheckItemRight(item, uiEntryCodes); } } private void CheckItemRight(MenuItem item, List<string> uiEntryCodes) { if (item.Value.Equals("Folder")) { List<MenuItem> childItems = new List<MenuItem>(); foreach (MenuItem childItem in item.ChildItems) { childItems.Add(childItem); } foreach (MenuItem childItem in childItems) { if (Session["ProxyStuffUserId"] != null && (childItem.Text == "µÈ´ýÎÒÈ·ÈÏÖ´ÐеÄÉêÇëµ¥" || childItem.Text == "·½°¸±¨Ïú")) { RemoveItem(childItem); } CheckItemRight(childItem, uiEntryCodes); } if (item.ChildItems.Count == 0) { RemoveItem(item); } } else if (!item.Value.Equals("open")) { if (!uiEntryCodes.Contains(item.Value)) { RemoveItem(item); } } } private void RemoveItem(MenuItem item) { if (item.Parent != null) { item.Parent.ChildItems.Remove(item); } else { this.NavigateMenu.Items.Remove(item); } } protected void PositionSelectCtl_SelectedIndexChanged(object sender, EventArgs e) { int currentPositionId = int.Parse(this.PositionSelectCtl.SelectedValue); Session["SelectedPosition"] = new OUTreeBLL().GetPositionById(currentPositionId); //Response.Redirect("~/MainPage.aspx"); Response.Redirect("~/Home.aspx"); } protected void LogOutBtn_Click(object sender, EventArgs e) { Session.Clear(); Response.Redirect("~/LogIn.aspx"); } protected void ModelDlgCloseBtn_Click(object sender, EventArgs e) { HtmlControl panel = (HtmlControl)this.FindControl("ModelDlg"); panel.Style["display"] = "none"; this.ModelDlgUpdatePanel.Update(); } public String divAlert_ClientID { get { return this.ModelDlgUpdatePanel.FindControl("divAlert").ClientID; } } }
gpl-2.0
denis-chmel/wordpress
wp-content/plugins/optimizePressPlugin/lib/functions/assets.php
22589
<?php class OptimizePress_Assets_Core { var $included_assets = array(); var $assets = array(); var $asset_keys = array(); var $parse_list = array(); var $lang; function __construct(){ global $wpdb; if(op_get_option('installed') == 'Y'){ require_once OP_ASSETS.'default.php'; $assets = $wpdb->get_col( "SELECT name FROM `{$wpdb->prefix}optimizepress_assets`" ); if($assets){ foreach($assets as $asset){ $this->load_addon($asset); } } add_action('wp_ajax_'.OP_SN.'-assets-folder-list', array($this, 'folder_list')); /* * Email marketing services integration hooks */ add_action('wp_ajax_'.OP_SN.'-email-provider-list', array($this, 'providerList')); add_action('wp_ajax_'.OP_SN.'-email-provider-details', array($this, 'providerDetails')); add_action('wp_ajax_'.OP_SN.'-email-provider-items', array($this, 'providerItems')); add_action('wp_ajax_'.OP_SN.'-email-provider-item-fields', array($this, 'providerItemFields')); /** * Live search hooks */ add_action('wp_ajax_'.OP_SN.'-live-search', array($this, 'liveSearch')); add_action('wp_ajax_nopriv_'.OP_SN.'-live-search', array($this, 'liveSearch')); add_filter('the_content',array($this,'fixptag')); /* * Content template */ add_action('wp_ajax_' . OP_SN . '-content-layout-delete', array($this, 'deleteContentLayout')); } } function deleteContentLayout() { check_ajax_referer('op_content_layout_delete', 'nonce'); $le = new OptimizePress_LiveEditor(); if ($le->delete_content_layout(op_post('layout')) == 1) { wp_send_json_success(); } else { wp_send_json_error(); } } /** * Returns list of enabled email marketing service providers * @author Luka Peharda <luka.peharda@gmail.com> * @return void */ function providerList() { require_once(OP_LIB . 'sections/dashboard/email_marketing_services.php'); require_once(OP_MOD . 'email/ProviderFactory.php'); $enabledProviders = array(); $services = new OptimizePress_Sections_Email_Marketing_Services(); $providers = $services->sections(); if (is_array($providers) && count($providers) > 0) { foreach ($providers as $type => $service) { /* * Removing GoToWebinar from provider list */ if ('gotowebinar' === $type) { continue; } $provider = OptimizePress_Modules_Email_ProviderFactory::getFactory($type, true); if (null !== $provider && true === $provider->isEnabled()) { $enabledProviders[$type] = $service['title']; } } } $arg = func_get_arg(0); if (empty($arg)) { echo json_encode(array('providers' => $enabledProviders)); /* * Every WP ajax function needs to be exited */ exit(); } return $enabledProviders; } /** * Outputs (JSON) email marketing service provider data (lists/forms) * @author Luka Peharda <luka.peharda@gmail.com> * @param string $provider * @param bool $return * @param bool $special * @return void */ function providerItems($type = null, $return = null, $special = null) { require_once(OP_MOD . 'email/ProviderFactory.php'); /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($type)) { $type = op_post('provider'); } /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($special)) { $special = (bool) op_post('special'); } $provider = OptimizePress_Modules_Email_ProviderFactory::getFactory($type, true); if (null === $provider) { exit(); } try { if ($type === 'infusionsoft' && $special === true) { $data = $provider->getFollowUpSequences(); } else { $data = $provider->getItems(); } } catch (Exception $e) { error_log('There seems to be an error with the integration data for "' . $type . '". Check EMS integration data for this provider.'); $data['lists'] = array('error' => array('name' => __('There seems to be an error with the integration data.', OP_SN))); } if (null === $return) { echo json_encode($data); /* * Every WP ajax function needs to be exited */ exit(); } return $data; } /** * Outputs (JSON) email marketing service provider data (lists/forms) * @author Luka Peharda <luka.peharda@gmail.com> * @param string $type * @param string $list * @param bool $return * @return void */ function providerItemFields($type = null, $list = null, $return = null) { require_once(OP_MOD . 'email/ProviderFactory.php'); /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($type)) { $type = op_post('provider'); } /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($list)) { $list = op_post('list'); } /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($special)) { $special = (bool) op_post('special'); } $provider = OptimizePress_Modules_Email_ProviderFactory::getFactory($type, true); if (null === $provider) { exit(); } if (empty($list)) { exit(); } $data = $provider->getListFields($list); if (null === $return) { echo json_encode($data); /* * Every WP ajax function needs to be exited */ exit(); } return $data; } /** * Outputs (JSON) email marketing service provider data (just list names and IDs) * @author Luka Peharda <luka.peharda@gmail.com> * @param string $provider * @param bool $return * @param bool $special * @return void */ function providerDetails($type = null, $return = null, $special = null) { require_once(OP_MOD . 'email/ProviderFactory.php'); /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($type)) { $type = op_post('provider'); } /* * If $type is not null that means that we are not calling this method via AJAX */ if (empty($special)) { $special = (bool) op_post('special'); } $provider = OptimizePress_Modules_Email_ProviderFactory::getFactory($type, true); if (null === $provider) { exit(); } if ($type === 'infusionsoft' && $special === true) { $data = $provider->getFollowUpSequences(); } else { $data = $provider->getData(); } if (null === $return) { echo json_encode($data); /* * Every WP ajax function needs to be exited */ exit(); } return $data; } /** * Returns provider enabled status * @author Luka Peharda <luka.peharda@gmail.com> * @param string $type * @return bool */ function providerEnabled($type) { require_once(OP_MOD . 'email/ProviderFactory.php'); $provider = OptimizePress_Modules_Email_ProviderFactory::getFactory($type, true); return $provider->isEnabled(); } /** * Registers user on provider * @author Luka Peharda <luka.peharda@gmail.com> * @param string $type * @param string $list * @param string $email * @param string $fname * @param string $lname * @return bool */ function providerRegister($type, $list, $email, $fname, $lname) { require_once(OP_MOD . 'email/ProviderFactory.php'); $provider = OptimizePress_Modules_Email_ProviderFactory::getFactory($type, true); return $provider->register($list, $email, $fname, $lname); } /** * Live Search function called from the live search element on key up or pressed enter * @author Zvonko Biškup <zbiskup@gmail.com> * @return string */ function liveSearch() { global $wpdb; if (!empty($_POST['all_pages'])) { // search through all pages $sql = " SELECT ID, post_title FROM $wpdb->posts WHERE post_status = 'publish' AND post_title LIKE '%".esc_sql($_POST['searchTerm'])."%' ORDER BY post_title LIMIT 10 "; $results = $wpdb->get_results($sql); } else { if (!empty($_POST['product']) && empty($_POST['category']) && empty($_POST['subcategory'])) { //within product subpages $post_parent = esc_sql($_POST['product']); } else if (!empty($_POST['product']) && !empty($_POST['category']) && empty($_POST['subcategory'])) { $post_parent = esc_sql($_POST['category']); } else if (!empty($_POST['product']) && !empty($_POST['category']) && !empty($_POST['subcategory'])) { $post_parent = esc_sql($_POST['subcategory']); } $temp = get_pages('child_of='.$post_parent); $results = array(); if (!empty($temp)) { foreach($temp as $result) { if (false !== stripos($result->post_title, esc_sql($_POST['searchTerm']))) { $obj = new stdClass(); $obj->ID = $result->ID; $obj->post_title = $result->post_title; array_push($results, $obj); } } } } if (!empty($results)) { foreach ($results as $result) { echo '<li class="op-live-search-results-item"><a href="'.get_permalink($result->ID).'">'.$result->post_title.'</a></li>'; } } else { echo '<li class="op-live-search-results-item op-live-search-results-item--empty">' . __('No results', OP_SN) . '</li>'; } exit(); } function fixptag($pee){ $pee = preg_replace('!\]<br \/>\s*<h([1-6]*)!i',']<h$1',$pee); $pee = preg_replace('!<p>\s*\[\/!', "[/", $pee); return $pee; } function assets($group='',$asset='',$clear=false){ global $wpdb; if(count($this->assets) == 0 || $clear){ $assets = array('core'=>array(),'addon'=>array(),'theme'=>array()); $assets = apply_filters('op_assets_before_addons',$assets); $assets_results = $wpdb->get_results( "SELECT name,title,settings FROM `{$wpdb->prefix}optimizepress_assets` ORDER BY title ASC" ); if($assets_results){ foreach($assets_results as $result){ $assets['addon'][$result->name] = array( 'title' => $result->title, 'settings' => $result->settings, ); } } $assets = apply_filters('op_assets_after_addons',$assets); $this->assets = array_filter($assets); } if(count($this->assets) > 0 && !empty($group)){ return isset($this->assets[$group]) && isset($this->assets[$group][$asset]) ? $this->assets[$group][$asset] : false; } return $this->assets; } function parse_assets(){ if(count($this->parse_list) == 0){ $assets = array(); $assets = apply_filters('op_assets_parse_list',$assets); $this->parse_list = array_filter($assets); } return $this->parse_list; } function lang(){ if(!isset($this->lang)){ $arr = array(); if(file_exists(OP_LIB.'js/assets/lang.php')){ include OP_LIB.'js/assets/lang.php'; } $this->lang = apply_filters(OP_SN.'-asset-lang',$arr); } return $this->lang; } function lang_key($key){ $lang = $this->lang(); if(isset($lang[$key])){ return $lang[$key]; } return $key; } function asset_keys(){ if(count($this->assets) == 0){ $this->assets(); } if(count($this->asset_keys) == 0){ $keys = array(); foreach($this->assets as $assets){ $keys = array_merge($keys,$assets); } $this->asset_keys = array_keys($keys); } return $this->asset_keys; } function refresh_assets($asset='',$clear=false){ static $assets; if(!isset($assets) || $clear){ $assets = apply_filters('op_addon_assets',array()); $assets = array_filter($assets); } if(!empty($asset)){ return isset($assets[$asset]) ? $assets[$asset] : false; } return $assets; } function save_assets(){ global $wpdb; $dir = @ dir(OP_ASSETS.'addon'); if($dir){ while(($file = $dir->read()) !== false){ if($file != '.' && $file != '..' && $file != 'index.php' && strpos($file, '.') !== 0){ $this->load_addon($file); } } } $assets = $this->refresh_assets('','',true); $keys = array_keys($assets); $str = ''; for($i=0,$il=count($keys);$i<$il;$i++){ $str .= ($str == '' ? '' :',').'%s'; } /* * On some occasions $str was empty and this is a check for it. I don't know what this table does or if it is used in any way */ if (empty($str)) { $wpdb->query("DELETE FROM `{$wpdb->prefix}optimizepress_assets`"); } else { $wpdb->query($wpdb->prepare("DELETE FROM `{$wpdb->prefix}optimizepress_assets` WHERE name NOT IN({$str})",$keys)); } foreach($assets as $tag => $info){ $this->check_add($tag,$info['title'],op_get_var($info,'settings','N')); } } function check_add($name,$title,$settings='N'){ global $wpdb; $entry = $wpdb->get_col( $wpdb->prepare( "SELECT id FROM `{$wpdb->prefix}optimizepress_assets` WHERE `name` = %s", $name )); if(!$entry){ $wpdb->insert($wpdb->prefix.'optimizepress_assets',array('name'=>$name,'title'=>$title,'settings'=>$settings)); } } function load_addon($asset){ if(!isset($this->included_assets[$asset]) && is_dir(OP_ASSETS.'addon/'.$asset) && file_exists(OP_ASSETS.'addon/'.$asset.'/'.$asset.'.php')){ $included_assets[$asset] = true; require_once OP_ASSETS.'addon/'.$asset.'/'.$asset.'.php'; } } function folder_list(){ $files = array(); $checks = array('image','style','checkbox'); foreach($checks as $chk){ if(($folders = op_post('folders',$chk)) && is_array($folders)){ $files[$chk] = $this->_process_files($folders,$chk); } } echo json_encode($files); exit; } function _process_files($folders,$type='style',$returnfiles=false){ $files = array(); static $checked_paths = array(); foreach($folders as $f){ if(isset($f['group']) && isset($f['tag']) && isset($f['folder'])){ switch($f['group']){ case 'addon': $path = apply_filters('op_assets_addons_path', OP_ASSETS.'addon/', $f['tag']); $url = apply_filters('op_assets_addons_url', OP_ASSETS_URL.'addon/', $f['tag']); break; case 'theme': if(defined('OP_THEME_PATH')){ $path = OP_THEME_PATH.'assets/'; $url = OP_THEME_URL.'assets/'; } elseif(defined('OP_PAGE_URL')){ $path = OP_PAGE_PATH.'assets/'; $url = OP_PAGE_URL.'assets/'; } break; default: $path = OP_ASSETS.'images/'; $url = OP_ASSETS_URL.'images/'; break; } $folder = ($f['folder'] == '' ? '':'/'.$f['folder']); if (strpos($folder, '/../') === 0) { $folder = str_replace('/../', '', $folder); $tmppath = $path.$folder; $url .= $folder.'/'; } else { $tmppath = $path.$f['tag'].$folder; $url .= $f['tag'].$folder.'/'; } if(isset($checked_paths[$tmppath])){ $files[$f['fieldid']] = $checked_paths[$tmppath]; } else { $newfiles = array(); if(is_dir($tmppath)){ $dir = @ dir($tmppath); if($dir){ while(($file = $dir->read()) !== false){ if($file != '.' && $file != '..' && $file != 'index.php' && strpos($file, '.') !== 0){ $newfiles[$file] = $url.$file; } } } } natsort($newfiles); $checked_paths[$tmppath] = $files[$f['fieldid']] = $newfiles; } if(!$returnfiles){ $func = '_generate_'.$type.'_selector'; $tmp = $this->$func($tmppath,$files[$f['fieldid']],$f['fieldid'],$f); $files[$f['fieldid']] = $tmp[0]; } } } return $files; } function _remove_ignore_vals($arr,$folder){ if(isset($folder['ignore_vals'])){ foreach($folder['ignore_vals'] as $ignore){ if(isset($arr[$ignore])){ unset($arr[$ignore]); } } } return $arr; } function _generate_image_selector($path,$files,$fieldid,$folder){ static $html = array(); static $array_elements = array(); if(!isset($html[$path])){ $arr = array(); $str = '<ul class="cf">'; $strarr = array(); foreach($files as $file => $url){ $strarr[$file] = '<li class="op-asset-dropdown-list-item"><a href="#"><img alt="'.esc_attr($file).'" src="'.esc_url($url).'" /></a></li>'; $arr[esc_attr($file)] = $file; } $strarr = $this->_remove_ignore_vals($strarr,$folder); $arr = $this->_remove_ignore_vals($arr,$folder); $str .= implode('',$strarr).'</ul>'; $html[$path] = $str; $array_elements[$path] = $arr; } return array($html[$path],$array_elements[$path]); } function _generate_style_selector($path,$files,$fieldid,$folder){ static $html = array(); static $array_elements = array(); if(!isset($html[$path])){ $styles = array(); $arr = array(); foreach($files as $file => $url){ $file = explode('.',$file); $file = end(explode('_',$file[0])); $styles[$file] = '<li class="op-asset-dropdown-list-item"><a href="#"><img alt="'.esc_attr($file).'" src="'.esc_url($url).'" /></a></li>'; $arr[esc_attr($file)] = $file; } $styles = $this->_remove_ignore_vals($styles,$folder); $arr = $this->_remove_ignore_vals($arr,$folder); $str = '<ul class="cf">'.implode('',$styles).'</ul>'; $html[$path] = $str; $array_elements[$path] = $arr; } return array($html[$path],$array_elements[$path]); } function _generate_checkbox_selector($path,$files,$fieldid){ static $html = array(); static $array_elements = array(); if(!isset($html[$path])){ $arr = array(); $str = '<ul class="cf">'; $count = 0; foreach($files as $file => $url){ $str .= '<li><label><input type="checkbox" name="'.$fieldid.'[]" id="'.$fieldid.$count.'" value="'.$file.'" /><img alt="'.esc_attr($file).'" src="'.esc_url($url).'" /></label></li>'; $count++; $arr[esc_attr($file)] = $file; } $str .= '</ul>'; $html[$path] = $str; $array_elements[$path] = $arr; } return array($html[$path],$array_elements[$path]); } function style_selector($folder,$fieldname='',$selected='',$addclass=''){ $files = $this->_process_files(array($folder),'',true); $selecthtml = $html = ''; //ksort($files[$folder['fieldid']]); foreach($files[$folder['fieldid']] as $file => $url){ $file = explode('.',$file); $file = explode('_', $file[0]); $file = end($file); $html .= '<li class="op-asset-dropdown-list-item"><a href="#"><img alt="'.esc_attr($file).'" src="'.esc_url($url).'" /></a></li>'; $selecthtml .= '<option value="'.esc_attr($file).'"'.($selected==$file?' selected="selected"':'').'>'.$url.'</option>'; } return ' <select name="'.$fieldname.'" id="'.$folder['fieldid'].'" class="style-selector" style="display:none">'.$selecthtml.'</select> <div class="op-asset-dropdown '.$addclass.'" id="'.$folder['fieldid'].'_container"> <a class="selected-item" href="#"></a> <div class="op-asset-dropdown-list">'.$html.'</div> </div>'; } /** * Generates markup for preset selector (similair to style selector but with less surrounding markup) * @param string $folder * @param string $fieldname * @param string $selected * @param string $addClass * @return string */ function preset_selector($folder, $fieldname = '', $selected = '', $addClass = '') { $files = $this->_process_files(array($folder), '', true); $select = $list = ''; foreach ($files[$folder['fieldid']] as $file => $url) { $file = explode('.', $file); $file = explode('_', $file[0]); $file = end($file); $list .= '<li class="op-asset-dropdown-list-item"><a href="#"><img alt="' . esc_attr($file) . '" src="' . esc_url($url) . '" /></a></li>'; $select .= '<option value="' . esc_attr($file) . '"' . ($selected == $file ? ' selected="selected"' : '') . '>' . $url . '</option>'; } return ' <div class="op-asset-dropdown-list"><ul>' . $list . '</ul></div> <select name="' . $fieldname . '" id="' . $folder['fieldid'] . '" class="preset-selector" style="display:none">' . $select . '</select>'; } function image_selector($folder,$fieldname='',$selected='',$addclass=''){ $files = $this->_process_files(array($folder),'',true); $selecthtml = $html = ''; //ksort($files[$folder['fieldid']]); foreach($files[$folder['fieldid']] as $file => $url){ $html .= '<li class="op-asset-dropdown-list-item"><a href="#"><img alt="'.esc_attr($file).'" src="'.esc_url($url).'" /></a></li>'; $selecthtml .= '<option value="'.esc_attr($file).'"'.($selected==$file?' selected="selected"':'').'>'.$url.'</option>'; } return ' <select name="'.$fieldname.'" id="'.$folder['fieldid'].'" class="style-selector" style="display:none">'.$selecthtml.'</select> <div class="op-asset-dropdown '.$addclass.'" id="'.$folder['fieldid'].'_container"> <a class="selected-item" href="#"></a> <div class="op-asset-dropdown-list">'.$html.'</div> </div>'; } } function _op_assets(){ static $op_assets; if(!isset($op_assets)){ $op_assets = new OptimizePress_Assets_Core; } $args = func_get_args(); if(count($args)){ $func = array_shift($args); return call_user_func_array(array($op_assets,$func),$args); } } function op_assets_provider_list() { return _op_assets('providerList', true); } function op_assets_provider_details($provider, $special = false) { return _op_assets('providerDetails', $provider, true, $special); } function op_assets_provider_items($provider, $special = false) { return _op_assets('providerItems', $provider, true, $special); } function op_assets_provider_item_fields($provider, $list, $special = false) { return _op_assets('providerItemFields', $provider, $list, true, $special); } function op_assets_provider_enabled($provider) { return _op_assets('providerEnabled', $provider); } function op_assets_provider_register($provider, $list, $email, $fname, $lname) { return _op_assets('providerRegister', $provider, $list, $email, $fname, $lname); } function op_assets($group='',$asset=''){ return _op_assets('assets',$group,$asset); } function op_assets_parse_list(){ return _op_assets('parse_assets'); } function op_asset_tags(){ return _op_assets('asset_keys'); } function op_assets_lang(){ return _op_assets('lang'); } function op_assets_lang_key($key=''){ return _op_assets('lang_key',$key); } function op_asset_font_style($atts,$prefix='font_'){ $vars = shortcode_atts(array( $prefix.'size' => '', $prefix.'font' => '', $prefix.'style' => '', $prefix.'color' => '', $prefix.'spacing' => '', $prefix.'shadow' => '', ), $atts); return op_font_style_str($vars,$prefix); }
gpl-2.0
MikePohatu/SystemLackey
source/JobBuilder/Panel2/FormPowerControl.Designer.cs
8904
namespace SystemLackey.UI.Forms { partial class FormPowerControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.labelJobID = new System.Windows.Forms.Label(); this.labelJobGuid = new System.Windows.Forms.Label(); this.labelName = new System.Windows.Forms.Label(); this.textName = new System.Windows.Forms.TextBox(); this.labelComments = new System.Windows.Forms.Label(); this.textComments = new System.Windows.Forms.TextBox(); this.buttonSave = new System.Windows.Forms.Button(); this.radioReboot = new System.Windows.Forms.RadioButton(); this.radioShutdown = new System.Windows.Forms.RadioButton(); this.radioLogoff = new System.Windows.Forms.RadioButton(); this.numericUpDownWait = new System.Windows.Forms.NumericUpDown(); this.labelWait = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWait)).BeginInit(); this.SuspendLayout(); // // labelJobID // this.labelJobID.AutoSize = true; this.labelJobID.Location = new System.Drawing.Point(12, 13); this.labelJobID.Name = "labelJobID"; this.labelJobID.Size = new System.Drawing.Size(48, 13); this.labelJobID.TabIndex = 0; this.labelJobID.Text = "Task ID:"; // // labelJobGuid // this.labelJobGuid.AutoSize = true; this.labelJobGuid.Location = new System.Drawing.Point(75, 13); this.labelJobGuid.Name = "labelJobGuid"; this.labelJobGuid.Size = new System.Drawing.Size(18, 13); this.labelJobGuid.TabIndex = 1; this.labelJobGuid.Text = "ID"; // // labelName // this.labelName.AutoSize = true; this.labelName.Location = new System.Drawing.Point(12, 33); this.labelName.Name = "labelName"; this.labelName.Size = new System.Drawing.Size(38, 13); this.labelName.TabIndex = 2; this.labelName.Text = "Name:"; // // textName // this.textName.Location = new System.Drawing.Point(78, 29); this.textName.Name = "textName"; this.textName.Size = new System.Drawing.Size(186, 20); this.textName.TabIndex = 3; // // labelComments // this.labelComments.AutoSize = true; this.labelComments.Location = new System.Drawing.Point(12, 53); this.labelComments.Name = "labelComments"; this.labelComments.Size = new System.Drawing.Size(56, 13); this.labelComments.TabIndex = 4; this.labelComments.Text = "Comments"; // // textComments // this.textComments.AcceptsReturn = true; this.textComments.Location = new System.Drawing.Point(78, 55); this.textComments.Multiline = true; this.textComments.Name = "textComments"; this.textComments.Size = new System.Drawing.Size(186, 195); this.textComments.TabIndex = 5; // // buttonSave // this.buttonSave.Location = new System.Drawing.Point(285, 227); this.buttonSave.Name = "buttonSave"; this.buttonSave.Size = new System.Drawing.Size(75, 23); this.buttonSave.TabIndex = 6; this.buttonSave.Text = "Save"; this.buttonSave.UseVisualStyleBackColor = true; this.buttonSave.Click += new System.EventHandler(this.buttonSave_Click); // // radioReboot // this.radioReboot.AutoSize = true; this.radioReboot.Checked = true; this.radioReboot.Location = new System.Drawing.Point(282, 29); this.radioReboot.Name = "radioReboot"; this.radioReboot.Size = new System.Drawing.Size(60, 17); this.radioReboot.TabIndex = 7; this.radioReboot.TabStop = true; this.radioReboot.Text = "Reboot"; this.radioReboot.UseVisualStyleBackColor = true; // // radioShutdown // this.radioShutdown.AutoSize = true; this.radioShutdown.Location = new System.Drawing.Point(282, 51); this.radioShutdown.Name = "radioShutdown"; this.radioShutdown.Size = new System.Drawing.Size(73, 17); this.radioShutdown.TabIndex = 8; this.radioShutdown.TabStop = true; this.radioShutdown.Text = "Shutdown"; this.radioShutdown.UseVisualStyleBackColor = true; // // radioLogoff // this.radioLogoff.AutoSize = true; this.radioLogoff.Location = new System.Drawing.Point(282, 72); this.radioLogoff.Name = "radioLogoff"; this.radioLogoff.Size = new System.Drawing.Size(55, 17); this.radioLogoff.TabIndex = 9; this.radioLogoff.TabStop = true; this.radioLogoff.Text = "Logoff"; this.radioLogoff.UseVisualStyleBackColor = true; // // numericUpDownWait // this.numericUpDownWait.Location = new System.Drawing.Point(282, 119); this.numericUpDownWait.Name = "numericUpDownWait"; this.numericUpDownWait.Size = new System.Drawing.Size(78, 20); this.numericUpDownWait.TabIndex = 10; this.numericUpDownWait.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // labelWait // this.labelWait.AutoSize = true; this.labelWait.Location = new System.Drawing.Point(282, 100); this.labelWait.Name = "labelWait"; this.labelWait.Size = new System.Drawing.Size(78, 13); this.labelWait.TabIndex = 11; this.labelWait.Text = "Wait (seconds)"; // // FormPowerControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.ClientSize = new System.Drawing.Size(366, 257); this.Controls.Add(this.labelWait); this.Controls.Add(this.numericUpDownWait); this.Controls.Add(this.radioLogoff); this.Controls.Add(this.radioShutdown); this.Controls.Add(this.radioReboot); this.Controls.Add(this.buttonSave); this.Controls.Add(this.textComments); this.Controls.Add(this.labelComments); this.Controls.Add(this.textName); this.Controls.Add(this.labelName); this.Controls.Add(this.labelJobGuid); this.Controls.Add(this.labelJobID); this.Name = "FormPowerControl"; this.Text = "Job Details"; ((System.ComponentModel.ISupportInitialize)(this.numericUpDownWait)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label labelJobID; private System.Windows.Forms.Label labelJobGuid; private System.Windows.Forms.Label labelName; private System.Windows.Forms.TextBox textName; private System.Windows.Forms.Label labelComments; private System.Windows.Forms.TextBox textComments; private System.Windows.Forms.Button buttonSave; private System.Windows.Forms.RadioButton radioReboot; private System.Windows.Forms.RadioButton radioShutdown; private System.Windows.Forms.RadioButton radioLogoff; private System.Windows.Forms.NumericUpDown numericUpDownWait; private System.Windows.Forms.Label labelWait; } }
gpl-2.0
cope-project/PraxManager
public/js/lang/ct.js
1309
loadLanguagePack({ "The current window has unsaved changes.": "La finestra actual té canvis sense desar.", "Are you sure you want to delete this form ?": "¿Segur que voleu suprimir aquest formulari?", "Are you sure you want to delete this subject ?": "¿Segur que voleu suprimir aquest tema?", "Are you sure you want to delete this question ?" : "¿Esteu segur que voleu eliminar aquesta pregunta?", "Copy" : "Copiar", "File upload error.": "Error de càrrega de fitxe.", "Are you sure you want to delete this internship ?" : "¿Esteu segur que voleu eliminar aquesta pràctica?", "Are you sure you want to archive this internship ?": "¿Esteu segur que voleu arxivar aquesta pràctica?", "Are you sure you want to remove this student ?":"¿Segur que vol eliminar aquest estudiant? ", "Are you sure you want to remove this manager ?": "¿Segur que vol eliminar aquest tutor? ", "Checkin Current Day": "Validació del dia actual", "Current Day": "Dia actual", "Pending": "Pendent", "Approved": "Aprovat", "Rejected":"Rebutjat", "Edit Checkin":"Validació diaria", "Checked in":"Registrat", "Sunday": "Dilluns", "Monday": "Dimarts", "Tuesday": "Dimecres", "Wednesday": "Dijous", "Thursday": "Divendres", "Friday": "Dissabte", "Saturday": "Diumenge", "Once": "Només una vegada" });
gpl-2.0
christopherstock/GC_Carpentry
_ASSETS/backup/old_site/v0.1/zenphoto/zp-core/rss/rss.php
7251
<?php $host = getRSSHost(); $channeltitle = getRSSChanneltitle(); $protocol = SERVER_PROTOCOL; if ($protocol == 'https_admin') { $protocol = 'http'; } $locale = getRSSLocale(); $validlocale = getRSSLocaleXML(); $modrewritesuffix = getRSSImageAndAlbumPaths("modrewritesuffix"); require_once(ZENFOLDER . "/lib-MimeTypes.php"); header('Content-Type: application/xml'); $rssmode = getRSSAlbumsmode(); $albumfolder = getRSSAlbumnameAndCollection("albumfolder"); $collection = getRSSAlbumnameAndCollection("collection"); $albumname = getRSSAlbumTitle(); $albumpath = getRSSImageAndAlbumPaths("albumpath"); $imagepath = getRSSImageAndAlbumPaths("imagepath"); $size = getRSSImageSize(); $items = getOption('feed_items'); // # of Items displayed on the feed $gallery = new Gallery(); ?> <rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/"> <channel> <title><?php echo html_encode($channeltitle.' '.strip_tags($albumname)); ?></title> <link><?php echo $protocol."://".$host.WEBPATH; ?></link> <atom:link href="<?php echo $protocol; ?>://<?php echo html_encode($_SERVER["HTTP_HOST"]); ?><?php echo html_encode($_SERVER["REQUEST_URI"]); ?>" rel="self" type="application/rss+xml" /> <description><?php echo strip_tags(get_language_string($gallery->get('Gallery_description'), $locale)); ?></description> <language><?php echo $validlocale; ?></language> <pubDate><?php echo date("r", time()); ?></pubDate> <lastBuildDate><?php echo date("r", time()); ?></lastBuildDate> <docs>http://blogs.law.harvard.edu/tech/rss</docs> <generator>ZenPhoto RSS Generator</generator> <?php if ($rssmode == "albums") { $result = getAlbumStatistic($items,getOption("feed_sortorder_albums"),$albumfolder); } else { $result = getImageStatistic($items,getOption("feed_sortorder"),$albumfolder,$collection); } foreach ($result as $item) { if($rssmode != "albums") { $ext = getSuffix($item->filename); $albumobj = $item->getAlbum(); $itemlink = $host.WEBPATH.$albumpath.pathurlencode($albumobj->name).$imagepath.pathurlencode($item->filename).$modrewritesuffix; $fullimagelink = $host.WEBPATH."/albums/".pathurlencode($albumobj->name)."/".$item->filename; $imagefile = "albums/".$albumobj->name."/".$item->filename; $thumburl = '<img border="0" src="'.$protocol.'://'.$host.$item->getCustomImage($size, NULL, NULL, NULL, NULL, NULL, NULL, TRUE).'" alt="'.get_language_string(get_language_string($item->get("title"),$locale)) .'" /><br />'; $itemcontent = '<![CDATA[<a title="'.html_encode(get_language_string($item->get("title"),$locale)).' in '.html_encode(get_language_string($albumobj->get("title"),$locale)).'" href="'.$protocol.'://'.$itemlink.'">'.$thumburl.'</a>' . get_language_string(get_language_string($item->get("desc"),$locale)) . ']]>'; $videocontent = '<![CDATA[<a title="'.html_encode(get_language_string($item->get("title"),$locale)).' in '.html_encode(get_language_string($albumobj->getTitle(),$locale)).'" href="'.$protocol.'://'.$itemlink.'"><img src="'.$protocol.'://'.$host.$item->getThumb().'" alt="'.get_language_string(get_language_string($item->get("title"),$locale)) .'" /></a>' . get_language_string(get_language_string($item->get("desc"),$locale)) . ']]>'; $datecontent = '<![CDATA[<br />Date: '.zpFormattedDate(DATE_FORMAT,$item->get('mtime')).']]>'; } else { $galleryobj = new Gallery(); $albumitem = new Album($galleryobj, $item['folder']); $totalimages = $albumitem->getNumImages(); $itemlink = $host.WEBPATH.$albumpath.pathurlencode($albumitem->name); $thumb = $albumitem->getAlbumThumbImage(); $thumburl = '<img border="0" src="'.$thumb->getCustomImage($size, NULL, NULL, NULL, NULL, NULL, NULL, TRUE).'" alt="'.get_language_string($albumitem->get("title"),$locale) .'" />'; $title = get_language_string($albumitem->get("title"),$locale); if(true || getOption("feed_sortorder_albums") == "latestupdated") { $filechangedate = filectime(ALBUM_FOLDER_SERVERPATH.internalToFilesystem($albumitem->name)); $latestimage = query_single_row("SELECT mtime FROM " . prefix('images'). " WHERE albumid = ".$albumitem->getAlbumID() . " AND `show` = 1 ORDER BY id DESC"); if($latestimage) { $count = db_count('images',"WHERE albumid = ".$albumitem->getAlbumID() . " AND mtime = ". $latestimage['mtime']); if($count == 1) { $imagenumber = sprintf(gettext('%s (1 new image)'),$title); } else { $imagenumber = sprintf(gettext('%1$s (%2$s new images)'),$title,$count); } } else { $imagenumber = $title; } $itemcontent = '<![CDATA[<a title="'.$title.'" href="'.$protocol.'://'.$itemlink.'">'.$thumburl.'</a>'. '<p>'.html_encode($imagenumber).'</p>'.get_language_string($albumitem->get("desc"),$locale).']]>'; $videocontent = ''; $datecontent = '<![CDATA['.sprintf(gettext("Last update: %s"),zpFormattedDate(DATE_FORMAT,$filechangedate)).']]>'; } else { if($totalimages == 1) { $imagenumber = sprintf(gettext('%s (1 image)'),$title); } else { $imagenumber = sprintf(gettext('%1$s (%2$s images)'),$title,$totalimages); } $itemcontent = '<![CDATA[<a title="'.html_encode($title).'" href="'.$protocol.'://'.$itemlink.'">'.$thumburl.'</a>'.get_language_string($albumitem->get("desc"),$locale).']]>'; $datecontent = '<![CDATA['.sprintf(gettext("Date: %s"),zpFormattedDate(DATE_FORMAT,$albumitem->get('mtime'))).']]>'; } $ext = getSuffix($thumb->filename); } $mimetype = getMimeString($ext); ?> <item> <title><?php if($rssmode != "albums") { html_encode(printf('%1$s (%2$s)', get_language_string($item->get("title"),$locale), get_language_string($albumobj->get("title"),$locale))); } else { echo html_encode($imagenumber); } ?></title> <link> <?php echo '<![CDATA['.$protocol.'://'.$itemlink. ']]>';?> </link> <description> <?php if ((($ext == "flv") || ($ext == "mp3") || ($ext == "mp4") || ($ext == "3gp") || ($ext == "mov")) AND $rssmode != "album") { echo $videocontent; } else { echo $itemcontent; } ?> <?php echo $datecontent; ?> </description> <?php // enables download of embeded content like images or movies in some RSS clients. just for testing, shall become a real option if(getOption("feed_enclosure") AND $rssmode != "albums") { ?> <enclosure url="<?php echo $protocol; ?>://<?php echo $fullimagelink; ?>" type="<?php echo $mimetype; ?>" length="<?php echo filesize($imagefile);?>" /> <?php } ?> <category> <?php if($rssmode != "albums") { echo html_encode(get_language_string($albumobj->get("title"),$locale)); } else { echo html_encode(get_language_string($albumitem->get("title"),$locale)); } ?> </category> <?php if(getOption("feed_mediarss") AND $rssmode != "albums") { ?> <media:content url="<?php echo $protocol; ?>://<?php echo $fullimagelink; ?>" type="image/jpeg" /> <media:thumbnail url="<?php echo $protocol; ?>://<?php echo $fullimagelink; ?>" width="<?php echo $size; ?>" height="<?php echo $size; ?>" /> <?php } ?> <guid><?php echo '<![CDATA['.$protocol.'://'.$itemlink.']]>';?></guid> <pubDate> <?php if($rssmode != "albums") { echo date("r",strtotime($item->get('date'))); } else { echo date("r",strtotime($albumitem->get('date'))); } ?> </pubDate> </item> <?php } ?> </channel> </rss>
gpl-2.0
Ellitsa93/AirportSystem
lines_database_manager_test.py
6537
import unittest import lines_database_manager class TestLinesDatabaseManager(unittest.TestCase): def setUp(self): lines_database_manager.create_tables() lines_database_manager.add_flight("Perfect Place", "21-Jul-2015 12:56") lines_database_manager.add_runway(0, "31-Dec-2050 23:59") lines_database_manager.add_runway(1, "12-Nov-2015 13:45") lines_database_manager.add_seat(1, 1, 10, 1, 1, 1) lines_database_manager.add_seat(1, 2, 15, 1, 2, 1) lines_database_manager.add_seat(1, 3, 7, 1, 1, 1) lines_database_manager.add_seat(1, 4, 11, 2, 2, 2) lines_database_manager.add_promo_code(1111, 10) def test_add_extras(self): query = "SELECT Count(*) FROM extras" lines_database_manager.cursor.execute(query, ()) count = lines_database_manager.cursor.fetchone() self.assertEqual(count[0], 4) def test_add_flight(self): query = "SELECT Count(*) FROM flights WHERE id = ?" lines_database_manager.cursor.execute(query, (1,)) count = lines_database_manager.cursor.fetchone() self.assertEqual(count[0], 1) def test_add_runway(self): query = "SELECT Count(*) FROM runway WHERE id = ?" lines_database_manager.cursor.execute(query, (1,)) count = lines_database_manager.cursor.fetchone() self.assertEqual(count[0], 1) def test_add_seat(self): query = "SELECT Count(*) FROM seats WHERE flight_id = ? and num = ?" lines_database_manager.cursor.execute(query, (1, 2)) count = lines_database_manager.cursor.fetchone() self.assertEqual(count[0], 1) def test_add_promo_code(self): query = "SELECT Count(*) FROM promo_codes WHERE code = ?" lines_database_manager.cursor.execute(query, (1111, )) count = lines_database_manager.cursor.fetchone() self.assertEqual(count[0], 1) def test_is_promo_code_correct_true(self): pomo_code_correct = lines_database_manager.is_promo_code_correct(1111) self.assertTrue(pomo_code_correct) def test_is_promo_code_correct_false(self): pomo_code_not_correct = lines_database_manager.is_promo_code_correct( 1234) self.assertFalse(pomo_code_not_correct) def test_get_promo_code_percent(self): persent = lines_database_manager.get_promo_code_percent(1111) self.assertEqual(persent, 10) def test_get_seat_price(self): price = lines_database_manager.get_seat_price(1, 2) self.assertEqual(price, 15) def test_get_free_runways(self): runways = lines_database_manager.get_free_runways() self.assertEqual(runways[0][0], 2) def test_get_flights(self): flights = lines_database_manager.get_flights("Perfect Place") self.assertEqual(flights[0][0], 1) def test_get_seats_count(self): seats = lines_database_manager.get_seats(1) self.assertEqual(len(seats), 4) def test_get_seats(self): seats = lines_database_manager.get_seats(1) self.assertEqual(seats[2][0], 3) def test_get_extras_prices_headphones(self): prices = lines_database_manager.get_extras_prices(1, 2) self.assertEqual(prices[0], 1) def test_get_extras_prices_champagne(self): prices = lines_database_manager.get_extras_prices(1, 2) self.assertEqual(prices[1], 2) def test_get_extras_prices_food(self): prices = lines_database_manager.get_extras_prices(1, 2) self.assertEqual(prices[2], 1) def test_get_ticket_id(self): id = lines_database_manager.get_ticket_id(1, 2) self.assertEqual(id, 2) def test_set_seat_sold(self): sold = lines_database_manager.set_seat_sold(1, 2) query = "SELECT sold FROM seats WHERE flight_id = ? and num = ?" lines_database_manager.cursor.execute(query, (1, 2)) seat = lines_database_manager.cursor.fetchone() self.assertEqual(seat[0], 1) def test_set_extras_to_seat_headphones(self): lines_database_manager.set_extras_to_seat(1, 3, 1, 0, 0) query = "SELECT headphones FROM seats WHERE flight_id = ? and num = ?" lines_database_manager.cursor.execute(query, (1, 3)) headphones = lines_database_manager.cursor.fetchone() self.assertEqual(headphones[0], 1) def test_set_extras_to_seat_champagne(self): lines_database_manager.set_extras_to_seat(1, 3, 1, 1, 0) query = "SELECT champagne FROM seats WHERE flight_id = ? and num = ?" lines_database_manager.cursor.execute(query, (1, 3)) champagne = lines_database_manager.cursor.fetchone() self.assertEqual(champagne[0], 1) def test_set_extras_to_seat_headphones(self): lines_database_manager.set_extras_to_seat(1, 3, 1, 1, 1) query = "SELECT food FROM seats WHERE flight_id = ? and num = ?" lines_database_manager.cursor.execute(query, (1, 3)) food = lines_database_manager.cursor.fetchone() self.assertEqual(food[0], 1) def test_get_destination(self): destination = lines_database_manager.get_destination(1) self.assertEqual(destination, "Perfect Place") def test_get_runway(self): runway = lines_database_manager.get_runway(1) self.assertEqual(runway[0], 0) def test_is_ticket_taken_true(self): lines_database_manager.set_seat_sold(1,2) is_taken = lines_database_manager.is_ticket_taken(1, 2) self.assertTrue(is_taken) def test_is_ticket_taken_false(self): is_taken = lines_database_manager.is_ticket_taken(1, 1) self.assertFalse(is_taken) def test_set_permission_given_at_time(self): lines_database_manager.set_permission_given_at_time(2, "12-Oct-2015 12:30") runway = lines_database_manager.get_runway(2) self.assertEqual(runway[1], "12-Oct-2015 12:30") def test_make_runway_free(self): lines_database_manager.make_runway_free(1) runway = lines_database_manager.get_runway(1) self.assertEqual(runway[0], 1) def tearDown(self): lines_database_manager.cursor.execute('DROP TABLE seats') lines_database_manager.cursor.execute('DROP TABLE flights') lines_database_manager.cursor.execute('DROP TABLE extras') lines_database_manager.cursor.execute('DROP TABLE promo_codes') lines_database_manager.cursor.execute('DROP TABLE runway') if __name__ == '__main__': unittest.main()
gpl-2.0
agacia/ovnis
src/edgeInfo.cpp
1790
/* * edgeInfo.cpp * * Created on: Aug 28, 2012 * Author: agata */ #include "edgeInfo.h" #include <sstream> #include <string> namespace ovnis { using namespace std; using namespace ns3; EdgeInfo::EdgeInfo() : id(""), laneId(""), length(0), maxSpeed(0) { traci = Names::Find<ovnis::SumoTraciConnection>("SumoTraci"); } EdgeInfo::EdgeInfo(string edgeId) : id(edgeId) { traci = Names::Find<ovnis::SumoTraciConnection>("SumoTraci"); string laneId = edgeId + "_0"; try { maxSpeed = traci->GetLaneMaxSpeed(laneId); length = traci->GetLaneLength(laneId); currentTravelTime = traci->GetEdgeTravelTime(edgeId); if (maxSpeed > 0) { staticCost = length / maxSpeed; } else { // XXX If maxSpeed is set to 0 (simulated accident), then return the expected travel time with the avg speed of 25m/s for calculating expected costs f the whole route (we assume we don't know any information) staticCost = length / 25; } // cout << edgeId << ": " << staticCost << "(" << length <<"/" << maxSpeed << ")" << endl; } catch (TraciException &e) { } } EdgeInfo::~EdgeInfo() { } string EdgeInfo::print() { stringstream out; out << id << "\t" << laneId << "\t" << length << "\t" << maxSpeed << "\t" << (length/maxSpeed) << "\t" << currentTravelTime << "\t"; return out.str(); } std::string EdgeInfo::getId() { return id; } std::string EdgeInfo::getLaneId() { return laneId; } double EdgeInfo::getLength() { return length; } double EdgeInfo::getMaxSpeed() { return maxSpeed; } double EdgeInfo::getStaticCost() { return staticCost; } double EdgeInfo::requestCurrentTravelTime() { currentTravelTime = traci->GetEdgeTravelTime(id); return currentTravelTime; } double EdgeInfo::getCurrentTravelTime() { return currentTravelTime; } } /* namespace ovnis */
gpl-2.0
OS2World/DEV-UTIL-SNAP
src/snaprtl/cpplib/iostream/cpp/flfdestr.cpp
3665
/**************************************************************************** * * Open Watcom Project * * Portions Copyright (c) 1983-2002 Sybase, Inc. All Rights Reserved. * * ======================================================================== * * This file contains Original Code and/or Modifications of Original * Code as defined in and that are subject to the Sybase Open Watcom * Public License version 1.0 (the 'License'). You may not use this file * except in compliance with the License. BY USING THIS FILE YOU AGREE TO * ALL TERMS AND CONDITIONS OF THE LICENSE. A copy of the License is * provided with the Original Code and Modifications, and is also * available at www.sybase.com/developer/opensource. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND SYBASE AND ALL CONTRIBUTORS HEREBY DISCLAIM * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR * NON-INFRINGEMENT. Please see the License for the specific language * governing rights and limitations under the License. * * ======================================================================== * * Description: WHEN YOU FIGURE OUT WHAT THIS FILE DOES, PLEASE * DESCRIBE IT HERE! * ****************************************************************************/ // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // % Copyright (C) 1992, by WATCOM International Inc. All rights % // % reserved. No part of this software may be reproduced or % // % used in any form or by any means - graphic, electronic or % // % mechanical, including photocopying, recording, taping or % // % information storage and retrieval systems - except with the % // % written permission of WATCOM International Inc. % // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // // Modified By Reason // ======== == ====== // 92/02/19 Steve McDowell Initial implementation. // 92/02/28 ... Modified to delay allocation of buffers // until overflow/underflow called. // 92/09/08 Greg Bentz Cleanup. // 93/03/22 Greg Bentz modify filebuf::open() and filebuf::attach() // to assume ios::binary unless ios::text is // found in the fstat() so that QNX is supported. // 93/07/22 Greg Bentz Make sure overflow() function sets up the // put area // 93/09/13 Greg Bentz filebuf::~filebuf() must close if !__attached // 93/10/15 Greg Bentz let __plusplus_open() determine if default // file mode is TEXT or BINARY // 93/10/15 Raymond Tang Modify filebuf::open() to return NULL if both // ios::noreplace and ios::nocreate are specified // 93/10/22 Raymond Tang Split into separate files. // 94/04/06 Greg Bentz combine header files #ifdef __SW_FH #include "iost.h" #else #include "variety.h" #include <fstream.h> #endif filebuf::~filebuf() { /*******************/ // Destroy the filebuf. // If a file is open and was not attached (ie. it was open'd), then // close it. if( fd() != EOF ) { if( out_waiting() ) { sync(); } if( !__attached ) { close(); } } }
gpl-2.0
espertechinc/nesper
src/NEsper.Common/common/internal/statement/multimatch/MultiMatchHandlerSubqueryPreevalNoDedup.cs
1717
/////////////////////////////////////////////////////////////////////////////////////// // Copyright (C) 2006-2019 Esper Team. All rights reserved. / // http://esper.codehaus.org / // ---------------------------------------------------------------------------------- / // The software in this package is published under the terms of the GPL license / // a copy of which has been included with this distribution in the license.txt file. / /////////////////////////////////////////////////////////////////////////////////////// using System.Collections.Generic; using com.espertech.esper.common.client; using com.espertech.esper.common.@internal.filtersvc; namespace com.espertech.esper.common.@internal.statement.multimatch { public class MultiMatchHandlerSubqueryPreevalNoDedup : MultiMatchHandler { protected internal static readonly MultiMatchHandlerSubqueryPreevalNoDedup INSTANCE = new MultiMatchHandlerSubqueryPreevalNoDedup(); private MultiMatchHandlerSubqueryPreevalNoDedup() { } public void Handle( ICollection<FilterHandleCallback> callbacks, EventBean theEvent) { foreach (var callback in callbacks) { if (callback.IsSubSelect) { callback.MatchFound(theEvent, callbacks); } } foreach (var callback in callbacks) { if (!callback.IsSubSelect) { callback.MatchFound(theEvent, callbacks); } } } } } // end of namespace
gpl-2.0
KylePreston/Soft-Hills-Website
wp-content/themes/timeturner/sidebar-index.php
228
<?php /** * The index-blog sidebar template file. * @package TimeTurner * @since TimeTurner 1.0.0 */ ?> <div id="sidebar"> <?php if ( dynamic_sidebar( 'sidebar-1' ) ) : else : ?> <?php endif; ?> </div> <!-- end of sidebar -->
gpl-2.0
netanelrevah/torah
torah/bereshit.py
1191
from torah.hebrew import HebrewLetter, HebrewFinalLetter from torah.scribe import HebrewWrittenWord, HebrewScribeLetter, HebrewScribeLetterSize, HebrewWrittenSentence __author__ = 'netanelrevah' BERESHIT = HebrewWrittenWord( HebrewScribeLetter(HebrewLetter.BET, size=HebrewScribeLetterSize.LARGE), HebrewLetter.RESH, HebrewLetter.ALEPH, HebrewLetter.SHIN, HebrewLetter.YOD, HebrewLetter.TAV) BARA = HebrewWrittenWord( HebrewLetter.BET, HebrewLetter.RESH, HebrewLetter.ALEPH) ELOHIM = HebrewWrittenWord( HebrewLetter.ALEPH, HebrewLetter.LAMED, HebrewLetter.HE, HebrewLetter.YOD, HebrewFinalLetter.MEM) ET = HebrewWrittenWord( HebrewLetter.ALEPH, HebrewLetter.TAV) HASHAMIM = HebrewWrittenWord( HebrewLetter.HE, HebrewLetter.SHIN, HebrewLetter.MEM, HebrewLetter.YOD, HebrewFinalLetter.MEM) VE_ET = HebrewWrittenWord( HebrewLetter.VAV, HebrewLetter.ALEPH, HebrewLetter.TAV) HA_ARETZ = HebrewWrittenWord( HebrewLetter.HE, HebrewLetter.ALEPH, HebrewLetter.RESH, HebrewFinalLetter.TZADI ) PASUK_A = HebrewWrittenSentence(BERESHIT, BARA, ELOHIM, ET, HASHAMIM, VE_ET, HA_ARETZ)
gpl-2.0
Bogstag/bogstag.se
app/Console/Commands/Oauth2TokenCommand.php
1015
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Http\Controllers\oauth2client\Oauth2ClientTrakt; /** * Class Oauth2TokenCommand. */ class Oauth2TokenCommand extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'oauth2token:refresh'; /** * The console command description. * * @var string */ protected $description = 'Refreshes oauth2 tokens'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { $this->info('Refreshing Tokens'); $this->refreshTrakt(); $this->info('Tokens refreshed'); } private function refreshTrakt() { $trakt = new Oauth2ClientTrakt(); $trakt->refreshToken(); } }
gpl-2.0
eighty20results/e20r-payment-warning-pmpro
libraries/paypal/merchant-sdk-php/lib/PayPal/EBLBaseComponents/RiskFilterDetailsType.php
495
<?php namespace PayPal\EBLBaseComponents; use PayPal\Core\PPXmlMessage; /** * Details of Risk Filter. */ class RiskFilterDetailsType extends PPXmlMessage { /** * * @access public * @namespace ebl * @var integer */ public $Id; /** * * @access public * @namespace ebl * @var string */ public $Name; /** * * @access public * @namespace ebl * @var string */ public $Description; }
gpl-2.0
shiyeling/test_import
WordPress/src/main/java/org/wordpress/android/ui/stats/StatsVisitorsAndViewsFragment.java
23485
package org.wordpress.android.ui.stats; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.v4.content.LocalBroadcastManager; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckedTextView; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.TextView; import com.android.volley.VolleyError; import com.jjoe64.graphview.GraphView; import com.jjoe64.graphview.GraphViewSeries; import org.wordpress.caredear.R; import org.wordpress.android.WordPress; import org.wordpress.android.ui.stats.models.VisitModel; import org.wordpress.android.ui.stats.models.VisitsModel; import org.wordpress.android.ui.stats.service.StatsService; import org.wordpress.android.util.AppLog; import org.wordpress.android.util.AppLog.T; import org.wordpress.android.util.DisplayUtils; import org.wordpress.android.util.FormatUtils; import org.wordpress.android.util.NetworkUtils; import org.wordpress.android.util.StringUtils; import org.wordpress.android.widgets.TypefaceCache; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.List; public class StatsVisitorsAndViewsFragment extends StatsAbstractFragment implements StatsBarGraph.OnGestureListener { public static final String TAG = StatsVisitorsAndViewsFragment.class.getSimpleName(); private static final String ARG_SELECTED_GRAPH_BAR = "ARG_SELECTED_GRAPH_BAR"; private static final String ARG_SELECTED_OVERVIEW_ITEM = "ARG_SELECTED_OVERVIEW_ITEM"; private LinearLayout mGraphContainer; private StatsBarGraph mGraphView; private GraphViewSeries mCurrentSeriesOnScreen; private LinearLayout mModuleButtonsContainer; private TextView mDateTextView; private String[] mStatsDate; private OnDateChangeListener mListener; final OverviewLabel[] overviewItems = {OverviewLabel.VIEWS, OverviewLabel.VISITORS, OverviewLabel.LIKES, OverviewLabel.COMMENTS}; // Restore the following variables on restart private Serializable mVisitsData; //VisitModel or VolleyError private int mSelectedOverviewItemIndex = 0; private int mSelectedBarGraphBarIndex = -1; // Container Activity must implement this interface public interface OnDateChangeListener { public void onDateChanged(String blogID, StatsTimeframe timeframe, String newDate); } @Override public void onAttach(Activity activity) { super.onAttach(activity); try { mListener = (OnDateChangeListener) activity; } catch (ClassCastException e) { throw new ClassCastException(activity.toString() + " must implement OnDateChangeListener"); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.stats_visitors_and_views_fragment, container, false); mDateTextView = (TextView) view.findViewById(R.id.stats_summary_date); mGraphContainer = (LinearLayout) view.findViewById(R.id.stats_bar_chart_fragment_container); mModuleButtonsContainer = (LinearLayout) view.findViewById(R.id.stats_pager_tabs); for (int i = 0; i < overviewItems.length; i++) { CheckedTextView rb = (CheckedTextView) inflater.inflate(R.layout.stats_visitors_and_views_button, container, false); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT); params.weight = 1; rb.setTypeface((TypefaceCache.getTypeface(view.getContext()))); params.setMargins(0, 0, 0, 0); rb.setGravity(Gravity.CENTER); rb.setLayoutParams(params); rb.setText(overviewItems[i].getLabel()); rb.setTag(overviewItems[i]); rb.setChecked(i == mSelectedOverviewItemIndex); rb.setOnClickListener(TopButtonsOnClickListener); if (i == (overviewItems.length -1)) { rb.setBackgroundResource(R.drawable.stats_visitors_and_views_button_latest_selector); } mModuleButtonsContainer.addView(rb); } mModuleButtonsContainer.setVisibility(View.VISIBLE); return view; } private View.OnClickListener TopButtonsOnClickListener = new View.OnClickListener() { @Override public void onClick(View v) { if (!isAdded()) { return; } CheckedTextView ctv = (CheckedTextView) v; if (ctv.isChecked()) { // already checked. Do nothing return; } int numberOfButtons = mModuleButtonsContainer.getChildCount(); int checkedId = -1; for (int i = 0; i < numberOfButtons; i++) { CheckedTextView currentCheckedTextView = (CheckedTextView) mModuleButtonsContainer.getChildAt(i); if (ctv == currentCheckedTextView) { checkedId = i; currentCheckedTextView.setChecked(true); } else { currentCheckedTextView.setChecked(false); } } if (checkedId == -1) return; mSelectedOverviewItemIndex = checkedId; updateUI(); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { AppLog.d(T.STATS, "StatsVisitorsAndViewsFragment > restoring instance state"); if (savedInstanceState.containsKey(ARG_REST_RESPONSE)) { mVisitsData = savedInstanceState.getSerializable(ARG_REST_RESPONSE); } if (savedInstanceState.containsKey(ARG_SELECTED_OVERVIEW_ITEM)) { mSelectedOverviewItemIndex = savedInstanceState.getInt(ARG_SELECTED_OVERVIEW_ITEM, 0); } if (savedInstanceState.containsKey(ARG_SELECTED_GRAPH_BAR)) { mSelectedBarGraphBarIndex = savedInstanceState.getInt(ARG_SELECTED_GRAPH_BAR, -1); } } } @Override public void onSaveInstanceState(Bundle outState) { //AppLog.d(T.STATS, "StatsVisitorsAndViewsFragment > saving instance state"); outState.putSerializable(ARG_REST_RESPONSE, mVisitsData); outState.putInt(ARG_SELECTED_GRAPH_BAR, mSelectedBarGraphBarIndex); outState.putInt(ARG_SELECTED_OVERVIEW_ITEM, mSelectedOverviewItemIndex); super.onSaveInstanceState(outState); } @Override public void onPause() { super.onPause(); LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity()); lbm.unregisterReceiver(mReceiver); } @Override public void onResume() { super.onResume(); LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getActivity()); lbm.registerReceiver(mReceiver, new IntentFilter(StatsService.ACTION_STATS_SECTION_UPDATED)); if (mVisitsData != null) { updateUI(); } else { setupNoResultsUI(true); mMoreDataListener.onRefreshRequested(new StatsService.StatsEndpointsEnum[]{StatsService.StatsEndpointsEnum.VISITS}); } } private VisitModel[] getDataToShowOnGraph(VisitsModel visitsData) { List<VisitModel> visitModels = visitsData.getVisits(); int numPoints = Math.min(getNumOfPoints(), visitModels.size()); int currentPointIndex = numPoints - 1; VisitModel[] visitModelsToShow = new VisitModel[numPoints]; for (int i = visitModels.size() -1; i >= 0 && currentPointIndex >= 0; i--) { VisitModel currentVisitModel = visitModels.get(i); visitModelsToShow[currentPointIndex] = currentVisitModel; currentPointIndex--; } return visitModelsToShow; } private void updateUI() { if (mVisitsData == null) { setupNoResultsUI(false); return; } if (mVisitsData instanceof VolleyError) { setupNoResultsUI(false); return; } final VisitModel[] dataToShowOnGraph = getDataToShowOnGraph((VisitsModel)mVisitsData); if (dataToShowOnGraph == null || dataToShowOnGraph.length == 0) { setupNoResultsUI(false); return; } final String[] horLabels = new String[dataToShowOnGraph.length]; mStatsDate = new String[dataToShowOnGraph.length]; GraphView.GraphViewData[] views = new GraphView.GraphViewData[dataToShowOnGraph.length]; OverviewLabel selectedStatsType = overviewItems[mSelectedOverviewItemIndex]; for (int i = 0; i < dataToShowOnGraph.length; i++) { int currentItemValue = 0; switch(selectedStatsType) { case VIEWS: currentItemValue = dataToShowOnGraph[i].getViews(); break; case VISITORS: currentItemValue = dataToShowOnGraph[i].getVisitors(); break; case LIKES: currentItemValue = dataToShowOnGraph[i].getLikes(); break; case COMMENTS: currentItemValue = dataToShowOnGraph[i].getComments(); break; } views[i] = new GraphView.GraphViewData(i, currentItemValue); String currentItemStatsDate = dataToShowOnGraph[i].getPeriod(); horLabels[i] = getDateLabelForBarInGraph(currentItemStatsDate); mStatsDate[i] = currentItemStatsDate; } mCurrentSeriesOnScreen = new GraphViewSeries(views); mCurrentSeriesOnScreen.getStyle().color = getResources().getColor(R.color.stats_bar_graph_views); mCurrentSeriesOnScreen.getStyle().padding = DisplayUtils.dpToPx(getActivity(), 5); if (mGraphContainer.getChildCount() >= 1 && mGraphContainer.getChildAt(0) instanceof GraphView) { mGraphView = (StatsBarGraph) mGraphContainer.getChildAt(0); } else { mGraphContainer.removeAllViews(); mGraphView = new StatsBarGraph(getActivity()); mGraphContainer.addView(mGraphView); } mGraphView.removeAllSeries(); mGraphView.addSeries(mCurrentSeriesOnScreen); //mGraphView.getGraphViewStyle().setNumHorizontalLabels(getNumOfHorizontalLabels(dataToShowOnGraph.length)); mGraphView.getGraphViewStyle().setNumHorizontalLabels(dataToShowOnGraph.length); mGraphView.setHorizontalLabels(horLabels); mGraphView.setGestureListener(this); int barSelectedOnGraph = mSelectedBarGraphBarIndex != -1 ? mSelectedBarGraphBarIndex : dataToShowOnGraph.length - 1; mGraphView.highlightBar(barSelectedOnGraph); updateUIBelowTheGraph(barSelectedOnGraph); } //update the area right below the graph private void updateUIBelowTheGraph(int itemPosition) { if (mVisitsData == null) { setupNoResultsUI(false); return; } if (mVisitsData instanceof VolleyError) { setupNoResultsUI(false); return; } final VisitModel[] dataToShowOnGraph = getDataToShowOnGraph((VisitsModel)mVisitsData); String date = mStatsDate[itemPosition]; if (date == null) { AppLog.w(AppLog.T.STATS, "Cannot update the area below the graph if a null date is passed!!"); return; } mDateTextView.setText(getDateForDisplayInLabels(date, getTimeframe())); VisitModel modelTapped = dataToShowOnGraph[itemPosition]; for (int i=0 ; i < mModuleButtonsContainer.getChildCount(); i++) { View o = mModuleButtonsContainer.getChildAt(i); if (o instanceof CheckedTextView) { CheckedTextView currentBtm = (CheckedTextView)o; OverviewLabel overviewItem = (OverviewLabel)currentBtm.getTag(); String labelPrefix = overviewItem.getLabel() + "\n"; switch (overviewItem) { case VIEWS: currentBtm.setText(labelPrefix + FormatUtils.formatDecimal(modelTapped.getViews())); break; case VISITORS: currentBtm.setText(labelPrefix + FormatUtils.formatDecimal(modelTapped.getVisitors())); break; case LIKES: currentBtm.setText(labelPrefix + FormatUtils.formatDecimal(modelTapped.getLikes())); break; case COMMENTS: currentBtm.setText(labelPrefix + FormatUtils.formatDecimal(modelTapped.getComments())); break; } } } } private String getDateForDisplayInLabels(String date, StatsTimeframe timeframe) { String prefix = getString(R.string.stats_for); switch (timeframe) { case DAY: return String.format(prefix, StatsUtils.parseDate(date, "yyyy-MM-dd", "MMMM d")); case WEEK: try { SimpleDateFormat sdf; Calendar c; final Date parsedDate; // Used in bar graph // first four digits are the year // followed by Wxx where xx is the month // followed by Wxx where xx is the day of the month // ex: 2013W07W22 = July 22, 2013 sdf = new SimpleDateFormat("yyyy'W'MM'W'dd"); //Calculate the end of the week parsedDate = sdf.parse(date); c = Calendar.getInstance(); c.setTime(parsedDate); // first day of this week c.setFirstDayOfWeek(Calendar.MONDAY); c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY ); String startDateLabel = StatsUtils.msToString(c.getTimeInMillis(), "MMMM dd"); // last day of this week c.add(Calendar.DAY_OF_WEEK, + 6); String endDateLabel = StatsUtils.msToString(c.getTimeInMillis(), "MMMM dd"); return String.format(prefix, startDateLabel + " - " + endDateLabel); } catch (ParseException e) { AppLog.e(AppLog.T.UTILS, e); return ""; } case MONTH: return String.format(prefix, StatsUtils.parseDate(date, "yyyy-MM-dd", "MMMM")); case YEAR: return String.format(prefix, StatsUtils.parseDate(date, "yyyy-MM-dd", "yyyy")); } return ""; } /** * Return the date string that is displayed under each bar in the graph */ private String getDateLabelForBarInGraph(String dateToFormat) { switch (getTimeframe()) { case DAY: return StatsUtils.parseDate(dateToFormat, "yyyy-MM-dd", "MMM d"); case WEEK: // first four digits are the year // followed by Wxx where xx is the month // followed by Wxx where xx is the day of the month // ex: 2013W07W22 = July 22, 2013 return StatsUtils.parseDate(dateToFormat, "yyyy'W'MM'W'dd", "MMM d"); case MONTH: return StatsUtils.parseDate(dateToFormat, "yyyy-MM", "MMM"); case YEAR: return StatsUtils.parseDate(dateToFormat, "yyyy-MM-dd", "yyyy"); default: return dateToFormat; } } private void setupNoResultsUI(boolean isLoading) { mSelectedBarGraphBarIndex = -1; Context context = mGraphContainer.getContext(); if (context != null) { LayoutInflater inflater = LayoutInflater.from(context); View emptyBarGraphView = inflater.inflate(R.layout.stats_bar_graph_empty, mGraphContainer, false); // We could show loading indicator here if (isLoading) { final TextView emptyLabel = (TextView) emptyBarGraphView.findViewById(R.id.stats_bar_graph_empty_label); emptyLabel.setText(""); } if (emptyBarGraphView != null) { mGraphContainer.removeAllViews(); mGraphContainer.addView(emptyBarGraphView); } } mDateTextView.setText(""); for (int i=0 ; i < mModuleButtonsContainer.getChildCount(); i++) { View o = mModuleButtonsContainer.getChildAt(i); if (o instanceof CheckedTextView) { CheckedTextView currentBtm = (CheckedTextView)o; OverviewLabel overviewItem = (OverviewLabel)currentBtm.getTag(); String labelPrefix = overviewItem.getLabel() + "\n 0" ; currentBtm.setText(labelPrefix); } } } private int getNumOfPoints() { if (!isAdded()) { return 0; } if(StatsUIHelper.shouldLoadMoreBars(getActivity())) { return 10; } else { return 7; } } @Override protected String getTitle() { return getString(R.string.stats_view_visitors_and_views); } /* * receives broadcast when data has been updated */ private final BroadcastReceiver mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { String action = StringUtils.notNullStr(intent.getAction()); if (!isAdded()) { return; } if (!action.equals(StatsService.ACTION_STATS_SECTION_UPDATED)) { return; } if (!intent.hasExtra(StatsService.EXTRA_ENDPOINT_NAME)) { return; } StatsService.StatsEndpointsEnum sectionToUpdate = (StatsService.StatsEndpointsEnum) intent.getSerializableExtra(StatsService.EXTRA_ENDPOINT_NAME); if (sectionToUpdate != StatsService.StatsEndpointsEnum.VISITS) { return; } if (action.equals(StatsService.ACTION_STATS_SECTION_UPDATED)) { Serializable dataObj = intent.getSerializableExtra(StatsService.EXTRA_ENDPOINT_DATA); mVisitsData = (dataObj == null || dataObj instanceof VolleyError) ? null : (VisitsModel) dataObj; mSelectedBarGraphBarIndex = -1; mSelectedOverviewItemIndex = 0; // Reset the bar to highlight if (mGraphView != null) { mGraphView.resetHighlightBar(); } updateUI(); } } }; @Override public void onBarTapped(int tappedBar) { //AppLog.d(AppLog.T.STATS, " Tapped bar date " + mStatsDate[tappedBar]); mSelectedBarGraphBarIndex = tappedBar; updateUIBelowTheGraph(tappedBar); if (!NetworkUtils.isNetworkAvailable(getActivity())) { return; } // Update Stats here String date = mStatsDate[tappedBar]; if (date == null) { AppLog.w(AppLog.T.STATS, "A bar was tapped but a null date is received!!"); return; } //Calculate the correct end date for the selected period String calculatedDate = null; try { SimpleDateFormat sdf; Calendar c = Calendar.getInstance(); c.setFirstDayOfWeek(Calendar.MONDAY); final Date parsedDate; switch (getTimeframe()) { case DAY: calculatedDate = date; break; case WEEK: // first four digits are the year // followed by Wxx where xx is the month // followed by Wxx where xx is the day of the month // ex: 2013W07W22 = July 22, 2013 sdf = new SimpleDateFormat("yyyy'W'MM'W'dd"); //Calculate the end of the week parsedDate = sdf.parse(date); c.setTime(parsedDate); // first day of this week c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); // last day of this week c.add(Calendar.DAY_OF_WEEK, +6); calculatedDate = StatsUtils.msToString(c.getTimeInMillis(), "yyyy-MM-dd"); break; case MONTH: sdf = new SimpleDateFormat("yyyy-MM"); //Calculate the end of the month parsedDate = sdf.parse(date); c.setTime(parsedDate); // last day of this month c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH)); calculatedDate = StatsUtils.msToString(c.getTimeInMillis(), "yyyy-MM-dd"); break; case YEAR: sdf = new SimpleDateFormat("yyyy-MM-dd"); //Calculate the end of the week parsedDate = sdf.parse(date); c.setTime(parsedDate); c.set(Calendar.MONTH, Calendar.DECEMBER); c.set(Calendar.DAY_OF_MONTH, 31); calculatedDate = StatsUtils.msToString(c.getTimeInMillis(), "yyyy-MM-dd"); break; } } catch (ParseException e) { AppLog.e(AppLog.T.UTILS, e); } if (calculatedDate == null) { AppLog.w(AppLog.T.STATS, "A call to request new stats stats is made but date received cannot be parsed!! " + date); return; } // Update the data below the graph if (mListener!= null) { // Should never be null final String blogId = StatsUtils.getBlogId(getLocalTableBlogID()); mListener.onDateChanged(blogId, getTimeframe(), calculatedDate); } } private enum OverviewLabel { VIEWS(R.string.stats_views), VISITORS(R.string.stats_visitors), LIKES(R.string.stats_likes), COMMENTS(R.string.stats_comments), ; private final int mLabelResId; private OverviewLabel(int labelResId) { mLabelResId = labelResId; } public String getLabel() { return WordPress.getContext().getString(mLabelResId); } public static String[] toStringArray(OverviewLabel[] timeframes) { String[] titles = new String[timeframes.length]; for (int i = 0; i < timeframes.length; i++) { titles[i] = timeframes[i].getLabel(); } return titles; } } @Override protected void resetDataModel() { mVisitsData = null; } }
gpl-2.0
oonym/l2InterludeServer
L2J_Server/java/net/sf/l2j/gameserver/instancemanager/OlympiadStadiaManager.java
2605
/* This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA * 02111-1307, USA. * * http://www.gnu.org/copyleft/gpl.html */ package net.sf.l2j.gameserver.instancemanager; import java.util.logging.Logger; import javolution.util.FastList; import net.sf.l2j.gameserver.model.L2Character; import net.sf.l2j.gameserver.model.zone.type.L2OlympiadStadiumZone; public class OlympiadStadiaManager { protected static Logger _log = Logger.getLogger(OlympiadStadiaManager.class.getName()); // ========================================================= private static OlympiadStadiaManager _instance; public static final OlympiadStadiaManager getInstance() { if (_instance == null) { System.out.println("Initializing OlympiadStadiaManager"); _instance = new OlympiadStadiaManager(); } return _instance; } // ========================================================= // ========================================================= // Data Field private FastList<L2OlympiadStadiumZone> _olympiadStadias; // ========================================================= // Constructor public OlympiadStadiaManager() { } // ========================================================= // Property - Public public void addStadium(L2OlympiadStadiumZone arena) { if (_olympiadStadias == null) { _olympiadStadias = new FastList<>(); } _olympiadStadias.add(arena); } public final L2OlympiadStadiumZone getStadium(L2Character character) { for (L2OlympiadStadiumZone temp : _olympiadStadias) { if (temp.isCharacterInZone(character)) { return temp; } } return null; } @Deprecated public final L2OlympiadStadiumZone getOlympiadStadiumById(int olympiadStadiumId) { for (L2OlympiadStadiumZone temp : _olympiadStadias) { if (temp.getStadiumId() == olympiadStadiumId) { return temp; } } return null; } }
gpl-2.0
ssvsergeyev/ZenPacks.zenoss.AWS
ZenPacks/zenoss/AWS/EC2Region.py
5440
############################################################################## # # Copyright (C) Zenoss, Inc. 2013, all rights reserved. # # This content is made available according to terms specified in # License.zenoss under the directory where your Zenoss product is installed. # ############################################################################## import logging LOG = logging.getLogger('zen.AWS') import operator from zope.component import adapts from zope.interface import implements from ZODB.transact import transact from Products.ZenRelations.RelSchema import ToOne, ToManyCont from Products.Zuul.decorators import info from Products.Zuul.form import schema from Products.Zuul.infos.component import ComponentInfo from Products.Zuul.interfaces.component import IComponentInfo from Products.Zuul.utils import ZuulMessageFactory as _t from ZenPacks.zenoss.AWS import MODULE_NAME from ZenPacks.zenoss.AWS.AWSComponent import AWSComponent class EC2Region(AWSComponent): ''' Model class for EC2Region. ''' meta_type = portal_type = 'EC2Region' _instance_device_ids = None _properties = AWSComponent._properties _relations = AWSComponent._relations + ( ('account', ToOne(ToManyCont, MODULE_NAME['EC2Account'], 'regions')), ('zones', ToManyCont(ToOne, MODULE_NAME['EC2Zone'], 'region')), ('instances', ToManyCont(ToOne, MODULE_NAME['EC2Instance'], 'region')), ('volumes', ToManyCont(ToOne, MODULE_NAME['EC2Volume'], 'region')), ('snapshots', ToManyCont(ToOne, MODULE_NAME['EC2Snapshot'], 'region')), ('vpcs', ToManyCont(ToOne, MODULE_NAME['EC2VPC'], 'region')), ('vpc_subnets', ToManyCont( ToOne, MODULE_NAME['EC2VPCSubnet'], 'region' )), ('elastic_ips', ToManyCont( ToOne, MODULE_NAME['EC2ElasticIP'], 'region' )), ('vpn_gateways', ToManyCont( ToOne, MODULE_NAME['VPNGateway'], 'region' )), ('queues', ToManyCont( ToOne, MODULE_NAME['SQSQueue'], 'region' )), ('images', ToManyCont( ToOne, MODULE_NAME['EC2Image'], 'region' )), ('reserved_instances', ToManyCont( ToOne, MODULE_NAME['EC2ReservedInstance'], 'region' )), ) def getDimension(self): return '' def getRegionId(self): return self.id def discover_guests(self): ''' Attempt to discover and link instance guest devices. ''' map(operator.methodcaller('discover_guest'), self.instances()) # First discovery. Initialize our instance device ids storage. if self._instance_device_ids is None: self._instance_device_ids = set(self.instances.objectIds()) return instance_device_ids = set(self.instances.objectIds()) terminated_device_ids = self._instance_device_ids.difference( instance_device_ids) # Delete guest devices for terminated instances. for device_id in terminated_device_ids: guest_device = self.findDeviceByIdExact(device_id) if guest_device: LOG.info( 'Deleting device %s after instance %s was terminated', guest_device.titleOrId(), guest_device.id) guest_device.deleteDevice() # Store instance device ids for next run. self._instance_device_ids = instance_device_ids def setVolumesStatuses(self, data): ''' Updates volumes statuses ''' for volume in self.volumes(): if volume.id in data: volume.status = data[volume.id] volume.index_object() def getVolumesStatuses(self): return True def setInstancesStates(self, data): ''' Updates instances states ''' for instance in self.instances(): if instance.id in data: instance.state = data[instance.id] instance.index_object() def getInstancesStates(self): return True class IEC2RegionInfo(IComponentInfo): ''' API Info interface for EC2Region. ''' account = schema.Entity(title=_t(u'Account')) zone_count = schema.Int(title=_t(u'Number of Zones')) image_count = schema.Int(title=_t(u'Number of Images')) instance_count = schema.Int(title=_t(u'Number of Instances')) volume_count = schema.Int(title=_t(u'Number of Volumes')) vpc_count = schema.Int(title=_t(u'Number of VPCs')) vpc_subnet_count = schema.Int(title=_t(u'Number of VPC Subnets')) class EC2RegionInfo(ComponentInfo): ''' API Info adapter factory for EC2Region. ''' implements(IEC2RegionInfo) adapts(EC2Region) @property @info def account(self): return self._object.device() @property def zone_count(self): return self._object.zones.countObjects() @property def image_count(self): return self._object.images.countObjects() @property def instance_count(self): return self._object.instances.countObjects() @property def volume_count(self): return self._object.volumes.countObjects() @property def vpc_count(self): return self._object.vpcs.countObjects() @property def vpc_subnet_count(self): return self._object.vpc_subnets.countObjects()
gpl-2.0
dzvinka-mytsyk/smalltowns
wp-content/plugins/wpglobus/includes/class-wpglobus-config.php
15228
<?php /** * @package WPGlobus */ /** * Class WPGlobus_Config */ class WPGlobus_Config { /** * Language by default * @var string */ public $default_language = 'en'; /** * Current language. Should be set to default initially. * @var string */ public $language = 'en'; /** * Enabled languages * @var string[] */ public $enabled_languages = array( 'en', 'es', 'de', 'fr', 'ru', ); /** * Hide from URL language by default * @var bool */ public $hide_default_language = true; /** * Opened languages * @var string[] */ public $open_languages = array(); /** * Flag images configuration * Look in /flags/ directory for a huge list of flags for usage * @var array */ public $flag = array(); /** * Location of flags (needs trailing slash!) * @var string */ public $flags_url = ''; /** * Stores languages in pairs code=>name * @var array */ public $language_name = array(); /** * Stores languages names in English * @var array */ public $en_language_name = array(); /** * Stores locales * @var array */ public $locale = array(); /** * Stores enabled locales * @since 1.0.10 * @var array */ public $enabled_locale = array(); /** * Stores version and update from WPGlobus Mini info * @var array */ public $version = array(); /** * Use flag name for navigation menu : 'name' || 'code' || '' * @var string */ public $show_flag_name = 'code'; /** * Use navigation menu by slug * for use in all nav menu set value to 'all' * @var string */ public $nav_menu = ''; /** * Add language selector to navigation menu which was created with wp_list_pages * @since 1.0.7 * @var bool */ public $selector_wp_list_pages = true; /** * Custom CSS * @var string */ public $custom_css = ''; /** * WPGlobus option key * @var string */ public $option = 'wpglobus_option'; /** * WPGlobus option versioning key * @var string */ public static $option_versioning = 'wpglobus_option_versioning'; /** * WPGlobus option key for $language_name * @var string */ public $option_language_names = 'wpglobus_option_language_names'; /** * WPGlobus option key for $en_language_name * @var string */ public $option_en_language_names = 'wpglobus_option_en_language_names'; /** * WPGlobus option key for $locale * @var string */ public $option_locale = 'wpglobus_option_locale'; /** * WPGlobus option key for $flag * @var string */ public $option_flags = 'wpglobus_option_flags'; /** * WPGlobus option key for meta settings * @var string */ public $option_post_meta_settings = 'wpglobus_option_post_meta_settings'; /** * @var string */ public $css_editor = ''; /** * WPGlobus devmode. * @var string */ public $toggle = 'on'; /** * @todo Refactor this * Duplicate var @see WPGlobus * @var array */ public $disabled_entities = array(); /** * WPGlobus extended options can be added via filter 'wpglobus_option_sections' * * @since 1.2.3 * @var array */ public $extended_options = array(); /** * Constructor */ public function __construct() { /** * @since 1.0.9 Hooked to 'plugins_loaded'. The 'init' is too late, because it happens after all * plugins already loaded their translations. */ add_action( 'plugins_loaded', array( $this, 'init_current_language' ), 0 ); add_action( 'plugins_loaded', array( $this, 'on_load_textdomain' ), 1 ); add_action( 'upgrader_process_complete', array( $this, 'on_activate' ), 10, 2 ); $this->_get_options(); } /** * Set the current language: if not found in the URL or REFERER, then keep the default * @since 1.1.1 */ public function init_current_language() { /** * Keep the default language if any of the code before does not detect another one. */ $this->language = $this->default_language; /** * Theoretically, we might not have any URL to get the language info from. */ $url_to_check = ''; if ( WPGlobus_WP::is_doing_ajax() ) { /** * If DOING_AJAX, we cannot retrieve the language information from the URL, * because it's always `admin-ajax`. * Therefore, we'll rely on the HTTP_REFERER (if it exists). */ if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) { $url_to_check = $_SERVER['HTTP_REFERER']; } } else { /** * If not AJAX and not ADMIN then we are at the front. Will use the current URL. */ if ( ! is_admin() ) { $url_to_check = WPGlobus_Utils::current_url(); } } /** * If we have an URL, extract language from it. * If extracted, set it as a current. */ if ( $url_to_check ) { $language_from_url = WPGlobus_Utils::extract_language_from_url( $url_to_check ); if ( $language_from_url ) { $this->language = $language_from_url; } } } /** * Check plugin version and update versioning option * * @param stdClass $object Plugin_Upgrader * @param array $options * * @return void */ public function on_activate( /** @noinspection PhpUnusedParameterInspection */ $object = null, $options = array() ) { if ( empty( $options['plugin'] ) or $options['plugin'] !== WPGLOBUS_PLUGIN_BASENAME or empty( $options['action'] ) or $options['action'] !== 'update' ) { /** * Not our business */ return; } /** * Here we can read the previous version value and do some actions if necessary. * For example, warn the users about breaking changes. * $version = get_option( self::$option_versioning ); * ... */ /** * Store the current version */ update_option( self::$option_versioning, array( 'current_version' => WPGLOBUS_VERSION ) ); } /** * Set current language * * @param string $locale */ public function set_language( $locale ) { /** * @todo Maybe use option for disable/enable setting current language corresponding with $locale ? */ foreach ( $this->locale as $language => $value ) { if ( $locale === $value ) { $this->language = $language; break; } } } /** * Check for enabled locale * @since 1.0.10 * * @param string $locale * * @return boolean */ public function is_enabled_locale( $locale ) { return in_array( $locale, $this->enabled_locale, true ); } /** * Load textdomain * @since 1.0.0 * @return void */ public function on_load_textdomain() { load_plugin_textdomain( 'wpglobus', false, basename( dirname( dirname( __FILE__ ) ) ) . '/languages' ); } /** * Set flags URL * @return void */ public function _set_flags_url() { $this->flags_url = WPGlobus::$PLUGIN_DIR_URL . 'flags/'; } /** * Set languages by default */ public function _set_languages() { /** * Names, flags and locales * Useful links * - languages in ISO 639-1 format http://en.wikipedia.org/wiki/List_of_ISO_639-1_codes * - regions http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 */ $this->language_name['en'] = "English"; $this->language_name['ru'] = "Русский"; $this->language_name['de'] = "Deutsch"; $this->language_name['zh'] = "中文"; $this->language_name['fi'] = "Suomi"; $this->language_name['fr'] = "Français"; $this->language_name['nl'] = "Nederlands"; $this->language_name['sv'] = "Svenska"; $this->language_name['it'] = "Italiano"; $this->language_name['ro'] = "Română"; $this->language_name['hu'] = "Magyar"; $this->language_name['ja'] = "日本語"; $this->language_name['es'] = "Español"; $this->language_name['vi'] = "Tiếng Việt"; $this->language_name['ar'] = "العربية"; $this->language_name['pt'] = "Português"; $this->language_name['br'] = "Português do Brazil"; $this->language_name['pl'] = "Polski"; $this->language_name['gl'] = "Galego"; $this->en_language_name['en'] = "English"; $this->en_language_name['ru'] = "Russian"; $this->en_language_name['de'] = "German"; $this->en_language_name['zh'] = "Chinese"; $this->en_language_name['fi'] = "Finnish"; $this->en_language_name['fr'] = "French"; $this->en_language_name['nl'] = "Dutch"; $this->en_language_name['sv'] = "Swedish"; $this->en_language_name['it'] = "Italian"; $this->en_language_name['ro'] = "Romanian"; $this->en_language_name['hu'] = "Hungarian"; $this->en_language_name['ja'] = "Japanese"; $this->en_language_name['es'] = "Spanish"; $this->en_language_name['vi'] = "Vietnamese"; $this->en_language_name['ar'] = "Arabic"; $this->en_language_name['pt'] = "Portuguese"; $this->en_language_name['br'] = "Portuguese Brazil"; $this->en_language_name['pl'] = "Polish"; $this->en_language_name['gl'] = "Galician"; #Locales $this->locale['en'] = "en_US"; $this->locale['ru'] = "ru_RU"; $this->locale['de'] = "de_DE"; $this->locale['zh'] = "zh_CN"; $this->locale['fi'] = "fi"; $this->locale['fr'] = "fr_FR"; $this->locale['nl'] = "nl_NL"; $this->locale['sv'] = "sv_SE"; $this->locale['it'] = "it_IT"; $this->locale['ro'] = "ro_RO"; $this->locale['hu'] = "hu_HU"; $this->locale['ja'] = "ja"; $this->locale['es'] = "es_ES"; $this->locale['vi'] = "vi"; $this->locale['ar'] = "ar"; $this->locale['pt'] = "pt_PT"; $this->locale['br'] = "pt_BR"; $this->locale['pl'] = "pl_PL"; $this->locale['gl'] = "gl_ES"; #flags $this->flag['en'] = 'us.png'; $this->flag['ru'] = 'ru.png'; $this->flag['de'] = 'de.png'; $this->flag['zh'] = 'cn.png'; $this->flag['fi'] = 'fi.png'; $this->flag['fr'] = 'fr.png'; $this->flag['nl'] = 'nl.png'; $this->flag['sv'] = 'se.png'; $this->flag['it'] = 'it.png'; $this->flag['ro'] = 'ro.png'; $this->flag['hu'] = 'hu.png'; $this->flag['ja'] = 'jp.png'; $this->flag['es'] = 'es.png'; $this->flag['vi'] = 'vn.png'; $this->flag['ar'] = 'arle.png'; $this->flag['pt'] = 'pt.png'; $this->flag['br'] = 'br.png'; $this->flag['pl'] = 'pl.png'; $this->flag['gl'] = 'galego.png'; } /** * Set default options * @return void */ protected function _set_default_options() { update_option( $this->option_language_names, $this->language_name ); update_option( $this->option_en_language_names, $this->en_language_name ); update_option( $this->option_locale, $this->locale ); update_option( $this->option_flags, $this->flag ); } /** * Get options from DB and wp-config.php * @return void */ protected function _get_options() { $wpglobus_option = get_option( $this->option ); /** * FIX: after "Reset All" Redux options we must reset all WPGlobus options * first of all look at $wpglobus_option['more_languages'] */ if ( isset( $wpglobus_option['more_languages'] ) && is_array( $wpglobus_option['more_languages'] ) ) { $wpglobus_option = array(); delete_option( $this->option ); delete_option( $this->option_language_names ); delete_option( $this->option_en_language_names ); delete_option( $this->option_locale ); delete_option( $this->option_flags ); } if ( isset( $wpglobus_option['more_languages'] ) ) { unset( $wpglobus_option['more_languages'] ); } /** * Get enabled languages and default language ( just one main language ) */ if ( isset( $wpglobus_option['enabled_languages'] ) && ! empty( $wpglobus_option['enabled_languages'] ) ) { $this->enabled_languages = array(); foreach ( $wpglobus_option['enabled_languages'] as $lang => $value ) { if ( ! empty( $value ) ) { $this->enabled_languages[] = $lang; } } /** * Set default language */ $this->default_language = $this->enabled_languages[0]; unset( $wpglobus_option['enabled_languages'] ); } /** * Set available languages for editors */ $this->open_languages = $this->enabled_languages; /** * Set flags URL */ $this->_set_flags_url(); /** * Get languages name * big array of used languages */ $this->language_name = get_option( $this->option_language_names ); if ( empty( $this->language_name ) ) { $this->_set_languages(); $this->_set_default_options(); } /** * Get locales */ $this->locale = get_option( $this->option_locale ); if ( empty( $this->locale ) ) { $this->_set_languages(); $this->_set_default_options(); } /** * Get enabled locales */ foreach ( $this->enabled_languages as $language ) { $this->enabled_locale[] = $this->locale[ $language ]; } /** * Get en_language_name */ $this->en_language_name = get_option( $this->option_en_language_names ); /** * Get option 'show_flag_name' */ if ( isset( $wpglobus_option['show_flag_name'] ) ) { $this->show_flag_name = $wpglobus_option['show_flag_name']; unset( $wpglobus_option['show_flag_name'] ); } if ( defined( 'WPGLOBUS_SHOW_FLAG_NAME' ) ) { if ( 'name' === WPGLOBUS_SHOW_FLAG_NAME ) { $this->show_flag_name = 'name'; } elseif ( false === WPGLOBUS_SHOW_FLAG_NAME || '' === WPGLOBUS_SHOW_FLAG_NAME ) { $this->show_flag_name = ''; } } /** * Get navigation menu slug for add flag in front-end 'use_nav_menu' */ $this->nav_menu = ''; if ( isset( $wpglobus_option['use_nav_menu'] ) ) { $this->nav_menu = ( $wpglobus_option['use_nav_menu'] == 'all' ) ? 'all' : $wpglobus_option['use_nav_menu']; unset( $wpglobus_option['use_nav_menu'] ); } if ( defined( 'WPGLOBUS_USE_NAV_MENU' ) ) { $this->nav_menu = WPGLOBUS_USE_NAV_MENU; } /** * Get selector_wp_list_pages option * @since 1.0.7 */ if ( empty( $wpglobus_option['selector_wp_list_pages']['show_selector'] ) || $wpglobus_option['selector_wp_list_pages']['show_selector'] == 0 ) { $this->selector_wp_list_pages = false; } if ( isset( $wpglobus_option['selector_wp_list_pages'] ) ) { unset( $wpglobus_option['selector_wp_list_pages'] ); } /** * Get custom CSS */ if ( isset( $wpglobus_option['css_editor'] ) ) { $this->css_editor = $wpglobus_option['css_editor']; unset( $wpglobus_option['css_editor'] ); } /** * Get flag files without path */ $option = get_option( $this->option_flags ); if ( ! empty( $option ) ) { $this->flag = $option; } /** * Get versioning info */ $option = get_option( self::$option_versioning ); if ( empty( $option ) ) { $this->version = array(); } else { $this->version = $option; } /** * WPGlobus devmode. */ if ( isset( $_GET['wpglobus'] ) && 'off' === $_GET['wpglobus'] ) { $this->toggle = 'off'; } else { $this->toggle = 'on'; } /** * Need additional check for devmode (toggle=OFF) * in case 'wpglobus' was not set to 'off' at /wp-admin/post.php * and $_SERVER[QUERY_STRING] is empty at the time of `wp_insert_post_data` action * @see WPGlobus::on_save_post_data */ if ( empty( $_SERVER['QUERY_STRING'] ) && isset( $_SERVER['HTTP_REFERER'] ) && WPGlobus_WP::is_pagenow( 'post.php' ) && false !== strpos( $_SERVER['HTTP_REFERER'], 'wpglobus=off' ) ) { $this->toggle = 'off'; } if ( isset( $wpglobus_option['last_tab'] ) ) { unset( $wpglobus_option['last_tab'] ); } /** * Remaining wpglobus options after unset() is extended options * @since 1.2.3 */ $this->extended_options = $wpglobus_option; } } //class # --- EOF
gpl-2.0
oehm-smith/JStockMvn
src/main/java/org/yccheok/jstock/gui/PasswordInputJDialog.java
4493
/* * PasswordJDialog.java * * Created on June 20, 2007, 9:59 PM * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or (at * your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * Copyright (C) 2007 Cheok YanCheng <yccheok@yahoo.com> */ package org.yccheok.jstock.gui; /** * * @author yccheok */ public class PasswordInputJDialog extends javax.swing.JDialog { /** Creates new form PasswordJDialog */ public PasswordInputJDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); jButton1 = new javax.swing.JButton(); jButton2 = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPasswordField1 = new javax.swing.JPasswordField(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Indicator Password"); setResizable(false); jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16x16/apply.png"))); // NOI18N jButton1.setText("OK"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); jPanel2.add(jButton1); jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/16x16/button_cancel.png"))); // NOI18N jButton2.setText("Cancel"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jPanel2.add(jButton2); getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); jLabel1.setText("Please enter your indicator password"); jPanel1.add(jLabel1); jPasswordField1.setPreferredSize(new java.awt.Dimension(100, 19)); jPanel1.add(jPasswordField1); getContentPane().add(jPanel1, java.awt.BorderLayout.CENTER); java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize(); setBounds((screenSize.width-400)/2, (screenSize.height-95)/2, 400, 95); }// </editor-fold>//GEN-END:initComponents private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed returnCode = false; this.setVisible(false); this.dispose(); }//GEN-LAST:event_jButton2ActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed returnCode = true; this.setVisible(false); this.dispose(); }//GEN-LAST:event_jButton1ActionPerformed public boolean isPasswordMatch(String password) { return new String(jPasswordField1.getPassword()).equals(password); } public boolean doModal() { this.setVisible(true); return returnCode; } private boolean returnCode = false; // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton1; private javax.swing.JButton jButton2; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPasswordField jPasswordField1; // End of variables declaration//GEN-END:variables }
gpl-2.0
Apple15/AppleCore
src/bindings/scriptdev2/scripts/northrend/naxxramas/boss_anubrekhan.cpp
6098
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: Boss_Anubrekhan SD%Complete: 70 SDComment: SDCategory: Naxxramas EndScriptData */ #include "precompiled.h" #include "naxxramas.h" enum { SAY_GREET = -1533000, SAY_AGGRO1 = -1533001, SAY_AGGRO2 = -1533002, SAY_AGGRO3 = -1533003, SAY_TAUNT1 = -1533004, SAY_TAUNT2 = -1533005, SAY_TAUNT3 = -1533006, SAY_TAUNT4 = -1533007, SAY_SLAY = -1533008, SPELL_IMPALE = 28783, //May be wrong spell id. Causes more dmg than I expect SPELL_IMPALE_H = 56090, SPELL_LOCUSTSWARM = 28785, //This is a self buff that triggers the dmg debuff SPELL_LOCUSTSWARM_H = 54021, //spellId invalid SPELL_SUMMONGUARD = 29508, //Summons 1 crypt guard at targeted location SPELL_SELF_SPAWN_5 = 29105, //This spawns 5 corpse scarabs ontop of us (most likely the pPlayer casts this on death) SPELL_SELF_SPAWN_10 = 28864, //This is used by the crypt guards when they die NPC_CRYPT_GUARD = 16573 }; struct MANGOS_DLL_DECL boss_anubrekhanAI : public ScriptedAI { boss_anubrekhanAI(Creature* pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_bIsRegularMode = pCreature->GetMap()->IsRegularDifficulty(); m_bHasTaunted = false; Reset(); } ScriptedInstance* m_pInstance; bool m_bIsRegularMode; uint32 m_uiImpaleTimer; uint32 m_uiLocustSwarmTimer; uint32 m_uiSummonTimer; bool m_bHasTaunted; void Reset() { m_uiImpaleTimer = 15000; // 15 seconds m_uiLocustSwarmTimer = urand(80000, 120000); // Random time between 80 seconds and 2 minutes for initial cast m_uiSummonTimer = m_uiLocustSwarmTimer + 45000; // 45 seconds after initial locust swarm } void KilledUnit(Unit* pVictim) { //Force the player to spawn corpse scarabs via spell if (pVictim->GetTypeId() == TYPEID_PLAYER) pVictim->CastSpell(pVictim, SPELL_SELF_SPAWN_5, true); if (urand(0, 4)) return; DoScriptText(SAY_SLAY, m_creature); } void Aggro(Unit* pWho) { switch(urand(0, 2)) { case 0: DoScriptText(SAY_AGGRO1, m_creature); break; case 1: DoScriptText(SAY_AGGRO2, m_creature); break; case 2: DoScriptText(SAY_AGGRO3, m_creature); break; } if (m_pInstance) m_pInstance->SetData(TYPE_ANUB_REKHAN, IN_PROGRESS); } void JustDied(Unit* pKiller) { if (m_pInstance) m_pInstance->SetData(TYPE_ANUB_REKHAN, DONE); } void JustReachedHome() { if (m_pInstance) m_pInstance->SetData(TYPE_ANUB_REKHAN, FAIL); } void MoveInLineOfSight(Unit* pWho) { if (!m_bHasTaunted && m_creature->IsWithinDistInMap(pWho, 60.0f)) { switch(urand(0, 4)) { case 0: DoScriptText(SAY_GREET, m_creature); break; case 1: DoScriptText(SAY_TAUNT1, m_creature); break; case 2: DoScriptText(SAY_TAUNT2, m_creature); break; case 3: DoScriptText(SAY_TAUNT3, m_creature); break; case 4: DoScriptText(SAY_TAUNT4, m_creature); break; } m_bHasTaunted = true; } ScriptedAI::MoveInLineOfSight(pWho); } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; // Impale if (m_uiImpaleTimer < uiDiff) { //Cast Impale on a random target //Do NOT cast it when we are afflicted by locust swarm if (!m_creature->HasAura(SPELL_LOCUSTSWARM) || !m_creature->HasAura(SPELL_LOCUSTSWARM_H)) { if (Unit* target = SelectUnit(SELECT_TARGET_RANDOM,0)) DoCastSpellIfCan(target, m_bIsRegularMode ? SPELL_IMPALE : SPELL_IMPALE_H); } m_uiImpaleTimer = 15000; } else m_uiImpaleTimer -= uiDiff; // Locust Swarm if (m_uiLocustSwarmTimer < uiDiff) { DoCastSpellIfCan(m_creature, m_bIsRegularMode ? SPELL_LOCUSTSWARM :SPELL_LOCUSTSWARM_H); m_uiLocustSwarmTimer = 90000; } else m_uiLocustSwarmTimer -= uiDiff; // Summon /*if (m_uiSummonTimer < uiDiff) { DoCastSpellIfCan(m_creature, SPELL_SUMMONGUARD); Summon_Timer = 45000; } else m_uiSummonTimer -= uiDiff;*/ DoMeleeAttackIfReady(); } }; CreatureAI* GetAI_boss_anubrekhan(Creature* pCreature) { return new boss_anubrekhanAI(pCreature); } void AddSC_boss_anubrekhan() { Script* NewScript; NewScript = new Script; NewScript->Name = "boss_anubrekhan"; NewScript->GetAI = &GetAI_boss_anubrekhan; NewScript->RegisterSelf(); }
gpl-2.0
alucardxlx/kaltar
Scripts/Mobiles/Vendors/PlayerVendor.cs
40254
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using Server; using Server.Items; using Server.Mobiles; using Server.Gumps; using Server.Prompts; using Server.Targeting; using Server.Misc; using Server.Multis; using Server.ContextMenus; namespace Server.Mobiles { [AttributeUsage( AttributeTargets.Class )] public class PlayerVendorTargetAttribute : Attribute { public PlayerVendorTargetAttribute() { } } public class VendorItem { private Item m_Item; private int m_Price; private string m_Description; private DateTime m_Created; private bool m_Valid; public Item Item{ get{ return m_Item; } } public int Price{ get{ return m_Price; } } public string FormattedPrice { get { if ( Core.ML ) return m_Price.ToString( "N0", CultureInfo.GetCultureInfo( "en-US" ) ); return m_Price.ToString(); } } public string Description { get{ return m_Description; } set { if ( value != null ) m_Description = value; else m_Description = ""; if ( Valid ) Item.InvalidateProperties(); } } public DateTime Created{ get{ return m_Created; } } public bool IsForSale{ get{ return Price >= 0; } } public bool IsForFree{ get{ return Price == 0; } } public bool Valid{ get{ return m_Valid; } } public VendorItem( Item item, int price, string description, DateTime created ) { m_Item = item; m_Price = price; if ( description != null ) m_Description = description; else m_Description = ""; m_Created = created; m_Valid = true; } public void Invalidate() { m_Valid = false; } } public class VendorBackpack : Backpack { public VendorBackpack() { Layer = Layer.Backpack; Weight = 1.0; } public override int DefaultMaxWeight{ get{ return 0; } } public override bool CheckHold( Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight ) { if ( !base.CheckHold( m, item, message, checkItems, plusItems, plusWeight ) ) return false; if ( Ethics.Ethic.IsImbued( item, true ) ) { if ( message ) m.SendMessage( "Imbued items may not be sold here." ); return false; } if ( !BaseHouse.NewVendorSystem && Parent is PlayerVendor ) { BaseHouse house = ((PlayerVendor)Parent).House; if ( house != null && house.IsAosRules && !house.CheckAosStorage( 1 + item.TotalItems + plusItems ) ) { if ( message ) m.SendLocalizedMessage( 1061839 ); // This action would exceed the secure storage limit of the house. return false; } } return true; } public override bool IsAccessibleTo( Mobile m ) { return true; } public override bool CheckItemUse( Mobile from, Item item ) { if ( !base.CheckItemUse( from, item ) ) return false; if ( item is Container || item is Engines.BulkOrders.BulkOrderBook ) return true; from.SendLocalizedMessage( 500447 ); // That is not accessible. return false; } public override bool CheckTarget( Mobile from, Target targ, object targeted ) { if ( !base.CheckTarget( from, targ, targeted ) ) return false; if ( from.AccessLevel >= AccessLevel.GameMaster ) return true; return targ.GetType().IsDefined( typeof( PlayerVendorTargetAttribute ), false ); } public override void GetChildContextMenuEntries( Mobile from, List<ContextMenuEntry> list, Item item ) { base.GetChildContextMenuEntries( from, list, item ); PlayerVendor pv = RootParent as PlayerVendor; if ( pv == null || pv.IsOwner( from ) ) return; VendorItem vi = pv.GetVendorItem( item ); if ( vi != null ) list.Add( new BuyEntry( item ) ); } private class BuyEntry : ContextMenuEntry { private Item m_Item; public BuyEntry( Item item ) : base( 6103 ) { m_Item = item; } public override bool NonLocalUse{ get{ return true; } } public override void OnClick() { if ( m_Item.Deleted ) return; PlayerVendor.TryToBuy( m_Item, Owner.From ); } } public override void GetChildNameProperties( ObjectPropertyList list, Item item ) { base.GetChildNameProperties( list, item ); PlayerVendor pv = RootParent as PlayerVendor; if ( pv == null ) return; VendorItem vi = pv.GetVendorItem( item ); if ( vi == null ) return; if ( !vi.IsForSale ) list.Add( 1043307 ); // Price: Not for sale. else if ( vi.IsForFree ) list.Add( 1043306 ); // Price: FREE! else list.Add( 1043304, vi.FormattedPrice ); // Price: ~1_COST~ } public override void GetChildProperties( ObjectPropertyList list, Item item ) { base.GetChildProperties( list, item ); PlayerVendor pv = RootParent as PlayerVendor; if ( pv == null ) return; VendorItem vi = pv.GetVendorItem( item ); if ( vi != null && vi.Description != null && vi.Description.Length > 0 ) list.Add( 1043305, vi.Description ); // <br>Seller's Description:<br>"~1_DESC~" } public override void OnSingleClickContained( Mobile from, Item item ) { if ( RootParent is PlayerVendor ) { PlayerVendor vendor = (PlayerVendor)RootParent; VendorItem vi = vendor.GetVendorItem( item ); if ( vi != null ) { if ( !vi.IsForSale ) item.LabelTo( from, 1043307 ); // Price: Not for sale. else if ( vi.IsForFree ) item.LabelTo( from, 1043306 ); // Price: FREE! else item.LabelTo( from, 1043304, vi.FormattedPrice ); // Price: ~1_COST~ if ( !String.IsNullOrEmpty( vi.Description ) ) { // The localized message (1043305) is no longer valid - <br>Seller's Description:<br>"~1_DESC~" item.LabelTo( from, "Description: {0}", vi.Description ); } } } base.OnSingleClickContained( from, item ); } public VendorBackpack( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } public class PlayerVendor : Mobile { private Hashtable m_SellItems; private Mobile m_Owner; private BaseHouse m_House; private int m_BankAccount; private int m_HoldGold; private string m_ShopName; private Timer m_PayTimer; private DateTime m_NextPayTime; private PlayerVendorPlaceholder m_Placeholder; public PlayerVendor( Mobile owner, BaseHouse house ) { Owner = owner; House = house; if ( BaseHouse.NewVendorSystem ) { m_BankAccount = 0; m_HoldGold = 4; } else { m_BankAccount = 1000; m_HoldGold = 0; } ShopName = "Shop Not Yet Named"; m_SellItems = new Hashtable(); CantWalk = true; if ( !Core.AOS ) NameHue = 0x35; InitStats( 75, 75, 75 ); InitBody(); InitOutfit(); TimeSpan delay = PayTimer.GetInterval(); m_PayTimer = new PayTimer( this, delay ); m_PayTimer.Start(); m_NextPayTime = DateTime.Now + delay; } public PlayerVendor( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 1 ); // version writer.Write( (bool) BaseHouse.NewVendorSystem ); writer.Write( (string) m_ShopName ); writer.WriteDeltaTime( (DateTime) m_NextPayTime ); writer.Write( (Item) House ); writer.Write( (Mobile) m_Owner ); writer.Write( (int) m_BankAccount ); writer.Write( (int) m_HoldGold ); writer.Write( (int) m_SellItems.Count ); foreach ( VendorItem vi in m_SellItems.Values ) { writer.Write( (Item) vi.Item ); writer.Write( (int) vi.Price ); writer.Write( (string) vi.Description ); writer.Write( (DateTime) vi.Created ); } } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); bool newVendorSystem = false; switch ( version ) { case 1: { newVendorSystem = reader.ReadBool(); m_ShopName = reader.ReadString(); m_NextPayTime = reader.ReadDeltaTime(); House = (BaseHouse) reader.ReadItem(); goto case 0; } case 0: { m_Owner = reader.ReadMobile(); m_BankAccount = reader.ReadInt(); m_HoldGold = reader.ReadInt(); m_SellItems = new Hashtable(); int count = reader.ReadInt(); for ( int i = 0; i < count; i++ ) { Item item = reader.ReadItem(); int price = reader.ReadInt(); if ( price > 100000000 ) price = 100000000; string description = reader.ReadString(); DateTime created = version < 1 ? DateTime.Now : reader.ReadDateTime(); if ( item != null ) { SetVendorItem( item, version < 1 && price <= 0 ? -1 : price, description, created ); } } break; } } bool newVendorSystemActivated = BaseHouse.NewVendorSystem && !newVendorSystem; if ( version < 1 || newVendorSystemActivated ) { if ( version < 1 ) { m_ShopName = "Shop Not Yet Named"; Timer.DelayCall( TimeSpan.Zero, new TimerStateCallback( UpgradeFromVersion0 ), newVendorSystemActivated ); } else { Timer.DelayCall( TimeSpan.Zero, new TimerCallback( FixDresswear ) ); } m_NextPayTime = DateTime.Now + PayTimer.GetInterval(); if ( newVendorSystemActivated ) { m_HoldGold += m_BankAccount; m_BankAccount = 0; } } TimeSpan delay = m_NextPayTime - DateTime.Now; m_PayTimer = new PayTimer( this, delay > TimeSpan.Zero ? delay : TimeSpan.Zero ); m_PayTimer.Start(); Blessed = false; if ( Core.AOS && NameHue == 0x35 ) NameHue = -1; } private void UpgradeFromVersion0( object newVendorSystem ) { List<Item> toRemove = new List<Item>(); foreach ( VendorItem vi in m_SellItems.Values ) if ( !CanBeVendorItem( vi.Item ) ) toRemove.Add( vi.Item ); else vi.Description = Utility.FixHtml( vi.Description ); foreach ( Item item in toRemove ) RemoveVendorItem( item ); House = BaseHouse.FindHouseAt( this ); if ( (bool) newVendorSystem ) ActivateNewVendorSystem(); } private void ActivateNewVendorSystem() { FixDresswear(); if ( House != null && !House.IsOwner( Owner ) ) Destroy( false ); } public void InitBody() { Hue = Utility.RandomSkinHue(); SpeechHue = 0x3B2; if ( !Core.AOS ) NameHue = 0x35; if ( this.Female = Utility.RandomBool() ) { this.Body = 0x191; this.Name = NameList.RandomName( "female" ); } else { this.Body = 0x190; this.Name = NameList.RandomName( "male" ); } } public virtual void InitOutfit() { Item item = new FancyShirt( Utility.RandomNeutralHue() ); item.Layer = Layer.InnerTorso; AddItem( item ); AddItem( new LongPants( Utility.RandomNeutralHue() ) ); AddItem( new BodySash( Utility.RandomNeutralHue() ) ); AddItem( new Boots( Utility.RandomNeutralHue() ) ); AddItem( new Cloak( Utility.RandomNeutralHue() ) ); Utility.AssignRandomHair( this ); Container pack = new VendorBackpack(); pack.Movable = false; AddItem( pack ); } [CommandProperty( AccessLevel.GameMaster )] public Mobile Owner { get{ return m_Owner; } set{ m_Owner = value; } } [CommandProperty( AccessLevel.GameMaster )] public int BankAccount { get{ return m_BankAccount; } set{ m_BankAccount = value; } } [CommandProperty( AccessLevel.GameMaster )] public int HoldGold { get{ return m_HoldGold; } set{ m_HoldGold = value; } } [CommandProperty( AccessLevel.GameMaster )] public string ShopName { get{ return m_ShopName; } set { if ( value == null ) m_ShopName = ""; else m_ShopName = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public DateTime NextPayTime { get{ return m_NextPayTime; } } public PlayerVendorPlaceholder Placeholder { get{ return m_Placeholder; } set{ m_Placeholder = value; } } public BaseHouse House { get{ return m_House; } set { if ( m_House != null ) m_House.PlayerVendors.Remove( this ); if ( value != null ) value.PlayerVendors.Add( this ); m_House = value; } } public int ChargePerDay { get { if ( BaseHouse.NewVendorSystem ) { return ChargePerRealWorldDay / 12; } else { long total = 0; foreach ( VendorItem vi in m_SellItems.Values ) { total += vi.Price; } total -= 500; if ( total < 0 ) total = 0; return (int)( 20 + (total / 500) ); } } } public int ChargePerRealWorldDay { get { if ( BaseHouse.NewVendorSystem ) { long total = 0; foreach ( VendorItem vi in m_SellItems.Values ) { total += vi.Price; } return (int)( 60 + (total / 500) * 3 ); } else { return ChargePerDay * 12; } } } public virtual bool IsOwner( Mobile m ) { if ( m.AccessLevel >= AccessLevel.GameMaster ) return true; if ( BaseHouse.NewVendorSystem && House != null ) { return House.IsOwner( m ); } else { return m == Owner; } } protected List<Item> GetItems() { List<Item> list = new List<Item>(); foreach ( Item item in this.Items ) if ( item.Movable && item != this.Backpack && item.Layer != Layer.Hair && item.Layer != Layer.FacialHair ) list.Add( item ); if ( this.Backpack != null ) list.AddRange( this.Backpack.Items ); return list; } public virtual void Destroy( bool toBackpack ) { Return(); if ( !BaseHouse.NewVendorSystem ) FixDresswear(); /* Possible cases regarding item return: * * 1. No item must be returned * -> do nothing. * 2. ( toBackpack is false OR the vendor is in the internal map ) AND the vendor is associated with a AOS house * -> put the items into the moving crate or a vendor inventory, * depending on whether the vendor owner is also the house owner. * 3. ( toBackpack is true OR the vendor isn't associated with any AOS house ) AND the vendor isn't in the internal map * -> put the items into a backpack. * 4. The vendor isn't associated with any house AND it's in the internal map * -> do nothing (we can't do anything). */ List<Item> list = GetItems(); if ( list.Count > 0 || HoldGold > 0 ) // No case 1 { if ( ( !toBackpack || this.Map == Map.Internal ) && House != null && House.IsAosRules ) // Case 2 { if ( House.IsOwner( Owner ) ) // Move to moving crate { if ( House.MovingCrate == null ) House.MovingCrate = new MovingCrate( House ); if ( HoldGold > 0 ) Banker.Deposit( House.MovingCrate, HoldGold ); foreach ( Item item in list ) { House.MovingCrate.DropItem( item ); } } else // Move to vendor inventory { VendorInventory inventory = new VendorInventory( House, Owner, Name, ShopName ); inventory.Gold = HoldGold; foreach ( Item item in list ) { inventory.AddItem( item ); } House.VendorInventories.Add( inventory ); } } else if ( ( toBackpack || House == null || !House.IsAosRules ) && this.Map != Map.Internal ) // Case 3 - Move to backpack { Container backpack = new Backpack(); if ( HoldGold > 0 ) Banker.Deposit( backpack, HoldGold ); foreach ( Item item in list ) { backpack.DropItem( item ); } backpack.MoveToWorld( this.Location, this.Map ); } } Delete(); } private void FixDresswear() { for ( int i = 0; i < Items.Count; ++i ) { Item item = Items[i] as Item; if ( item is BaseHat ) item.Layer = Layer.Helm; else if ( item is BaseMiddleTorso ) item.Layer = Layer.MiddleTorso; else if ( item is BaseOuterLegs ) item.Layer = Layer.OuterLegs; else if ( item is BaseOuterTorso ) item.Layer = Layer.OuterTorso; else if ( item is BasePants ) item.Layer = Layer.Pants; else if ( item is BaseShirt ) item.Layer = Layer.Shirt; else if ( item is BaseWaist ) item.Layer = Layer.Waist; else if ( item is BaseShoes ) { if ( item is Sandals ) item.Hue = 0; item.Layer = Layer.Shoes; } } } public override void OnAfterDelete() { base.OnAfterDelete(); m_PayTimer.Stop(); House = null; if ( Placeholder != null ) Placeholder.Delete(); } public override bool IsSnoop( Mobile from ) { return false; } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( BaseHouse.NewVendorSystem ) { list.Add( 1062449, ShopName ); // Shop Name: ~1_NAME~ } } public VendorItem GetVendorItem( Item item ) { return (VendorItem) m_SellItems[item]; } private VendorItem SetVendorItem( Item item, int price, string description ) { return SetVendorItem( item, price, description, DateTime.Now ); } private VendorItem SetVendorItem( Item item, int price, string description, DateTime created ) { RemoveVendorItem( item ); VendorItem vi = new VendorItem( item, price, description, created ); m_SellItems[item] = vi; item.InvalidateProperties(); return vi; } private void RemoveVendorItem( Item item ) { VendorItem vi = GetVendorItem( item ); if ( vi != null ) { vi.Invalidate(); m_SellItems.Remove( item ); foreach ( Item subItem in item.Items ) { RemoveVendorItem( subItem ); } item.InvalidateProperties(); } } private bool CanBeVendorItem( Item item ) { Item parent = item.Parent as Item; if ( parent == this.Backpack ) return true; if ( parent is Container ) { VendorItem parentVI = GetVendorItem( parent ); if ( parentVI != null ) return !parentVI.IsForSale; } return false; } public override void OnSubItemAdded( Item item ) { base.OnSubItemAdded( item ); if ( GetVendorItem( item ) == null && CanBeVendorItem( item ) ) { // TODO: default price should be dependent to the type of object SetVendorItem( item, 999, "" ); } } public override void OnSubItemRemoved( Item item ) { base.OnSubItemRemoved( item ); if ( item.GetBounce() == null ) RemoveVendorItem( item ); } public override void OnSubItemBounceCleared( Item item ) { base.OnSubItemBounceCleared( item ); if ( !CanBeVendorItem( item ) ) RemoveVendorItem( item ); } public override void OnItemRemoved( Item item ) { base.OnItemRemoved( item ); if ( item == this.Backpack ) { foreach ( Item subItem in item.Items ) { RemoveVendorItem( subItem ); } } } public override bool OnDragDrop( Mobile from, Item item ) { if ( !IsOwner( from ) ) { SayTo( from, 503209 ); // I can only take item from the shop owner. return false; } if ( item is Gold ) { if ( BaseHouse.NewVendorSystem ) { if ( this.HoldGold < 1000000 ) { SayTo( from, 503210 ); // I'll take that to fund my services. this.HoldGold += item.Amount; item.Delete(); return true; } else { from.SendLocalizedMessage( 1062493 ); // Your vendor has sufficient funds for operation and cannot accept this gold. return false; } } else { if ( this.BankAccount < 1000000 ) { SayTo( from, 503210 ); // I'll take that to fund my services. this.BankAccount += item.Amount; item.Delete(); return true; } else { from.SendLocalizedMessage( 1062493 ); // Your vendor has sufficient funds for operation and cannot accept this gold. return false; } } } else { bool newItem = ( GetVendorItem( item ) == null ); if ( this.Backpack != null && this.Backpack.TryDropItem( from, item, false ) ) { if ( newItem ) OnItemGiven( from, item ); return true; } else { SayTo( from, 503211 ); // I can't carry any more. return false; } } } public override bool CheckNonlocalDrop( Mobile from, Item item, Item target ) { if ( IsOwner( from ) ) { if ( GetVendorItem( item ) == null ) { // We must wait until the item is added Timer.DelayCall( TimeSpan.Zero, new TimerStateCallback( NonLocalDropCallback ), new object[] { from, item } ); } return true; } else { SayTo( from, 503209 ); // I can only take item from the shop owner. return false; } } private void NonLocalDropCallback( object state ) { object[] aState = (object[]) state; Mobile from = (Mobile) aState[0]; Item item = (Item) aState[1]; OnItemGiven( from, item ); } private void OnItemGiven( Mobile from, Item item ) { VendorItem vi = GetVendorItem( item ); if ( vi != null ) { string name; if ( !String.IsNullOrEmpty( item.Name ) ) name = item.Name; else name = "#" + item.LabelNumber.ToString(); from.SendLocalizedMessage( 1043303, name ); // Type in a price and description for ~1_ITEM~ (ESC=not for sale) from.Prompt = new VendorPricePrompt( this, vi ); } } public override bool AllowEquipFrom( Mobile from ) { if ( BaseHouse.NewVendorSystem && IsOwner( from ) ) return true; return base.AllowEquipFrom( from ); } public override bool CheckNonlocalLift( Mobile from, Item item ) { if ( item.IsChildOf( this.Backpack ) ) { if ( IsOwner( from ) ) { return true; } else { SayTo( from, 503223 ); // If you'd like to purchase an item, just ask. return false; } } else if ( BaseHouse.NewVendorSystem && IsOwner( from ) ) { return true; } return base.CheckNonlocalLift( from, item ); } public bool CanInteractWith( Mobile from, bool ownerOnly ) { if ( !from.CanSee( this ) || !Utility.InUpdateRange( from, this ) || !from.CheckAlive() ) return false; if ( ownerOnly ) return IsOwner( from ); if ( House != null && House.IsBanned( from ) && !IsOwner( from ) ) { from.SendLocalizedMessage( 1062674 ); // You can't shop from this home as you have been banned from this establishment. return false; } return true; } public override void OnDoubleClick( Mobile from ) { if ( IsOwner( from ) ) { SendOwnerGump( from ); } else if ( CanInteractWith( from, false ) ) { OpenBackpack( from ); } } public override void DisplayPaperdollTo( Mobile m ) { if ( BaseHouse.NewVendorSystem ) { base.DisplayPaperdollTo( m ); } else if ( CanInteractWith( m, false ) ) { OpenBackpack( m ); } } public void SendOwnerGump( Mobile to ) { if ( BaseHouse.NewVendorSystem ) { to.CloseGump( typeof( NewPlayerVendorOwnerGump ) ); to.CloseGump( typeof( NewPlayerVendorCustomizeGump ) ); to.SendGump( new NewPlayerVendorOwnerGump( this ) ); } else { to.CloseGump( typeof( PlayerVendorOwnerGump ) ); to.CloseGump( typeof( PlayerVendorCustomizeGump ) ); to.SendGump( new PlayerVendorOwnerGump( this ) ); } } public void OpenBackpack( Mobile from ) { if ( this.Backpack != null ) { SayTo( from, IsOwner( from ) ? 1010642 : 503208 ); // Take a look at my/your goods. this.Backpack.DisplayTo( from ); } } public static void TryToBuy( Item item, Mobile from ) { PlayerVendor vendor = item.RootParent as PlayerVendor; if ( vendor == null || !vendor.CanInteractWith( from, false ) ) return; if ( vendor.IsOwner( from ) ) { vendor.SayTo( from, 503212 ); // You own this shop, just take what you want. return; } VendorItem vi = vendor.GetVendorItem( item ); if ( vi == null ) { vendor.SayTo( from, 503216 ); // You can't buy that. } else if ( !vi.IsForSale ) { vendor.SayTo( from, 503202 ); // This item is not for sale. } else if ( vi.Created + TimeSpan.FromMinutes( 1.0 ) > DateTime.Now ) { from.SendMessage( "You cannot buy this item right now. Please wait one minute and try again." ); } else { from.CloseGump( typeof( PlayerVendorBuyGump ) ); from.SendGump( new PlayerVendorBuyGump( vendor, vi ) ); } } public void CollectGold( Mobile to ) { if ( HoldGold > 0 ) { SayTo( to, "How much of the {0} that I'm holding would you like?", HoldGold.ToString() ); to.SendMessage( "Enter the amount of gold you wish to withdraw (ESC = CANCEL):" ); to.Prompt = new CollectGoldPrompt( this ); } else { SayTo( to, 503215 ); // I am holding no gold for you. } } public int GiveGold( Mobile to, int amount ) { if ( amount <= 0 ) return 0; if ( amount > HoldGold ) { SayTo( to, "I'm sorry, but I'm only holding {0} gold for you.", HoldGold.ToString() ); return 0; } int amountGiven = Banker.DepositUpTo( to, amount ); HoldGold -= amountGiven; if ( amountGiven > 0 ) { to.SendLocalizedMessage( 1060397, amountGiven.ToString() ); // ~1_AMOUNT~ gold has been deposited into your bank box. } if ( amountGiven == 0 ) { SayTo( to, 1070755 ); // Your bank box cannot hold the gold you are requesting. I will keep the gold until you can take it. } else if ( amount > amountGiven ) { SayTo( to, 1070756 ); // I can only give you part of the gold now, as your bank box is too full to hold the full amount. } else if ( HoldGold > 0 ) { SayTo( to, 1042639 ); // Your gold has been transferred. } else { SayTo( to, 503234 ); // All the gold I have been carrying for you has been deposited into your bank account. } return amountGiven; } public void Dismiss( Mobile from ) { Container pack = this.Backpack; if ( pack != null && pack.Items.Count > 0 ) { SayTo( from, 1038325 ); // You cannot dismiss me while I am holding your goods. return; } if ( HoldGold > 0 ) { GiveGold( from, HoldGold ); if ( HoldGold > 0 ) return; } Destroy( true ); } public void Rename( Mobile from ) { from.SendLocalizedMessage( 1062494 ); // Enter a new name for your vendor (20 characters max): from.Prompt = new VendorNamePrompt( this ); } public void RenameShop( Mobile from ) { from.SendLocalizedMessage( 1062433 ); // Enter a new name for your shop (20 chars max): from.Prompt = new ShopNamePrompt( this ); } public bool CheckTeleport( Mobile to ) { if ( Deleted || !IsOwner( to ) || House == null || this.Map == Map.Internal ) return false; if ( House.IsInside( to ) || to.Map != House.Map || !House.InRange( to, 5 ) ) return false; if ( Placeholder == null ) { Placeholder = new PlayerVendorPlaceholder( this ); Placeholder.MoveToWorld( this.Location, this.Map ); this.MoveToWorld( to.Location, to.Map ); to.SendLocalizedMessage( 1062431 ); // This vendor has been moved out of the house to your current location temporarily. The vendor will return home automatically after two minutes have passed once you are done managing its inventory or customizing it. } else { Placeholder.RestartTimer(); to.SendLocalizedMessage( 1062430 ); // This vendor is currently temporarily in a location outside its house. The vendor will return home automatically after two minutes have passed once you are done managing its inventory or customizing it. } return true; } public void Return() { if ( Placeholder != null ) Placeholder.Delete(); } public override void GetContextMenuEntries( Mobile from, List<ContextMenuEntry> list ) { if ( from.Alive && Placeholder != null && IsOwner( from ) ) { list.Add( new ReturnVendorEntry( this ) ); } base.GetContextMenuEntries( from, list ); } private class ReturnVendorEntry : ContextMenuEntry { private PlayerVendor m_Vendor; public ReturnVendorEntry( PlayerVendor vendor ) : base( 6214 ) { m_Vendor = vendor; } public override void OnClick() { Mobile from = Owner.From; if ( !m_Vendor.Deleted && m_Vendor.IsOwner( from ) && from.CheckAlive() ) m_Vendor.Return(); } } public override bool HandlesOnSpeech( Mobile from ) { return ( from.Alive && from.GetDistanceToSqrt( this ) <= 3 ); } public bool WasNamed( string speech ) { return this.Name != null && Insensitive.StartsWith( speech, this.Name ); } public override void OnSpeech( SpeechEventArgs e ) { Mobile from = e.Mobile; if ( e.Handled || !from.Alive || from.GetDistanceToSqrt( this ) > 3 ) return; if ( e.HasKeyword( 0x3C ) || (e.HasKeyword( 0x171 ) && WasNamed( e.Speech )) ) // vendor buy, *buy* { if ( IsOwner( from ) ) { SayTo( from, 503212 ); // You own this shop, just take what you want. } else if ( House == null || !House.IsBanned( from ) ) { from.SendLocalizedMessage( 503213 ); // Select the item you wish to buy. from.Target = new PVBuyTarget(); e.Handled = true; } } else if ( e.HasKeyword( 0x3D ) || (e.HasKeyword( 0x172 ) && WasNamed( e.Speech )) ) // vendor browse, *browse { if ( House != null && House.IsBanned( from ) && !IsOwner( from ) ) { SayTo( from, 1062674 ); // You can't shop from this home as you have been banned from this establishment. } else { OpenBackpack( from ); e.Handled = true; } } else if ( e.HasKeyword( 0x3E ) || (e.HasKeyword( 0x173 ) && WasNamed( e.Speech )) ) // vendor collect, *collect { if ( IsOwner( from ) ) { CollectGold( from ); e.Handled = true; } } else if ( e.HasKeyword( 0x3F ) || (e.HasKeyword( 0x174 ) && WasNamed( e.Speech )) ) // vendor status, *status { if ( IsOwner( from ) ) { SendOwnerGump( from ); e.Handled = true; } else { SayTo( from, 503226 ); // What do you care? You don't run this shop. } } else if ( e.HasKeyword( 0x40 ) || (e.HasKeyword( 0x175 ) && WasNamed( e.Speech )) ) // vendor dismiss, *dismiss { if ( IsOwner( from ) ) { Dismiss( from ); e.Handled = true; } } else if ( e.HasKeyword( 0x41 ) || (e.HasKeyword( 0x176 ) && WasNamed( e.Speech )) ) // vendor cycle, *cycle { if ( IsOwner( from ) ) { this.Direction = this.GetDirectionTo( from ); e.Handled = true; } } } private class PayTimer : Timer { public static TimeSpan GetInterval() { if ( BaseHouse.NewVendorSystem ) return TimeSpan.FromDays( 1.0 ); else return TimeSpan.FromMinutes( Clock.MinutesPerUODay ); } private PlayerVendor m_Vendor; public PayTimer( PlayerVendor vendor, TimeSpan delay ) : base( delay, GetInterval() ) { m_Vendor = vendor; Priority = TimerPriority.OneMinute; } protected override void OnTick() { m_Vendor.m_NextPayTime = DateTime.Now + this.Interval; int pay; int totalGold; if ( BaseHouse.NewVendorSystem ) { pay = m_Vendor.ChargePerRealWorldDay; totalGold = m_Vendor.HoldGold; } else { pay = m_Vendor.ChargePerDay; totalGold = m_Vendor.BankAccount + m_Vendor.HoldGold; } if ( pay > totalGold ) { m_Vendor.Destroy( !BaseHouse.NewVendorSystem ); } else { if ( !BaseHouse.NewVendorSystem ) { if ( m_Vendor.BankAccount >= pay ) { m_Vendor.BankAccount -= pay; pay = 0; } else { pay -= m_Vendor.BankAccount; m_Vendor.BankAccount = 0; } } m_Vendor.HoldGold -= pay; } } } [PlayerVendorTarget] private class PVBuyTarget : Target { public PVBuyTarget() : base( 3, false, TargetFlags.None ) { AllowNonlocal = true; } protected override void OnTarget( Mobile from, object targeted ) { if ( targeted is Item ) { TryToBuy( (Item) targeted, from ); } } } private class VendorPricePrompt : Prompt { private PlayerVendor m_Vendor; private VendorItem m_VI; public VendorPricePrompt( PlayerVendor vendor, VendorItem vi ) { m_Vendor = vendor; m_VI = vi; } public override void OnResponse( Mobile from, string text ) { if ( !m_VI.Valid || !m_Vendor.CanInteractWith( from, true ) ) return; string firstWord; int sep = text.IndexOfAny( new char[] { ' ', ',' } ); if ( sep >= 0 ) firstWord = text.Substring( 0, sep ); else firstWord = text; int price; string description; try { price = Convert.ToInt32( firstWord ); if ( sep >= 0 ) description = text.Substring( sep + 1 ).Trim(); else description = ""; } catch { price = -1; description = text.Trim(); } SetInfo( from, price, Utility.FixHtml( description ) ); } public override void OnCancel( Mobile from ) { if ( !m_VI.Valid || !m_Vendor.CanInteractWith( from, true ) ) return; SetInfo( from, -1, "" ); } private void SetInfo( Mobile from, int price, string description ) { Item item = m_VI.Item; bool setPrice = false; if ( price < 0 ) // Not for sale { price = -1; if ( item is Container ) { if ( item is LockableContainer && ((LockableContainer)item).Locked ) m_Vendor.SayTo( from, 1043298 ); // Locked items may not be made not-for-sale. else if ( item.Items.Count > 0 ) m_Vendor.SayTo( from, 1043299 ); // To be not for sale, all items in a container must be for sale. else setPrice = true; } else if ( item is BaseBook || item is Engines.BulkOrders.BulkOrderBook ) { setPrice = true; } else { m_Vendor.SayTo( from, 1043301 ); // Only the following may be made not-for-sale: books, containers, keyrings, and items in for-sale containers. } } else { if ( price > 100000000 ) { price = 100000000; from.SendMessage( "You cannot price items above 100,000,000 gold. The price has been adjusted." ); } setPrice = true; } if ( setPrice ) { m_Vendor.SetVendorItem( item, price, description ); } else { m_VI.Description = description; } } } private class CollectGoldPrompt : Prompt { private PlayerVendor m_Vendor; public CollectGoldPrompt( PlayerVendor vendor ) { m_Vendor = vendor; } public override void OnResponse( Mobile from, string text ) { if ( !m_Vendor.CanInteractWith( from, true ) ) return; text = text.Trim(); int amount; try { amount = Convert.ToInt32( text ); } catch { amount = 0; } GiveGold( from, amount ); } public override void OnCancel( Mobile from ) { if ( !m_Vendor.CanInteractWith( from, true ) ) return; GiveGold( from, 0 ); } private void GiveGold( Mobile to, int amount ) { if ( amount <= 0 ) { m_Vendor.SayTo( to, "Very well. I will hold on to the money for now then." ); } else { m_Vendor.GiveGold( to, amount ); } } } private class VendorNamePrompt : Prompt { private PlayerVendor m_Vendor; public VendorNamePrompt( PlayerVendor vendor ) { m_Vendor = vendor; } public override void OnResponse( Mobile from, string text ) { if ( !m_Vendor.CanInteractWith( from, true ) ) return; string name = text.Trim(); if ( !NameVerification.Validate( name, 1, 20, true, true, true, 0, NameVerification.Empty ) ) { m_Vendor.SayTo( from, "That name is unacceptable." ); return; } m_Vendor.Name = Utility.FixHtml( name ); from.SendLocalizedMessage( 1062496 ); // Your vendor has been renamed. from.SendGump( new NewPlayerVendorOwnerGump( m_Vendor ) ); } } private class ShopNamePrompt : Prompt { private PlayerVendor m_Vendor; public ShopNamePrompt( PlayerVendor vendor ) { m_Vendor = vendor; } public override void OnResponse( Mobile from, string text ) { if ( !m_Vendor.CanInteractWith( from, true ) ) return; string name = text.Trim(); if ( !NameVerification.Validate( name, 1, 20, true, true, true, 0, NameVerification.Empty ) ) { m_Vendor.SayTo( from, "That name is unacceptable." ); return; } m_Vendor.ShopName = Utility.FixHtml( name ); from.SendGump( new NewPlayerVendorOwnerGump( m_Vendor ) ); } } public override bool CanBeDamaged() { return false; } } public class PlayerVendorPlaceholder : Item { private PlayerVendor m_Vendor; private ExpireTimer m_Timer; [CommandProperty( AccessLevel.GameMaster )] public PlayerVendor Vendor{ get{ return m_Vendor; } } public PlayerVendorPlaceholder( PlayerVendor vendor ) : base( 0x1F28 ) { Hue = 0x672; Movable = false; m_Vendor = vendor; m_Timer = new ExpireTimer( this ); m_Timer.Start(); } public PlayerVendorPlaceholder( Serial serial ) : base( serial ) { } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( m_Vendor != null ) list.Add( 1062498, m_Vendor.Name ); // reserved for vendor ~1_NAME~ } public void RestartTimer() { m_Timer.Stop(); m_Timer.Start(); } private class ExpireTimer : Timer { private PlayerVendorPlaceholder m_Placeholder; public ExpireTimer( PlayerVendorPlaceholder placeholder ) : base( TimeSpan.FromMinutes( 2.0 ) ) { m_Placeholder = placeholder; Priority = TimerPriority.FiveSeconds; } protected override void OnTick() { m_Placeholder.Delete(); } } public override void OnDelete() { if ( m_Vendor != null && !m_Vendor.Deleted ) { m_Vendor.MoveToWorld( this.Location, this.Map ); m_Vendor.Placeholder = null; } } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.WriteEncodedInt( (int) 0 ); writer.Write( (Mobile) m_Vendor ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadEncodedInt(); m_Vendor = (PlayerVendor) reader.ReadMobile(); Timer.DelayCall( TimeSpan.Zero, new TimerCallback( Delete ) ); } } }
gpl-2.0
W1-VeldpausThom/website-ThomVeldpaus.nl-
Opleiding/PHP/portfolio/index.php
7463
<?php $websiteTitle = "Portfolio Thom Veldpaus"; //regel 113 $datum_jaar = date ('Y'); //regel 16 $h1 = "Welkom op mijn portfolio!"; /*menuitems*/ $menuHome = '<table class="tablemenu"><tr><td><a href="index.php">Home</a></td>'; //regel 13 $menuHobbys = "<td><a href='hobbys.php'>Hobby's</a></td>";//regel 13 $menuOpleiding = "<td><a href='opleiding.php'>Opleiding</a></td>";//regel 13 $menuContact = "<td><a href='contact.php'>Contact</a></td></tr></table>";//regel 13 /*genereren van menu*/ $menu = "<div class='menu'>$menuHome $menuHobbys $menuOpleiding $menuContact </div>"; //regel 137 /*Up to date copyright text on the bottom of the website.*/ $copyright = "<p class='bericht' style='text-align: center;'>copyright &copy;$datum_jaar </p>"; //regel 246 /*Genereren van de $welkomBoodschap op regel */ /*$tijd_meter geeft het uur aan van de 24-uursklok in een getal voorbeeld: wanneer $tijd_meter = 18 dan kan het 18:00 tm 18:59 zijn*/ $tijd_meter = date('G'); /*dayOfTheWeek geeft de nummer van de dag weer in een getal 1 tm 7 waar maandag = 1 tm zondag = 7*/ $dayOfTheWeek = date('N'); $tijd = date('H:i');//"H" is uur en "i" is minuut gescheiden door een puntkomma(':') teken /*Het volgende zorgt ervoor dat het nummer van $dayOfTheWeek een geschreven dag word in de welkomstboodschap*/ if ($dayOfTheWeek > 0) { if($dayOfTheWeek >1) { if($dayOfTheWeek > 2) { if($dayOfTheWeek > 3) { if($dayOfTheWeek > 4) { if($dayOfTheWeek > 5) { if($dayOfTheWeek > 6) { $dagVanDeWeek = "Zondag"; } else { $dagVanDeWeek = "Zaterdag"; } } else { $dagVanDeWeek = "Vrijdag"; } } else { $dagVanDeWeek = "Donderdag"; } } else { $dagVanDeWeek = "Woensdag"; } } else { $dagVanDeWeek = "Dinsdag"; } } else { $dagVanDeWeek = "Maandag"; } } /*dit genereerd de uiteindelijke boodschap op regel 146*/ if ($tijd_meter < 24) { if($tijd_meter > 17) { $welkomBoodschap = "Goedenavond bezoeker! Het is vandaag $dagVanDeWeek $tijd" ; } else { if($tijd_meter > 12) { $welkomBoodschap = "Goedemiddag bezoeker! Het is vandaag $dagVanDeWeek $tijd" ; } else { if($tijd_meter > 6) { $welkomBoodschap = "Goedemorgen bezoeker! Het is vandaag $dagVanDeWeek $tijd" ; } else { $welkomBoodschap = "Slaap lekker, het is al $dagVanDeWeek $tijd !" ; } } } } echo <<<HTML <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title> $websiteTitle </title> <!-- verbinding leggen met het STYLE.css bestand in de CSS map onder de hoofdmap. --> <link rel="stylesheet" href="./CSS/STYLE.css" type="text/css" /> <link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Ubuntu:regular,bold&subset=Latin" /> </head> <body> <!-- DIV classe content1 wordt geopend--> <div class="content1"> <a href="index.php"> <img src="waashazig.jpg" alt="waashazig" id="toplogo" /> </a> <!-- DIV classe "menu" wordt geopend --> $menu </div> <div class="content2"> <div class="content3"> <p class="bericht"> <!--Hier staat de welkomst boodschap--> $welkomBoodschap </p> </div> <div class="content4"> <table class="htmltags"> <tr> <th class="thvak">Vak</th> <th class="cijfer">Cijfer</th> </tr> <tr class="evenrij"> <td class="tdvak">Duits</td> <td class="tdcijfer">8</td> </tr> <tr class="onevenrij"> <td class="tdvak">Economie</td> <td class="tdcijfer">6</td> </tr> <tr class="evenrij"> <td class="tdvak">Nederlandse taal</td> <td class="tdcijfer">7</td> </tr> <tr class="onevenrij"> <td class="tdvak">Engelse taal</td> <td class="tdcijfer">8</td> </tr> <tr class="evenrij"> <td class="tdvak">Wiskunde</td> <td class="tdcijfer">7</td> </tr> <tr class="onevenrij"> <td class="tdvak">Biologie</td> <td class="tdcijfer">6</td> </tr> <tr class="evenrij"> <td class="tdvak">Geschiedenis en staatsinrichting</td> <td class="tdcijfer">7</td> </tr> </table> <table class="htmltags"> <tr> <th class="tag">Tag</th> <th class="afgeleid">Afgeleid van</th> <th class="uitleg">Uitleg</th> </tr> <tr class="evenrij"> <td class="tag">&lt;html&gt;</td> <td class="afgeleid">HyperText Markup Language</td> <td class="uitleg"> Je opend en sluit elk HTML document met de HTML tag, het gebruik van deze tag is verplicht. </td> </tr> <tr class="onevenrij"> <td class="tag">&lt;head&gt;</td> <td class="afgeleid">*</td> <td class="uitleg"> In deze tag worden de instellingen van de pagina bepaald, denk aan de paginatitel, het te koppelen CSS bestand en eventueel gebruikte lettertypen die online beschikbaar zijn. Deze tag wordt gebruikt na de HTML en DOCTYPE tag en moet worden gesloten voor het openen van de BODY tag. </td> </tr> <tr class="evenrij"> <td class="tag">&lt;body&gt;</td> <td class="afgeleid">*</td> <td class="uitleg"> Deze tag is net als de HEAD tag verplicht te gebruiken. De BODY wil eigenlijk zeggen het "zichtbare" deel van de webpagina. Alles wat hierin wordt gezet wordt op de daadwerkelijke pagina weergegeven. </td> </tr> <tr class="onevenrij"> <td class="tag">&lt;title&gt;</td> <td class="afgeleid">*</td> <td class="uitleg"> Deze tag plaats je in de HEAD van je pagina. Alles wat je tussen deze tags zet is hetgene wat op het tabblad van de pagina wordt weergegeven. </td> </tr> <tr class="onevenrij"> <td class="tag">&lt;/title&gt;</td> <td class="afgeleid">*</td> <td class="uitleg"> Een tag sluiten doe je door het plaatsen van een / aan het begin van een tag. na het "minder dan" (&lt;) teken met daarop volgend de tag die je wilt sluiten net als in dit voorbeeld is gedaan met de &lt;title&gt; -tag. </td> </tr> </table> $copyright </div> </div> <br /> </body> </html> HTML ?>
gpl-2.0
yast/yast-storage-ng
src/lib/y2storage/proposal/settings_generator.rb
7165
# Copyright (c) [2018-2021] SUSE LLC # # All Rights Reserved. # # This program is free software; you can redistribute it and/or modify it # under the terms of version 2 of the GNU General Public License as published # by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for # more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, contact SUSE LLC. # # To contact SUSE LLC about this file by physical or electronic mail, you may # find current contact information at www.suse.com. require "y2storage/proposal/settings_adjustment" module Y2Storage module Proposal # Class for a settings generator used to perform the initial proposal # # @see InitialGuidedProposal class SettingsGenerator include Yast::Logger # Constructor # # A copy of the given settings is internally stored. # # @param settings [ProposalSettings] base settings def initialize(settings) @settings = settings.deep_copy @adjustments = SettingsAdjustment.new end # This attribute contains information about any adjustment done to the settings # # @return [Proposal::SettingsAdjustment] attr_reader :adjustments # Next settings generated from the current version of the settings. The new settings are # generated by disabling some of its properties. A copy of the stored {#settings} is returned. # # @see #calculate_next_settings # # @return [ProposalSettings, nil] nil if nothing else can be disabled in the current settings def next_settings initial_settings || calculate_next_settings end private # Next settings to use for a new attempt of the {InitialGuidedProposal} # # It tries to disable any property from the first configurable volume: adjust by ram, # snapshots or the volume itself. # # @see #next_settings # # @return [ProposalSettings, nil] nil if nothing else can be disabled in the current settings def calculate_next_settings volume = first_configurable_volume return nil if volume.nil? settings_after_disabling_adjust_by_ram(volume) || settings_after_disabling_snapshots(volume) || settings_after_disabling_volume(volume) end # Current settings # # This settings are used to calculate the next settings # # @return [ProposalSettings] attr_reader :settings # Settings to use for first time # # The first time that {#next_settings} is called, a copy of the original settings # is returned. # # @return [ProposalSettings] def initial_settings return nil if @used_initial_settings @used_initial_settings = true copy_settings end # Copies current settings # # @return [ProposalSettings] def copy_settings settings.deep_copy end # Returns the first volume (according to disable_order) whose settings could be modified. # # @note Volumes without disable order are never altered. # # @return [VolumeSpecification, nil] def first_configurable_volume settings.volumes.select { |v| configurable_volume?(v) }.min_by(&:disable_order) end # Copy of the current settings after disabling adjust by ram property from the # given volume specification. # # @param volume [VolumeSpecification] # @return [ProposalSettings, nil] nil if adjust by ram is already disabled def settings_after_disabling_adjust_by_ram(volume) return nil unless adjust_by_ram_active_and_configurable?(volume) disable_volume_property(volume, :adjust_by_ram) copy_settings end # Copy of the current settings after disabling snapshots property from the # given volume specification. # # @param volume [VolumeSpecification] # @return [ProposalSettings, nil] nil if snapshots is already disabled def settings_after_disabling_snapshots(volume) return nil unless snapshots_active_and_configurable?(volume) disable_volume_property(volume, :snapshots) copy_settings end # Copy of the current settings after disabling the given volume specification # # @param volume [VolumeSpecification] # @return [ProposalSettings, nil] nil if the volume is already disabled def settings_after_disabling_volume(volume) return nil unless proposed_active_and_configurable?(volume) disable_volume_property(volume, :proposed) copy_settings end def disable_volume_property(volume, property) log.info("Disabling '#{property}' for '#{volume.mount_point}'") volume.public_send(:"#{property}=", false) @adjustments = adjustments.add_volume_attr(volume, property, false) end # A volume is configurable if it is proposed and its settings can be modified. # That is, #adjust_by_ram, #snapshots or #proposed are true and some of them # could be change to false. # # @note A volume is considered configurable if it has disable order. Otherwise, # only the user is allowed to manually disable the volume or any of its features # (e.g. snapshots) using the UI. # # @param volume [VolumeSpecification] # @return [Boolean] def configurable_volume?(volume) volume.proposed? && !volume.disable_order.nil? && ( proposed_active_and_configurable?(volume) || adjust_by_ram_active_and_configurable?(volume) || snapshots_active_and_configurable?(volume)) end # Whether the volume is proposed and it could be configured # # @param volume [VolumeSpecification] # @return [Boolean] def proposed_active_and_configurable?(volume) active_and_configurable?(volume, :proposed) end # Whether the volume has adjust_by_ram to true and it could be configured # # @param volume [VolumeSpecification] # @return [Boolean] def adjust_by_ram_active_and_configurable?(volume) active_and_configurable?(volume, :adjust_by_ram) end # Whether the volume has snapshots to true and it could be configured # # @param volume [VolumeSpecification] # @return [Boolean] def snapshots_active_and_configurable?(volume) return false unless volume.fs_type.is?(:btrfs) active_and_configurable?(volume, :snapshots) end # Whether a volume has an attribute to true and it could be configured # # @param volume [VolumeSpecification] # @param attr [String, Symbol] # # @return [Boolean] def active_and_configurable?(volume, attr) volume.send(attr) && volume.send("#{attr}_configurable") end end end end
gpl-2.0
stevezuoli/BooxApp
boox-opensource/code/src/feed_reader/rss_feed_parser.cpp
6741
// -*- mode: c++; c-basic-offset: 4; -*- #include "rss_feed_parser.h" #include <QDebug> #include <QXmlStreamReader> #include "article.h" #include "feed.h" namespace onyx { namespace feed_reader { RssFeedParser::RssFeedParser() : FeedParser(), feed_(), xml_reader_(), current_article_(), current_text_(), pudate_(""){ } RssFeedParser::~RssFeedParser() { } void RssFeedParser::startNewFeedInternal(shared_ptr<Feed> feed) { feed_ = feed; current_text_.clear(); pudate_.clear(); xml_reader_.clear(); current_article_.reset(); qDebug() << "Starting new feed:" << feed->feed_url(); } bool RssFeedParser::appendInternal(const QByteArray& data) { xml_reader_.addData(data); return parseMore(); } bool RssFeedParser::hasErrorInternal() const { return xml_reader_.hasError() && xml_reader_.error() != QXmlStreamReader::PrematureEndOfDocumentError; } QString RssFeedParser::errorStringInternal() const { return xml_reader_.errorString(); } bool RssFeedParser::finishedInternal() const { return xml_reader_.atEnd() && !xml_reader_.hasError(); } const shared_ptr<Feed> RssFeedParser::feedInternal() const { return feed_; } namespace { bool is_new_article(const Article& article, const vector<shared_ptr<Article> >& articles) { for (size_t i = 0; i < articles.size(); ++i) { if (article.url() == articles[i]->url()) { return false; } } return true; } } // TODO can we probe the header and check out of which type the feed is, rss 2.0, rdf, or atom /** give a varible to store type like QString feed_type_ do switch in handleStartElement with feed_type_ specified and then as well as handleEndElement; Comparison of the RSS and Atom tags Atom RSS 2.0 RSS 1.0 Channel Container feed channel channel Title title title title URL link link link Summary subtitle description description Date updated lastBuildDate dc:date Logo icon image image Author author managingEditor - Item Container entry item item Title title title title URL link link link Description summary description description Date updated pubDate dc:date Image logo - image Image Container Logo image image Title title title Article URL link link URL image file url url */ void RssFeedParser::handleStartElement() { shared_ptr<QString> name(new QString(xml_reader_.name().toString())); tag_stack_.push(name); current_text_.clear(); if (*name == "item" || *name == "entry") { current_article_.reset(new Article(feed_)); } } void RssFeedParser::handleEndElement() { if (tag_stack_.size() && xml_reader_.name() == *(tag_stack_.top())) { tag_stack_.pop(); } if (xml_reader_.name() == "title") { if (tag_stack_.size() && (*(tag_stack_.top()) == "channel" || *(tag_stack_.top()) == "feed") && feed_->title().isEmpty()) { feed_->set_title(current_text_); } if (tag_stack_.size() && (*(tag_stack_.top()) == "item" || *(tag_stack_.top()) == "entry") && current_article_.get() && current_article_->title().isEmpty()) { current_article_->set_title(current_text_); } } else if (xml_reader_.name() == "link" || xml_reader_.name() == "id") { if (tag_stack_.size() && *(tag_stack_.top()) == "channel" && feed_->site_url().isEmpty()) { feed_->set_site_url(current_text_); } if (tag_stack_.size() && (*(tag_stack_.top()) == "item" || *(tag_stack_.top()) == "entry") && current_article_.get() && current_article_->url().isEmpty()) { current_article_->set_url(current_text_); } } else if (xml_reader_.name() == "description" || xml_reader_.namespaceUri() == "http://purl.org/rss/1.0/modules/content/") { if (tag_stack_.size() && (*(tag_stack_.top()) == "item" || *(tag_stack_.top()) == "entry") && current_article_.get() /*&& current_article_->text().isEmpty()*/) { //Add Link at head if (!current_article_->url().isEmpty()) { current_text_ = "Link: <a href =\"" + current_article_->url()+ "\">" + current_article_->url() + "</a><br/><br/>" +current_text_; } current_article_->set_text(current_text_); } } else if (xml_reader_.name() == "pubDate" || xml_reader_.name() == "updated" || xml_reader_.name() == "date") { if (tag_stack_.size() && (*(tag_stack_.top()) == "item" || *(tag_stack_.top()) == "entry") && current_article_.get() && current_article_->pubdate().isEmpty()) { current_article_->set_pubdate(current_text_); } } else if ((xml_reader_.name() == "item" || xml_reader_.name() == "entry") && current_article_.get()) { qDebug() << "One article parsed."; feed_->mutable_articles()->push_back(current_article_); if (is_new_article(*current_article_, feed_->articles())) { new_articles_.push_back(current_article_); } current_article_.reset(); } else { qDebug() << "Ignoring tag: " << xml_reader_.name(); } } bool RssFeedParser::parseMore() { DCHECK(feed_.get()); while (!xml_reader_.atEnd()) { xml_reader_.readNext(); if (xml_reader_.isStartElement()) { handleStartElement(); } else if (xml_reader_.isEndElement()) { handleEndElement(); } else if (xml_reader_.isCharacters() && !xml_reader_.isWhitespace()) { current_text_ += xml_reader_.text().toString(); } } if (xml_reader_.hasError() && xml_reader_.error() != QXmlStreamReader::PrematureEndOfDocumentError) { qWarning() << "XML ERROR:" << xml_reader_.errorString(); return false; } else { return true; } } void RssFeedParser::finalizeInternal() { feed_->mutable_articles()->insert(feed_->mutable_articles()->begin(), new_articles_.begin(), new_articles_.end()); } } // namespace feed_reader } // namespace onyx
gpl-2.0
sdwolf/CodenameOne
CodenameOne/src/com/codename1/ui/Calendar.java
27218
/* * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores * CA 94065 USA or visit www.oracle.com if you need additional information or * have any questions. */ package com.codename1.ui; import com.codename1.ui.animations.CommonTransitions; import com.codename1.ui.animations.Transition; import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import com.codename1.ui.events.DataChangedListener; import com.codename1.ui.plaf.Style; import com.codename1.ui.layouts.BorderLayout; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.layouts.FlowLayout; import com.codename1.ui.layouts.GridLayout; import com.codename1.ui.list.DefaultListModel; import com.codename1.ui.list.ListModel; import com.codename1.ui.plaf.UIManager; import com.codename1.ui.util.EventDispatcher; import java.util.Date; import java.util.Map; import java.util.TimeZone; import java.util.Vector; /** * Date widget for selecting a date/time value. * To localize strings for month names * use the values "Calendar.Month" using the 3 first characters of the month name * in the resource localization e.g. "Calendar.Jan", "Calendar.Feb" etc... * To localize strings for day names * use the values "Calendar.Day" in the resource localization e.g. "Calendar.Sunday", "Calendar.Monday" etc... * * @author Iddo Ari, Shai Almog */ public class Calendar extends Container { private ComboBox month; private ComboBox year; private MonthView mv; private Label dateLabel; private static final String[] MONTHS = new String[]{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; private static final String[] DAYS = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"}; private static final String[] LABELS = {"Su", "M", "Tu", "W", "Th", "F", "Sa"}; static final long MINUTE = 1000 * 60; static final long HOUR = MINUTE * 60; static final long DAY = HOUR * 24; static final long WEEK = DAY * 7; private EventDispatcher dispatcher = new EventDispatcher(); private EventDispatcher dataChangeListeners = new EventDispatcher(); private long[] dates = new long[42]; private boolean changesSelectedDateEnabled = true; private TimeZone tmz; /** * Creates a new instance of Calendar set to the given date based on time * since epoch (the java.util.Date convention) * * @param time time since epoch */ public Calendar(long time) { this(time, java.util.TimeZone.getDefault()); } /** * Constructs a calendar with the current date and time */ public Calendar() { this(System.currentTimeMillis()); } /** * Creates a new instance of Calendar set to the given date based on time * since epoch (the java.util.Date convention) * * @param time time since epoch * @param tmz a reference timezone */ public Calendar(long time, TimeZone tmz) { super(new BorderLayout()); this.tmz = tmz; setUIID("Calendar"); mv = new MonthView(time); Image leftArrow = UIManager.getInstance().getThemeImageConstant("calendarLeftImage"); if(leftArrow != null) { Image rightArrow = UIManager.getInstance().getThemeImageConstant("calendarRightImage"); final Button left = new Button(leftArrow); final Button right = new Button(rightArrow); ActionListener progress = new ActionListener() { private boolean lock = false; public void actionPerformed(ActionEvent evt) { if(lock) { return; } lock = true; int month = mv.getMonth(); int year = mv.getYear(); if(evt.getSource() == left) { month--; if(month < java.util.Calendar.JANUARY) { month = java.util.Calendar.DECEMBER; year--; } } else { month++; if(month > java.util.Calendar.DECEMBER) { month = java.util.Calendar.JANUARY; year++; } } boolean tran = UIManager.getInstance().isThemeConstant("calTransitionBool", true); if(tran) { Transition cm; if(UIManager.getInstance().isThemeConstant("calTransitionVertBool", false)) { cm = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, evt.getSource() == left, 300); } else { cm = CommonTransitions.createSlide(CommonTransitions.SLIDE_HORIZONTAL, evt.getSource() == left, 300); } MonthView newMv = new MonthView(mv.currentDay); newMv.setMonth(year, month); replaceAndWait(mv, newMv, cm); mv = newMv; newMv.fireActionEvent(); } else { mv.setMonth(year, month); componentChanged(); } dateLabel.setText(getLocalizedMonth(month) + " " + year); lock = false; } }; left.addActionListener(progress); right.addActionListener(progress); left.setUIID("CalendarLeft"); right.setUIID("CalendarRight"); Container dateCnt = new Container(new BorderLayout()); dateCnt.setUIID("CalendarDate"); dateLabel = new Label(); dateLabel.setUIID("CalendarDateLabel"); dateLabel.setText(getLocalizedMonth(mv.getMonth()) + " " + mv.getYear()); dateCnt.addComponent(BorderLayout.CENTER, dateLabel); dateCnt.addComponent(BorderLayout.EAST, right); dateCnt.addComponent(BorderLayout.WEST, left); addComponent(BorderLayout.NORTH, dateCnt); } else { month = new ComboBox(); year = new ComboBox(); Vector months = new Vector(); for (int i = 0; i < MONTHS.length; i++) { months.addElement("" + getLocalizedMonth(i)); } ListModel monthsModel = new DefaultListModel(months); int selected = months.indexOf(getLocalizedMonth(mv.getMonth())); month.setModel(monthsModel); month.setSelectedIndex(selected); month.addActionListener(mv); java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTime(new java.util.Date(time)); month.getStyle().setBgTransparency(0); int y = cal.get(java.util.Calendar.YEAR); Vector years = new Vector(); for (int i = 2100; i >= 1900; i--) { years.addElement("" + i); } ListModel yearModel = new DefaultListModel(years); selected = years.indexOf("" + y); year.setModel(yearModel); year.setSelectedIndex(selected); year.getStyle().setBgTransparency(0); year.addActionListener(mv); Container cnt = new Container(new BoxLayout(BoxLayout.X_AXIS)); cnt.setRTL(false); Container dateCnt = new Container(new BoxLayout(BoxLayout.X_AXIS)); dateCnt.setUIID("CalendarDate"); dateCnt.addComponent(month); dateCnt.addComponent(year); cnt.addComponent(dateCnt); Container upper = new Container(new FlowLayout(Component.CENTER)); upper.addComponent(cnt); addComponent(BorderLayout.NORTH, upper); } addComponent(BorderLayout.CENTER, mv); } /** * Returns the time for the current calendar. * * @return the time for the current calendar. */ public long getSelectedDay() { return mv.getSelectedDay(); } private String getLocalizedMonth(int i) { Map<String, String> t = getUIManager().getBundle(); String text = MONTHS[i]; if (t != null) { Object o = t.get("Calendar." + text); if (o != null) { text = (String) o; } } return text; } void componentChanged() { java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.set(java.util.Calendar.YEAR, mv.getYear()); cal.set(java.util.Calendar.MONTH, mv.getMonth()); cal.set(java.util.Calendar.DAY_OF_MONTH, mv.getDayOfMonth()); if(month != null) { month.getParent().revalidate(); } } /** * Return the date object matching the current selection * * @return the date object matching the current selection */ public Date getDate() { return new Date(mv.getSelectedDay()); } /** * Sets the current date in the view and the selected date to be the same. * * @param d new date */ public void setDate(Date d) { mv.setSelectedDay(d.getTime()); mv.setCurrentDay(mv.selectedDay, true); componentChanged(); } /** * Sets the Calendar min and max years * @param minYear the min year * @param maxYear the max year */ public void setYearRange(int minYear, int maxYear) { if (minYear > maxYear) { throw new IllegalArgumentException("Max year should be bigger or equal than min year!"); } //The year combobox may not exist in the current context if (year != null) { Object previouslySelectedYear = year.getSelectedItem(); Vector years = new Vector(); for (int i = maxYear; i >= minYear; i--) { years.addElement("" + i); } ListModel yearModel = new DefaultListModel(years); year.setModel(yearModel); if (years.contains(previouslySelectedYear)) { year.setSelectedItem(previouslySelectedYear); } } } /** * This method sets the Calendar selected day * @param d the selected day */ public void setSelectedDate(Date d){ mv.setSelectedDay(d.getTime()); } /** * Sets the Calendar view on the given date, only the the month and year * are being considered. * * @param d the date to set the calendar view on. */ public void setCurrentDate(Date d){ mv.setCurrentDay(d.getTime(), true); componentChanged(); } /** * Returns the currently viewed date (as opposed to the selected date) * @return the currently viewed date */ public Date getCurrentDate() { return new Date(mv.getCurrentDay()); } /** * Sets the Calendar timezone, if not specified Calendar will use the * default timezone * @param tmz the timezone */ public void setTimeZone(TimeZone tmz){ this.tmz = tmz; } /** * Gets the Calendar timezone * * @return Calendar TimeZone */ public TimeZone getTimeZone(){ return tmz; } /** * Sets the selected style of the month view component within the calendar * * @param s style for the month view */ public void setMonthViewSelectedStyle(Style s) { mv.setSelectedStyle(s); } /** * Sets the un selected style of the month view component within the calendar * * @param s style for the month view */ public void setMonthViewUnSelectedStyle(Style s) { mv.setUnselectedStyle(s); } /** * Gets the selected style of the month view component within the calendar * * @return the style of the month view */ public Style getMonthViewSelectedStyle() { return mv.getSelectedStyle(); } /** * Gets the un selected style of the month view component within the calendar * * @return the style of the month view */ public Style getMonthViewUnSelectedStyle() { return mv.getUnselectedStyle(); } /** * Fires when a change is made to the month view of this component * * @param l listener to add */ public void addActionListener(ActionListener l) { mv.addActionListener(l); } /** * Fires when a change is made to the month view of this component * * @param l listener to remove */ public void removeActionListener(ActionListener l) { mv.removeActionListener(l); } /** * Allows tracking selection changes in the calendar in real time * * @param l listener to add */ public void addDataChangeListener(DataChangedListener l) { mv.addDataChangeListener(l); } /** * Allows tracking selection changes in the calendar in real time * * @param l listener to remove */ public void removeDataChangeListener(DataChangedListener l) { mv.removeDataChangeListener(l); } /** * This flag determines if selected date can be changed by selecting an * alternative date * * @param changesSelectedDateEnabled if true pressing on a date will cause * the selected date to be changed to the pressed one */ public void setChangesSelectedDateEnabled(boolean changesSelectedDateEnabled) { this.changesSelectedDateEnabled = changesSelectedDateEnabled; } /** * This flag determines if selected date can be changed by selecting an * alternative date * * @return true if enabled */ public boolean isChangesSelectedDateEnabled() { return changesSelectedDateEnabled; } /** * This method creates the Day Button Component for the Month View * * @return a Button that corresponds to the Days Components */ protected Button createDay() { Button day = new Button(); day.setAlignment(CENTER); day.setUIID("CalendarDay"); day.setEndsWith3Points(false); day.setTickerEnabled(false); return day; } /** * This method creates the Day title Component for the Month View * * @param day the relevant day values are 0-6 where 0 is sunday. * @return a Label that corresponds to the relevant Day */ protected Label createDayTitle(int day) { String value = getUIManager().localize("Calendar." + DAYS[day], LABELS[day]); Label dayh = new Label(value, "CalendarTitle"); dayh.setEndsWith3Points(false); dayh.setTickerEnabled(false); return dayh; } /** * This method updates the Button day. * * @param dayButton the button to be updated * @param day the new button day */ protected void updateButtonDayDate(Button dayButton, int year, int currentMonth, int day) { updateButtonDayDate(dayButton, currentMonth, day); } /** * This method updates the Button day. * * @param dayButton the button to be updated * @param day the new button day */ protected void updateButtonDayDate(Button dayButton, int currentMonth, int day) { dayButton.setText("" + day); } class MonthView extends Container implements ActionListener{ long currentDay; private Button[] buttons = new Button[42]; private Button selected; private long selectedDay = -1; private Container titles; private Container days; public long getCurrentDay() { return currentDay; } public MonthView(long time) { super(new BoxLayout(BoxLayout.Y_AXIS)); setUIID("MonthView"); titles = new Container(new GridLayout(1, 7)); days = new Container(new GridLayout(6, 7)); addComponent(titles); addComponent(days); if(UIManager.getInstance().isThemeConstant("calTitleDayStyleBool", false)) { titles.setUIID("CalendarTitleArea"); days.setUIID("CalendarDayArea"); } for (int iter = 0; iter < DAYS.length; iter++) { titles.addComponent(createDayTitle(iter)); } for (int iter = 0; iter < buttons.length; iter++) { buttons[iter] = createDay(); days.addComponent(buttons[iter]); if (iter <= 7) { buttons[iter].setNextFocusUp(year); } buttons[iter].addActionListener(this); } setCurrentDay(time); } public void setCurrentDay(long day){ setCurrentDay(day, false); } private void setCurrentDay(long day, boolean force) { repaint(); java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTime(new Date(currentDay)); cal.set(java.util.Calendar.HOUR, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 1); cal.set(java.util.Calendar.MINUTE, 0); cal.set(java.util.Calendar.SECOND, 0); cal.set(java.util.Calendar.MILLISECOND, 0); int yearOld = cal.get(java.util.Calendar.YEAR); int monthOld = cal.get(java.util.Calendar.MONTH); int dayOld = cal.get(java.util.Calendar.DAY_OF_MONTH); Date dateObject = new Date(day); cal.setTime(dateObject); cal.set(java.util.Calendar.HOUR, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 1); cal.set(java.util.Calendar.MINUTE, 0); cal.set(java.util.Calendar.SECOND, 0); cal.set(java.util.Calendar.MILLISECOND, 0); int yearNew = cal.get(java.util.Calendar.YEAR); int monthNew = cal.get(java.util.Calendar.MONTH); int dayNew = cal.get(java.util.Calendar.DAY_OF_MONTH); if(month != null) { year.setSelectedItem("" + yearNew); month.setSelectedIndex(monthNew); } else { if(dateLabel != null) { dateLabel.setText(getLocalizedMonth(monthNew) + " " + yearNew); } } if (yearNew != yearOld || monthNew != monthOld || dayNew != dayOld || force) { currentDay = cal.getTime().getTime(); if(selectedDay == -1){ selectedDay = currentDay; } int month = cal.get(java.util.Calendar.MONTH); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); long startDate = cal.getTime().getTime(); int dow = cal.get(java.util.Calendar.DAY_OF_WEEK); cal.setTime(new Date(cal.getTime().getTime() - DAY)); cal.set(java.util.Calendar.HOUR, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 1); cal.set(java.util.Calendar.MINUTE, 0); cal.set(java.util.Calendar.SECOND, 0); cal.set(java.util.Calendar.MILLISECOND, 0); int lastDay = cal.get(java.util.Calendar.DAY_OF_MONTH); int i = 0; if(dow > java.util.Calendar.SUNDAY){ //last day of previous month while (dow > java.util.Calendar.SUNDAY) { cal.setTime(new Date(cal.getTime().getTime() - DAY)); dow = cal.get(java.util.Calendar.DAY_OF_WEEK); } int previousMonthSunday = cal.get(java.util.Calendar.DAY_OF_MONTH); for (; i <= lastDay - previousMonthSunday; i++) { buttons[i].setUIID("CalendarDay"); buttons[i].setEnabled(false); buttons[i].setText("" + (previousMonthSunday + i)); } } //last day of current month cal.set(java.util.Calendar.MONTH, (month + 1) % 12); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); cal.setTime(new Date(cal.getTime().getTime() - DAY)); lastDay = cal.get(java.util.Calendar.DAY_OF_MONTH); int j = i; for (; j < buttons.length && (j - i + 1) <= lastDay; j++) { buttons[j].setEnabled(true); dates[j] = startDate; if(dates[j] == selectedDay){ buttons[j].setUIID("CalendarSelectedDay"); selected = buttons[j]; }else{ buttons[j].setUIID("CalendarDay"); } updateButtonDayDate(buttons[j], yearNew, month, j - i + 1); startDate += DAY; } int d = 1; for (; j < buttons.length; j++) { buttons[j].setUIID("CalendarDay"); buttons[j].setEnabled(false); buttons[j].setText("" + d++); } } } public int getDayOfMonth() { java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTime(new Date(currentDay)); return cal.get(java.util.Calendar.DAY_OF_MONTH); } public int getMonth() { java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTime(new Date(currentDay)); return cal.get(java.util.Calendar.MONTH); } public void incrementMonth() { int month = getMonth(); month++; int year = getYear(); if (month > java.util.Calendar.DECEMBER) { month = java.util.Calendar.JANUARY; year++; } setMonth(year, month); } private long getSelectedDay() { return selectedDay; } public void setSelectedDay(long selectedDay){ java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTime(new Date(selectedDay)); cal.set(java.util.Calendar.HOUR, 1); cal.set(java.util.Calendar.HOUR_OF_DAY, 1); cal.set(java.util.Calendar.MINUTE, 0); cal.set(java.util.Calendar.SECOND, 0); cal.set(java.util.Calendar.MILLISECOND, 0); this.selectedDay = cal.getTime().getTime(); } private void setMonth(int year, int month) { java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTimeZone(TimeZone.getDefault()); cal.set(java.util.Calendar.MONTH, month); cal.set(java.util.Calendar.DAY_OF_MONTH, 1); cal.set(java.util.Calendar.YEAR, year); Date date = cal.getTime(); long d = date.getTime(); // if this is past the last day of the month (e.g. going from January 31st // to Febuary) we need to decrement the day until the month is correct while (cal.get(java.util.Calendar.MONTH) != month) { d -= DAY; cal.setTime(new Date(d)); } setCurrentDay(d); } public void decrementMonth() { int month = getMonth(); month--; int year = getYear(); if (month < java.util.Calendar.JANUARY) { month = java.util.Calendar.DECEMBER; year--; } setMonth(year, month); } public int getYear() { java.util.Calendar cal = java.util.Calendar.getInstance(tmz); cal.setTime(new Date(currentDay)); return cal.get(java.util.Calendar.YEAR); } public void addActionListener(ActionListener l) { dispatcher.addListener(l); } public void removeActionListener(ActionListener l) { dispatcher.removeListener(l); } /** * Allows tracking selection changes in the calendar in real time * * @param l listener to add */ public void addDataChangeListener(DataChangedListener l) { dataChangeListeners.addListener(l); } /** * Allows tracking selection changes in the calendar in real time * * @param l listener to remove */ public void removeDataChangeListener(DataChangedListener l) { dataChangeListeners.removeListener(l); } protected void fireActionEvent() { componentChanged(); super.fireActionEvent(); dispatcher.fireActionEvent(new ActionEvent(Calendar.this)); } public void actionPerformed(ActionEvent evt) { Object src = evt.getSource(); if(src instanceof ComboBox){ setMonth(Integer.parseInt((String)year.getSelectedItem()), month.getSelectedIndex()); componentChanged(); return; } if(changesSelectedDateEnabled){ for (int iter = 0; iter < buttons.length; iter++) { if (src == buttons[iter]) { if(selected != null){ selected.setUIID("CalendarDay"); } buttons[iter].setUIID("CalendarSelectedDay"); selectedDay = dates[iter]; selected = buttons[iter]; fireActionEvent(); if (!getComponentForm().isSingleFocusMode()) { setHandlesInput(false); } revalidate(); return; } } } } } }
gpl-2.0
AnGlez/ver-con-las-manos
wp-content/themes/bridge/toolbar_examples.php
80878
<?php $example_url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'] .'/'; ?> <div id="toolbar" class="on"> <span class="open opened" href="#"> <span class="opener"> <span class="number"> 42+ </span> <span>Bridge Demos</span> </span> <a class="qbutton green" href="#" target="_blank">See All Demos</a> </span> <div class="toolbar_preview"> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <p>All Demo Settings And Content Can Be Imported</p> </div> <div id="toolbar_outer"> <div id="toolbar_inner"> <div id="toolbar_inner2"> <?php if (!strpos($example_url,'bridge/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_original_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_original_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Original<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge2/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_original_left_menu_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_original_left_menu_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Left Menu<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge2/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge3/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_business_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_business_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Business<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge3/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge13/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_winery_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_winery_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Winery<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge13/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge9/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_cafe_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_cafe_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Cafe<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge9/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge16/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_portfolio_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_portfolio_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Portfolio Masonry<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge16/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge4/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_agency_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_agency_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Agency<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge4/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } // if (!strpos($example_url,'bridge44/')){ // ?> <!-- <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_coming_soon_simple_big.jpg">--> <!-- <span class="new">NEW</span>--> <!-- <div class="toolbar_image">--> <!-- <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_coming_soon_simple_small.jpg" alt="" />--> <!-- <div class="menu_switcher_hover_outer">--> <!-- <div class="menu_switcher_hover_inner">--> <!-- <div class="menu_switcher_hover">--> <!-- <div class="desc">--> <!-- <p>--> <!-- Bridge Coming Soon Simple<br/>--> <!-- Demo--> <!-- </p>--> <!-- <a class="qbutton" href="http://demo.qodeinteractive.com/bridge44/" target="_blank">LAUNCH</a>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- --><?php // } // if (!strpos($example_url,'bridge45/')){ // ?> <!-- <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_coming_soon_creative_big.jpg">--> <!-- <span class="new">NEW</span>--> <!-- <div class="toolbar_image">--> <!-- <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_coming_soon_creative_small.jpg" alt="" />--> <!-- <div class="menu_switcher_hover_outer">--> <!-- <div class="menu_switcher_hover_inner">--> <!-- <div class="menu_switcher_hover">--> <!-- <div class="desc">--> <!-- <p>--> <!-- Bridge Coming Soon Creative<br/>--> <!-- Demo--> <!-- </p>--> <!-- <a class="qbutton" href="http://demo.qodeinteractive.com/bridge45/" target="_blank">LAUNCH</a>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- </div>--> <!-- --><?php // } if (!strpos($example_url,'bridge42/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_collection_big.jpg"> <span class="new">NEW</span> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_collection_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Collection<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge42/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge43/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_creative_vintage_big.jpg"> <span class="new">NEW</span> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_creative_vintage_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Creative Vintage<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge43/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge40/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_chocolaterie_big.jpg"> <div class="toolbar_image"> <img src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_chocolaterie_small.jpg" alt="" /> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Chocolaterie<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge40/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge41/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_branding_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_branding_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Branding<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge41/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge38/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_studio_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_studio_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Studio<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge38/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge36/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_simple_blog_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_simple_blog_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Simple Blog<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge36/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge39/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_contemporary_art_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_contemporary_art_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Contemporary Art<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge39/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge34/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_parallax_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_parallax_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Parallax<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge34/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge35/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_minimal_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_minimal_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Minimal<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge35/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge37/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_pinterest_blog_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_pinterest_blog_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Pinterest Blog<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge37/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge32/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_small_brand_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_small_brand_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Small Brand<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge32/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge33/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_creative_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_creative_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Creative<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge33/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge30/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_mist_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_mist_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Mist<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge30/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge31/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_architecture_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_architecture_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Architecture<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge31/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge28/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_wireframey_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_wireframey_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Wireframey<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge28/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge29/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_denim_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_denim_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Denim<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge29/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge26/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_health_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_health_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Health<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge26/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge22/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_dark_parallax_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_dark_parallax_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Dark Parallax<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge22/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge25/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_pinterest_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_pinterest_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Portfolio Pinterest<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge25/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge27/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_flat_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_flat_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Flat<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge27/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge19/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_catalog_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_catalog_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Catalog<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge19/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge20/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_portfolio2_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_portfolio2_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Portfolio<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge20/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge21/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_minimalist_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_minimalist_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Minimalist<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge21/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge18/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_creative_business_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_creative_business_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Creative Business<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge18/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge24/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_avenue_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_avenue_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Avenue<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge24/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge23/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_split_screen_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_split_screen_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Split Screen<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge23/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge11/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_modern_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_modern_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Modern<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge11/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge15/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_construct_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_construct_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Construct<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge15/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge14/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_restaurant_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_restaurant_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Restaurant<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge14/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge12/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_university_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_university_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge University<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge12/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge10/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_one_page_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_one_page_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge One Page<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge10/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge8/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_fashion_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_fashion_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Fashion<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge8/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge5/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_luxury_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_luxury_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Estate<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge5/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge7/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_urban_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_urban_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Urban<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge7/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge17/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_vintage_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_vintage_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Vintage<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge17/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } if (!strpos($example_url,'bridge6/')){ ?> <div class="website_holder" data-image="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_light_big.jpg"> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/bridge_light_small.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Bridge Light<br/> Demo </p> <a class="qbutton" href="http://demo.qodeinteractive.com/bridge6/" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <?php } ?> <div class="website_holder placeholder" data-image=""> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/placeholder.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Placeholder<br/> </p> <a class="qbutton" href="#" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> <div class="website_holder placeholder last" data-image=""> <div class="toolbar_image"> <img src="" data-src="http://demo.qodeinteractive.com/bridge/demo_images/examples/placeholder.jpg" alt="" /> <div class="loading_more_examples"><div class="five_rotating_circles"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div></div> <div class="menu_switcher_hover_outer"> <div class="menu_switcher_hover_inner"> <div class="menu_switcher_hover"> <div class="desc"> <p> Placeholder<br/> </p> <a class="qbutton" href="#" target="_blank">LAUNCH</a> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div>
gpl-2.0
LeungGeorge/Helper
00_Test/udp_sender/udp_sender/main.cpp
1340
#include <iostream> #include <string> #include "udp_sender.h" using namespace std; int main() { struct UdpHeartPack udpPack; string hello = "hello world"; for(int i = 0; i < hello.length(); i++) udpPack.UDPData[i] = hello[i]; udpPack.UDPData[hello.length()] = '\0'; char* pPack = (char*)&udpPack; WSADATA wsaData; BOOL fBroadcast = TRUE; char sendBuff[1024]; int nCount = 0; if(WSAStartup(MAKEWORD(1, 1), &wsaData) != 0) { WSACleanup(); std::cout << "Can't initiates windows socket!Program stop.\n"; return -1; } SOCKET sockListener = socket(PF_INET, SOCK_DGRAM, 0); setsockopt(sockListener, SOL_SOCKET, SO_BROADCAST, (CHAR*)&fBroadcast, sizeof(BOOL)); SOCKADDR_IN saUdpServ; saUdpServ.sin_family = AF_INET; saUdpServ.sin_addr.s_addr = htonl(INADDR_BROADCAST); //saUdpServ.sin_addr.S_un.S_addr = inet_addr("10.103.243.85"); saUdpServ.sin_port = htons(UDP_PORT); while(true){ Sleep(100); sprintf(sendBuff, "Message %d is : ok", nCount++); int rt = sendto(sockListener, sendBuff, lstrlen(sendBuff) + 1, 0, (SOCKADDR*)&saUdpServ, sizeof(SOCKADDR_IN)); std::cout << sendBuff << ",rt = " << rt << std::endl; } closesocket(sockListener); WSACleanup(); return 0; }
gpl-2.0
the-dani/kunnandidagen
plugins/joomgallery/joomrecaptcha/joomrecaptcha.php
4969
<?php // $HeadURL: https://joomgallery.org/svn/joomgallery/JG-2.0/Plugins/JoomreCaptcha/trunk/joomrecaptcha.php $ // $Id: joomrecaptcha.php 3746 2012-04-08 17:53:28Z chraneco $ /******************************************************************************\ ** JoomGallery Plugin 'JoomreCaptcha'2.0 ** ** By: JoomGallery::ProjectTeam ** ** Copyright (C) 2010 - 2012 Chraneco ** ** With some code from the PHP library that handles calling reCAPTCHA ** ** by Mike Crawford and Ben Maurer ** ** Copyright (c) 2007 reCAPTCHA -- http://recaptcha.net ** ** Released under GNU GPL Public License ** ** License: http://www.gnu.org/copyleft/gpl.html ** \******************************************************************************/ // Check to ensure this file is included in Joomla! defined('_JEXEC') or die('Restricted access'); jimport('joomla.plugin.plugin'); /** * JoomGallery EasyCaptcha Plugin * * @package Joomla * @subpackage JoomGallery * @since 1.5 */ class plgJoomGalleryJoomreCaptcha extends JPlugin { /** * onJoomGetCaptcha method * * Method is called whenever spam protection is necessary in JoomGallery * * @param string $ambit A string which determines the ambit in which the captcha will be displayed (for example 'comments') * @return string The HTML output of the captcha * @since 1.5 */ public function onJoomGetCaptcha($ambit = '') { $user = JFactory::getUser(); if($user->get('id') && !$this->params->get('enabled_for')) { return ''; } $language = JFactory::getLanguage(); $lang = $language->getTag(); $lang = substr($lang, 0, 2); $html = ' <div class="jg_cmtl"> &nbsp; </div> <div class="jg_cmtr"> <script type="text/javascript"> var RecaptchaOptions = { theme : \''.$this->params->get('theme').'\', lang : \''.$lang.'\' }; </script> <script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k='.$this->params->get('publickey').'"></script> <noscript> <iframe src="http://www.google.com/recaptcha/api/noscript?k='.$this->params->get('publickey').'" height="300" width="500" frameborder="0"></iframe> <br /> <textarea name="recaptcha_challenge_field" rows="3" cols="40"></textarea> <input type="hidden" name="recaptcha_response_field" value="manual_challenge"> </noscript> </div>'; return $html; } /** * onJoomCheckCaptcha method * * Method is called when a captcha should be validated * * @param string $ambit A string which determines the ambit in which the captcha will be displayed (for example 'comments') * @return array An array with result information, boolean false if a check isn't necessary in the context * @since 1.5 */ public function onJoomCheckCaptcha($ambit = '') { $user = JFactory::getUser(); if($user->get('id') && !$this->params->get('enabled_for')) { return false; } // Load the language file $this->loadLanguage(); $server = 'www.google.com'; $request = 'privatekey='.urlencode(stripslashes($this->params->get('privatekey'))); $request .= '&remoteip='.urlencode(stripslashes($_SERVER['REMOTE_ADDR'])); $request .= '&challenge='.urlencode(stripslashes(JRequest::getVar('recaptcha_challenge_field'))); $request .= '&response='.urlencode(stripslashes(JRequest::getVar('recaptcha_response_field'))); $http_request = "POST /recaptcha/api/verify HTTP/1.0\r\n"; $http_request .= "Host: ".$server."\r\n"; $http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n"; $http_request .= "Content-Length: ".strlen($request)."\r\n"; $http_request .= "User-Agent: reCAPTCHA/PHP\r\n"; $http_request .= "\r\n"; $http_request .= $request; $fs = @fsockopen($server, 80); if(!$fs) { throw new Exception(JText::_('PLG_JOOMGALLERY_JOOMRECAPTCHA_COULD_NOT_OPEN_SOCKET')); } fwrite($fs, $http_request); $response = ''; while(!feof($fs)) { // One TCP-IP packet $response .= fgets($fs, 1160); } fclose($fs); $response = explode("\r\n\r\n", $response, 2); $response = explode("\n", $response[1]); if($response[0] == 'true') { $valid = true; $error = ''; } else { $valid = false; $error = $response[1]; if($error == 'incorrect-captcha-sol') { $error = JText::_('PLG_JOOMGALLERY_JOOMRECAPTCHA_SECURITY_CODE_WRONG'); } } return array('valid' => $valid, 'error' => $error); } }
gpl-2.0
chronoxor/Depth
include/concept/details/MConceptPredicateMethodX.hpp
4109
/*! * \file MConceptPredicateMethodX.hpp Template checking conception. * Checks if template argument is a class predicate method * (general declaration). * \brief General declaration of the class predicate method template checking conception. * \author Ivan Shynkarenka aka 4ekucT * \version 1.0 * \date 26.04.2006 */ /*==========================================================================*/ /* FILE DESCRIPTION: General declaration of the class predicate method template checking conception. AUTHOR: Ivan Shynkarenka aka 4ekucT GROUP: The NULL workgroup PROJECT: The Depth PART: Conception checking details VERSION: 1.0 CREATED: 26.04.2006 22:36:42 EMAIL: chronoxor@gmail.com WWW: http://code.google.com/p/depth COPYRIGHT: (C) 2005-2010 The NULL workgroup. All Rights Reserved. */ /*--------------------------------------------------------------------------*/ /* Copyright (C) 2005-2010 The NULL workgroup. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /*--------------------------------------------------------------------------*/ /* FILE ID: $Id$ CHANGE LOG: $Log$ */ /*==========================================================================*/ #ifndef __MCONCEPTPREDICATEMETHODX_HPP__ #define __MCONCEPTPREDICATEMETHODX_HPP__ /*==========================================================================*/ #include <Depth/include/common/IStatic.hpp> /*==========================================================================*/ /* NAMESPACE DECLARATIONS */ /*==========================================================================*/ namespace NDepth { /*--------------------------------------------------------------------------*/ namespace NConcept { /*--------------------------------------------------------------------------*/ namespace NFunctions { /*==========================================================================*/ /* META-CLASS DECLARATIONS */ /*==========================================================================*/ //! General declaration of the class predicate method template checking conception meta-class. /*! Now class predicate method conception supports only 10 method arguments. This conception has protected constructor, so you cannot use more than 10 method arguments. It will lead to compiler error if you try. Other versions of the same class uses template specialization to implement other class method predicate checking conceptions. */ template <typename T_PredicateMethod, class T_Class, typename T_Argument1 = void, typename T_Argument2 = void, typename T_Argument3 = void, typename T_Argument4 = void, typename T_Argument5 = void, typename T_Argument6 = void, typename T_Argument7 = void, typename T_Argument8 = void, typename T_Argument9 = void, typename T_Argument10 = void, typename T_Unused = void> class MConceptPredicateMethod : public NDepth::NCommon::IStatic { }; /*==========================================================================*/ } /*--------------------------------------------------------------------------*/ } /*--------------------------------------------------------------------------*/ } /*==========================================================================*/ #endif
gpl-2.0
ORCHARD-Minecraft-Mod-Class/RandomMine
src/main/java/com/orchard/randommine/items/ItemModPickaxe.java
283
package com.orchard.randommine.items; import net.minecraft.item.ItemPickaxe; public class ItemModPickaxe extends ItemPickaxe { public ItemModPickaxe(String unlocalizedName, ToolMaterial material) { super(material); this.setUnlocalizedName(unlocalizedName); } }
gpl-2.0
favedit/MoPlatform
mp-platform/webroot/ajs/2-base/MValue.js
461
//========================================================== // <T>可加载和保存数据的接口。</T> // // @manger // @history 091012 MAOCY 创建 //========================================================== function MValue(o){ o = RClass.inherits(this, o); //.......................................................... // @method o.loadValue = RMethod.virtual(o, 'loadValue'); o.saveValue = RMethod.virtual(o, 'saveValue'); return o; }
gpl-2.0
Xeenice/grape-galaxy
src/org/grape/galaxy/client/ResourceManager.java
12424
package org.grape.galaxy.client; import com.google.gwt.core.client.JavaScriptObject; public final class ResourceManager { private static boolean prepared; private static JavaScriptObject identityCube; private ResourceManager() { } public static void prepareResources() { if (prepared) { return; } prepareMaterials(); prepareObjects(); prepared = true; } public static native JavaScriptObject getMaterial(String name) /*-{ var material = $wnd.g_pack.getObjects(name, "o3d.Material")[0]; if (material === undefined) { return null; } return material; }-*/; public static native void bindMaterialParameters(JavaScriptObject transform) /*-{ var children = transform.children; for ( var i = 0; i < children.length; i++) { @org.grape.galaxy.client.ResourceManager::bindMaterialParameters(Lcom/google/gwt/core/client/JavaScriptObject;)(children[i]); } var shapes = transform.shapes; for ( var i = 0; i < shapes.length; i++) { var elements = shapes[i].elements; for ( var i = 0; i < elements.length; i++) { var lightWorldPos = elements[i].material .getParam("lightWorldPos"); if (lightWorldPos !== undefined) { lightWorldPos.bind($wnd.g_globalParams .getParam("lightWorldPos")); } } } }-*/; public static native JavaScriptObject cloneTransform(JavaScriptObject pack, String name) /*-{ var foundTransform = @org.grape.galaxy.client.ResourceManager::findTransform(Ljava/lang/String;)(name); if (foundTransform == null) { return null; } var clonedTransform = pack.createObject("Transform"); clonedTransform.identity(); var shapes = foundTransform.shapes; for ( var i = 0; i < shapes.length; i++) { clonedTransform.addShape(shapes[i]); } // TODO в дальнейшем может понадобиться реализация клонирования с учетом иерархии return clonedTransform; }-*/; public static native JavaScriptObject cloneTransformAndShapes( JavaScriptObject pack, String name) /*-{ var foundTransform = @org.grape.galaxy.client.ResourceManager::findTransform(Ljava/lang/String;)(name); if (foundTransform == null) { return null; } var clonedTransform = pack.createObject("Transform"); clonedTransform.identity(); var shapes = foundTransform.shapes; for ( var i = 0; i < shapes.length; i++) { clonedTransform.addShape($wnd.o3djs.shape.duplicateShape(pack, shapes[i])); } // TODO в дальнейшем может понадобиться реализация клонирования с учетом иерархии return clonedTransform; }-*/; public static native JavaScriptObject getIdentityCube() /*-{ var identityCube = @org.grape.galaxy.client.ResourceManager::identityCube; if (identityCube == null) { identityCube = $wnd.o3djs.primitives.createCube($wnd.g_pack, $wnd.o3djs.material.createConstantMaterial($wnd.g_pack, $wnd.g_viewInfo, [ 1, 1, 1, 1 ]), 1); @org.grape.galaxy.client.ResourceManager::identityCube = identityCube; } return identityCube; }-*/; public static native JavaScriptObject createParticleSystem( JavaScriptObject pack) /*-{ var clockParam = $wnd.g_globalParams.getParam("clock"); return $wnd.o3djs.particles.createParticleSystem(pack, $wnd.g_viewInfo, clockParam); }-*/; public static native JavaScriptObject createStaticParticleSystem( JavaScriptObject pack) /*-{ var zeroClockParam = $wnd.g_globalParams.getParam("zeroClock"); return $wnd.o3djs.particles.createParticleSystem(pack, $wnd.g_viewInfo, zeroClockParam); }-*/; public static native void removeParticleEmitter(JavaScriptObject emitter) /*-{ var pack = emitter.particleSystem.pack; pack.removeObject(emitter.material); pack.removeObject(emitter.rampSampler_); pack.removeObject(emitter.colorSampler_); pack.removeObject(emitter.vertexBuffer_); pack.removeObject(emitter.indexBuffer_); pack.removeObject(emitter.streamBank_); pack.removeObject(emitter.shape); var drawElements = emitter.primitive_.drawElements; for ( var i = 0; i < drawElements.length; i++) { pack.removeObject(drawElements[i]); } pack.removeObject(emitter.primitive_); if (emitter.rampTexture_ != emitter.particleSystem.defaultRampTexture) { pack.removeObject(emitter.rampTexture_); } }-*/; public static native JavaScriptObject getMaterialTexture(String materialName) /*-{ var material = $wnd.g_pack.getObjects(materialName, "o3d.Material")[0]; if (material == null) { return null; } var samplerParam = material.getParam('diffuseSampler'); if (samplerParam == null) { return null; } return samplerParam.value.texture; }-*/; private static native JavaScriptObject findTransform(String name) /*-{ var galaxyTransform = $wnd.g_pack.getObjects("galaxy", "o3d.Transform")[0]; if (galaxyTransform === undefined) { return null; } var foundTransform = @org.grape.galaxy.client.ResourceManager::findTransform(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;)(galaxyTransform, name); if (foundTransform == null) { return null; } return foundTransform; }-*/; private static native JavaScriptObject findTransform( JavaScriptObject transform, String name) /*-{ var children = transform.children; for ( var i = 0; i < children.length; i++) { // поиск нужного объект на текущем уровне иерархии var child = children[i]; if (child.name == name) { return child; } } for ( var i = 0; i < children.length; i++) { // спуск ниже по иерархии var child = children[i]; var foundTransform = @org.grape.galaxy.client.ResourceManager::findTransform(Lcom/google/gwt/core/client/JavaScriptObject;Ljava/lang/String;)(child, name); if (foundTransform != null) { return foundTransform; } } return null; }-*/; private static native void prepareMaterials() /*-{ @org.grape.galaxy.client.ResourceManager::prepareAtmosphereMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareSelectionMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareGateFieldMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareArrowMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareMapMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareMapCursorMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareGuideLineMaterial()(); @org.grape.galaxy.client.ResourceManager::prepareShieldMaterial()(); }-*/; private static native void prepareObjects() /*-{ @org.grape.galaxy.client.ResourceManager::preparePlanets()(); @org.grape.galaxy.client.ResourceManager::prepareShips()(); }-*/; private static native JavaScriptObject createAlphaBlendState() /*-{ var state = $wnd.g_pack.createObject("State"); state.getStateParam("AlphaBlendEnable").value = true; state.getStateParam("SourceBlendFunction").value = $wnd.g_o3d.State.BLENDFUNC_SOURCE_ALPHA; state.getStateParam("DestinationBlendFunction").value = $wnd.g_o3d.State.BLENDFUNC_INVERSE_SOURCE_ALPHA; state.getStateParam("ZWriteEnable").value = false; return state; }-*/; private static native JavaScriptObject setAlphaStateEffect( String materialName, String effectName) /*-{ var material = $wnd.g_pack.getObjects(materialName, "o3d.Material")[0]; if (material === undefined) { return null; } $wnd.g_pack.removeObject(material.state); $wnd.g_pack.removeObject(material.effect); material.drawList = $wnd.g_viewInfo.zOrderedDrawList; var effect = $wnd.g_pack.createObject("Effect"); effect.loadFromFXString($doc.getElementById(effectName).value); material.effect = effect; effect.createUniformParameters(material); material.state = @org.grape.galaxy.client.ResourceManager::createAlphaBlendState()(); return material; }-*/; private static native JavaScriptObject setEffect(String materialName, String effectName) /*-{ var material = $wnd.g_pack.getObjects(materialName, "o3d.Material")[0]; if (material === undefined) { return null; } $wnd.g_pack.removeObject(material.effect); var effect = $wnd.g_pack.createObject("Effect"); effect.loadFromFXString($doc.getElementById(effectName).value); material.effect = effect; effect.createUniformParameters(material); return material; }-*/; private static native void prepareAtmosphereMaterial() /*-{ @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("atmosphere", "fx-atmosphere"); }-*/; private static native void prepareSelectionMaterial() /*-{ @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("selection", "fx-selection"); }-*/; private static native void prepareGateFieldMaterial() /*-{ var material = @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("gatefield", "fx-gatefield"); material.getParam("color").value = [ 1, 1, 1, 1 ]; }-*/; private static native void prepareArrowMaterial() /*-{ var material = @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("arrow", "fx-arrow"); material.getParam("color").value = [ 1, 1, 1, 1 ]; }-*/; private static native void prepareMapMaterial() /*-{ var material = @org.grape.galaxy.client.ResourceManager::setEffect(Ljava/lang/String;Ljava/lang/String;)("map", "fx-map"); material.getParam("sizeInSectors").value = 5; }-*/; private static native void prepareMapCursorMaterial() /*-{ @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("mapcursor", "fx-mapcursor"); }-*/; private static native void prepareGuideLineMaterial() /*-{ var material = @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("guideline", "fx-guideline"); material.getParam("lengthScale").value = 1; material.getParam("color").value = [ 1, 1, 1, 1 ]; }-*/; private static native void prepareShieldMaterial() /*-{ var material = @org.grape.galaxy.client.ResourceManager::setAlphaStateEffect(Ljava/lang/String;Ljava/lang/String;)("shield", "fx-shield"); material.getParam("time").bind($wnd.g_globalParams.getParam("clock")); }-*/; private static native void preparePlanets() /*-{ var planetTransform = @org.grape.galaxy.client.ResourceManager::findTransform(Ljava/lang/String;)("Planet"); planetTransform.name = "Planet0"; for ( var i = 1; i < 10; i++) { var material = $wnd.g_pack.getObjects("planet" + i, "o3d.Material")[0]; var clonedTransform = $wnd.g_pack.createObject("Transform"); clonedTransform.name = "Planet" + i; clonedTransform.copyParams(planetTransform); clonedTransform.parent = planetTransform.parent; var shapes = planetTransform.shapes; for ( var j = 0; j < shapes.length; j++) { var shape = $wnd.o3djs.shape.duplicateShape($wnd.g_pack, shapes[j]); clonedTransform.addShape(shape); shape.elements[0].material = material; } } }-*/; private static native void prepareShips() /*-{ var shipMaterial = $wnd.g_pack.getObjects("ship", "o3d.Material")[0]; var shipTransform = @org.grape.galaxy.client.ResourceManager::findTransform(Ljava/lang/String;)("Ship"); var enemyShipMaterial = $wnd.g_pack.createObject("Material"); enemyShipMaterial.name = "enemyShip"; enemyShipMaterial.copyParams(shipMaterial); enemyShipMaterial.getParam("lightColor").value = [ @org.grape.galaxy.client.ViewConstants::ENEMY_COL_R, @org.grape.galaxy.client.ViewConstants::ENEMY_COL_G, @org.grape.galaxy.client.ViewConstants::ENEMY_COL_B, 1.0 ]; var enemyShipTransform = $wnd.g_pack.createObject("Transform"); enemyShipTransform.name = "EnemyShip"; enemyShipTransform.copyParams(shipTransform); enemyShipTransform.parent = shipTransform.parent; var shapes = shipTransform.shapes; for ( var j = 0; j < shapes.length; j++) { var shape = $wnd.o3djs.shape.duplicateShape($wnd.g_pack, shapes[j]); enemyShipTransform.addShape(shape); shape.elements[0].material = enemyShipMaterial; } shipTransform.name = "OwnShip"; shipMaterial.name = "ownShip"; shipMaterial.getParam("lightColor").value = [ @org.grape.galaxy.client.ViewConstants::OWN_COL_R, @org.grape.galaxy.client.ViewConstants::OWN_COL_G, @org.grape.galaxy.client.ViewConstants::OWN_COL_B, 1.0 ]; }-*/; }
gpl-2.0
ecometro/ecometro
application/models/Step3Ge4Field1.php
2158
<?php /** * Class Model for res_4_1 table */ class Model_Step3Ge4Field1 extends Zend_Db_Table_Abstract { protected $_name = 'ges_4_1'; protected $_primary = 'id'; protected $_dependentTables = array('Model_Step3Ge4'); /** * [createStep3Ge4Field1 create a new row in the ges_4_1 table] * @param [type] $id [description] * @return [type] [description] */ public function createStep3Ge4Field1($id) { // create a new row in the projects table $row = $this->createRow(); if($row) { try { // set the row data $row->s_3_ge_4_id = $id; // now fetch the id of the row you just created and return it $id = $row->save(); // return the id of the inserted row return $id; } catch (Zend_Exception $e) { throw new Zend_Exception(Zend_Registry::get('Zend_Translate')->translate('No se ha podido guardar el campo.')); } } else { throw new Zend_Exception(Zend_Registry::get('Zend_Translate')->translate('No se ha podido crear el campo.')); } } /** * [getTableName description] * @return [type] [description] */ public function getTableName() { $db = Zend_Db_Table_Abstract::getDefaultAdapter(); $sql = "SHOW TABLE STATUS LIKE '" . $this->_name . "';"; $result = $db->query($sql)->fetchObject(); return ($result->Comment); } /** * [getFieldType description] * @return [type] [description] */ public function getFieldType() { $db = Zend_Db_Table_Abstract::getDefaultAdapter(); $sql = "SHOW FIELDS FROM " . $this->_name . " WHERE Field='" . 'usuario_dato_1' . "';"; $result = $db->query($sql)->fetchObject(); return ($result->Type); } /** * [getFieldComment description] * @return [type] [description] */ public function getFieldComment() { $db = Zend_Db_Table_Abstract::getDefaultAdapter(); $dbName = $db->fetchOne("select DATABASE();"); $sql = "SELECT column_comment FROM information_schema.columns WHERE table_schema = '" . $dbName . "' and table_name = '" . $this->_name . "' and column_name = '" . 'usuario_dato_1' . "';"; $result = $db->query($sql)->fetchObject(); return ($result->column_comment); } }
gpl-2.0
drew1080/cheater-chef
wp-content/themes/demet-cheater/functions.php
12534
<?php if ( function_exists('register_sidebar') ) { register_sidebar(array( 'name' => 'Left Sidebar', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', )); register_sidebar( array( 'name' => 'Right Sidebar', 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '</li>', 'before_title' => '<h2 class="widgettitle">', 'after_title' => '</h2>', )); } $themename = "Demet"; $shortname = str_replace(' ', '_', strtolower($themename)); function get_theme_option($option) { global $shortname; return stripslashes(get_option($shortname . '_' . $option)); } function get_theme_settings($option) { return stripslashes(get_option($option)); } function cats_to_select() { $categories = get_categories('hide_empty=0'); $categories_array[] = array('value'=>'0', 'title'=>'Select'); foreach ($categories as $cat) { if($cat->category_count == '0') { $posts_title = 'No posts!'; } elseif($cat->category_count == '1') { $posts_title = '1 post'; } else { $posts_title = $cat->category_count . ' posts'; } $categories_array[] = array('value'=> $cat->cat_ID, 'title'=> $cat->cat_name . ' ( ' . $posts_title . ' )'); } return $categories_array; } $options = array ( array( "type" => "open"), array( "name" => "Logo Image", "desc" => "Enter the logo image full path. Leave it blank if you don't want to use logo image.", "id" => $shortname."_logo", "std" => get_bloginfo('template_url') . "/images/logo.png", "type" => "text"), array( "name" => "Featured Posts Enabled?", "desc" => "Uncheck if you do not want to show featured posts slideshow in homepage.", "id" => $shortname."_featured_posts", "std" => "true", "type" => "checkbox"), array( "name" => "Featured Posts Category", "desc" => "Last 5 posts form the selected categoey will be listed as featured at homepage. <br />The selected category should contain at last 2 posts with images. <br /> <br /> <b>How to add images to your featured posts slideshow?</b> <br /> <b>&raquo;</b> If you are using WordPress version 2.9 and above: Just set \"Post Thumbnail\" when adding new post for the posts in selected category above. <br /> <b>&raquo;</b> If you are using WordPress version under 2.9 you have to add custom fields in each post on the category you set as featured category. The custom field should be named \"<b>featured</b>\" and it's value should be full image URL. <a href=\"http://newwpthemes.com/public/featured_custom_field.jpg\" target=\"_blank\">Click here</a> for a screenshot. <br /> <br /> In both situation, the image sizes should be: Width: <b>540 px</b>. Height: <b>300 px.</b>", "id" => $shortname."_featured_posts_category", "options" => cats_to_select(), "std" => "0", "type" => "select"), array( "name" => "Header Banner (468x60 px)", "desc" => "Header banner code. You may use any html code here, including your 468x60 px Adsense code.", "id" => $shortname."_ad_header", "type" => "textarea", "std" => '<a href="http://newwpthemes.com/hosting/hostgator.php"><img src="http://newwpthemes.com/hosting/hg468.gif" /></a>' ), array( "name" => "Sidebar 125x125 px Ads", "desc" => "Add your 125x125 px ads here. You can add unlimited ads. Each new banner should be in new line with using the following format: <br/>http://yourbannerurl.com/banner.gif, http://theurl.com/to_link.html", "id" => $shortname."_ads_125", "type" => "textarea", "std" => 'http://newwpthemes.com/hosting/wpwh12.gif, http://newwpthemes.com/hosting/wpwebhost.php http://newwpthemes.com/uploads/newwp/newwp12.png,http://newwpthemes.com/ http://newwpthemes.com/hosting/hg125.gif, http://newwpthemes.com/hosting/hostgator.php' ), array( "name" => "Twitter", "desc" => "Enter your twitter account url here.", "id" => $shortname."_twitter", "std" => "http://twitter.com/WPTwits", "type" => "text"), array( "name" => "Twitter Text", "desc" => "", "id" => $shortname."_twittertext", "std" => "Follow me!", "type" => "text"), array( "name" => "Sidebar 1 Bottom Banner", "desc" => "Sidebar 1 Bottom Banner code.", "id" => $shortname."_ad_sidebar1_bottom", "type" => "textarea", "std" => '' ), array( "name" => "Sidebar 2 Bottom Banner", "desc" => "Sidebar 2 Bottom Banner code.", "id" => $shortname."_ad_sidebar2_bottom", "type" => "textarea", "std" => '<a href="http://newwpthemes.com"><img src="http://newwpthemes.com/uploads/newwp/newwp12.png" /></a>' ), array( "name" => "Head Scrip(s)", "desc" => "The content of this box will be added immediately before &lt;/head&gt; tag. Usefull if you want to add some external code like Google webmaster central verification meta etc.", "id" => $shortname."_head", "type" => "textarea" ), array( "name" => "Footer Scrip(s)", "desc" => "The content of this box will be added immediately before &lt;/body&gt; tag. Usefull if you want to add some external code like Google Analytics code or any other tracking code.", "id" => $shortname."_footer", "type" => "textarea" ), array( "type" => "close") ); function mytheme_add_admin() { global $themename, $shortname, $options; if ( $_GET['page'] == basename(__FILE__) ) { if ( 'save' == $_REQUEST['action'] ) { foreach ($options as $value) { update_option( $value['id'], $_REQUEST[ $value['id'] ] ); } foreach ($options as $value) { if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], $_REQUEST[ $value['id'] ] ); } else { delete_option( $value['id'] ); } } echo '<meta http-equiv="refresh" content="0;url=themes.php?page=functions.php&saved=true">'; die; } } add_theme_page($themename . " Theme Options", "".$themename . " Theme Options", 'edit_themes', basename(__FILE__), 'mytheme_admin'); } function mytheme_admin_init() { global $themename, $shortname, $options; $get_theme_options = get_option($shortname . '_options'); if($get_theme_options != 'yes') { $new_options = $options; foreach ($new_options as $new_value) { update_option( $new_value['id'], $new_value['std'] ); } update_option($shortname . '_options', 'yes'); } } if(!function_exists('get_sidebars')) { function get_sidebars($args='') { get_sidebar($args); } } function mytheme_admin() { global $themename, $shortname, $options; if ( $_REQUEST['saved'] ) echo '<div id="message" class="updated fade"><p><strong>'.$themename.' settings saved.</strong></p></div>'; ?> <div class="wrap"> <h2><?php echo $themename; ?> Theme Options | <a href="http://newwpthemes.com/forum/" target="_blank" style="font-size: 14px;">NewWpThemes.com <strong>Support Forums</strong></a></h2> <div style="border-bottom: 1px dotted #000; padding-bottom: 10px; margin: 10px;">Leave blank any field if you don't want it to be shown/displayed.</div> <?php $buy_theme_name = str_replace(' ', '-', strtolower(trim($themename))); ?> <form method="post"> <?php foreach ($options as $value) { switch ( $value['type'] ) { case "open": ?> <table width="100%" border="0" style=" padding:10px;"> <?php break; case "close": ?> </table><br /> <?php break; case "title": ?> <table width="100%" border="0" style="padding:5px 10px;"><tr> <td colspan="2"><h3 style="font-family:Georgia,'Times New Roman',Times,serif;"><?php echo $value['name']; ?></h3></td> </tr> <?php break; case 'text': ?> <tr> <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td> <td width="80%"><input style="width:100%;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" type="<?php echo $value['type']; ?>" value="<?php echo get_theme_settings( $value['id'] ); ?>" /></td> </tr> <tr> <td><small><?php echo $value['desc']; ?></small></td> </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr> <?php break; case 'textarea': ?> <tr> <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td> <td width="80%"><textarea name="<?php echo $value['id']; ?>" style="width:100%; height:140px;" type="<?php echo $value['type']; ?>" cols="" rows=""><?php echo get_theme_settings( $value['id'] ); ?></textarea></td> </tr> <tr> <td><small><?php echo $value['desc']; ?></small></td> </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr> <?php break; case 'select': ?> <tr> <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td> <td width="80%"> <select style="width:240px;" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>"> <?php foreach ($value['options'] as $option) { ?> <option value="<?php echo $option['value']; ?>" <?php if ( get_theme_settings( $value['id'] ) == $option['value']) { echo ' selected="selected"'; } ?>><?php echo $option['title']; ?></option> <?php } ?> </select> </td> </tr> <tr> <td><small><?php echo $value['desc']; ?></small></td> </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr> <?php break; case "checkbox": ?> <tr> <td width="20%" rowspan="2" valign="middle"><strong><?php echo $value['name']; ?></strong></td> <td width="80%"><?php if(get_theme_settings($value['id'])){ $checked = "checked=\"checked\""; }else{ $checked = ""; } ?> <input type="checkbox" name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>" value="true" <?php echo $checked; ?> /> </td> </tr> <tr> <td><small><?php echo $value['desc']; ?></small></td> </tr><tr><td colspan="2" style="margin-bottom:5px;border-bottom:1px dotted #000000;">&nbsp;</td></tr><tr><td colspan="2">&nbsp;</td></tr> <?php break; } } ?> <!--</table>--> <p class="submit"> <input name="save" type="submit" value="Save changes" /> <input type="hidden" name="action" value="save" /> </p> </form> <?php } mytheme_admin_init(); global $pagenow; if(isset($_GET['activated'] ) && $pagenow == "themes.php") { wp_redirect( admin_url('themes.php?page=functions.php') ); exit(); } add_action('admin_menu', 'mytheme_add_admin'); function sidebar_ads_125() { global $shortname; $option_name = $shortname."_ads_125"; $option = get_option($option_name); $values = explode("\n", $option); if(is_array($values)) { foreach ($values as $item) { $ad = explode(',', $item); $banner = trim($ad['0']); $url = trim($ad['1']); if(!empty($banner) && !empty($url)) { echo "<a href=\"$url\" target=\"_new\"><img class=\"ad125\" src=\"$banner\" /></a> \n"; } } } } ?> <?php if ( function_exists("add_theme_support") ) { add_theme_support("post-thumbnails"); } ?> <?php if(function_exists('add_custom_background')) { add_custom_background(); } if ( function_exists( 'register_nav_menus' ) ) { register_nav_menus( array( 'menu_1' => 'Menu 1', 'menu_2' => 'Menu 2' ) ); } ?>
gpl-2.0
anotherxiachong/Pooling2
src/com/another/pooling/AboutActivity.java
1537
package com.another.pooling; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.EditText; import android.widget.TextView; public class AboutActivity extends FragmentActivity { private EditText text; private TextView back; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_about); text = (EditText) findViewById(R.id.text_about); text.setText("拼 v2.3.0\n\n版权所有©兰州大学大鱼海棠团队"); back = (TextView) findViewById(R.id.back_tv_about); back.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub AboutActivity.this.finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.about, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
gpl-2.0
dailin/wesnoth
src/gui/dialogs/language_selection.cpp
2527
/* Copyright (C) 2008 - 2014 by Mark de Wever <koraq@xs4all.nl> Part of the Battle for Wesnoth Project http://www.wesnoth.org/ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. See the COPYING file for more details. */ #define GETTEXT_DOMAIN "wesnoth-lib" #include "gui/dialogs/language_selection.hpp" #include "gui/auxiliary/find_widget.tpp" #ifdef GUI2_EXPERIMENTAL_LISTBOX #include "gui/widgets/list.hpp" #else #include "gui/widgets/listbox.hpp" #endif #include "gui/widgets/settings.hpp" #include "gui/widgets/window.hpp" #include "language.hpp" #include "preferences.hpp" #include "utils/foreach.tpp" namespace gui2 { /*WIKI * @page = GUIWindowDefinitionWML * @order = 2_language_selection * * == Language selection == * * This shows the dialog to select the language to use. When the dialog is * closed with the OK button it also updates the selected language in the * preferences. * * @begin{table}{dialog_widgets} * * language_list & & listbox & m & * This listbox contains the list with available languages. $ * * - & & control & o & * Show the name of the language in the current row. $ * * @end{table} */ /** * @todo show we also reset the translations and is the tips of day call * really needed? */ REGISTER_DIALOG(language_selection) void tlanguage_selection::pre_show(CVideo& /*video*/, twindow& window) { tlistbox& list = find_widget<tlistbox>(&window, "language_list", false); window.keyboard_capture(&list); const std::vector<language_def>& languages = get_languages(); const language_def& current_language = get_language(); FOREACH(const AUTO & lang, languages) { string_map item; item.insert(std::make_pair("label", lang.language)); list.add_row(item); if(lang == current_language) { list.select_row(list.get_item_count() - 1); } } } void tlanguage_selection::post_show(twindow& window) { if(get_retval() == twindow::OK) { const int res = find_widget<tlistbox>(&window, "language_list", false) .get_selected_row(); assert(res != -1); const std::vector<language_def>& languages = get_languages(); ::set_language(languages[res]); preferences::set_language(languages[res].localename); } } } // namespace gui2
gpl-2.0
tolokoban/taquin-3d
src/mod/taquin.hollow-cube.js
1389
module.exports = function(side) { if (typeof side === 'undefined') side = 1; var grp = new THREE.Group(); var mat1 = new THREE.LineBasicMaterial({ color: new THREE.Color(.5,.5,.5), linewidth: 1 }); var mat0 = new THREE.LineBasicMaterial({ color: new THREE.Color(.1,.1,.1), linewidth: 1 }); var a, b; var i, j; var c = side/2; var line; var mat; for ( i=0 ; i<4 ; i++ ) { a = (i - 1.5) * c / 1.5; for ( j=0 ; j<4 ; j++ ) { b = (j - 1.5) * c / 1.5; if ( (i == 0 || i == 3) && (j == 0 || j == 3) ) { mat = mat1; } else { mat = mat0; } line = new THREE.Geometry(); line.vertices.push( new THREE.Vector3(a, b, -c), new THREE.Vector3(a, b, c) ); grp.add( new THREE.Line( line, mat ) ); line = new THREE.Geometry(); line.vertices.push( new THREE.Vector3(a, -c, b), new THREE.Vector3(a, c, b) ); grp.add( new THREE.Line( line, mat ) ); line = new THREE.Geometry(); line.vertices.push( new THREE.Vector3(-c, a, b), new THREE.Vector3(c, a, b) ); grp.add( new THREE.Line( line, mat ) ); } } return grp; };
gpl-2.0
oscarito9410/wpHotel
Becarios/Becarios/Bd/ReportHelper.cs.cs
2885
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Becarios.Bd { public class ReportHelper { public String dbPath = "Data Source=localhost;Database=hotelcolonia;Uid=root;Password=1234"; private MySqlDataAdapter miAdaptador = new MySql.Data.MySqlClient.MySqlDataAdapter(); public Common.Gastos getGastos(int idCliente=0) { var dataSetGastos = new Common.Gastos(); using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath)) { MidbConexion.Open(); MySqlCommand miComando = new MySqlCommand() { Connection=MidbConexion }; if (idCliente>0) { miComando.CommandText = "SELECT*FROM total_gasto WHERE ID_CLIENTE=?id_cliente ORDER BY CLV_ORDEN ASC"; miComando.Parameters.AddWithValue("?id_cliente", idCliente); } else { miComando.CommandText = "SELECT*FROM total_gasto ORDER BY CLV_ORDEN ASC"; } miAdaptador.SelectCommand = miComando; miAdaptador.Fill(dataSetGastos,"total_gasto"); return dataSetGastos; } } public Common.Gastos getTicket(int clvOrden) { var dataSetGastos = new Common.Gastos(); using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath)) { MidbConexion.Open(); MySqlCommand miComando = new MySqlCommand() { Connection = MidbConexion }; miComando.CommandText = "SELECT*FROM total_gasto WHERE clv_orden=?clv"; miComando.Parameters.AddWithValue("?clv", clvOrden); miAdaptador.SelectCommand = miComando; miAdaptador.Fill(dataSetGastos, "total_gasto"); return dataSetGastos; } } public Common.Habitacion_Cliente getHabitaciones() { var dataSetHabitacion = new Common.Habitacion_Cliente(); using (MySqlConnection MidbConexion = new MySqlConnection(this.dbPath)) { MidbConexion.Open(); MySqlCommand miComando = new MySqlCommand() { Connection = MidbConexion }; miComando.CommandText = "SELECT*FROM habitacion_cliente"; miAdaptador.SelectCommand = miComando; miAdaptador.Fill(dataSetHabitacion, "habitacion_cliente"); return dataSetHabitacion; } } } }
gpl-2.0
rfkrocktk/django-locality
src/locality/settings.py
1835
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = () MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': '/tmp/locality.db' } } TIME_ZONE = "UTC" LANGUAGE_CODE = "en-us" SITE_ID = 1 USE_I18N = True USE_L10N = True MEDIA_ROOT = '' MEDIA_URL = '' STATIC_ROOT = '' STATIC_URL = '/static/' ADMIN_MEDIA_PREFIX = '/static/admin/' STATICFILES_DIRS = () STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) SECRET_KEY = 'd=eh)2xs8*px19*9_54-)q1=l=q*wy=(v+e002w95c@!)p_8)n' TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'django.template.loaders.eggs.Loader', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', ) ROOT_URLCONF = 'locality.urls' TEMPLATE_DIRS = () INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.admin', 'locality', ) LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' } }, 'loggers': { 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, } }
gpl-2.0
vinstah/silent-mafia
new.php
1043
<section id="main"> <header id="notice"><h2>Updates</h2></header> <article> <p class="poster"><small>your mumma</small> on 10:11 a.m. 2/04/2012</p> <p class="post">Smity will be doing the BETA testing</p> <p class="poster"><small>posted by Vinstah on <time datetime="2010-10-17T23:17:43+13:00">Sunday, 17<sup>th</sup> October at 11:17 p.m NZDST</time></small></p> <p class="post">Welcome to Silent Mafia. Please use the links at top to sign in or register. <br />Reminder :- Activation e-mails can take up to 24 hours to arrive on some E-mail providers for example Yahoo! </p> <p class="poster"> <small>posted by Vinstah on <time datetime="2010-08-05T13:26:45+12:00">Wednesday, 17<sup>th</sup> March at 1:26 p.m NZST</time></small></p> <p class="post">It\'s been great seeing alot of new players registering to play, the staff welcome you all. please read the rules and abide by them, players who state that they "did not know of such rules" will get the same discipline.</p> </article> </section>
gpl-2.0
ljx0305/ice
java-compat/src/Ice/src/main/java/IceInternal/Functional_TwowayCallbackInt.java
1533
// ********************************************************************** // // Copyright (c) 2003-2017 ZeroC, Inc. All rights reserved. // // This copy of Ice is licensed to you under the terms described in the // ICE_LICENSE file included in this distribution. // // ********************************************************************** package IceInternal; public abstract class Functional_TwowayCallbackInt extends Functional_TwowayCallback implements Ice.TwowayCallbackInt { public Functional_TwowayCallbackInt(Functional_IntCallback responseCb, Functional_GenericCallback1<Ice.Exception> exceptionCb, Functional_BoolCallback sentCb) { super(responseCb != null, exceptionCb, sentCb); _responseCb = responseCb; } protected Functional_TwowayCallbackInt(boolean userExceptionCb, Functional_IntCallback responseCb, Functional_GenericCallback1<Ice.Exception> exceptionCb, Functional_BoolCallback sentCb) { super(exceptionCb, sentCb); CallbackBase.check(responseCb != null || (userExceptionCb && exceptionCb != null)); _responseCb = responseCb; } @Override public void response(int arg) { if(_responseCb != null) { _responseCb.apply(arg); } } final private Functional_IntCallback _responseCb; }
gpl-2.0
rex-xxx/mt6572_x201
frameworks/opt/telephony/src/java/com/android/internal/telephony/Call.java
6142
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.internal.telephony; import java.util.List; import android.util.Log; /** * {@hide} */ public abstract class Call { /* Enums */ public enum State { IDLE, ACTIVE, HOLDING, DIALING, ALERTING, INCOMING, WAITING, DISCONNECTED, DISCONNECTING; public boolean isAlive() { return !(this == IDLE || this == DISCONNECTED || this == DISCONNECTING); } public boolean isRinging() { return this == INCOMING || this == WAITING; } public boolean isDialing() { return this == DIALING || this == ALERTING; } } /* Instance Variables */ public State state = State.IDLE; // Flag to indicate if the current calling/caller information // is accurate. If false the information is known to be accurate. // // For CDMA, during call waiting/3 way, there is no network response // if call waiting is answered, network timed out, dropped, 3 way // merged, etc. protected boolean isGeneric = false; /// M: [mtk04070][111118][ALPS00093395]MTK added. @{ public boolean isMptyCall = false; public boolean lastMptyState = false; /// @} protected final String LOG_TAG = "Call"; /* Instance Methods */ /** Do not modify the List result!!! This list is not yours to keep * It will change across event loop iterations top */ public abstract List<Connection> getConnections(); public abstract Phone getPhone(); public abstract boolean isMultiparty(); public abstract void hangup() throws CallStateException; /** * hasConnection * * @param c a Connection object * @return true if the call contains the connection object passed in */ public boolean hasConnection(Connection c) { return c.getCall() == this; } /** * hasConnections * @return true if the call contains one or more connections */ public boolean hasConnections() { List connections = getConnections(); if (connections == null) { return false; } return connections.size() > 0; } /** * getState * @return state of class call */ public State getState() { return state; } /** * isIdle * * FIXME rename * @return true if the call contains only disconnected connections (if any) */ public boolean isIdle() { return !getState().isAlive(); } /** * Returns the Connection associated with this Call that was created * first, or null if there are no Connections in this Call */ public Connection getEarliestConnection() { List l; long time = Long.MAX_VALUE; Connection c; Connection earliest = null; l = getConnections(); if (l.size() == 0) { return null; } for (int i = 0, s = l.size() ; i < s ; i++) { c = (Connection) l.get(i); long t; t = c.getCreateTime(); if (t < time) { earliest = c; time = t; } } return earliest; } public long getEarliestCreateTime() { List l; long time = Long.MAX_VALUE; l = getConnections(); if (l.size() == 0) { return 0; } for (int i = 0, s = l.size() ; i < s ; i++) { Connection c = (Connection) l.get(i); long t; t = c.getCreateTime(); time = t < time ? t : time; } return time; } public long getEarliestConnectTime() { long time = Long.MAX_VALUE; List l = getConnections(); if (l.size() == 0) { return 0; } for (int i = 0, s = l.size() ; i < s ; i++) { Connection c = (Connection) l.get(i); long t; t = c.getConnectTime(); time = t < time ? t : time; } return time; } public boolean isDialingOrAlerting() { return getState().isDialing(); } public boolean isRinging() { return getState().isRinging(); } /** * Returns the Connection associated with this Call that was created * last, or null if there are no Connections in this Call */ public Connection getLatestConnection() { List l = getConnections(); if (l.size() == 0) { return null; } long time = 0; Connection latest = null; for (int i = 0, s = l.size() ; i < s ; i++) { Connection c = (Connection) l.get(i); long t = c.getCreateTime(); if (t > time) { latest = c; time = t; } } return latest; } /** * To indicate if the connection information is accurate * or not. false means accurate. Only used for CDMA. */ public boolean isGeneric() { return isGeneric; } /** * Set the generic instance variable */ public void setGeneric(boolean generic) { isGeneric = generic; } /** * Hangup call if it is alive */ public void hangupIfAlive() { if (getState().isAlive()) { try { hangup(); } catch (CallStateException ex) { Log.w(LOG_TAG, " hangupIfActive: caught " + ex); } } } }
gpl-2.0
Surfing-Chef/tuffbeans
inc/custom-header.php
1868
<?php /** * Sample implementation of the Custom Header feature * * You can add an optional custom header image to header.php like so ... * <?php the_header_image_tag(); ?> * * @link https://developer.wordpress.org/themes/functionality/custom-headers/ * * @package tuffbeans */ /** * Set up the WordPress core custom header feature. * * @uses tuffbeans_header_style() */ function tuffbeans_custom_header_setup() { add_theme_support( 'custom-header', apply_filters( 'tuffbeans_custom_header_args', array( 'default-image' => '', 'default-text-color' => '000000', 'width' => 1000, 'height' => 250, 'flex-height' => true, 'wp-head-callback' => 'tuffbeans_header_style', ) ) ); } add_action( 'after_setup_theme', 'tuffbeans_custom_header_setup' ); if ( ! function_exists( 'tuffbeans_header_style' ) ) : /** * Styles the header image and text displayed on the blog. * * @see tuffbeans_custom_header_setup(). */ function tuffbeans_header_style() { $header_text_color = get_header_textcolor(); /* * If no custom options for text are set, let's bail. * get_header_textcolor() options: Any hex value, 'blank' to hide text. Default: add_theme_support( 'custom-header' ). */ if ( get_theme_support( 'custom-header', 'default-text-color' ) === $header_text_color ) { return; } // If we get this far, we have custom styles. Let's do this. ?> <style type="text/css"> <?php // Has the text been hidden? if ( ! display_header_text() ) : ?> .site-title, .site-description { position: absolute; clip: rect(1px, 1px, 1px, 1px); } <?php // If the user has set a custom color for the text use that. else : ?> .site-title a, .site-description { color: #<?php echo esc_attr( $header_text_color ); ?>; } <?php endif; ?> </style> <?php } endif;
gpl-2.0
mapolat/mapCasting
include/smarty/libs/plugins/modifier.regex_replace.php
1565
<?php /** * Smarty plugin * * @package Smarty * @subpackage PluginsModifier */ /** * Smarty regex_replace modifier plugin * * Type: modifier<br> * Name: regex_replace<br> * Purpose: regular expression search/replace * * @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php * regex_replace (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string $string input string * @param string|array $search regular expression(s) to search for * @param string|array $replace string(s) that should be replaced * @return string */ function smarty_modifier_regex_replace($string, $search, $replace) { if (is_array($search)) { foreach ($search as $idx => $s) { $search[$idx] = _smarty_regex_replace_check($s); } } else { $search = _smarty_regex_replace_check($search); } return preg_replace($search, $replace, $string); } /** * @param string $search string(s) that should be replaced * @return string * @ignore */ function _smarty_regex_replace_check($search) { // null-byte injection detection // anything behind the first null-byte is ignored if (($pos = strpos($search, "\0")) !== false) { $search = substr($search, 0, $pos); } // remove eval-modifier from $search if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) { $search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]); } return $search; } ?>
gpl-2.0
gggeek/ezpublish-kernel
eZ/Publish/Core/MVC/Symfony/FieldType/ImageAsset/ParameterProvider.php
2922
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. */ declare(strict_types=1); namespace eZ\Publish\Core\MVC\Symfony\FieldType\ImageAsset; use eZ\Publish\API\Repository\Exceptions\NotFoundException; use eZ\Publish\API\Repository\Repository; use eZ\Publish\API\Repository\Values\Content\Field; use eZ\Publish\Core\MVC\Symfony\FieldType\View\ParameterProviderInterface; use eZ\Publish\API\Repository\Values\Content\ContentInfo; class ParameterProvider implements ParameterProviderInterface { /** @var \eZ\Publish\API\Repository\Repository */ private $repository; /** @var \eZ\Publish\API\Repository\PermissionResolver */ private $permissionsResolver; /** @var \eZ\Publish\Core\Repository\FieldTypeService */ private $fieldTypeService; /** * @param \eZ\Publish\API\Repository\Repository $repository */ public function __construct(Repository $repository) { $this->repository = $repository; $this->permissionsResolver = $repository->getPermissionResolver(); $this->fieldTypeService = $repository->getFieldTypeService(); } /** * {@inheritdoc} */ public function getViewParameters(Field $field): array { $fieldType = $this->fieldTypeService->getFieldType($field->fieldTypeIdentifier); if ($fieldType->isEmptyValue($field->value)) { return [ 'available' => null, ]; } try { $contentInfo = $this->loadContentInfo( (int)$field->value->destinationContentId ); return [ 'available' => !$contentInfo->isTrashed() && $this->userHasPermissions($contentInfo), ]; } catch (NotFoundException $exception) { return [ 'available' => false, ]; } } /** * @param int $id * * @return \eZ\Publish\API\Repository\Values\Content\ContentInfo * * @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException */ private function loadContentInfo(int $id): ContentInfo { return $this->repository->sudo( function (Repository $repository) use ($id) { return $repository->getContentService()->loadContentInfo($id); } ); } /** * @param \eZ\Publish\API\Repository\Values\Content\ContentInfo $contentInfo * * @return bool */ private function userHasPermissions(ContentInfo $contentInfo): bool { if ($this->permissionsResolver->canUser('content', 'read', $contentInfo)) { return true; } if ($this->permissionsResolver->canUser('content', 'view_embed', $contentInfo)) { return true; } return false; } }
gpl-2.0
ekaltman/citetool-jpcrr
streamtools/outputs/flac.cpp
1979
#include "outputs/internal.hpp" #include "outputs/argexpand.hpp" #include <cstdio> #include <stdexcept> #include <string> #include <sstream> #include <fcntl.h> namespace { class output_driver_flac : public output_driver { public: output_driver_flac(const std::string& _filename, const std::string& _options) { filename = _filename; options = _options; set_audio_callback(make_bound_method(*this, &output_driver_flac::audio_callback)); } ~output_driver_flac() { pclose(out); } void ready() { const audio_settings& a = get_audio_settings(); std::stringstream commandline; std::string executable = "flac"; std::string x = expand_arguments_common(options, "--", "=", executable); commandline << executable <<" --force-raw-format --endian=little " << "--channels=2 --bps=16 --sign=signed --sample-rate=" << a.get_rate() << " " << x << " -o " << filename << " -"; std::string s = commandline.str(); out = popen(s.c_str(), "w"); if(!out) { std::stringstream str; str << "Can't run flac (" << s << ")"; throw std::runtime_error(str.str()); } #if defined(_WIN32) || defined(_WIN64) setmode(fileno(out), O_BINARY); #endif } void audio_callback(short left, short right) { uint8_t rawdata[4]; rawdata[1] = ((unsigned short)left >> 8) & 0xFF; rawdata[0] = ((unsigned short)left) & 0xFF; rawdata[3] = ((unsigned short)right >> 8) & 0xFF; rawdata[2] = ((unsigned short)right) & 0xFF; if(fwrite(rawdata, 1, 4, out) < 4) throw std::runtime_error("Error writing sample to flac"); } private: FILE* out; std::string filename; std::string options; }; class output_driver_flac_factory : output_driver_factory { public: output_driver_flac_factory() : output_driver_factory("flac") { } output_driver& make(const std::string& type, const std::string& name, const std::string& parameters) { return *new output_driver_flac(name, parameters); } } factory; }
gpl-2.0
jeveloper/gameserver
gameLogic/src/com/jeveloper/gameserver/beans/Player.java
1900
/* * Player.java * * Created on March 15, 2007, 10:19 PM * * To change this template, choose Tools | Template Manager * and open the template in the editor. */ package com.jeveloper.gameserver.beans; import com.jeveloper.gameserver.core.IPlay; import java.io.Serializable; /** * * @author serge */ public class Player implements Serializable, Comparable<Player>{ private int id =0; //not internal but external private String name =""; private Integer points=0; // total points , WE MIGHT NEED To keep this in a draw or player list, or have Ranking within game private PlayList player_combinations; /** Creates a new instance of Player */ public Player() { } public Player(int _id, String _name) { setId(_id); setName(_name); setPlayer_combinations(new PlayList()); } public Player(int _id, String _name, int max_plays) { setId(_id); setName(_name); setPlayer_combinations(new PlayList(max_plays)); } public void addPlay(IPlay play){ player_combinations.addPlay(play); } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getPoints() { return points; } public void setPoints(Integer points) { this.points = points; } public PlayList getPlayer_combinations() { return player_combinations; } public void setPlayer_combinations(PlayList player_combinations) { this.player_combinations = player_combinations; } public int compareTo(Player o) { return points.compareTo(o.getPoints()); } }
gpl-2.0
vdkhanh/kata-tdd-1-duy-khanh-vo
Exercise/src/main/DelimiterNumberCreator.java
597
package main; import java.util.Arrays; import java.util.List; public class DelimiterNumberCreator extends NumberCreator { private static final String BEGIN_OF_NUMBER = "\n"; public DelimiterNumberCreator(String numbers) { this.numbers = numbers; } @Override public List<String> getDelimiters() { int delimiterIndex = USE_SPECIFIED_DELIMITER.length(); return Arrays.asList(numbers.substring(delimiterIndex, delimiterIndex + 1)); } @Override public String getNumberAfterDelimiter() { return numbers.substring(numbers.indexOf(BEGIN_OF_NUMBER) + 1); } }
gpl-2.0
kunj1988/Magento2
app/code/Magento/Sales/Test/Unit/Model/Order/Pdf/Config/XsdTest.php
14175
<?php /** * Test for validation rules implemented by XSD schema for sales PDF rendering configuration * * Copyright © Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Sales\Test\Unit\Model\Order\Pdf\Config; class XsdTest extends \PHPUnit\Framework\TestCase { /** * @var string */ protected static $_schemaPath; /** * @var string */ protected static $_schemaFilePath; public static function setUpBeforeClass() { $urnResolver = new \Magento\Framework\Config\Dom\UrnResolver(); self::$_schemaPath = $urnResolver->getRealPath('urn:magento:module:Magento_Sales:etc/pdf.xsd'); self::$_schemaFilePath = $urnResolver->getRealPath('urn:magento:module:Magento_Sales:etc/pdf_file.xsd'); } protected function setUp() { if (!function_exists('libxml_set_external_entity_loader')) { $this->markTestSkipped('Skipped on HHVM. Will be fixed in MAGETWO-45033'); } } /** * @param string $fixtureXml * @param array $expectedErrors * @dataProvider schemaByExemplarDataProvider */ public function testSchemaByExemplar($fixtureXml, array $expectedErrors) { $this->_testSchema(self::$_schemaPath, $fixtureXml, $expectedErrors); } /** * @param string $fixtureXml * @param array $expectedErrors * @dataProvider fileSchemaByExemplarDataProvider */ public function testFileSchemaByExemplar($fixtureXml, array $expectedErrors) { $this->_testSchema(self::$_schemaFilePath, $fixtureXml, $expectedErrors); } /** * Test schema against exemplar data * * @param string $schema * @param string $fixtureXml * @param array $expectedErrors */ protected function _testSchema($schema, $fixtureXml, array $expectedErrors) { $validationStateMock = $this->createMock(\Magento\Framework\Config\ValidationStateInterface::class); $validationStateMock->method('isValidationRequired') ->willReturn(true); $dom = new \Magento\Framework\Config\Dom($fixtureXml, $validationStateMock, [], null, null, '%message%'); $actualResult = $dom->validate($schema, $actualErrors); $this->assertEquals(empty($expectedErrors), $actualResult); $this->assertEquals($expectedErrors, $actualErrors); } /** * @return array */ public function schemaByExemplarDataProvider() { $result = $this->_getExemplarTestData(); $result['non-valid totals missing title'] = [ '<config><totals><total name="i1"><source_field>foo</source_field></total></totals></config>', [ 'Element \'total\': Missing child element(s). Expected is one of ( title, title_source_field, ' . 'font_size, display_zero, sort_order, model, amount_prefix ).' ], ]; $result['non-valid totals missing source_field'] = [ '<config><totals><total name="i1"><title>Title</title></total></totals></config>', [ 'Element \'total\': Missing child element(s). Expected is one of ( source_field, ' . 'title_source_field, font_size, display_zero, sort_order, model, amount_prefix ).' ], ]; return $result; } /** * @return array */ public function fileSchemaByExemplarDataProvider() { $result = $this->_getExemplarTestData(); $result['valid totals missing title'] = [ '<config><totals><total name="i1"><source_field>foo</source_field></total></totals></config>', [], ]; $result['valid totals missing source_field'] = [ '<config><totals><total name="i1"><title>Title</title></total></totals></config>', [], ]; return $result; } /** * Return use cases, common for both merged configuration and individual files. * Reused by appropriate data providers. * * @return array * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _getExemplarTestData() { return [ 'valid empty' => ['<config/>', []], 'valid empty renderers' => ['<config><renderers/></config>', []], 'valid empty totals' => ['<config><totals/></config>', []], 'valid empty renderers and totals' => ['<config><renderers/><totals/></config>', []], 'non-valid unknown node in <config>' => [ '<config><unknown/></config>', ['Element \'unknown\': This element is not expected.'], ], 'valid pages' => [ '<config><renderers><page type="p1"/><page type="p2"/></renderers></config>', [], ], 'non-valid non-unique pages' => [ '<config><renderers><page type="p1"/><page type="p1"/></renderers></config>', [ 'Element \'page\': Duplicate key-sequence [\'p1\'] ' . 'in unique identity-constraint \'uniquePageRenderer\'.' ], ], 'non-valid unknown node in renderers' => [ '<config><renderers><unknown/></renderers></config>', ['Element \'unknown\': This element is not expected. Expected is ( page ).'], ], 'valid page renderers' => [ '<config><renderers><page type="p1"><renderer product_type="prt1">Class\A</renderer>' . '<renderer product_type="prt2">Class\B</renderer></page></renderers></config>', [], ], 'non-valid non-unique page renderers' => [ '<config><renderers><page type="p1"><renderer product_type="prt1">Class\A</renderer>' . '<renderer product_type="prt1">Class\B</renderer></page></renderers></config>', [ 'Element \'renderer\': Duplicate key-sequence [\'prt1\'] ' . 'in unique identity-constraint \'uniqueProductTypeRenderer\'.' ], ], 'non-valid empty renderer class name' => [ '<config><renderers><page type="p1"><renderer product_type="prt1"/></page></renderers></config>', [ 'Element \'renderer\': [facet \'pattern\'] The value \'\' is not accepted ' . 'by the pattern \'[A-Z][a-zA-Z\d]*(\\\\[A-Z][a-zA-Z\d]*)*\'.', 'Element \'renderer\': \'\' is not a valid value of the atomic type \'classNameType\'.' ], ], 'non-valid unknown node in page' => [ '<config><renderers><page type="p1"><unknown/></page></renderers></config>', ['Element \'unknown\': This element is not expected. Expected is ( renderer ).'], ], 'valid totals' => [ '<config><totals><total name="i1"><title>Title1</title><source_field>src_fld1</source_field></total>' . '<total name="i2"><title>Title2</title><source_field>src_fld2</source_field></total>' . '</totals></config>', [], ], 'non-valid non-unique total items' => [ '<config><totals><total name="i1"><title>Title1</title><source_field>src_fld1</source_field></total>' . '<total name="i1"><title>Title2</title><source_field>src_fld2</source_field></total>' . '</totals></config>', [ 'Element \'total\': Duplicate key-sequence [\'i1\'] ' . 'in unique identity-constraint \'uniqueTotalItem\'.' ], ], 'non-valid unknown node in total items' => [ '<config><totals><unknown/></totals></config>', ['Element \'unknown\': This element is not expected. Expected is ( total ).'], ], 'non-valid totals empty title' => [ '<config><totals><total name="i1"><title/><source_field>foo</source_field></total></totals></config>', [ 'Element \'title\': [facet \'minLength\'] The value has a length of \'0\'; ' . 'this underruns the allowed minimum length of \'1\'.', 'Element \'title\': \'\' is not a valid value of the atomic type \'nonEmptyString\'.' ], ], 'non-valid totals empty source_field' => [ '<config><totals><total name="i1"><title>Title</title><source_field/></total></totals></config>', [ 'Element \'source_field\': [facet \'pattern\'] The value \'\' is not accepted ' . 'by the pattern \'[a-z0-9_]+\'.', 'Element \'source_field\': \'\' is not a valid value of the atomic type \'fieldType\'.' ], ], 'non-valid totals empty title_source_field' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<title_source_field/></total></totals></config>', [ 'Element \'title_source_field\': [facet \'pattern\'] The value \'\' is not accepted ' . 'by the pattern \'[a-z0-9_]+\'.', 'Element \'title_source_field\': \'\' is not a valid value of the atomic type \'fieldType\'.' ], ], 'non-valid totals bad model' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<model>a model</model></total></totals></config>', [ 'Element \'model\': [facet \'pattern\'] The value \'a model\' is not accepted ' . 'by the pattern \'[A-Z][a-zA-Z\d]*(\\\\[A-Z][a-zA-Z\d]*)*\'.', 'Element \'model\': \'a model\' is not a valid value of the atomic type \'classNameType\'.' ], ], 'valid totals title_source_field' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<title_source_field>bar</title_source_field></total></totals></config>', [], ], 'valid totals model' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<model>Class\A</model></total></totals></config>', [], ], 'valid totals font_size' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<font_size>9</font_size></total></totals></config>', [], ], 'non-valid totals font_size 0' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<font_size>0</font_size></total></totals></config>', ['Element \'font_size\': \'0\' is not a valid value of the atomic type \'xs:positiveInteger\'.'], ], 'non-valid totals font_size' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<font_size>A</font_size></total></totals></config>', ['Element \'font_size\': \'A\' is not a valid value of the atomic type \'xs:positiveInteger\'.'], ], 'valid totals display_zero' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<display_zero>1</display_zero></total></totals></config>', [], ], 'valid totals display_zero true' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<display_zero>true</display_zero></total></totals></config>', [], ], 'non-valid totals display_zero' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<display_zero>A</display_zero></total></totals></config>', ['Element \'display_zero\': \'A\' is not a valid value of the atomic type \'xs:boolean\'.'], ], 'valid totals sort_order' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<sort_order>100</sort_order></total></totals></config>', [], ], 'valid totals sort_order 0' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<sort_order>0</sort_order></total></totals></config>', [], ], 'non-valid totals sort_order' => [ '<config><totals><total name="i1"><title>Title</title><source_field>foo</source_field>' . '<sort_order>A</sort_order></total></totals></config>', [ 'Element \'sort_order\': \'A\' is not a valid value ' . 'of the atomic type \'xs:nonNegativeInteger\'.' ], ], 'valid totals title with translate attribute' => [ '<config><totals><total name="i1"><title translate="true">Title</title>' . '<source_field>foo</source_field></total></totals></config>', [], ], 'non-valid totals title with bad translate attribute' => [ '<config><totals><total name="i1"><title translate="unknown">Title</title>' . '<source_field>foo</source_field></total></totals></config>', [ 'Element \'title\', attribute \'translate\': \'unknown\' is not a valid value ' . 'of the atomic type \'xs:boolean\'.' ], ] ]; } }
gpl-2.0
cyberpython/java-gnome
generated/bindings/org/gnome/unixprint/GtkPrintJob.java
7887
/* * java-gnome, a UI library for writing GTK and GNOME programs from Java! * * Copyright © 2006-2011 Operational Dynamics Consulting, Pty Ltd and Others * * The code in this file, and the program it is a part of, is made available * to you by its authors as open source software: you can redistribute it * and/or modify it under the terms of the GNU General Public License version * 2 ("GPL") as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GPL for more details. * * You should have received a copy of the GPL along with this program. If not, * see http://www.gnu.org/licenses/. The authors of this program may be * contacted through http://java-gnome.sourceforge.net/. * * Linking this library statically or dynamically with other modules is making * a combined work based on this library. Thus, the terms and conditions of * the GPL cover the whole combination. As a special exception (the * "Claspath Exception"), the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent modules, * and to copy and distribute the resulting executable under terms of your * choice, provided that you also meet, for each linked independent module, * the terms and conditions of the license of that module. An independent * module is a module which is not derived from or based on this library. If * you modify this library, you may extend the Classpath Exception to your * version of the library, but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. */ package org.gnome.unixprint; /* * THIS FILE IS GENERATED CODE! * * To modify its contents or behaviour, either update the generation program, * change the information in the source defs file, or implement an override for * this class. */ import org.freedesktop.bindings.BlacklistedMethodError; import org.freedesktop.bindings.FIXME; import org.freedesktop.cairo.Surface; import org.gnome.glib.GlibException; import org.gnome.glib.Signal; import org.gnome.gtk.PageSetup; import org.gnome.gtk.PrintSettings; import org.gnome.gtk.PrintStatus; import org.gnome.unixprint.Plumbing; import org.gnome.unixprint.PrintJob; import org.gnome.unixprint.Printer; final class GtkPrintJob extends Plumbing { private GtkPrintJob() {} static final long createPrintJob(String title, Printer printer, PrintSettings settings, PageSetup pageSetup) { long result; if (title == null) { throw new IllegalArgumentException("title can't be null"); } if (printer == null) { throw new IllegalArgumentException("printer can't be null"); } if (settings == null) { throw new IllegalArgumentException("settings can't be null"); } if (pageSetup == null) { throw new IllegalArgumentException("pageSetup can't be null"); } synchronized (lock) { result = gtk_print_job_new(title, pointerOf(printer), pointerOf(settings), pointerOf(pageSetup)); return result; } } private static native final long gtk_print_job_new(String title, long printer, long settings, long pageSetup); static final PrintSettings getSettings(PrintJob self) { long result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_print_job_get_settings(pointerOf(self)); return (PrintSettings) objectFor(result); } } private static native final long gtk_print_job_get_settings(long self); static final Printer getPrinter(PrintJob self) { long result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_print_job_get_printer(pointerOf(self)); return (Printer) objectFor(result); } } private static native final long gtk_print_job_get_printer(long self); static final String getTitle(PrintJob self) { String result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_print_job_get_title(pointerOf(self)); return result; } } private static native final String gtk_print_job_get_title(long self); static final PrintStatus getStatus(PrintJob self) { int result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_print_job_get_status(pointerOf(self)); return (PrintStatus) enumFor(PrintStatus.class, result); } } private static native final int gtk_print_job_get_status(long self); static final boolean setSourceFile(PrintJob self, String filename) throws GlibException { boolean result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } if (filename == null) { throw new IllegalArgumentException("filename can't be null"); } synchronized (lock) { result = gtk_print_job_set_source_file(pointerOf(self), filename); return result; } } private static native final boolean gtk_print_job_set_source_file(long self, String filename) throws GlibException; static final Surface getSurface(PrintJob self) throws GlibException { long result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_print_job_get_surface(pointerOf(self)); return (Surface) entityFor(Surface.class, result); } } private static native final long gtk_print_job_get_surface(long self) throws GlibException; static final void setTrackPrintStatus(PrintJob self, boolean trackStatus) { if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { gtk_print_job_set_track_print_status(pointerOf(self), trackStatus); } } private static native final void gtk_print_job_set_track_print_status(long self, boolean trackStatus); static final boolean getTrackPrintStatus(PrintJob self) { boolean result; if (self == null) { throw new IllegalArgumentException("self can't be null"); } synchronized (lock) { result = gtk_print_job_get_track_print_status(pointerOf(self)); return result; } } private static native final boolean gtk_print_job_get_track_print_status(long self); @SuppressWarnings("unused") static final boolean send(PrintJob self, FIXME callback, FIXME userData, FIXME dnotify) throws BlacklistedMethodError { throw new BlacklistedMethodError("GtkPrintJobCompleteFunc"); } interface StatusChangedSignal extends Signal { void onStatusChanged(PrintJob source); } static final void connect(PrintJob self, GtkPrintJob.StatusChangedSignal handlerInstance, boolean after) { connectSignal(self, handlerInstance, GtkPrintJob.class, "status-changed", after); } protected static final void receiveStatusChanged(Signal handler, long source) { ((GtkPrintJob.StatusChangedSignal) handler).onStatusChanged((PrintJob) objectFor(source)); } }
gpl-2.0
Kingpin007/SPOJ
SMPWOW - Wow.py
199
__author__ = 'Anirudh' def main(): x = int(input()) print('W', end='') j = 0 while j < x: print('o', end='') j += 1 print('w') if __name__ == '__main__': main()
gpl-2.0
gdoteof/iusecoins
sites/all/themes/clean/page-node-2.tpl.php
1701
<?php // $Id: page.tpl.php,v 1.1.2.5.2.14.2.12 2010/03/01 13:37:46 psynaptic Exp $ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html<?php print drupal_attributes($html_attr); ?>> <head> <?php print $head; ?> <?php print $styles; ?> <!--[if lt IE 8]><link type="text/css" rel="stylesheet" media="all" href="<?php print $base_theme; ?>css/ie-lt8.css" /><![endif]--> <?php print $scripts; ?> <title><?php print $head_title; ?></title> </head> <body<?php print drupal_attributes($attr); ?>> <div id="page"> <div class="limiter clear-block"> <div id="main" class="clear-block"> <?php if ($left): ?> <div id="left" class="sidebar"> <?php print $left; ?> </div> <?php endif; ?> <div class="usermessage"><?php print $header; ?></div> <div class="tshirt-logo"> <img src="/sites/all/themes/clean/images/shirt.png"></div> <div id="content" class="clear-block"> <?php print $tabs; ?> <?php print $messages; ?> <?php print $help; ?> <?php if ($title): ?> <h1 class="page-title"><?php print $title; ?></h1> <?php endif; ?> <?php print $content; ?> </div> <?php if ($right): ?> <div id="right" class="sidebar"> <?php print $right; ?> </div> <?php endif; ?> </div> </div> </div> <div id="footer"> <div class="limiter clear-block"> <?php print $feed_icons; ?> <?php print $footer; ?> <?php print $footer_message; ?> </div> </div> <?php print $closure; ?> </body> </html>
gpl-2.0
ulfjack/cqs
Engine/net/cqs/engine/battles/WithdrawAction.java
4650
package net.cqs.engine.battles; import java.util.logging.Level; import net.cqs.config.BattleMessageEnum; import net.cqs.config.BattleStateEnum; import net.cqs.config.Constants; import net.cqs.config.units.UnitSystem; import net.cqs.engine.base.UnitIterator; import net.cqs.engine.base.UnitMap; public final class WithdrawAction extends BattleAction { private final FleetEntry entry; private final int side; public WithdrawAction(FleetEntry entry, int side) { this.entry = entry; this.side = side; } protected BattleStateEnum cleanUpAfterPunish(Battle battle, long time) { Battle.logger.entering("Battle", "cleanUpAfterPunish"); // boolean attackerStart = battle.sides[Battle.ATTACKER_SIDE].size() != 0; boolean defenderStart = battle.sides[Battle.DEFENDER_SIDE].size() != 0; Battle.logger.fine(entry.fleet+" has "+entry.fleet.getTotalUnits()+" units left."); UnitMap map = new UnitMap(); entry.fleet.checkAndFixUnits(time, map); battle.battleLogger.unitsFixed(entry.fleet, map); entry.fleet.checkAndFixCargo(time); Battle.logger.fine("Removing "+entry.fleet); boolean survive = entry.fleet.containsUnits(battle.selector); if (survive) battle.battleLogger.withdrawSuccess(side, entry.fleet); else battle.battleLogger.withdrawFailure(side, entry.fleet); try { battle.sides[side].remove(time, entry, survive ? RemoveReason.WITHDRAW : RemoveReason.LOST); } catch (Throwable e) { Battle.logger.log(Level.SEVERE, "Ignored Exception", e); entry.fleet.reset(time); } boolean attackerLeft = battle.sides[Battle.ATTACKER_SIDE].size() != 0; boolean defenderLeft = battle.sides[Battle.DEFENDER_SIDE].size() != 0; if (attackerLeft && defenderLeft) return BattleStateEnum.UNDECIDED; if (attackerLeft) { if (!defenderStart) battle.battleLogger.message(BattleMessageEnum.NO_DEFENDER_WIN); return BattleStateEnum.ATTACKER; } if (defenderLeft) return BattleStateEnum.DEFENDER; return BattleStateEnum.ALLDEAD; } private void calculateDamage(BattleSide bySide, UnitMap units, float[] result) { Battle.logger.entering("WithdrawEvent", "calculateDamage"); UnitSystem us = bySide.getUnitSystem(); UnitIterator it = units.unitIterator(); while (it.hasNext()) { it.next(); for (int i = 0; i < us.groupCount(bySide.isSpace()); i++) result[i] += it.value()*bySide.modifiedAttackValue(it.key(), i); } } void distributeDamage(Battle battle, BattleSide toside, float[] damageNew) { UnitSystem us = battle.getUnitSystem(); float[] damageDone = new float[us.groupCount(battle.isSpace())]; int[] groupUnitCount = entry.activeUnits.calculateGroupCount(battle.selector); toside.distributeDamage(damageNew, damageDone, entry, groupUnitCount); } public BattleStateEnum punish(Battle battle, long time) { Battle.logger.entering("Battle", "punish"); UnitSystem us = battle.getUnitSystem(); BattleSide byside = battle.sides[1-side]; BattleSide toside = battle.sides[side]; if (byside.size() == 0) return cleanUpAfterPunish(battle, time); if (toside.size() == 0) return cleanUpAfterPunish(battle, time); // choose active units UnitMap activeUnits = new UnitMap(); float targetPower = entry.fleet.getPower(battle.selector); float maxPower = Constants.BATTLE_POWER_FACTOR*targetPower; byside.chooseUnits(activeUnits, maxPower); entry.chooseAllUnits(battle.selector); // calculate damage float[] damage = new float[us.groupCount(battle.isSpace())]; calculateDamage(byside, activeUnits, damage); battle.adjustPunishmentDamage(1-side, damage); // calculate size proportions float[] proportion = entry.activeUnits.calculateGroupProportion(battle.selector); // multiply with proportion on damaged side and random for (int i = 0; i < us.groupCount(battle.isSpace()); i++) { damage[i] *= battle.getRandom(); damage[i] *= proportion[i]; } // distribute damage distributeDamage(battle, toside, damage); return cleanUpAfterPunish(battle, time); } @Override public void execute(Battle battle, long time) { Battle.logger.entering("WithdrawEvent", "execute"); try { battle.checkValidity(); BattleStateEnum winner = punish(battle, time); Battle.logger.fine("The winner is: "+winner); switch (winner) { case UNDECIDED : battle.withdrawUndecided(time); break; case ATTACKER : battle.withdrawAttacker(time); break; case DEFENDER : battle.withdrawDefender(time); break; case ALLDEAD : battle.withdrawAllDead(time); break; default : battle.endBattle(time, BattleStateEnum.ALLKILLED); break; } } catch (Throwable e) { Battle.logger.log(Level.SEVERE, "Ignored Exception", e); battle.endBattle(time, BattleStateEnum.ALLKILLED); } } }
gpl-2.0
arthurmelo88/palmetalADP
adempierelbr/boleto/src/org/adempierelbr/process/ProcReturnCNAB.java
3104
/****************************************************************************** * Product: ADempiereLBR - ADempiere Localization Brazil * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * * with this program; if not, write to the Free Software Foundation, Inc., * * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * *****************************************************************************/ package org.adempierelbr.process; import java.util.logging.Level; import org.adempierelbr.util.AdempiereLBR; import org.adempierelbr.util.ReturnCNABUtil; import org.adempierelbr.util.TextUtil; import org.compiere.process.ProcessInfoParameter; import org.compiere.process.SvrProcess; /** * ProcReturnCNAB * * Process Return CNAB * * @author Mario Grigioni (Kenos, www.kenos.com.br) * @version $Id: ProcReturnCNAB.java, 03/12/2007 09:21:00 mgrigioni */ public class ProcReturnCNAB extends SvrProcess { /** Arquivo */ private String p_FileName = ""; /** Diretório Arquivo de Log */ private String p_FilePath = ""; /** * Prepare - e.g., get Parameters. */ protected void prepare() { ProcessInfoParameter[] para = getParameter(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else if (name.equals("FileName")) p_FileName = (String)para[i].getParameter(); else if(name.equals("File_Directory")) p_FilePath = (String)para[i].getParameter(); else log.log(Level.SEVERE, "prepare - Unknown Parameter: " + name); } } // prepare /** * Perform process. * @return Message * @throws Exception if not successful */ protected String doIt() throws Exception { log.info("ReturnCNAB Process " + "Arquivo: " + p_FileName); if (p_FileName == null || p_FileName.equals("")) throw new IllegalArgumentException("Arquivo Inválido"); String[] linhas = TextUtil.readFile(p_FileName); if (!(p_FilePath.endsWith(AdempiereLBR.getFileSeparator()))) p_FilePath += AdempiereLBR.getFileSeparator(); String RoutingNo = linhas[0].substring(76, 79); //Cód. Banco int LBR_Bank_ID = AdempiereLBR.getLBR_Bank_ID(RoutingNo, get_TrxName()); if (LBR_Bank_ID == -1) throw new IllegalArgumentException("Arquivo Inválido"); ReturnCNABUtil.returnCNAB(LBR_Bank_ID, p_FilePath, linhas, get_TrxName()); return "ReturnCNAB Process Completed " + "Arquivo: " + p_FileName; } // doIt } // ProcReturnCNAB
gpl-2.0
andrewsmm/SimpleShopApiBundle
src/SimpleShopApiBundle/Controller/CategoryController.php
1001
<?php namespace SimpleShopApiBundle\Controller; use FOS\RestBundle\Controller\FOSRestController as RestController; use FOS\RestBundle\View\View; class CategoryController extends RestController{ public $_view; function __construct(){ $this->_view = View::create(); } public function viewResult($data){ return $this->_view->setData(array_merge(['status'=>'ok'],$data)) ->setStatusCode(200); } public function getCategoriesAction() { $categories = $this->getDoctrine() ->getManager() ->getRepository('SimpleShopApiBundle:Category') ->findAll(); return $this->viewResult(['categories'=>$categories]); } public function getCategoryAction($id) { $category = $this->getDoctrine() ->getManager() ->getRepository('SimpleShopApiBundle:Category') ->findOneById($id); return $this->viewResult(['category'=>$category]); } }
gpl-2.0
MerryMage/dynarmic
tests/A32/test_arm_instructions.cpp
16062
/* This file is part of the dynarmic project. * Copyright (c) 2016 MerryMage * SPDX-License-Identifier: 0BSD */ #include <catch2/catch.hpp> #include "./testenv.h" #include "dynarmic/frontend/A32/location_descriptor.h" #include "dynarmic/interface/A32/a32.h" using namespace Dynarmic; static A32::UserConfig GetUserConfig(ArmTestEnv* testenv) { A32::UserConfig user_config; user_config.optimizations &= ~OptimizationFlag::FastDispatch; user_config.callbacks = testenv; return user_config; } TEST_CASE("arm: Opt Failure: Const folding in MostSignificantWord", "[arm][A32]") { // This was a randomized test-case that was failing. // This was due to constant folding for MostSignificantWord // failing to take into account an associated GetCarryFromOp // pseudoinstruction. ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe30ad071, // movw, sp, #41073 0xe75efd3d, // smmulr lr, sp, sp 0xa637af1e, // shadd16ge r10, r7, lr 0xf57ff01f, // clrex 0x86b98879, // sxtahhi r8, r9, r9, ror #16 0xeafffffe, // b +#0 }; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 6; jit.Run(); // If we don't trigger the GetCarryFromOp ASSERT, we're fine. } TEST_CASE("arm: Unintended modification in SetCFlag", "[arm][A32]") { // This was a randomized test-case that was failing. // // IR produced for location {12, !T, !E} was: // %0 = GetRegister r1 // %1 = SubWithCarry %0, #0x3e80000, #1 // %2 = GetCarryFromOp %1 // %3 = GetOverflowFromOp %1 // %4 = MostSignificantBit %1 // SetNFlag %4 // %6 = IsZero %1 // SetZFlag %6 // SetCFlag %2 // SetVFlag %3 // %10 = GetRegister r5 // %11 = AddWithCarry %10, #0x8a00, %2 // SetRegister r4, %11 // // The reference to %2 in instruction %11 was the issue, because instruction %8 // told the register allocator it was a Use but then modified the value. // Changing the EmitSet*Flag instruction to declare their arguments as UseScratch // solved this bug. ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe35f0cd9, // cmp pc, #55552 0xe11c0474, // tst r12, r4, ror r4 0xe1a006a7, // mov r0, r7, lsr #13 0xe35107fa, // cmp r1, #0x3E80000 0xe2a54c8a, // adc r4, r5, #35328 0xeafffffe, // b +#0 }; jit.Regs() = { 0x6973b6bb, 0x267ea626, 0x69debf49, 0x8f976895, 0x4ecd2d0d, 0xcf89b8c7, 0xb6713f85, 0x15e2aa5, 0xcd14336a, 0xafca0f3e, 0xace2efd9, 0x68fb82cd, 0x775447c0, 0xc9e1f8cd, 0xebe0e626, 0x0}; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 6; jit.Run(); REQUIRE(jit.Regs()[0] == 0x00000af1); REQUIRE(jit.Regs()[1] == 0x267ea626); REQUIRE(jit.Regs()[2] == 0x69debf49); REQUIRE(jit.Regs()[3] == 0x8f976895); REQUIRE(jit.Regs()[4] == 0xcf8a42c8); REQUIRE(jit.Regs()[5] == 0xcf89b8c7); REQUIRE(jit.Regs()[6] == 0xb6713f85); REQUIRE(jit.Regs()[7] == 0x015e2aa5); REQUIRE(jit.Regs()[8] == 0xcd14336a); REQUIRE(jit.Regs()[9] == 0xafca0f3e); REQUIRE(jit.Regs()[10] == 0xace2efd9); REQUIRE(jit.Regs()[11] == 0x68fb82cd); REQUIRE(jit.Regs()[12] == 0x775447c0); REQUIRE(jit.Regs()[13] == 0xc9e1f8cd); REQUIRE(jit.Regs()[14] == 0xebe0e626); REQUIRE(jit.Regs()[15] == 0x00000014); REQUIRE(jit.Cpsr() == 0x200001d0); } TEST_CASE("arm: shsax (Edge-case)", "[arm][A32]") { // This was a randomized test-case that was failing. // // The issue here was one of the words to be subtracted was 0x8000. // When the 2s complement was calculated by (~a + 1), it was 0x8000. ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe63dbf59, // shsax r11, sp, r9 0xeafffffe, // b +#0 }; jit.Regs() = { 0x3a3b8b18, 0x96156555, 0xffef039f, 0xafb946f2, 0x2030a69a, 0xafe09b2a, 0x896823c8, 0xabde0ded, 0x9825d6a6, 0x17498000, 0x999d2c95, 0x8b812a59, 0x209bdb58, 0x2f7fb1d4, 0x0f378107, 0x00000000}; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 2; jit.Run(); REQUIRE(jit.Regs()[0] == 0x3a3b8b18); REQUIRE(jit.Regs()[1] == 0x96156555); REQUIRE(jit.Regs()[2] == 0xffef039f); REQUIRE(jit.Regs()[3] == 0xafb946f2); REQUIRE(jit.Regs()[4] == 0x2030a69a); REQUIRE(jit.Regs()[5] == 0xafe09b2a); REQUIRE(jit.Regs()[6] == 0x896823c8); REQUIRE(jit.Regs()[7] == 0xabde0ded); REQUIRE(jit.Regs()[8] == 0x9825d6a6); REQUIRE(jit.Regs()[9] == 0x17498000); REQUIRE(jit.Regs()[10] == 0x999d2c95); REQUIRE(jit.Regs()[11] == 0x57bfe48e); REQUIRE(jit.Regs()[12] == 0x209bdb58); REQUIRE(jit.Regs()[13] == 0x2f7fb1d4); REQUIRE(jit.Regs()[14] == 0x0f378107); REQUIRE(jit.Regs()[15] == 0x00000004); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: uasx (Edge-case)", "[arm][A32]") { // UASX's Rm<31:16> == 0x0000. // An implementation that depends on addition overflow to detect // if diff >= 0 will fail this testcase. ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe6549f35, // uasx r9, r4, r5 0xeafffffe, // b +#0 }; jit.Regs()[4] = 0x8ed38f4c; jit.Regs()[5] = 0x0000261d; jit.Regs()[15] = 0x00000000; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 2; jit.Run(); REQUIRE(jit.Regs()[4] == 0x8ed38f4c); REQUIRE(jit.Regs()[5] == 0x0000261d); REQUIRE(jit.Regs()[9] == 0xb4f08f4c); REQUIRE(jit.Regs()[15] == 0x00000004); REQUIRE(jit.Cpsr() == 0x000301d0); } TEST_CASE("arm: smuad (Edge-case)", "[arm][A32]") { ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xE700F211, // smuad r0, r1, r2 0xeafffffe, // b +#0 }; jit.Regs() = { 0, // Rd 0x80008000, // Rn 0x80008000, // Rm 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 2; jit.Run(); REQUIRE(jit.Regs()[0] == 0x80000000); REQUIRE(jit.Regs()[1] == 0x80008000); REQUIRE(jit.Regs()[2] == 0x80008000); REQUIRE(jit.Cpsr() == 0x080001d0); } TEST_CASE("arm: Test InvalidateCacheRange", "[arm][A32]") { ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe3a00005, // mov r0, #5 0xe3a0100D, // mov r1, #13 0xe0812000, // add r2, r1, r0 0xeafffffe, // b +#0 (infinite loop) }; jit.Regs() = {}; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 4; jit.Run(); REQUIRE(jit.Regs()[0] == 5); REQUIRE(jit.Regs()[1] == 13); REQUIRE(jit.Regs()[2] == 18); REQUIRE(jit.Regs()[15] == 0x0000000c); REQUIRE(jit.Cpsr() == 0x000001d0); // Change the code test_env.code_mem[1] = 0xe3a01007; // mov r1, #7 jit.InvalidateCacheRange(/*start_memory_location = */ 4, /* length_in_bytes = */ 4); // Reset position of PC jit.Regs()[15] = 0; test_env.ticks_left = 4; jit.Run(); REQUIRE(jit.Regs()[0] == 5); REQUIRE(jit.Regs()[1] == 7); REQUIRE(jit.Regs()[2] == 12); REQUIRE(jit.Regs()[15] == 0x0000000c); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: Step blx", "[arm]") { ArmTestEnv test_env; A32::UserConfig config = GetUserConfig(&test_env); config.optimizations |= OptimizationFlag::FastDispatch; Dynarmic::A32::Jit jit{config}; test_env.code_mem = { 0xe12fff30, // blx r0 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xeafffffe, // b +#0 (infinite loop) }; jit.Regs()[0] = 8; jit.Regs()[15] = 0; // PC = 0 jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 10; jit.Step(); REQUIRE(jit.Regs()[0] == 8); REQUIRE(jit.Regs()[14] == 4); REQUIRE(jit.Regs()[15] == 8); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: Step bx", "[arm]") { ArmTestEnv test_env; A32::UserConfig config = GetUserConfig(&test_env); config.optimizations |= OptimizationFlag::FastDispatch; Dynarmic::A32::Jit jit{config}; test_env.code_mem = { 0xe12fff10, // bx r0 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xeafffffe, // b +#0 (infinite loop) }; jit.Regs()[0] = 8; jit.Regs()[15] = 0; // PC = 0 jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 10; jit.Step(); REQUIRE(jit.Regs()[0] == 8); REQUIRE(jit.Regs()[15] == 8); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: Test stepping", "[arm]") { ArmTestEnv test_env; Dynarmic::A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xeafffffe, // b +#0 (infinite loop) }; jit.Regs()[0] = 8; jit.Regs()[15] = 0; // PC = 0 jit.SetCpsr(0x000001d0); // User-mode for (size_t i = 0; i < 5; ++i) { test_env.ticks_left = 10; jit.Step(); REQUIRE(jit.Regs()[15] == (i + 1) * 4); REQUIRE(jit.Cpsr() == 0x000001d0); } test_env.ticks_left = 20; jit.Run(); REQUIRE(jit.Regs()[15] == 80); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: Test stepping 2", "[arm]") { ArmTestEnv test_env; Dynarmic::A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe12fff10, // bx r0 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xeafffffe, // b +#0 (infinite loop) }; jit.Regs()[0] = 4; jit.Regs()[15] = 0; // PC = 0 jit.SetCpsr(0x000001d0); // User-mode for (size_t i = 0; i < 5; ++i) { test_env.ticks_left = 10; jit.Step(); REQUIRE(jit.Regs()[15] == (i + 1) * 4); REQUIRE(jit.Cpsr() == 0x000001d0); } test_env.ticks_left = 20; jit.Run(); REQUIRE(jit.Regs()[15] == 80); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: Test stepping 3", "[arm]") { ArmTestEnv test_env; Dynarmic::A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xe12fff10, // bx r0 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xe320f000, // nop 0xeafffffe, // b +#0 (infinite loop) }; jit.Regs()[0] = 4; jit.Regs()[15] = 0; // PC = 0 jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 10; jit.Step(); REQUIRE(jit.Regs()[15] == 4); REQUIRE(jit.Cpsr() == 0x000001d0); test_env.ticks_left = 20; jit.Run(); REQUIRE(jit.Regs()[15] == 20); REQUIRE(jit.Cpsr() == 0x000001d0); } TEST_CASE("arm: PackedAbsDiffSumS8", "[arm][A32]") { // This was a randomized test-case that was failing. // In circumstances there were cases when the upper 32 bits of an argument to psadbw were not zero. ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0x87414354, // smlsldhi r4, r1, r4, r3 0xe7886412, // usad8a r8, r2, r4, r6 0xeafffffe, // b +#0 }; jit.Regs() = { 0xea85297c, 0x417ad918, 0x64f8b70b, 0xcca0373e, 0xbc722361, 0xc528c69e, 0xca926de8, 0xd665d210, 0xb5650555, 0x4a24b25b, 0xaed44144, 0xe87230b2, 0x98e391de, 0x126efc0c, 0xe591fd11, 0x00000000, }; jit.SetCpsr(0xb0000010); test_env.ticks_left = 3; jit.Run(); REQUIRE(jit.Regs()[0] == 0xea85297c); REQUIRE(jit.Regs()[1] == 0x417ad918); REQUIRE(jit.Regs()[2] == 0x64f8b70b); REQUIRE(jit.Regs()[3] == 0xcca0373e); REQUIRE(jit.Regs()[4] == 0xb685ec9f); REQUIRE(jit.Regs()[5] == 0xc528c69e); REQUIRE(jit.Regs()[6] == 0xca926de8); REQUIRE(jit.Regs()[7] == 0xd665d210); REQUIRE(jit.Regs()[8] == 0xca926f76); REQUIRE(jit.Regs()[9] == 0x4a24b25b); REQUIRE(jit.Regs()[10] == 0xaed44144); REQUIRE(jit.Regs()[11] == 0xe87230b2); REQUIRE(jit.Regs()[12] == 0x98e391de); REQUIRE(jit.Regs()[13] == 0x126efc0c); REQUIRE(jit.Regs()[14] == 0xe591fd11); REQUIRE(jit.Regs()[15] == 0x00000008); REQUIRE(jit.Cpsr() == 0xb0000010); } TEST_CASE("arm: vclt.f32 with zero", "[arm][A32]") { ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xf3b93628, // vclt.f32 d3, d24, #0 0xeafffffe, // b +#0 }; jit.ExtRegs()[48] = 0x3a87d9f1; jit.ExtRegs()[49] = 0x80796dc0; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 2; jit.Run(); REQUIRE(jit.ExtRegs()[6] == 0x00000000); REQUIRE(jit.ExtRegs()[7] == 0x00000000); } TEST_CASE("arm: vcvt.s16.f64", "[arm][A32]") { ArmTestEnv test_env; A32::Jit jit{GetUserConfig(&test_env)}; test_env.code_mem = { 0xeebe8b45, // vcvt.s16.f64 d8, d8, #6 0xeafffffe, // b +#0 }; jit.ExtRegs()[16] = 0x9a7110b0; jit.ExtRegs()[17] = 0xcd78f4e7; jit.SetCpsr(0x000001d0); // User-mode test_env.ticks_left = 2; jit.Run(); REQUIRE(jit.ExtRegs()[16] == 0xffff8000); REQUIRE(jit.ExtRegs()[17] == 0xffffffff); } TEST_CASE("arm: Memory access (fastmem)", "[arm][A32]") { constexpr size_t address_width = 12; constexpr size_t memory_size = 1ull << address_width; // 4K constexpr size_t page_size = 4 * 1024; constexpr size_t buffer_size = 2 * page_size; char buffer[buffer_size]; void* buffer_ptr = reinterpret_cast<void*>(buffer); size_t buffer_size_nconst = buffer_size; char* backing_memory = reinterpret_cast<char*>(std::align(page_size, memory_size, buffer_ptr, buffer_size_nconst)); A32FastmemTestEnv env{backing_memory}; Dynarmic::A32::UserConfig config{&env}; config.fastmem_pointer = backing_memory; config.recompile_on_fastmem_failure = false; config.processor_id = 0; Dynarmic::A32::Jit jit{config}; memset(backing_memory, 0, memory_size); memcpy(backing_memory + 0x100, "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", 57); env.MemoryWrite32(0, 0xE5904000); // LDR R4, [R0] env.MemoryWrite32(4, 0xE5814000); // STR R4, [R1] env.MemoryWrite32(8, 0xEAFFFFFE); // B . jit.Regs()[0] = 0x100; jit.Regs()[1] = 0x1F0; jit.Regs()[15] = 0; // PC = 0 jit.SetCpsr(0x000001d0); // User-mode env.ticks_left = 3; jit.Run(); REQUIRE(strncmp(backing_memory + 0x100, backing_memory + 0x1F0, 4) == 0); }
gpl-2.0
haidarafif0809/qwooxcqmkozzxce
proses_tbs_edit_retur_pembelian.php
10810
<?php // memasukan file yang ada pada db.php include 'sanitasi.php'; include 'db.php'; $kode_barang = stringdoang($_POST['kode_barang']); $harga = angkadoang($_POST['harga']); $jumlah_retur = angkadoang($_POST['jumlah_retur']); $satuan_produk = stringdoang($_POST['satuan_produk']); $satuan_beli = stringdoang($_POST['satuan_beli']); $pajak = angkadoang($_POST['tax1']); $potongan = stringdoang($_POST['potongan1']); $a = $harga * $jumlah_retur; if(strpos($potongan, "%") !== false) { $potongan_jadi = $a * $potongan / 100; $potongan_tampil = $potongan_jadi; } else { $potongan_jadi = $potongan; $potongan_tampil = $potongan; } $satu = 1; $x = $a - $potongan_tampil; $hasil_tax = $satu + ($pajak / 100); $hasil_tax2 = $x / $hasil_tax; $tax_persen1 = $x - $hasil_tax2; $tax_persen = round($tax_persen1); $subtotal = $harga * $jumlah_retur - $potongan_jadi; $no_faktur_retur = stringdoang($_POST['no_faktur_retur']); $no_faktur_pembelian = stringdoang($_POST['no_faktur_pembelian']); $cek2 = $db->query("SELECT * FROM detail_pembelian WHERE kode_barang = '$kode_barang' AND no_faktur = '$no_faktur_pembelian'"); $data= mysqli_fetch_array($cek2); $konversi = $db->query("SELECT $data[jumlah_barang] / konversi AS jumlah_beli FROM satuan_konversi WHERE kode_produk = '$kode_barang' AND id_satuan = '$data[satuan]' "); $num_rows = mysqli_num_rows($konversi); $data_konversi = mysqli_fetch_array($konversi); if ($num_rows > 0 ){ $jumlah_beli = $data_konversi['jumlah_beli']; } else{ $jumlah_beli = $data['jumlah_barang']; } $perintah = $db->prepare("INSERT INTO tbs_retur_pembelian (no_faktur_retur,no_faktur_pembelian,kode_barang,nama_barang,jumlah_beli,jumlah_retur,harga,subtotal,potongan,tax,satuan,satuan_beli) VALUES (?,?,?,?,'$jumlah_beli',?,'$harga',?,?,?,?,?)"); $perintah->bind_param("ssssiiiiss", $no_faktur_retur, $no_faktur_pembelian, $kode_barang, $nama_barang, $jumlah_retur, $subtotal, $potongan_tampil, $tax_persen,$satuan_produk,$satuan_beli); $no_faktur_retur = stringdoang($_POST['no_faktur_retur']); $no_faktur_pembelian = stringdoang($_POST['no_faktur_pembelian']); $nama_barang = stringdoang($_POST['nama_barang']); $kode_barang = stringdoang($_POST['kode_barang']); $perintah->execute(); if (!$perintah) { die('Query Error : '.$db->errno. ' - '.$db->error); } else { } ?> <?php //untuk menampilkan semua data yang ada pada tabel tbs pembelian dalam DB $perintah = $db->query("SELECT tp.id,tp.no_faktur_pembelian,tp.kode_barang,tp.nama_barang,tp.jumlah_beli,tp.jumlah_retur,tp.satuan,tp.harga,tp.potongan,tp.tax,tp.subtotal, s.nama AS satuan_retur, ss.nama AS satuan_beli FROM tbs_retur_pembelian tp INNER JOIN satuan s ON tp.satuan = s.id INNER JOIN satuan ss ON tp.satuan_beli = ss.id WHERE tp.no_faktur_retur = '$no_faktur_retur' ORDER BY id DESC LIMIT 1"); //menyimpan data sementara yang ada pada $perintah $data1 = mysqli_fetch_array($perintah); // menampilkan data echo "<tr class='tr-id-".$data1['id']."'> <td>". $data1['no_faktur_pembelian'] ."</td> <td>". $data1['kode_barang'] ."</td> <td>". $data1['nama_barang'] ."</td> <td>". rp($data1['jumlah_beli']) ." ".$data1['satuan_beli']."</td> <td class='edit-jumlah' data-id='".$data1['id']."' data-faktur='".$data1['no_faktur_pembelian']."' data-kode='".$data1['kode_barang']."'> <span id='text-jumlah-".$data1['id']."'> ".$data1['jumlah_retur']." </span> <input type='hidden' id='input-jumlah-".$data1['id']."' value='".$data1['jumlah_retur']."' class='input_jumlah' data-id='".$data1['id']."' autofocus='' data-faktur='".$data1['no_faktur_pembelian']."' data-kode='".$data1['kode_barang']."' data-harga='".$data1['harga']."' data-satuan='".$data1['satuan']."' onkeydown='return numbersonly(this, event);'> </td> <td>". $data1['satuan_retur']."</td> <td>". rp($data1['harga']) ."</td> <td><span id='text-potongan-".$data1['id']."'>". rp($data1['potongan']) ."</span></td> <td><span id='text-tax-".$data1['id']."'>". rp($data1['tax']) ."</span></td> <td><span id='text-subtotal-".$data1['id']."'>". rp($data1['subtotal']) ."</span></td> <td><button class='btn btn-danger btn-hapus-tbs' id='btn-hapus-".$data1['id']."' data-id='". $data1['id'] ."' data-kode-barang='". $data1['kode_barang'] ."' data-faktur='". $data1['no_faktur_pembelian'] ."' data-subtotal='". $data1['subtotal'] ."'> <span class='glyphicon glyphicon-trash'> </span> Hapus </button> </td> </tr>"; //Untuk Memutuskan Koneksi Ke Database mysqli_close($db); ?> <script type="text/javascript"> $(".edit-jumlah").dblclick(function(){ var id = $(this).attr("data-id"); $("#text-jumlah-"+id+"").hide(); $("#input-jumlah-"+id+"").attr("type", "text"); }); $(".input_jumlah").blur(function(){ var id = $(this).attr("data-id"); var jumlah_baru = $(this).val(); if (jumlah_baru == '') { jumlah_baru = 0; } var kode_barang = $(this).attr("data-kode"); var no_faktur = $(this).attr("data-faktur"); var harga = $(this).attr("data-harga"); var jumlah_retur = $("#text-jumlah-"+id+"").text(); var no_faktur_retur = $("#nomorfaktur").val(); var satuan = $(this).attr("data-satuan"); var subtotal_lama = bersihPemisah(bersihPemisah(bersihPemisah(bersihPemisah($("#text-subtotal-"+id+"").text())))); var potongan = bersihPemisah(bersihPemisah(bersihPemisah(bersihPemisah($("#text-potongan-"+id+"").text())))); var sub_total = parseInt(harga,10) * parseInt(jumlah_baru,10); var total_tbs = parseInt(harga,10) * parseInt(jumlah_retur,10); // rupiah to persen var potongan_tbs = parseInt(Math.round(potongan, 10)) / parseInt(total_tbs) * 100; //rupiah to persen var jumlah_potongan = parseInt(Math.round(potongan_tbs)) * parseInt(sub_total) / 100; var tax = bersihPemisah(bersihPemisah(bersihPemisah(bersihPemisah($("#text-tax-"+id+"").text())))); var subtotal = parseInt(harga,10) * parseInt(jumlah_baru,10) - parseInt(jumlah_potongan,10); var subtotal_penjualan = bersihPemisah(bersihPemisah(bersihPemisah(bersihPemisah($("#total_retur_pembelian").val())))); subtotal_penjualan = parseInt(subtotal_penjualan,10) - parseInt(subtotal_lama,10) + parseInt(subtotal,10); var tax_tbs = tax / subtotal_lama * 100; var jumlah_tax = tax_tbs * subtotal / 100; if (jumlah_baru == 0) { alert ("Jumlah Retur Tidak Boleh 0!"); $("#input-jumlah-"+id+"").val(jumlah_retur); $("#text-jumlah-"+id+"").text(jumlah_retur); $("#text-jumlah-"+id+"").show(); $("#input-jumlah-"+id+"").attr("type", "hidden"); } else{ $.post("cek_total_tbs_edit_retur_pembelian.php",{kode_barang:kode_barang, jumlah_baru:jumlah_baru, no_faktur:no_faktur,no_faktur_retur:no_faktur_retur,satuan:satuan},function(data){ if (data < 0) { alert ("Jumlah Yang Di Masukan Melebihi Stok !"); $("#input-jumlah-"+id+"").val(jumlah_retur); $("#text-jumlah-"+id+"").show(); $("#input-jumlah-"+id+"").attr("type", "hidden"); } else{ $.post("update_pesanan_barang_retur_pembelian.php",{harga:harga,jumlah_retur:jumlah_retur,jumlah_tax:Math.round(jumlah_tax),jumlah_potongan:jumlah_potongan,id:id,jumlah_baru:jumlah_baru,kode_barang:kode_barang,subtotal:subtotal},function(info){ $("#text-jumlah-"+id+"").show(); $("#text-jumlah-"+id+"").text(jumlah_baru); $("#text-subtotal-"+id+"").text(tandaPemisahTitik(subtotal)); $("#btn-hapus-"+id).attr("data-subtotal", subtotal); $("#input-jumlah-"+id+"").attr("type", "hidden"); $("#text-tax-"+id+"").text(Math.round(jumlah_tax)); $("#text-potongan-"+id+"").text(Math.round(jumlah_potongan)); $("#total_retur_pembelian").val(tandaPemisahTitik(subtotal_penjualan)); $("#total_retur_pembelian1").val(tandaPemisahTitik(subtotal_penjualan)); }); } }); } $("#kode_barang").focus(); }); </script>
gpl-2.0
Rogach/SimplyMindMap
src/org/rogach/simplymindmap/controller/actions/instance/TextNodeAction.java
302
package org.rogach.simplymindmap.controller.actions.instance; /* TextNodeAction...*/ public class TextNodeAction extends NodeAction { protected String text; public String getText() { return this.text; } public void setText(String value){ this.text = value; } } /* TextNodeAction*/
gpl-2.0
wdantas/ImobControl
admin/application/models/caracteristicas_imovel/mdlrecursosproximos.php
488
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); class MdlRecursosProximos extends CI_Model{ public function __construct() { parent::__construct(); } public function setRecursosProximos($dataRecursos){ if(!empty($dataRecursos) || !$this->verificaExistencia->duplicado('recursos_proximos','slug',$dataRecursos['slug'])): $this->db->insert('recursos_proximos',$dataRecursos); else: return 0; endif; } }
gpl-2.0
joomla-projects/media-manager-improvement
administrator/components/com_users/Model/LevelsModel.php
5749
<?php /** * @package Joomla.Administrator * @subpackage com_users * * @copyright Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\Component\Users\Administrator\Model; defined('_JEXEC') or die; use Joomla\CMS\Component\ComponentHelper; use Joomla\CMS\MVC\Model\ListModel; use Joomla\CMS\MVC\Factory\MVCFactoryInterface; use Joomla\CMS\Table\Table; use Joomla\CMS\Factory; use Joomla\CMS\Language\Text; use Joomla\Database\DatabaseQuery; /** * Methods supporting a list of user access level records. * * @since 1.6 */ class LevelsModel extends ListModel { /** * Override parent constructor. * * @param array $config An optional associative array of configuration settings. * @param MVCFactoryInterface $factory The factory. * * @see \Joomla\CMS\MVC\Model\BaseDatabaseModel * @since 3.2 */ public function __construct($config = array(), MVCFactoryInterface $factory = null) { if (empty($config['filter_fields'])) { $config['filter_fields'] = array( 'id', 'a.id', 'title', 'a.title', 'ordering', 'a.ordering', ); } parent::__construct($config, $factory); } /** * Method to auto-populate the model state. * * Note. Calling getState in this method will result in recursion. * * @param string $ordering An optional ordering field. * @param string $direction An optional direction (asc|desc). * * @return void * * @since 1.6 */ protected function populateState($ordering = 'a.ordering', $direction = 'asc') { // Load the parameters. $params = ComponentHelper::getParams('com_users'); $this->setState('params', $params); // List state information. parent::populateState($ordering, $direction); } /** * Method to get a store id based on model configuration state. * * This is necessary because the model is used by the component and * different modules that might need different sets of data or different * ordering requirements. * * @param string $id A prefix for the store id. * * @return string A store id. */ protected function getStoreId($id = '') { // Compile the store id. $id .= ':' . $this->getState('filter.search'); return parent::getStoreId($id); } /** * Build an SQL query to load the list data. * * @return DatabaseQuery */ protected function getListQuery() { // Create a new query object. $db = $this->getDbo(); $query = $db->getQuery(true); // Select the required fields from the table. $query->select( $this->getState( 'list.select', 'a.*' ) ); $query->from($db->quoteName('#__viewlevels') . ' AS a'); // Add the level in the tree. $query->group('a.id, a.title, a.ordering, a.rules'); // Filter the items over the search string if set. $search = $this->getState('filter.search'); if (!empty($search)) { if (stripos($search, 'id:') === 0) { $query->where('a.id = ' . (int) substr($search, 3)); } else { $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%')); $query->where('a.title LIKE ' . $search); } } $query->group('a.id'); // Add the list ordering clause. $query->order($db->escape($this->getState('list.ordering', 'a.ordering')) . ' ' . $db->escape($this->getState('list.direction', 'ASC'))); return $query; } /** * Method to adjust the ordering of a row. * * @param integer $pk The ID of the primary key to move. * @param integer $direction Increment, usually +1 or -1 * * @return boolean False on failure or error, true otherwise. */ public function reorder($pk, $direction = 0) { // Sanitize the id and adjustment. $pk = (!empty($pk)) ? $pk : (int) $this->getState('level.id'); $user = Factory::getUser(); // Get an instance of the record's table. $table = Table::getInstance('viewlevel', 'Joomla\\CMS\Table\\'); // Load the row. if (!$table->load($pk)) { $this->setError($table->getError()); return false; } // Access checks. $allow = $user->authorise('core.edit.state', 'com_users'); if (!$allow) { $this->setError(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED')); return false; } // Move the row. // TODO: Where clause to restrict category. $table->move($pk); return true; } /** * Saves the manually set order of records. * * @param array $pks An array of primary key ids. * @param integer $order Order position * * @return boolean Boolean true on success, boolean false * * @throws \Exception */ public function saveorder($pks, $order) { $table = Table::getInstance('viewlevel', 'Joomla\\CMS\Table\\'); $user = Factory::getUser(); $conditions = array(); if (empty($pks)) { Factory::getApplication()->enqueueMessage(Text::_('COM_USERS_ERROR_LEVELS_NOLEVELS_SELECTED'), 'error'); return false; } // Update ordering values foreach ($pks as $i => $pk) { $table->load((int) $pk); // Access checks. $allow = $user->authorise('core.edit.state', 'com_users'); if (!$allow) { // Prune items that you can't change. unset($pks[$i]); Factory::getApplication()->enqueueMessage(Text::_('JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED'), 'error'); } elseif ($table->ordering != $order[$i]) { $table->ordering = $order[$i]; if (!$table->store()) { $this->setError($table->getError()); return false; } } } // Execute reorder for each category. foreach ($conditions as $cond) { $table->load($cond[0]); $table->reorder($cond[1]); } return true; } }
gpl-2.0
XoopsModules25x/weblog
class/class.weblog.php
11628
<?php /* * $Id: class.weblog.php 11979 2013-08-25 20:45:24Z beckmi $ * Copyright (c) 2003 by Hiro SAKAI (http://wellwine.zive.net/) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * You may not change or alter any portion of this comment or credits * of supporting developers from this source code or any supporting * source code which is considered copyrighted (c) material of the * original comment or credit authors. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ include_once(sprintf('%s/modules/%s/class/class.weblogtree.php', XOOPS_ROOT_PATH, $xoopsModule->dirname())); class Weblog { var $handler; function Weblog() { $this->handler =& xoops_getmodulehandler('entry'); } function &getInstance() { static $instance; if (!isset($instance)) { $instance = new Weblog(); } return $instance; } function &newInstance() { return $this->handler->create(); } function saveEntry(&$entry) { return $this->handler->insert($entry); } function removeEntry($blog_id) { $entry =& $this->handler->create(); $entry->setVar('blog_id', intval($blog_id)); return $this->handler->delete($entry); } function isOwner($blog_id, $user_id) { $criteria = new criteriaCompo(new criteria('user_id', $user_id)); $criteria->add(new criteria('blog_id', $blog_id)); $count = $this->handler->getCount($criteria); if ($count == 1) { return true; } return false; } function getCountByUser($currentuid, $user_id=0) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); if ($user_id > 0) { $criteria = new criteriaCompo($criteria); $criteria->add(new criteria('user_id', $user_id)); } return $this->handler->getCount($criteria); } function getCountByCategory($currentuid, $cat_id, $user_id=0) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); if ($cat_id>0) { $criteria->add(new criteria('cat_id', $cat_id)); } if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } return $this->handler->getCount($criteria); } function getCountByDate($currentuid, $cat_id, $user_id=0, $date, $useroffset) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); if ($date>0) { $date_num = strlen(strval($date)) ; $criteria->add( new criteria(sprintf('left(from_unixtime(created+%d)+0,%d)',$useroffset*3600 , $date_num) , $date) ) ; } if ($cat_id>0) { $criteria->add(new criteria('cat_id', $cat_id)); } if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } return $this->handler->getCount($criteria); } function getEntries($currentuid, $user_id=0, $start=0, $perPage=0, $order='DESC', $useroffset=0) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); if ($user_id > 0) { $criteria = new criteriaCompo($criteria); $criteria->add(new criteria('user_id', $user_id)); } $criteria->setSort('created'); $criteria->setOrder($order); if ($start > 0) { $criteria->setStart($start); } if ($perPage > 0 ) { $criteria->setLimit($perPage); } $result = $this->handler->getObjects($criteria, false, 'details', $useroffset); return $result; } function getEntriesByCreated($currentuid, $from, $to, $user_id=0, $start=0, $perPage=0, $order='DESC') { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); $criteria->add(new criteria('created', $from, '>')); $criteria->add(new criteria('created', $to, '<')); if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } $criteria->setSort('created'); $criteria->setOrder($order); if ($start > 0) { $criteria->setStart($start); } if ($perPage > 0 ) { $criteria->setLimit($perPage); } $result = $this->handler->getObjects($criteria); return $result; } function getEntriesByCategory($currentuid, $cat_id=0, $user_id=0, $start=0, $perPage=0, $order='DESC', $useroffset=0) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); if ($cat_id>0) { $criteria->add(new criteria('cat_id', $cat_id)); } if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } $criteria->setSort('created'); $criteria->setOrder($order); if ($start > 0) { $criteria->setStart($start); } if ($perPage > 0 ) { $criteria->setLimit($perPage); } $result = $this->handler->getObjects($criteria, false , 'details', $useroffset); return $result; } function getEntry($currentuid, $blog_id=0, $user_id=0, $useroffset=0) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); $criteria->add(new criteria('blog_id', $blog_id)); if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } $result = $this->handler->getObjects($criteria, true, 'details', $useroffset); if (isset($result[$blog_id])) { return $result[$blog_id]; } else { return $result; } } function incrementReads($blog_id) { return $this->handler->incrementReads($blog_id); } function updateComments($blog_id, $total_num) { return $this->handler->updateComments($blog_id, $total_num); } function getPrevNext($blog_id , $created , $currentuid=0 , $isAdmin=0 , $cat_id=0 , $user_id=0 ){ if( empty($isAdmin) ){ $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); }else{ $criteria = NULL ; } $criteria = new criteriaCompo($criteria); if( $cat_id > 0){ $criteria->add(new criteria('cat_id', $cat_id)); } if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } return $this->handler->getPrevNextBlog_id($blog_id , $created , $criteria) ; } /** * get count of categories specified in array * @author hodaka <hodaka@hodaka.net> */ function getCountByCategoryArray($currentuid, $cid_array=array(), $user_id=0) { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); $criteria->add(new Criteria('cat_id', "(".implode(',', $cid_array).")", 'IN')); if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } return $this->handler->getCount($criteria); } function getEntriesForArchives($currentuid , $blogger_id , $date , $cat_id , $start=0 , $perPage=0 , $order='DESC' , $useroffset=0 ){ $date = intval($date) ; // basic $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); // by user_id if( $blogger_id > 0 ) $criteria->add( new criteria('user_id', $blogger_id) ) ; // by category if( $cat_id > 0 ) $criteria->add( new criteria('cat_id', $cat_id) ) ; // by date if( $date > 0 ){ $date_num = strlen(strval($date)) ; $criteria->add( new criteria(sprintf('left(from_unixtime(created+%d)+0,%d)',$useroffset*3600 , $date_num) , $date) ) ; } // order , start , Limit $criteria->setSort('created'); $criteria->setOrder($order); if ($start > 0) { $criteria->setStart($start); } if ($perPage > 0 ) { $criteria->setLimit($perPage); } $result = $this->handler->getObjects($criteria, false, 'details' , $useroffset); return $result; } /** * get entries of categories specified in array sorted order by created for archive.php * @author hodaka <hodaka@hodaka.org> */ function getLatestEntriesByCategoryArray($currentuid, $cid_array=array(), $user_id=0, $start=0, $perPage=0, $order='DESC') { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); $criteria->add(new Criteria('cat_id', "(".implode(',', $cid_array).")", 'IN')); if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } $criteria->setSort('created'); $criteria->setOrder($order); if ($start > 0) { $criteria->setStart($start); } if ($perPage > 0 ) { $criteria->setLimit($perPage); } $result = $this->handler->getObjects($criteria); return $result; } /** * get entries of categories specified in array sorted order by cat_id, created for index.php * @author hodaka <hodaka@hodaka.org> */ function getEntriesByCategoryArray($currentuid, $cid_array=array(), $user_id=0, $start=0, $perPage=0, $order='DESC') { $criteria = new criteriaCompo(new criteria('user_id', $currentuid)); $criteria->add(new criteria('private', 'N'), 'OR'); $criteria = new criteriaCompo($criteria); $criteria->add(new Criteria('cat_id', "(".implode(',', $cid_array).")", 'IN')); if ($user_id > 0) { $criteria->add(new criteria('user_id', $user_id)); } $criteria->setSort('cat_id, created'); $criteria->setOrder($order); if ($start > 0) { $criteria->setStart($start); } if ($perPage > 0 ) { $criteria->setLimit($perPage); } $result = $this->handler->getObjects($criteria); return $result; } }
gpl-2.0
iarwen/cdy
src/main/java/com/cdy/dao/UserDao.java
1450
package com.cdy.dao; import com.cdy.domain.User; import org.springframework.stereotype.Repository; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * User对象Dao */ @Repository public class UserDao extends BaseDao<User> { public void remove(String id) { User u = this.findById(Integer.parseInt(id)); if (u == null) return; this.remove(u); } /** * 根据用户名查询User对象 * * @param userName 用户名 * @return 对应userName的User对象,如果不存在,返回null。 */ public User getUserByUserName(String userName) { List<User> users = this.find( "from User u where u.userName = :userName" , "userName", userName); if (users.size() == 0) { return null; } else { return users.get(0); } } /** * 根据用户名为模糊查询条件,查询出所有前缀匹配的User对象 * * @param userName 用户名查询条件 * @return 用户名模糊匹配的所有User对象 */ public List<User> queryUserByUserName(String userName) { List<String> orders = new ArrayList<>(); orders.add("id"); Map<String, Object> params = new HashMap<>(); params.put("userName", "%" + userName + "%"); return this.find("from User u where u.userName like :userName", params, orders); } }
gpl-2.0
ulisesolivenza/rx
backend/sessionService/src/main/java/com/backend/app/services/SessionService.java
618
package com.backend.app.services; import com.backend.app.dto.AuthorizationContext; import com.backend.app.dto.LoginContext; import com.backend.app.model.Session; import com.backend.app.model.SessionHealthCheck; import rx.Observable; import java.util.Optional; import java.util.UUID; /** * Created by ulises on 10/10/15. */ public interface SessionService { Observable<Optional<Session>> login(LoginContext principal); Observable<Optional<Session>> logout(UUID sessionId); Observable<Boolean> authorize(AuthorizationContext authorizationContext); Observable<SessionHealthCheck> healtcheck(); }
gpl-2.0
Maurogik/SCEngine
sources/SCETextures.cpp
13471
/******PROJECT:Sand Castle Engine******/ /**************************************/ /*********AUTHOR:Gwenn AUBERT**********/ /*********FILE:SCETextures.cpp*********/ /**************************************/ #include "../headers/SCETextures.hpp" #include "../headers/SCETools.hpp" #include "../headers/SCEMetadataParser.hpp" #include "../headers/SCEInternal.hpp" //disable unneeded image formats #define STBI_NO_TGA #define STBI_NO_GIF #define STBI_NO_PNM #define STBI_NO_PIC #define STBI_NO_HDR #define STBI_NO_PSD #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include <map> #include <vector> #include <algorithm> #include <iostream> #include <fstream> using namespace std; #define DEBUG_TEXTURE_NAME "Textures/Color_Debug.jpg" #define FORMAT_STR "Format" #define DDS_STR "DDS" #define UNCOMPRESSED_STR "UNCOMPRESSED" #define MIPMAPS_STR "Mipmaps" #define WRAPPING_STR "Wrapping" #define CLAMP_STR "Clamp" #define REPEAT_STR "Repeat" namespace SCE { namespace TextureUtils { //Only here to allow for automatic creation/destruction of data struct TexturesData { TexturesData() : loadedTextures(), createdTextures() { //some setup of stb_image needed stbi_set_flip_vertically_on_load(1); } ~TexturesData() { Internal::Log("Cleaning up texture system, will delete loaded textures"); auto beginIt = begin(loadedTextures); auto endIt = end(loadedTextures); for(auto iterator = beginIt; iterator != endIt; iterator++) { Internal::Log("Deleting texture : " + iterator->first); glDeleteTextures(1, &(iterator->second)); } for(GLuint texId : createdTextures) { glDeleteTextures(1, &texId); } } std::map<std::string, GLuint> loadedTextures; std::vector<GLuint> createdTextures; }; /* File/Compilation Unit scope variable */ TexturesData texturesData; GLuint debugTexture = GL_INVALID_INDEX; /* Utiliatry loading/parsing funtions */ SCETextureFormat formatFromString(const string &formatString) { SCETextureFormat res = DDS_FORMAT; if(Tools::ToLowerCase(formatString) == Tools::ToLowerCase(DDS_STR)){ //res == DDS_FORMAT; } else if(Tools::ToLowerCase(formatString) == Tools::ToLowerCase(UNCOMPRESSED_STR)){ res = UNCOMPRESSED_FORMAT; } else { Debug::RaiseError("Unknow texture format : " + formatString); } return res; } SCETextureWrap wrapModeFromString(const string &wrapString) { SCETextureWrap res = CLAMP_WRAP; if(Tools::ToLowerCase(wrapString) == Tools::ToLowerCase(CLAMP_STR)){ //res == CLAMP_WRAP; } else if(Tools::ToLowerCase(wrapString) == Tools::ToLowerCase(REPEAT_STR)){ res = REPEAT_WRAP; } else { Debug::RaiseError("Unknow texture wrap mode: " + wrapString); } return res; } GLuint createTextureWithData(uint width, uint height, GLint internalGPUFormat, GLenum textureFormat, GLenum componentType, SCETextureWrap wrapMode, bool mipmapsOn, void* textureData) { GLuint textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); glTexImage2D(GL_TEXTURE_2D, 0, internalGPUFormat, width, height, 0, textureFormat, componentType, textureData); if(mipmapsOn) { glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } if(wrapMode == SCETextureWrap::CLAMP_WRAP) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } return textureID; } //loads texture from disk and create and OpenGL texture with it GLuint loadTexture(const string &filename, SCETextureFormat compressionFormat, SCETextureWrap wrapMode, bool mipmapsOn) { string fullTexturePath = RESSOURCE_PATH + filename; if(!ifstream(fullTexturePath.c_str())) { fullTexturePath = ENGINE_RESSOURCE_PATH + filename; } Internal::Log(std::string("TODO : Compression format not yet used : ") + std::to_string(compressionFormat)); int width, height, nbComponent; unsigned char* textureData = stbi_load(fullTexturePath.c_str(), &width, &height, &nbComponent, //will store the actual number of component read 0); // force to fill # number of component if not zero if(!textureData) { Debug::RaiseError("Coul not load image at : " + fullTexturePath); } GLuint textureID = GL_INVALID_INDEX; GLint internalGPUFormat; GLenum textureFormat, type; type = GL_UNSIGNED_BYTE; switch(nbComponent) { case 0 : Debug::RaiseError(std::string("texture contains no component !") + std::to_string(nbComponent)); break; case 1 : internalGPUFormat = GL_R8; textureFormat = GL_R; break; case 2 : internalGPUFormat = GL_RG16; textureFormat = GL_RG; break; case 3 : internalGPUFormat = GL_RGB32F; textureFormat = GL_RGB; break; case 4 : internalGPUFormat = GL_RGBA32F; textureFormat = GL_RGBA; break; default : Debug::RaiseError(std::string("Unexpected number of texture component : ") + std::to_string(nbComponent)); break; } if(textureData && nbComponent > 0 && nbComponent <= 4) { textureID = createTextureWithData(width, height, internalGPUFormat, textureFormat, type, wrapMode, mipmapsOn, textureData); } if(textureData) { stbi_image_free(textureData); } return textureID; } /* Texture file loading and parsing */ GLuint loadTextureFromMetadata(const string &filename, SCETextureFormat fallbackFormat, SCETextureWrap fallbackWrapMode, bool fallbackMipmaps) { string fullTexturePath = RESSOURCE_PATH + filename; string metadataFile = fullTexturePath + TEXTURE_METADATA_SUFIX; if(!ifstream(metadataFile.c_str())) { fullTexturePath = ENGINE_RESSOURCE_PATH + filename; metadataFile = fullTexturePath + TEXTURE_METADATA_SUFIX; } //load texture metada ifstream fileStream(metadataFile.c_str(), ios::in); map<string, string> lineData; if(fileStream.is_open()) { string currLine; string name, formatStr, mipmapStr, wrappingModeStr; while (getline(fileStream, currLine)) { lineData = MetadataParser::GetLineData(currLine); if(lineData.count("Name") > 0) { name = lineData["Name"]; } if(lineData.count(FORMAT_STR) > 0) { formatStr = lineData[FORMAT_STR]; } if(lineData.count(MIPMAPS_STR) > 0) { mipmapStr = lineData[MIPMAPS_STR]; } if(lineData.count(WRAPPING_STR) > 0) { wrappingModeStr = lineData[WRAPPING_STR]; } } fileStream.close(); bool mipmapsOn = mipmapStr != "false"; //texture format SCETextureFormat format = formatFromString(formatStr); SCETextureWrap wrapMode = wrapModeFromString(wrappingModeStr); return loadTexture(name, format, wrapMode, mipmapsOn); } else { //try to open as a raw image directly return loadTexture(filename, fallbackFormat, fallbackWrapMode, fallbackMipmaps); } } /* Public interface */ GLuint CreateTexture(int width, int height, vec4 color, SCETextureFormat compressionFormat, SCETextureWrap wrapMode, bool mipmapsOn) { Internal::Log(std::string("TODO : Compression format not yet used : ") + std::to_string(compressionFormat)); uint channelCount = 4; unsigned char *textureData = new unsigned char [width * height * channelCount]; int xstart, ystart; for(int x = 0; x < width; ++x){ xstart = x * height * channelCount; for(int y = 0; y < height; ++y){ ystart = y * channelCount; textureData[xstart + ystart + 0] = Tools::FloatToColorRange(color.x); textureData[xstart + ystart + 1] = Tools::FloatToColorRange(color.y); textureData[xstart + ystart + 2] = Tools::FloatToColorRange(color.z); textureData[xstart + ystart + 3] = Tools::FloatToColorRange(color.w); } } GLuint texId = createTextureWithData(width, height, GL_RGBA32F, GL_RGBA, GL_UNSIGNED_BYTE, wrapMode, mipmapsOn, textureData); texturesData.createdTextures.push_back(texId); return texId; } GLuint LoadTexture(const string& textureName, SCETextureFormat fallbackFormat, SCETextureWrap fallbackWrapMode, bool fallbackMipmaps) { //texture has already been loaded if(texturesData.loadedTextures.count(textureName) > 0) { Internal::Log("Texture " + textureName + " already loaded, using it directly"); return texturesData.loadedTextures[textureName]; } GLuint texId = loadTextureFromMetadata(textureName, fallbackFormat, fallbackWrapMode, fallbackMipmaps); texturesData.loadedTextures[textureName] = texId; return texId; } void DeleteTexture(GLuint textureId) { auto itLoaded = find_if(begin(texturesData.loadedTextures), end(texturesData.loadedTextures), [&textureId](std::pair<string, GLuint> entry) { return entry.second == textureId; } ); //texture id was found in loaded textures if(itLoaded != end(texturesData.loadedTextures)) { Internal::Log("Delete texture : " + itLoaded->first); glDeleteTextures(1, &(itLoaded->second)); texturesData.loadedTextures.erase(itLoaded); } auto itCreated = find(begin(texturesData.createdTextures), end(texturesData.createdTextures), textureId); //texture id was found in created textures if(itCreated != end(texturesData.createdTextures)) { glDeleteTextures(1, &textureId); texturesData.createdTextures.erase(itCreated); } } void BindTexture(GLuint textureId, GLuint textureUnit, GLuint samplerUniformId) { // Bind the texture to a texture Unit glActiveTexture(GL_TEXTURE0 + textureUnit); if(debugTexture != GL_INVALID_INDEX)//use debug texture { glBindTexture(GL_TEXTURE_2D, debugTexture); } else { glBindTexture(GL_TEXTURE_2D, textureId); } // Set the sampler uniform to the texture unit glUniform1i(samplerUniformId, textureUnit); } void BindSafeTexture(GLuint textureId, GLuint textureUnit, GLuint samplerUniformId) { // Bind the texture to a texture Unit glActiveTexture(GL_TEXTURE0 + textureUnit); glBindTexture(GL_TEXTURE_2D, textureId); // Set the sampler uniform to the texture unit glUniform1i(samplerUniformId, textureUnit); } #ifdef SCE_DEBUG_ENGINE void EnableDebugTexture() { debugTexture = LoadTexture(DEBUG_TEXTURE_NAME); } void DisableDebugTexture() { debugTexture = GL_INVALID_INDEX; } bool ToggleDebugTexture() { if(debugTexture == GL_INVALID_INDEX) { EnableDebugTexture(); return true; } else { DisableDebugTexture(); return false; } } #endif } }
gpl-2.0
datake/agent
QuadProg++.hh
2972
#ifndef _QUADPROGPP #define _QUADPROGPP /* File QuadProg++.hh The quadprog_solve() function implements the algorithm of Goldfarb and Idnani for the solution of a (convex) Quadratic Programming problem by means of a dual method. The problem is in the form: min 0.5 * x G x + g0 x s.t. CE^T x + ce0 = 0 CI^T x + ci0 >= 0 The matrix and vectors dimensions are as follows: G: n * n g0: n CE: n * p ce0: p CI: n * m ci0: m x: n The function will return the cost of the solution written in the x vector or std::numeric_limits::infinity() if the problem is infeasible. In the latter case the value of the x vector is not correct. References: D. Goldfarb, A. Idnani. A numerically stable dual method for solving strictly convex quadratic programs. Mathematical Programming 27 (1983) pp. 1-33. Notes: 1. pay attention in setting up the vectors ce0 and ci0. If the constraints of your problem are specified in the form A^T x = b and C^T x >= d, then you should set ce0 = -b and ci0 = -d. 2. The matrices have column dimension equal to MATRIX_DIM, a constant set to 20 in this file (by means of a #define macro). If the matrices are bigger than 20 x 20 the limit could be increased by means of a -DMATRIX_DIM=n on the compiler command line. 3. The matrix G is modified within the function since it is used to compute the G = L^T L cholesky factorization for further computations inside the function. If you need the original matrix G you should make a copy of it and pass the copy to the function. Author: Luca Di Gaspero DIEGM - University of Udine, Italy l.digaspero@uniud.it http://www.diegm.uniud.it/digaspero/ The author will be grateful if the researchers using this software will acknowledge the contribution of this function in their research papers. LICENSE Copyright 2006 Luca Di Gaspero This file is part of QuadProg++. QuadProg++ 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. QuadProg++ 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 QuadProg++; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef MATRIX_DIM #define MATRIX_DIM 100 #endif double solve_quadprog(double G[][MATRIX_DIM], double g0[], int n, double CE[][MATRIX_DIM], double ce0[], int p, double CI[][MATRIX_DIM], double ci0[], int m, double x[]); #endif // #define _QUADPROGPP
gpl-2.0
helaili/GHRemote
modules/issues/client/issues.client.module.js
130
'use strict'; // Use Applicaion configuration module to register a new module ApplicationConfiguration.registerModule('issues');
gpl-2.0