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
#include "consoletools.h" #include "log/logger.h" #include <QTextStream> #include <Windows.h> LOGGER(ConsoleTools); class ConsoleTools::Private { public: Private() { hConsole = ::GetStdHandle(STD_INPUT_HANDLE); if (hConsole == INVALID_HANDLE_VALUE) { LOG_ERROR("Unable to get console handle"); } } HANDLE hConsole; }; ConsoleTools::ConsoleTools() : d(new Private) { } ConsoleTools::~ConsoleTools() { enableEcho(); delete d; } bool ConsoleTools::enableEcho() { DWORD value; ::GetConsoleMode(d->hConsole, &value); value |= ENABLE_ECHO_INPUT; ::SetConsoleMode(d->hConsole, value); return true; } bool ConsoleTools::disableEcho() { DWORD value; ::GetConsoleMode(d->hConsole, &value); value &= ~ENABLE_ECHO_INPUT; ::SetConsoleMode(d->hConsole, value); return true; } QString ConsoleTools::readLine() { QTextStream stream(stdin); return stream.readLine(); } QString ConsoleTools::readPassword() { disableEcho(); QTextStream stream(stdin); QString pw = stream.readLine(); enableEcho(); return pw; }
MKV21/glimpse_client
src/console/consoletools_win.cpp
C++
bsd-3-clause
1,142
// Copyright 2013 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 "extensions/common/permissions/api_permission_set.h" #include "base/containers/contains.h" #include "base/logging.h" #include "base/ranges/algorithm.h" #include "base/stl_util.h" #include "base/strings/string_number_conversions.h" #include "base/values.h" #include "extensions/common/error_utils.h" #include "extensions/common/manifest_constants.h" #include "extensions/common/permissions/permissions_info.h" using extensions::mojom::APIPermissionID; namespace extensions { namespace errors = manifest_errors; namespace { // Helper object that is implicitly constructible from both a PermissionID and // from an mojom::APIPermissionID. struct PermissionIDCompareHelper { PermissionIDCompareHelper(const PermissionID& id) : id(id.id()) {} PermissionIDCompareHelper(const APIPermissionID id) : id(id) {} APIPermissionID id; }; bool CreateAPIPermission(const std::string& permission_str, const base::Value* permission_value, APIPermissionSet::ParseSource source, APIPermissionSet* api_permissions, std::u16string* error, std::vector<std::string>* unhandled_permissions) { const APIPermissionInfo* permission_info = PermissionsInfo::GetInstance()->GetByName(permission_str); if (permission_info) { std::unique_ptr<APIPermission> permission( permission_info->CreateAPIPermission()); if (source != APIPermissionSet::kAllowInternalPermissions && permission_info->is_internal()) { // An internal permission specified in permissions list is an error. if (error) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kPermissionNotAllowedInManifest, permission_str); } return false; } std::string error_details; if (!permission->FromValue(permission_value, &error_details, unhandled_permissions)) { if (error) { if (error_details.empty()) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermission, permission_info->name()); } else { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermissionWithDetail, permission_info->name(), error_details); } return false; } VLOG(1) << "Parse permission failed."; } else { api_permissions->insert(std::move(permission)); } return true; } if (unhandled_permissions) unhandled_permissions->push_back(permission_str); else VLOG(1) << "Unknown permission[" << permission_str << "]."; return true; } bool ParseChildPermissions(const std::string& base_name, const base::Value* permission_value, APIPermissionSet::ParseSource source, APIPermissionSet* api_permissions, std::u16string* error, std::vector<std::string>* unhandled_permissions) { if (permission_value) { if (!permission_value->is_list()) { if (error) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermission, base_name); return false; } VLOG(1) << "Permission value is not a list."; // Failed to parse, but since error is NULL, failures are not fatal so // return true here anyway. return true; } base::Value::ConstListView list_view = permission_value->GetListDeprecated(); for (size_t i = 0; i < list_view.size(); ++i) { std::string permission_str; if (!list_view[i].is_string()) { // permission should be a string if (error) { *error = ErrorUtils::FormatErrorMessageUTF16( errors::kInvalidPermission, base_name + '.' + base::NumberToString(i)); return false; } VLOG(1) << "Permission is not a string."; continue; } if (!CreateAPIPermission(base_name + '.' + list_view[i].GetString(), nullptr, source, api_permissions, error, unhandled_permissions)) return false; } } return CreateAPIPermission(base_name, nullptr, source, api_permissions, error, nullptr); } } // namespace void APIPermissionSet::insert(APIPermissionID id) { const APIPermissionInfo* permission_info = PermissionsInfo::GetInstance()->GetByID(id); DCHECK(permission_info); insert(permission_info->CreateAPIPermission()); } void APIPermissionSet::insert(std::unique_ptr<APIPermission> permission) { BaseSetOperators<APIPermissionSet>::insert(std::move(permission)); } // static bool APIPermissionSet::ParseFromJSON( const base::Value* permissions, APIPermissionSet::ParseSource source, APIPermissionSet* api_permissions, std::u16string* error, std::vector<std::string>* unhandled_permissions) { if (!permissions->is_list()) { if (error) { *error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidPermission, "<root>"); return false; } VLOG(1) << "Root Permissions value is not a list."; // Failed to parse, but since error is NULL, failures are not fatal so // return true here anyway. return true; } base::Value::ConstListView list_view = permissions->GetListDeprecated(); for (size_t i = 0; i < list_view.size(); ++i) { std::string permission_str; const base::Value* permission_value = nullptr; // permission should be a string or a single key dict. if (list_view[i].is_string()) { permission_str = list_view[i].GetString(); } else if (list_view[i].is_dict() && list_view[i].DictSize() == 1) { auto dict_iter = list_view[i].DictItems().begin(); permission_str = dict_iter->first; permission_value = &dict_iter->second; } else { if (error) { *error = ErrorUtils::FormatErrorMessageUTF16(errors::kInvalidPermission, base::NumberToString(i)); return false; } VLOG(1) << "Permission is not a string or single key dict."; continue; } // Check if this permission is a special case where its value should // be treated as a list of child permissions. if (PermissionsInfo::GetInstance()->HasChildPermissions(permission_str)) { if (!ParseChildPermissions(permission_str, permission_value, source, api_permissions, error, unhandled_permissions)) return false; continue; } if (!CreateAPIPermission(permission_str, permission_value, source, api_permissions, error, unhandled_permissions)) return false; } return true; } PermissionID::PermissionID(APIPermissionID id) : std::pair<APIPermissionID, std::u16string>(id, std::u16string()) {} PermissionID::PermissionID(APIPermissionID id, const std::u16string& parameter) : std::pair<APIPermissionID, std::u16string>(id, parameter) {} PermissionID::~PermissionID() { } PermissionIDSet::PermissionIDSet() { } PermissionIDSet::PermissionIDSet( std::initializer_list<APIPermissionID> permissions) { for (auto permission : permissions) { permissions_.insert(PermissionID(permission)); } } PermissionIDSet::PermissionIDSet(const PermissionIDSet& other) = default; PermissionIDSet::~PermissionIDSet() { } void PermissionIDSet::insert(APIPermissionID permission_id) { insert(permission_id, std::u16string()); } void PermissionIDSet::insert(APIPermissionID permission_id, const std::u16string& permission_detail) { permissions_.insert(PermissionID(permission_id, permission_detail)); } void PermissionIDSet::InsertAll(const PermissionIDSet& permission_set) { for (const auto& permission : permission_set.permissions_) { permissions_.insert(permission); } } void PermissionIDSet::erase(APIPermissionID permission_id) { auto lower_bound = permissions_.lower_bound(PermissionID(permission_id)); auto upper_bound = lower_bound; while (upper_bound != permissions_.end() && upper_bound->id() == permission_id) { ++upper_bound; } permissions_.erase(lower_bound, upper_bound); } std::vector<std::u16string> PermissionIDSet::GetAllPermissionParameters() const { std::vector<std::u16string> params; for (const auto& permission : permissions_) { params.push_back(permission.parameter()); } return params; } bool PermissionIDSet::ContainsID(PermissionID permission_id) const { auto it = permissions_.lower_bound(permission_id); return it != permissions_.end() && it->id() == permission_id.id(); } bool PermissionIDSet::ContainsID(APIPermissionID permission_id) const { return ContainsID(PermissionID(permission_id)); } bool PermissionIDSet::ContainsAllIDs( const std::set<APIPermissionID>& permission_ids) const { return std::includes(permissions_.begin(), permissions_.end(), permission_ids.begin(), permission_ids.end(), [] (const PermissionIDCompareHelper& lhs, const PermissionIDCompareHelper& rhs) { return lhs.id < rhs.id; }); } bool PermissionIDSet::ContainsAnyID( const std::set<APIPermissionID>& permission_ids) const { for (APIPermissionID id : permission_ids) { if (ContainsID(id)) return true; } return false; } bool PermissionIDSet::ContainsAnyID(const PermissionIDSet& other) const { for (const auto& id : other) { if (ContainsID(id)) return true; } return false; } PermissionIDSet PermissionIDSet::GetAllPermissionsWithID( APIPermissionID permission_id) const { PermissionIDSet subset; auto it = permissions_.lower_bound(PermissionID(permission_id)); while (it != permissions_.end() && it->id() == permission_id) { subset.permissions_.insert(*it); ++it; } return subset; } PermissionIDSet PermissionIDSet::GetAllPermissionsWithIDs( const std::set<APIPermissionID>& permission_ids) const { PermissionIDSet subset; for (const auto& permission : permissions_) { if (base::Contains(permission_ids, permission.id())) { subset.permissions_.insert(permission); } } return subset; } bool PermissionIDSet::Includes(const PermissionIDSet& subset) const { return base::ranges::includes(permissions_, subset.permissions_); } bool PermissionIDSet::Equals(const PermissionIDSet& set) const { return permissions_ == set.permissions_; } // static PermissionIDSet PermissionIDSet::Difference(const PermissionIDSet& set_1, const PermissionIDSet& set_2) { return PermissionIDSet(base::STLSetDifference<std::set<PermissionID>>( set_1.permissions_, set_2.permissions_)); } size_t PermissionIDSet::size() const { return permissions_.size(); } bool PermissionIDSet::empty() const { return permissions_.empty(); } PermissionIDSet::PermissionIDSet(const std::set<PermissionID>& permissions) : permissions_(permissions) { } } // namespace extensions
chromium/chromium
extensions/common/permissions/api_permission_set.cc
C++
bsd-3-clause
11,420
# Copyright 2019 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. import os import sys import json from command_executor import CommandExecutor _THIS_DIR = os.path.abspath(os.path.dirname(__file__)) _PARENT_DIR = os.path.join(_THIS_DIR, os.pardir) sys.path.insert(1, _PARENT_DIR) import chrome_paths sys.path.remove(_PARENT_DIR) sys.path.insert(0,os.path.join(chrome_paths.GetSrc(), 'third_party', 'catapult', 'telemetry', 'third_party', 'websocket-client')) import websocket class WebSocketCommands: CREATE_WEBSOCKET = \ '/session/:sessionId' SEND_OVER_WEBSOCKET = \ '/session/:sessionId/chromium/send_command_from_websocket' class WebSocketConnection(object): def __init__(self, server_url, session_id): self._server_url = server_url.replace('http', 'ws') self._session_id = session_id self._command_id = -1 cmd_params = {'sessionId': session_id} path = CommandExecutor.CreatePath( WebSocketCommands.CREATE_WEBSOCKET, cmd_params) self._websocket = websocket.create_connection(self._server_url + path) def SendCommand(self, cmd_params): cmd_params['id'] = self._command_id self._command_id -= 1 self._websocket.send(json.dumps(cmd_params)) def ReadMessage(self): return self._websocket.recv() def Close(self): self._websocket.close();
chromium/chromium
chrome/test/chromedriver/client/websocket_connection.py
Python
bsd-3-clause
1,471
// Copyright 2019 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 "components/autofill/core/browser/payments/test_authentication_requester.h" #include <string> #include "build/build_config.h" #include "components/autofill/core/browser/data_model/credit_card.h" namespace autofill { TestAuthenticationRequester::TestAuthenticationRequester() {} TestAuthenticationRequester::~TestAuthenticationRequester() {} base::WeakPtr<TestAuthenticationRequester> TestAuthenticationRequester::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } void TestAuthenticationRequester::OnCVCAuthenticationComplete( const CreditCardCVCAuthenticator::CVCAuthenticationResponse& response) { did_succeed_ = response.did_succeed; if (*did_succeed_) { DCHECK(response.card); number_ = response.card->number(); } } #if BUILDFLAG(IS_ANDROID) bool TestAuthenticationRequester::ShouldOfferFidoAuth() const { return false; } bool TestAuthenticationRequester::UserOptedInToFidoFromSettingsPageOnMobile() const { return false; } #endif #if !BUILDFLAG(IS_IOS) void TestAuthenticationRequester::OnFIDOAuthenticationComplete( const CreditCardFIDOAuthenticator::FidoAuthenticationResponse& response) { did_succeed_ = response.did_succeed; if (*did_succeed_) { DCHECK(response.card); number_ = response.card->number(); } failure_type_ = response.failure_type; } void TestAuthenticationRequester::OnFidoAuthorizationComplete( bool did_succeed) { did_succeed_ = did_succeed; } void TestAuthenticationRequester::IsUserVerifiableCallback( bool is_user_verifiable) { is_user_verifiable_ = is_user_verifiable; } #endif void TestAuthenticationRequester::OnOtpAuthenticationComplete( const CreditCardOtpAuthenticator::OtpAuthenticationResponse& response) { did_succeed_ = response.result == CreditCardOtpAuthenticator::OtpAuthenticationResponse::Result::kSuccess; if (*did_succeed_) { DCHECK(response.card); number_ = response.card->number(); } } } // namespace autofill
chromium/chromium
components/autofill/core/browser/payments/test_authentication_requester.cc
C++
bsd-3-clause
2,142
package ping import ( "bytes" "errors" "io" "time" context "github.com/ipfs/go-ipfs/Godeps/_workspace/src/golang.org/x/net/context" host "github.com/ipfs/go-ipfs/p2p/host" inet "github.com/ipfs/go-ipfs/p2p/net" peer "github.com/ipfs/go-ipfs/p2p/peer" logging "github.com/ipfs/go-ipfs/vendor/go-log-v1.0.0" u "github.com/ipfs/go-ipfs/util" ) var log = logging.Logger("ping") const PingSize = 32 const ID = "/ipfs/ping" type PingService struct { Host host.Host } func NewPingService(h host.Host) *PingService { ps := &PingService{h} h.SetStreamHandler(ID, ps.PingHandler) return ps } func (p *PingService) PingHandler(s inet.Stream) { buf := make([]byte, PingSize) for { _, err := io.ReadFull(s, buf) if err != nil { log.Debug(err) return } _, err = s.Write(buf) if err != nil { log.Debug(err) return } } } func (ps *PingService) Ping(ctx context.Context, p peer.ID) (<-chan time.Duration, error) { s, err := ps.Host.NewStream(ID, p) if err != nil { return nil, err } out := make(chan time.Duration) go func() { defer close(out) for { select { case <-ctx.Done(): return default: t, err := ping(s) if err != nil { log.Debugf("ping error: %s", err) return } select { case out <- t: case <-ctx.Done(): return } } } }() return out, nil } func ping(s inet.Stream) (time.Duration, error) { buf := make([]byte, PingSize) u.NewTimeSeededRand().Read(buf) before := time.Now() _, err := s.Write(buf) if err != nil { return 0, err } rbuf := make([]byte, PingSize) _, err = io.ReadFull(s, rbuf) if err != nil { return 0, err } if !bytes.Equal(buf, rbuf) { return 0, errors.New("ping packet was incorrect!") } return time.Now().Sub(before), nil }
willglynn/go-ipfs
p2p/protocol/ping/ping.go
GO
mit
1,786
import * as React from 'react' import { ICommonImageDiffProperties } from './modified-image-diff' import { ImageContainer } from './image-container' interface IOnionSkinState { readonly crossfade: number } export class OnionSkin extends React.Component< ICommonImageDiffProperties, IOnionSkinState > { public constructor(props: ICommonImageDiffProperties) { super(props) this.state = { crossfade: 1 } } public render() { const style: React.CSSProperties = { height: this.props.maxSize.height, width: this.props.maxSize.width, } const maxSize: React.CSSProperties = { maxHeight: this.props.maxSize.height, maxWidth: this.props.maxSize.width, } return ( <div className="image-diff-onion-skin"> <div className="sizing-container" ref={this.props.onContainerRef}> <div className="image-container" style={style}> <div className="image-diff-previous" style={style}> <ImageContainer image={this.props.previous} onElementLoad={this.props.onPreviousImageLoad} style={maxSize} /> </div> <div className="image-diff-current" style={{ ...style, opacity: this.state.crossfade, }} > <ImageContainer image={this.props.current} onElementLoad={this.props.onCurrentImageLoad} style={maxSize} /> </div> </div> </div> <input style={{ width: this.props.maxSize.width / 2, }} className="slider" type="range" max={1} min={0} value={this.state.crossfade} step={0.001} onChange={this.onValueChange} /> </div> ) } private onValueChange = (e: React.ChangeEvent<HTMLInputElement>) => { this.setState({ crossfade: e.currentTarget.valueAsNumber }) } }
j-f1/forked-desktop
app/src/ui/diff/image-diffs/onion-skin.tsx
TypeScript
mit
2,059
'use strict'; const hljs = require('highlight.js'); const languages = hljs.listLanguages(); const fs = require('fs'); const result = { languages: languages, aliases: {} }; languages.forEach(lang => { result.aliases[lang] = lang; const def = require('highlight.js/lib/languages/' + lang)(hljs); const aliases = def.aliases; if (aliases) { aliases.forEach(alias => { result.aliases[alias] = lang; }); } }); const stream = fs.createWriteStream('highlight_alias.json'); stream.write(JSON.stringify(result)); stream.on('end', () => { stream.end(); });
hexojs/hexo-util
scripts/build_highlight_alias.js
JavaScript
mit
583
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace ScintillaNET { /// <summary> /// Provides data for the <see cref="Scintilla.DoubleClick" /> event. /// </summary> public class DoubleClickEventArgs : EventArgs { private readonly Scintilla scintilla; private readonly int bytePosition; private int? position; /// <summary> /// Gets the line double clicked. /// </summary> /// <returns>The zero-based index of the double clicked line.</returns> public int Line { get; private set; } /// <summary> /// Gets the modifier keys (SHIFT, CTRL, ALT) held down when double clicked. /// </summary> /// <returns>A bitwise combination of the Keys enumeration indicating the modifier keys.</returns> public Keys Modifiers { get; private set; } /// <summary> /// Gets the zero-based document position of the text double clicked. /// </summary> /// <returns> /// The zero-based character position within the document of the double clicked text; /// otherwise, -1 if not a document position. /// </returns> public int Position { get { if (position == null) position = scintilla.Lines.ByteToCharPosition(bytePosition); return (int)position; } } /// <summary> /// Initializes a new instance of the <see cref="DoubleClickEventArgs" /> class. /// </summary> /// <param name="scintilla">The <see cref="Scintilla" /> control that generated this event.</param> /// <param name="modifiers">The modifier keys that where held down at the time of the double click.</param> /// <param name="bytePosition">The zero-based byte position of the double clicked text.</param> /// <param name="line">The zero-based line index of the double clicked text.</param> public DoubleClickEventArgs(Scintilla scintilla, Keys modifiers, int bytePosition, int line) { this.scintilla = scintilla; this.bytePosition = bytePosition; Modifiers = modifiers; Line = line; if (bytePosition == -1) position = -1; } } }
suvjunmd/ScintillaNET
src/ScintillaNET/DoubleClickEventArgs.cs
C#
mit
2,400
module Gitlab module SlashCommands class IssueShow < IssueCommand def self.match(text) /\Aissue\s+show\s+#{Issue.reference_prefix}?(?<iid>\d+)/.match(text) end def self.help_message "issue show <id>" end def execute(match) issue = find_by_iid(match[:iid]) if issue Gitlab::SlashCommands::Presenters::IssueShow.new(issue).present else Gitlab::SlashCommands::Presenters::Access.new.not_found end end end end end
t-zuehlsdorff/gitlabhq
lib/gitlab/slash_commands/issue_show.rb
Ruby
mit
529
'use strict'; /* jQuery UI Sortable plugin wrapper @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config */ angular.module('mpk').value('uiSortableConfig',{}).directive('uiSortable', [ 'uiSortableConfig', '$timeout', '$log', function(uiSortableConfig, $timeout, $log) { return { require: '?ngModel', link: function(scope, element, attrs, ngModel) { var savedNodes; function combineCallbacks(first,second){ if(second && (typeof second === 'function')) { return function(e, ui) { first(e, ui); second(e, ui); }; } return first; } var opts = {}; var callbacks = { receive: null, remove:null, start:null, stop:null, update:null }; angular.extend(opts, uiSortableConfig); if (ngModel) { // When we add or remove elements, we need the sortable to 'refresh' // so it can find the new/removed elements. scope.$watch(attrs.ngModel+'.length', function() { // Timeout to let ng-repeat modify the DOM $timeout(function() { element.sortable('refresh'); }); }); callbacks.start = function(e, ui) { // Save the starting position of dragged item ui.item.sortable = { index: ui.item.index(), cancel: function () { ui.item.sortable._isCanceled = true; }, isCanceled: function () { return ui.item.sortable._isCanceled; }, _isCanceled: false }; }; callbacks.activate = function(/*e, ui*/) { // We need to make a copy of the current element's contents so // we can restore it after sortable has messed it up. // This is inside activate (instead of start) in order to save // both lists when dragging between connected lists. savedNodes = element.contents(); // If this list has a placeholder (the connected lists won't), // don't inlcude it in saved nodes. var placeholder = element.sortable('option','placeholder'); // placeholder.element will be a function if the placeholder, has // been created (placeholder will be an object). If it hasn't // been created, either placeholder will be false if no // placeholder class was given or placeholder.element will be // undefined if a class was given (placeholder will be a string) if (placeholder && placeholder.element && typeof placeholder.element === 'function') { var phElement = placeholder.element(); // workaround for jquery ui 1.9.x, // not returning jquery collection if (!phElement.jquery) { phElement = angular.element(phElement); } // exact match with the placeholder's class attribute to handle // the case that multiple connected sortables exist and // the placehoilder option equals the class of sortable items var excludes = element.find('[class="' + phElement.attr('class') + '"]'); savedNodes = savedNodes.not(excludes); } }; callbacks.update = function(e, ui) { // Save current drop position but only if this is not a second // update that happens when moving between lists because then // the value will be overwritten with the old value if(!ui.item.sortable.received) { ui.item.sortable.dropindex = ui.item.index(); ui.item.sortable.droptarget = ui.item.parent(); // Cancel the sort (let ng-repeat do the sort for us) // Don't cancel if this is the received list because it has // already been canceled in the other list, and trying to cancel // here will mess up the DOM. element.sortable('cancel'); } // Put the nodes back exactly the way they started (this is very // important because ng-repeat uses comment elements to delineate // the start and stop of repeat sections and sortable doesn't // respect their order (even if we cancel, the order of the // comments are still messed up). savedNodes.detach(); if (element.sortable('option','helper') === 'clone') { // first detach all the savedNodes and then restore all of them // except .ui-sortable-helper element (which is placed last). // That way it will be garbage collected. savedNodes = savedNodes.not(savedNodes.last()); } savedNodes.appendTo(element); // If received is true (an item was dropped in from another list) // then we add the new item to this list otherwise wait until the // stop event where we will know if it was a sort or item was // moved here from another list if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0, ui.item.sortable.moved); }); } }; callbacks.stop = function(e, ui) { // If the received flag hasn't be set on the item, this is a // normal sort, if dropindex is set, the item was moved, so move // the items in the list. if(!ui.item.sortable.received && ('dropindex' in ui.item.sortable) && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice( ui.item.sortable.dropindex, 0, ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]); }); } else { // if the item was not moved, then restore the elements // so that the ngRepeat's comment are correct. if((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) && element.sortable('option','helper') !== 'clone') { savedNodes.detach().appendTo(element); } } }; callbacks.receive = function(e, ui) { // An item was dropped here from another list, set a flag on the // item. ui.item.sortable.received = true; }; callbacks.remove = function(e, ui) { // Remove the item from this list's model and copy data into item, // so the next list can retrive it if (!ui.item.sortable.isCanceled()) { scope.$apply(function () { ui.item.sortable.moved = ngModel.$modelValue.splice( ui.item.sortable.index, 1)[0]; }); } }; scope.$watch(attrs.uiSortable, function(newVal /*, oldVal*/) { angular.forEach(newVal, function(value, key) { if(callbacks[key]) { if( key === 'stop' ){ // call apply after stop value = combineCallbacks( value, function() { scope.$apply(); }); } // wrap the callback value = combineCallbacks(callbacks[key], value); } element.sortable('option', key, value); }); }, true); angular.forEach(callbacks, function(value, key) { opts[key] = combineCallbacks(value, opts[key]); }); } else { $log.info('ui.sortable: ngModel not provided!', element); } // Create sortable element.sortable(opts); } }; } ]);
mabotech/maboss-admin
public/kanban/scripts/directives/sortable.js
JavaScript
mit
8,434
using System; using ProvisioningLibrary; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Table; namespace ProvisioningLibrary { public class GroupBudgetState : TableEntity { private string _ResourceId = string.Empty; public GroupBudgetState() { } public GroupBudgetState(string groupId) : this() { this.RowKey = groupId; this.PartitionKey = groupId; } public string GroupId { get { return this.PartitionKey; } } public long UnitsBudgetted { get; set; } public long UnitsAllocated { get; set; } public long UnitsUsed { get; set; } } }
GabrieleCastellani/SCAMP
ProvisioningLibrary/VolatileStorage/GroupBudgetState.cs
C#
mit
755
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_GoogleBase * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Google Base Item Types Model * * @method Mage_GoogleBase_Model_Resource_Item _getResource() * @method Mage_GoogleBase_Model_Resource_Item getResource() * @method int getTypeId() * @method Mage_GoogleBase_Model_Item setTypeId(int $value) * @method int getProductId() * @method Mage_GoogleBase_Model_Item setProductId(int $value) * @method string getGbaseItemId() * @method Mage_GoogleBase_Model_Item setGbaseItemId(string $value) * @method int getStoreId() * @method Mage_GoogleBase_Model_Item setStoreId(int $value) * @method string getPublished() * @method Mage_GoogleBase_Model_Item setPublished(string $value) * @method string getExpires() * @method Mage_GoogleBase_Model_Item setExpires(string $value) * @method int getImpr() * @method Mage_GoogleBase_Model_Item setImpr(int $value) * @method int getClicks() * @method Mage_GoogleBase_Model_Item setClicks(int $value) * @method int getViews() * @method Mage_GoogleBase_Model_Item setViews(int $value) * @method int getIsHidden() * @method Mage_GoogleBase_Model_Item setIsHidden(int $value) * * @deprecated after 1.5.1.0 * @category Mage * @package Mage_GoogleBase * @author Magento Core Team <core@magentocommerce.com> */ class Mage_GoogleBase_Model_Item extends Mage_Core_Model_Abstract { const ATTRIBUTES_REGISTRY_KEY = 'gbase_attributes_registry'; const TYPES_REGISTRY_KEY = 'gbase_types_registry'; protected function _construct() { parent::_construct(); $this->_init('googlebase/item'); } /** * Return Service Item Instance * * @return Mage_GoogleBase_Model_Service_Item */ public function getServiceItem() { return Mage::getModel('googlebase/service_item')->setStoreId($this->getStoreId()); } /** * Target Country * * @return string Two-letters country ISO code */ public function getTargetCountry() { return Mage::getSingleton('googlebase/config')->getTargetCountry($this->getStoreId()); } /** * Save item to Google Base * * @return Mage_GoogleBase_Model_Item */ public function insertItem() { $this->_checkProduct() ->_prepareProductObject(); $typeModel = $this->_getTypeModel(); $this->getServiceItem() ->setItem($this) ->setObject($this->getProduct()) ->setAttributeValues($this->_getAttributeValues()) ->setItemType($typeModel->getGbaseItemtype()) ->insert(); $this->setTypeId($typeModel->getTypeId()); return $this; } /** * Update Item data * * @return Mage_GoogleBase_Model_Item */ public function updateItem() { $this->_checkProduct() ->_prepareProductObject(); $this->loadByProduct($this->getProduct()); if ($this->getId()) { $typeModel = $this->_getTypeModel(); $this->getServiceItem() ->setItem($this) ->setObject($this->getProduct()) ->setAttributeValues($this->_getAttributeValues()) ->setItemType($typeModel->getGbaseItemtype()) ->update(); } return $this; } /** * Delete Item from Google Base * * @return Mage_GoogleBase_Model_Item */ public function deleteItem() { $this->getServiceItem()->setItem($this)->delete(); return $this; } /** * Delete Item from Google Base * * @return Mage_GoogleBase_Model_Item */ public function hideItem() { $this->getServiceItem()->setItem($this)->hide(); $this->setIsHidden(1); $this->save(); return $this; } /** * Delete Item from Google Base * * @return Mage_GoogleBase_Model_Item */ public function activateItem() { $this->getServiceItem()->setItem($this)->activate(); $this->setIsHidden(0); $this->save(); return $this; } /** * Load Item Model by Product * * @param Mage_Catalog_Model_Product $product * @return Mage_GoogleBase_Model_Item */ public function loadByProduct($product) { if (!$this->getProduct()) { $this->setProduct($product); } $this->getResource()->loadByProduct($this); return $this; } /** * Product Setter * * @param Mage_Catalog_Model_Product * @return Mage_GoogleBase_Model_Item */ public function setProduct($product) { if (!($product instanceof Mage_Catalog_Model_Product)) { Mage::throwException(Mage::helper('googlebase')->__('Invalid Product Model for Google Base Item')); } $this->setData('product', $product); $this->setProductId($product->getId()); $this->setStoreId($product->getStoreId()); return $this; } /** * Check product instance * * @return Mage_GoogleBase_Model_Item */ protected function _checkProduct() { if (!($this->getProduct() instanceof Mage_Catalog_Model_Product)) { Mage::throwException(Mage::helper('googlebase')->__('Invalid Product Model for Google Base Item')); } return $this; } /** * Copy Product object and assign additional data to the copy * * @return Mage_GoogleBase_Model_Item */ protected function _prepareProductObject() { $product = clone $this->getProduct(); /* @var $product Mage_Catalog_Model_Product */ $url = $product->getProductUrl(false); if (!Mage::getStoreConfigFlag('web/url/use_store')) { $urlInfo = parse_url($url); $store = $product->getStore()->getCode(); if (isset($urlInfo['query']) && $urlInfo['query'] != '') { $url .= '&___store=' . $store; } else { $url .= '?___store=' . $store; } } $product->setUrl($url) ->setQuantity( $this->getProduct()->getStockItem()->getQty() ) ->setImageUrl( Mage::helper('catalog/product')->getImageUrl($product) ); $this->setProduct($product); return $this; } /** * Return Product attribute values array * * @return array Product attribute values */ protected function _getAttributeValues() { $result = array(); $productAttributes = $this->_getProductAttributes(); foreach ($this->_getAttributesCollection() as $attribute) { $attributeId = $attribute->getAttributeId(); if (isset($productAttributes[$attributeId])) { $productAttribute = $productAttributes[$attributeId]; if ($attribute->getGbaseAttribute()) { $name = $attribute->getGbaseAttribute(); } else { $name = $this->_getAttributeLabel($productAttribute, $this->getProduct()->getStoreId()); } $value = $productAttribute->getGbaseValue(); $type = Mage::getSingleton('googlebase/attribute')->getGbaseAttributeType($productAttribute); if ($name && $value && $type) { $result[$name] = array( 'value' => $value, 'type' => $type ); } } } return $result; } /** * Return Product Attribute Store Label * * @param Mage_Catalog_Model_Resource_Eav_Attribute $attribute * @param int $storeId Store View Id * @return string Attribute Store View Label or Attribute code */ protected function _getAttributeLabel($attribute, $storeId) { $frontendLabel = $attribute->getFrontend()->getLabel(); if (is_array($frontendLabel)) { $frontendLabel = array_shift($frontendLabel); } if (!$this->_translations) { $moduleName = Mage_Catalog_Model_Entity_Attribute::MODULE_NAME; $separator = Mage_Core_Model_Translate::SCOPE_SEPARATOR; $this->_translations = Mage::getModel('core/translate_string') ->load($moduleName . $separator . $frontendLabel) ->getStoreTranslations(); } if (isset($this->_translations[$storeId])) { return $this->_translations[$storeId]; } else { return $attribute->getAttributeCode(); } } /** * Return Google Base Item Type Model for current Product Attribute Set * * @return Mage_GoogleBase_Model_Type */ protected function _getTypeModel() { $registry = Mage::registry(self::TYPES_REGISTRY_KEY); $attributeSetId = $this->getProduct()->getAttributeSetId(); if (is_array($registry) && isset($registry[$attributeSetId])) { return $registry[$attributeSetId]; } $model = Mage::getModel('googlebase/type')->loadByAttributeSetId($attributeSetId, $this->getTargetCountry()); $registry[$attributeSetId] = $model; Mage::unregister(self::TYPES_REGISTRY_KEY); Mage::register(self::TYPES_REGISTRY_KEY, $registry); return $model; } /** * Return Product attributes array * * @return array Product attributes */ protected function _getProductAttributes() { $product = $this->getProduct(); $attributes = $product->getAttributes(); $result = array(); foreach ($attributes as $attribute) { $value = $attribute->getFrontend()->getValue($product); if (is_string($value) && strlen($value) && $product->hasData($attribute->getAttributeCode())) { $attribute->setGbaseValue($value); $result[$attribute->getAttributeId()] = $attribute; } } return $result; } /** * Get Product Media files info * * @return array Media files info */ protected function _getProductImages() { $product = $this->getProduct(); $galleryData = $product->getData('media_gallery'); if (!isset($galleryData['images']) || !is_array($galleryData['images'])) { return array(); } $result = array(); foreach ($galleryData['images'] as $image) { $image['url'] = Mage::getSingleton('catalog/product_media_config') ->getMediaUrl($image['file']); $result[] = $image; } return $result; } /** * Return attribute collection for current Product Attribute Set * * @return Mage_GoogleBase_Model_Mysql4_Attribute_Collection */ protected function _getAttributesCollection() { $registry = Mage::registry(self::ATTRIBUTES_REGISTRY_KEY); $attributeSetId = $this->getProduct()->getAttributeSetId(); if (is_array($registry) && isset($registry[$attributeSetId])) { return $registry[$attributeSetId]; } $collection = Mage::getResourceModel('googlebase/attribute_collection') ->addAttributeSetFilter($attributeSetId, $this->getTargetCountry()) ->load(); $registry[$attributeSetId] = $collection; Mage::unregister(self::ATTRIBUTES_REGISTRY_KEY); Mage::register(self::ATTRIBUTES_REGISTRY_KEY, $registry); return $collection; } }
hansbonini/cloud9-magento
www/app/code/core/Mage/GoogleBase/Model/Item.php
PHP
mit
12,442
// Copyright 2018 the V8 project 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 "src/snapshot/roots-serializer.h" #include "src/execution/isolate.h" #include "src/heap/heap.h" #include "src/objects/objects-inl.h" #include "src/objects/slots.h" namespace v8 { namespace internal { RootsSerializer::RootsSerializer(Isolate* isolate, RootIndex first_root_to_be_serialized) : Serializer(isolate), first_root_to_be_serialized_(first_root_to_be_serialized), can_be_rehashed_(true) { for (size_t i = 0; i < static_cast<size_t>(first_root_to_be_serialized); ++i) { root_has_been_serialized_[i] = true; } } int RootsSerializer::SerializeInObjectCache(HeapObject heap_object) { int index; if (!object_cache_index_map_.LookupOrInsert(heap_object, &index)) { // This object is not part of the object cache yet. Add it to the cache so // we can refer to it via cache index from the delegating snapshot. SerializeObject(heap_object); } return index; } void RootsSerializer::Synchronize(VisitorSynchronization::SyncTag tag) { sink_.Put(kSynchronize, "Synchronize"); } void RootsSerializer::VisitRootPointers(Root root, const char* description, FullObjectSlot start, FullObjectSlot end) { RootsTable& roots_table = isolate()->roots_table(); if (start == roots_table.begin() + static_cast<int>(first_root_to_be_serialized_)) { // Serializing the root list needs special handling: // - Only root list elements that have been fully serialized can be // referenced using kRootArray bytecodes. for (FullObjectSlot current = start; current < end; ++current) { SerializeRootObject(*current); size_t root_index = current - roots_table.begin(); root_has_been_serialized_.set(root_index); } } else { Serializer::VisitRootPointers(root, description, start, end); } } void RootsSerializer::CheckRehashability(HeapObject obj) { if (!can_be_rehashed_) return; if (!obj.NeedsRehashing()) return; if (obj.CanBeRehashed()) return; can_be_rehashed_ = false; } } // namespace internal } // namespace v8
enclose-io/compiler
lts/deps/v8/src/snapshot/roots-serializer.cc
C++
mit
2,307
// 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 "gpu/command_buffer/service/gles2_cmd_copy_texture_chromium.h" #include <algorithm> #include "base/basictypes.h" #include "gpu/command_buffer/service/gl_utils.h" #include "gpu/command_buffer/service/gles2_cmd_decoder.h" #define SHADER(src) \ "#ifdef GL_ES\n" \ "precision mediump float;\n" \ "#define TexCoordPrecision mediump\n" \ "#else\n" \ "#define TexCoordPrecision\n" \ "#endif\n" #src #define SHADER_2D(src) \ "#define SamplerType sampler2D\n" \ "#define TextureLookup texture2D\n" SHADER(src) #define SHADER_RECTANGLE_ARB(src) \ "#define SamplerType sampler2DRect\n" \ "#define TextureLookup texture2DRect\n" SHADER(src) #define SHADER_EXTERNAL_OES(src) \ "#extension GL_OES_EGL_image_external : require\n" \ "#define SamplerType samplerExternalOES\n" \ "#define TextureLookup texture2D\n" SHADER(src) #define FRAGMENT_SHADERS(src) \ SHADER_2D(src), SHADER_RECTANGLE_ARB(src), SHADER_EXTERNAL_OES(src) namespace { const GLfloat kIdentityMatrix[16] = {1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; enum VertexShaderId { VERTEX_SHADER_COPY_TEXTURE, VERTEX_SHADER_COPY_TEXTURE_FLIP_Y, NUM_VERTEX_SHADERS, }; enum FragmentShaderId { FRAGMENT_SHADER_COPY_TEXTURE_2D, FRAGMENT_SHADER_COPY_TEXTURE_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_EXTERNAL_OES, FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_2D, FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_EXTERNAL_OES, FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_2D, FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_EXTERNAL_OES, NUM_FRAGMENT_SHADERS, }; const char* vertex_shader_source[NUM_VERTEX_SHADERS] = { // VERTEX_SHADER_COPY_TEXTURE SHADER( uniform vec2 u_vertex_translate; uniform vec2 u_half_size; attribute vec4 a_position; varying TexCoordPrecision vec2 v_uv; void main(void) { gl_Position = a_position + vec4(u_vertex_translate, 0.0, 0.0); v_uv = a_position.xy * vec2(u_half_size.s, u_half_size.t) + vec2(u_half_size.s, u_half_size.t); }), // VERTEX_SHADER_COPY_TEXTURE_FLIP_Y SHADER( uniform vec2 u_vertex_translate; uniform vec2 u_half_size; attribute vec4 a_position; varying TexCoordPrecision vec2 v_uv; void main(void) { gl_Position = a_position + vec4(u_vertex_translate, 0.0, 0.0); v_uv = a_position.xy * vec2(u_half_size.s, -u_half_size.t) + vec2(u_half_size.s, u_half_size.t); }), }; const char* fragment_shader_source[NUM_FRAGMENT_SHADERS] = { // FRAGMENT_SHADER_COPY_TEXTURE_* FRAGMENT_SHADERS( uniform SamplerType u_sampler; uniform mat4 u_tex_coord_transform; varying TexCoordPrecision vec2 v_uv; void main(void) { TexCoordPrecision vec4 uv = u_tex_coord_transform * vec4(v_uv, 0, 1); gl_FragColor = TextureLookup(u_sampler, uv.st); }), // FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_* FRAGMENT_SHADERS( uniform SamplerType u_sampler; uniform mat4 u_tex_coord_transform; varying TexCoordPrecision vec2 v_uv; void main(void) { TexCoordPrecision vec4 uv = u_tex_coord_transform * vec4(v_uv, 0, 1); gl_FragColor = TextureLookup(u_sampler, uv.st); gl_FragColor.rgb *= gl_FragColor.a; }), // FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_* FRAGMENT_SHADERS( uniform SamplerType u_sampler; uniform mat4 u_tex_coord_transform; varying TexCoordPrecision vec2 v_uv; void main(void) { TexCoordPrecision vec4 uv = u_tex_coord_transform * vec4(v_uv, 0, 1); gl_FragColor = TextureLookup(u_sampler, uv.st); if (gl_FragColor.a > 0.0) gl_FragColor.rgb /= gl_FragColor.a; }), }; // Returns the correct vertex shader id to evaluate the copy operation for // the CHROMIUM_flipy setting. VertexShaderId GetVertexShaderId(bool flip_y) { // bit 0: flip y static VertexShaderId shader_ids[] = { VERTEX_SHADER_COPY_TEXTURE, VERTEX_SHADER_COPY_TEXTURE_FLIP_Y, }; unsigned index = flip_y ? 1 : 0; return shader_ids[index]; } // Returns the correct fragment shader id to evaluate the copy operation for // the premultiply alpha pixel store settings and target. FragmentShaderId GetFragmentShaderId(bool premultiply_alpha, bool unpremultiply_alpha, GLenum target) { enum { SAMPLER_2D, SAMPLER_RECTANGLE_ARB, SAMPLER_EXTERNAL_OES, NUM_SAMPLERS }; // bit 0: premultiply alpha // bit 1: unpremultiply alpha static FragmentShaderId shader_ids[][NUM_SAMPLERS] = { { FRAGMENT_SHADER_COPY_TEXTURE_2D, FRAGMENT_SHADER_COPY_TEXTURE_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_EXTERNAL_OES, }, { FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_2D, FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_PREMULTIPLY_ALPHA_EXTERNAL_OES, }, { FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_2D, FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_UNPREMULTIPLY_ALPHA_EXTERNAL_OES, }, { FRAGMENT_SHADER_COPY_TEXTURE_2D, FRAGMENT_SHADER_COPY_TEXTURE_RECTANGLE_ARB, FRAGMENT_SHADER_COPY_TEXTURE_EXTERNAL_OES, }}; unsigned index = (premultiply_alpha ? (1 << 0) : 0) | (unpremultiply_alpha ? (1 << 1) : 0); switch (target) { case GL_TEXTURE_2D: return shader_ids[index][SAMPLER_2D]; case GL_TEXTURE_RECTANGLE_ARB: return shader_ids[index][SAMPLER_RECTANGLE_ARB]; case GL_TEXTURE_EXTERNAL_OES: return shader_ids[index][SAMPLER_EXTERNAL_OES]; default: break; } NOTREACHED(); return shader_ids[0][SAMPLER_2D]; } void CompileShader(GLuint shader, const char* shader_source) { glShaderSource(shader, 1, &shader_source, 0); glCompileShader(shader); #ifndef NDEBUG GLint compile_status; glGetShaderiv(shader, GL_COMPILE_STATUS, &compile_status); if (GL_TRUE != compile_status) DLOG(ERROR) << "CopyTextureCHROMIUM: shader compilation failure."; #endif } void DeleteShader(GLuint shader) { if (shader) glDeleteShader(shader); } bool BindFramebufferTexture2D(GLenum target, GLuint texture_id, GLuint framebuffer) { DCHECK(target == GL_TEXTURE_2D || target == GL_TEXTURE_RECTANGLE_ARB); glActiveTexture(GL_TEXTURE0); glBindTexture(target, texture_id); // NVidia drivers require texture settings to be a certain way // or they won't report FRAMEBUFFER_COMPLETE. glTexParameterf(target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glBindFramebufferEXT(GL_FRAMEBUFFER_EXT, framebuffer); glFramebufferTexture2DEXT(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, target, texture_id, 0); #ifndef NDEBUG GLenum fb_status = glCheckFramebufferStatusEXT(GL_FRAMEBUFFER); if (GL_FRAMEBUFFER_COMPLETE != fb_status) { DLOG(ERROR) << "CopyTextureCHROMIUM: Incomplete framebuffer."; return false; } #endif return true; } void DoCopyTexImage2D(const gpu::gles2::GLES2Decoder* decoder, GLenum source_target, GLuint source_id, GLuint dest_id, GLenum dest_internal_format, GLsizei width, GLsizei height, GLuint framebuffer) { DCHECK(source_target == GL_TEXTURE_2D || source_target == GL_TEXTURE_RECTANGLE_ARB); if (BindFramebufferTexture2D(source_target, source_id, framebuffer)) { glBindTexture(GL_TEXTURE_2D, dest_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glCopyTexImage2D(GL_TEXTURE_2D, 0 /* level */, dest_internal_format, 0 /* x */, 0 /* y */, width, height, 0 /* border */); } decoder->RestoreTextureState(source_id); decoder->RestoreTextureState(dest_id); decoder->RestoreTextureUnitBindings(0); decoder->RestoreActiveTexture(); decoder->RestoreFramebufferBindings(); } void DoCopyTexSubImage2D(const gpu::gles2::GLES2Decoder* decoder, GLenum source_target, GLuint source_id, GLuint dest_id, GLint xoffset, GLint yoffset, GLint source_x, GLint source_y, GLsizei source_width, GLsizei source_height, GLuint framebuffer) { DCHECK(source_target == GL_TEXTURE_2D || source_target == GL_TEXTURE_RECTANGLE_ARB); if (BindFramebufferTexture2D(source_target, source_id, framebuffer)) { glBindTexture(GL_TEXTURE_2D, dest_id); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glCopyTexSubImage2D(GL_TEXTURE_2D, 0 /* level */, xoffset, yoffset, source_x, source_y, source_width, source_height); } decoder->RestoreTextureState(source_id); decoder->RestoreTextureState(dest_id); decoder->RestoreTextureUnitBindings(0); decoder->RestoreActiveTexture(); decoder->RestoreFramebufferBindings(); } } // namespace namespace gpu { CopyTextureCHROMIUMResourceManager::CopyTextureCHROMIUMResourceManager() : initialized_(false), vertex_shaders_(NUM_VERTEX_SHADERS, 0u), fragment_shaders_(NUM_FRAGMENT_SHADERS, 0u), buffer_id_(0u), framebuffer_(0u) {} CopyTextureCHROMIUMResourceManager::~CopyTextureCHROMIUMResourceManager() { // |buffer_id_| and |framebuffer_| can be not-null because when GPU context is // lost, this class can be deleted without releasing resources like // GLES2DecoderImpl. } void CopyTextureCHROMIUMResourceManager::Initialize( const gles2::GLES2Decoder* decoder) { static_assert( kVertexPositionAttrib == 0u, "kVertexPositionAttrib must be 0"); DCHECK(!buffer_id_); DCHECK(!framebuffer_); DCHECK(programs_.empty()); // Initialize all of the GPU resources required to perform the copy. glGenBuffersARB(1, &buffer_id_); glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); const GLfloat kQuadVertices[] = {-1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f}; glBufferData( GL_ARRAY_BUFFER, sizeof(kQuadVertices), kQuadVertices, GL_STATIC_DRAW); glGenFramebuffersEXT(1, &framebuffer_); decoder->RestoreBufferBindings(); initialized_ = true; } void CopyTextureCHROMIUMResourceManager::Destroy() { if (!initialized_) return; glDeleteFramebuffersEXT(1, &framebuffer_); framebuffer_ = 0; std::for_each(vertex_shaders_.begin(), vertex_shaders_.end(), DeleteShader); std::for_each( fragment_shaders_.begin(), fragment_shaders_.end(), DeleteShader); for (ProgramMap::const_iterator it = programs_.begin(); it != programs_.end(); ++it) { const ProgramInfo& info = it->second; glDeleteProgram(info.program); } glDeleteBuffersARB(1, &buffer_id_); buffer_id_ = 0; } void CopyTextureCHROMIUMResourceManager::DoCopyTexture( const gles2::GLES2Decoder* decoder, GLenum source_target, GLuint source_id, GLenum source_internal_format, GLuint dest_id, GLenum dest_internal_format, GLsizei width, GLsizei height, bool flip_y, bool premultiply_alpha, bool unpremultiply_alpha) { bool premultiply_alpha_change = premultiply_alpha ^ unpremultiply_alpha; // GL_INVALID_OPERATION is generated if the currently bound framebuffer's // format does not contain a superset of the components required by the base // format of internalformat. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glCopyTexImage2D.xml bool source_format_contain_superset_of_dest_format = (source_internal_format == dest_internal_format && source_internal_format != GL_BGRA_EXT) || (source_internal_format == GL_RGBA && dest_internal_format == GL_RGB); // GL_TEXTURE_RECTANGLE_ARB on FBO is supported by OpenGL, not GLES2, // so restrict this to GL_TEXTURE_2D. if (source_target == GL_TEXTURE_2D && !flip_y && !premultiply_alpha_change && source_format_contain_superset_of_dest_format) { DoCopyTexImage2D(decoder, source_target, source_id, dest_id, dest_internal_format, width, height, framebuffer_); return; } // Use kIdentityMatrix if no transform passed in. DoCopyTextureWithTransform(decoder, source_target, source_id, dest_id, width, height, flip_y, premultiply_alpha, unpremultiply_alpha, kIdentityMatrix); } void CopyTextureCHROMIUMResourceManager::DoCopySubTexture( const gles2::GLES2Decoder* decoder, GLenum source_target, GLuint source_id, GLenum source_internal_format, GLuint dest_id, GLenum dest_internal_format, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLsizei dest_width, GLsizei dest_height, GLsizei source_width, GLsizei source_height, bool flip_y, bool premultiply_alpha, bool unpremultiply_alpha) { bool premultiply_alpha_change = premultiply_alpha ^ unpremultiply_alpha; // GL_INVALID_OPERATION is generated if the currently bound framebuffer's // format does not contain a superset of the components required by the base // format of internalformat. // https://www.khronos.org/opengles/sdk/docs/man/xhtml/glCopyTexImage2D.xml bool source_format_contain_superset_of_dest_format = (source_internal_format == dest_internal_format && source_internal_format != GL_BGRA_EXT) || (source_internal_format == GL_RGBA && dest_internal_format == GL_RGB); // GL_TEXTURE_RECTANGLE_ARB on FBO is supported by OpenGL, not GLES2, // so restrict this to GL_TEXTURE_2D. if (source_target == GL_TEXTURE_2D && !flip_y && !premultiply_alpha_change && source_format_contain_superset_of_dest_format) { DoCopyTexSubImage2D(decoder, source_target, source_id, dest_id, xoffset, yoffset, x, y, width, height, framebuffer_); return; } DoCopyTextureInternal(decoder, source_target, source_id, dest_id, xoffset, yoffset, x, y, width, height, dest_width, dest_height, source_width, source_height, flip_y, premultiply_alpha, unpremultiply_alpha, kIdentityMatrix); } void CopyTextureCHROMIUMResourceManager::DoCopyTextureWithTransform( const gles2::GLES2Decoder* decoder, GLenum source_target, GLuint source_id, GLuint dest_id, GLsizei width, GLsizei height, bool flip_y, bool premultiply_alpha, bool unpremultiply_alpha, const GLfloat transform_matrix[16]) { GLsizei dest_width = width; GLsizei dest_height = height; DoCopyTextureInternal(decoder, source_target, source_id, dest_id, 0, 0, 0, 0, width, height, dest_width, dest_height, width, height, flip_y, premultiply_alpha, unpremultiply_alpha, transform_matrix); } void CopyTextureCHROMIUMResourceManager::DoCopyTextureInternal( const gles2::GLES2Decoder* decoder, GLenum source_target, GLuint source_id, GLuint dest_id, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLsizei dest_width, GLsizei dest_height, GLsizei source_width, GLsizei source_height, bool flip_y, bool premultiply_alpha, bool unpremultiply_alpha, const GLfloat transform_matrix[16]) { DCHECK(source_target == GL_TEXTURE_2D || source_target == GL_TEXTURE_RECTANGLE_ARB || source_target == GL_TEXTURE_EXTERNAL_OES); DCHECK_GE(xoffset, 0); DCHECK_LE(xoffset + width, dest_width); DCHECK_GE(yoffset, 0); DCHECK_LE(yoffset + height, dest_height); if (!initialized_) { DLOG(ERROR) << "CopyTextureCHROMIUM: Uninitialized manager."; return; } VertexShaderId vertex_shader_id = GetVertexShaderId(flip_y); DCHECK_LT(static_cast<size_t>(vertex_shader_id), vertex_shaders_.size()); FragmentShaderId fragment_shader_id = GetFragmentShaderId( premultiply_alpha, unpremultiply_alpha, source_target); DCHECK_LT(static_cast<size_t>(fragment_shader_id), fragment_shaders_.size()); ProgramMapKey key(vertex_shader_id, fragment_shader_id); ProgramInfo* info = &programs_[key]; // Create program if necessary. if (!info->program) { info->program = glCreateProgram(); GLuint* vertex_shader = &vertex_shaders_[vertex_shader_id]; if (!*vertex_shader) { *vertex_shader = glCreateShader(GL_VERTEX_SHADER); CompileShader(*vertex_shader, vertex_shader_source[vertex_shader_id]); } glAttachShader(info->program, *vertex_shader); GLuint* fragment_shader = &fragment_shaders_[fragment_shader_id]; if (!*fragment_shader) { *fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); CompileShader(*fragment_shader, fragment_shader_source[fragment_shader_id]); } glAttachShader(info->program, *fragment_shader); glBindAttribLocation(info->program, kVertexPositionAttrib, "a_position"); glLinkProgram(info->program); #ifndef NDEBUG GLint linked; glGetProgramiv(info->program, GL_LINK_STATUS, &linked); if (!linked) DLOG(ERROR) << "CopyTextureCHROMIUM: program link failure."; #endif info->vertex_translate_handle = glGetUniformLocation(info->program, "u_vertex_translate"); info->tex_coord_transform_handle = glGetUniformLocation(info->program, "u_tex_coord_transform"); info->half_size_handle = glGetUniformLocation(info->program, "u_half_size"); info->sampler_handle = glGetUniformLocation(info->program, "u_sampler"); } glUseProgram(info->program); glUniformMatrix4fv(info->tex_coord_transform_handle, 1, GL_FALSE, transform_matrix); GLint x_translate = xoffset - x; GLint y_translate = yoffset - y; if (!x_translate && !y_translate) { glUniform2f(info->vertex_translate_handle, 0.0f, 0.0f); } else { // transform offsets from ([0, dest_width], [0, dest_height]) coord. // to ([-1, 1], [-1, 1]) coord. GLfloat x_translate_on_vertex = ((2.f * x_translate) / dest_width); GLfloat y_translate_on_vertex = ((2.f * y_translate) / dest_height); // Pass translation to the shader program. glUniform2f(info->vertex_translate_handle, x_translate_on_vertex, y_translate_on_vertex); } if (source_target == GL_TEXTURE_RECTANGLE_ARB) glUniform2f(info->half_size_handle, source_width / 2.0f, source_height / 2.0f); else glUniform2f(info->half_size_handle, 0.5f, 0.5f); if (BindFramebufferTexture2D(GL_TEXTURE_2D, dest_id, framebuffer_)) { #ifndef NDEBUG // glValidateProgram of MACOSX validates FBO unlike other platforms, so // glValidateProgram must be called after FBO binding. crbug.com/463439 glValidateProgram(info->program); GLint validation_status; glGetProgramiv(info->program, GL_VALIDATE_STATUS, &validation_status); if (GL_TRUE != validation_status) { DLOG(ERROR) << "CopyTextureCHROMIUM: Invalid shader."; return; } #endif decoder->ClearAllAttributes(); glEnableVertexAttribArray(kVertexPositionAttrib); glBindBuffer(GL_ARRAY_BUFFER, buffer_id_); glVertexAttribPointer(kVertexPositionAttrib, 2, GL_FLOAT, GL_FALSE, 0, 0); glUniform1i(info->sampler_handle, 0); glBindTexture(source_target, source_id); glTexParameterf(source_target, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterf(source_target, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(source_target, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(source_target, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glDisable(GL_DEPTH_TEST); glDisable(GL_STENCIL_TEST); glDisable(GL_CULL_FACE); glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE); glDepthMask(GL_FALSE); glDisable(GL_BLEND); bool need_scissor = xoffset || yoffset || width != dest_width || height != dest_height; if (need_scissor) { glEnable(GL_SCISSOR_TEST); glScissor(xoffset, yoffset, width, height); } else { glDisable(GL_SCISSOR_TEST); } glViewport(0, 0, dest_width, dest_height); glDrawArrays(GL_TRIANGLE_FAN, 0, 4); } decoder->RestoreAllAttributes(); decoder->RestoreTextureState(source_id); decoder->RestoreTextureState(dest_id); decoder->RestoreTextureUnitBindings(0); decoder->RestoreActiveTexture(); decoder->RestoreProgramBindings(); decoder->RestoreBufferBindings(); decoder->RestoreFramebufferBindings(); decoder->RestoreGlobalState(); } } // namespace gpu
Teamxrtc/webrtc-streaming-node
third_party/webrtc/src/chromium/src/gpu/command_buffer/service/gles2_cmd_copy_texture_chromium.cc
C++
mit
22,247
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.resources.implementation; import com.fasterxml.jackson.annotation.JsonProperty; import com.microsoft.azure.Page; import java.util.List; /** * An instance of this class defines a page of Azure resources and a link to * get the next page of resources, if any. * * @param <T> type of Azure resource */ public class PageImpl<T> implements Page<T> { /** * The link to the next page. */ @JsonProperty("nextLink") private String nextPageLink; /** * The list of items. */ @JsonProperty("value") private List<T> items; /** * Gets the link to the next page. * * @return the link to the next page. */ @Override public String nextPageLink() { return this.nextPageLink; } /** * Gets the list of items. * * @return the list of items in {@link List}. */ @Override public List<T> items() { return items; } /** * Sets the link to the next page. * * @param nextPageLink the link to the next page. * @return this Page object itself. */ public PageImpl<T> setNextPageLink(String nextPageLink) { this.nextPageLink = nextPageLink; return this; } /** * Sets the list of items. * * @param items the list of items in {@link List}. * @return this Page object itself. */ public PageImpl<T> setItems(List<T> items) { this.items = items; return this; } }
jianghaolu/azure-sdk-for-java
azure-mgmt-resources/src/main/java/com/microsoft/azure/management/resources/implementation/PageImpl.java
Java
mit
1,747
@extends($master) @section('page', trans('ticketit::admin.category-edit-title', ['name' => ucwords($category->name)])) @section('content') @include('ticketit::shared.header') <div class="well bs-component"> {!! CollectiveForm::model($category, [ 'route' => [$setting->grab('admin_route').'.category.update', $category->id], 'method' => 'PATCH', 'class' => 'form-horizontal' ]) !!} <legend>{{ trans('ticketit::admin.category-edit-title', ['name' => ucwords($category->name)]) }}</legend> @include('ticketit::admin.category.form', ['update', true]) {!! CollectiveForm::close() !!} </div> @stop
thekordy/ticketit
src/Views/bootstrap3/admin/category/edit.blade.php
PHP
mit
781
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Api2 * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Request content interpreter factory * * @category Mage * @package Mage_Api2 * @author Magento Core Team <core@magentocommerce.com> */ abstract class Mage_Api2_Model_Request_Interpreter { /** * Request body interpreters factory * * @param string $type * @return Mage_Api2_Model_Request_Interpreter_Interface * @throws Exception|Mage_Api2_Exception */ public static function factory($type) { /** @var $helper Mage_Api2_Helper_Data */ $helper = Mage::helper('api2/data'); $adapters = $helper->getRequestInterpreterAdapters(); if (empty($adapters) || !is_array($adapters)) { throw new Exception('Request interpreter adapters is not set.'); } $adapterModel = null; foreach ($adapters as $item) { $itemType = $item->type; if ($itemType == $type) { $adapterModel = $item->model; break; } } if ($adapterModel === null) { throw new Mage_Api2_Exception( sprintf('Server can not understand Content-Type HTTP header media type "%s"', $type), Mage_Api2_Model_Server::HTTP_BAD_REQUEST ); } $adapter = Mage::getModel($adapterModel); if (!$adapter) { throw new Exception(sprintf('Request interpreter adapter "%s" not found.', $type)); } return $adapter; } }
hansbonini/cloud9-magento
www/app/code/core/Mage/Api2/Model/Request/Interpreter.php
PHP
mit
2,436
/*************************************************************************/ /* control_editor_plugin.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* http://www.godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */ /* */ /* 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. */ /*************************************************************************/ #if 0 #include "control_editor_plugin.h" #include "print_string.h" #include "editor_node.h" #include "os/keyboard.h" #include "scene/main/viewport.h" void ControlEditor::_add_control(Control *p_control,const EditInfo& p_info) { if (controls.has(p_control)) return; controls.insert(p_control,p_info); p_control->call_deferred("connect","visibility_changed",this,"_visibility_changed",varray(p_control->get_instance_ID())); } void ControlEditor::_remove_control(Control *p_control) { p_control->call_deferred("disconnect","visibility_changed",this,"_visibility_changed"); controls.erase(p_control); } void ControlEditor::_clear_controls(){ while(controls.size()) _remove_control(controls.front()->key()); } void ControlEditor::_visibility_changed(ObjectID p_control) { Object *c = ObjectDB::get_instance(p_control); if (!c) return; Control *ct = c->cast_to<Control>(); if (!ct) return; _remove_control(ct); } void ControlEditor::_node_removed(Node *p_node) { Control *control = (Control*)p_node; //not a good cast, but safe if (controls.has(control)) _remove_control(control); if (current_window==p_node) { _clear_controls(); } update(); } // slow as hell Control* ControlEditor::_select_control_at_pos(const Point2& p_pos,Node* p_node) { for (int i=p_node->get_child_count()-1;i>=0;i--) { Control *r=_select_control_at_pos(p_pos,p_node->get_child(i)); if (r) return r; } Control *c=p_node->cast_to<Control>(); if (c) { Rect2 rect = c->get_window_rect(); if (c->get_window()==current_window) { rect.pos=transform.xform(rect.pos).floor(); } if (rect.has_point(p_pos)) return c; } return NULL; } void ControlEditor::_key_move(const Vector2& p_dir, bool p_snap) { if (drag!=DRAG_NONE) return; Vector2 motion=p_dir; if (p_snap) motion*=snap_val->get_text().to_double(); undo_redo->create_action("Edit Control"); for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); undo_redo->add_do_method(control,"set_pos",control->get_pos()+motion); undo_redo->add_undo_method(control,"set_pos",control->get_pos()); } undo_redo->commit_action(); } void ControlEditor::_input_event(InputEvent p_event) { if (p_event.type==InputEvent::MOUSE_BUTTON) { const InputEventMouseButton &b=p_event.mouse_button; if (b.button_index==BUTTON_RIGHT) { if (controls.size() && drag!=DRAG_NONE) { //cancel drag for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); control->set_pos(E->get().drag_pos); control->set_size(E->get().drag_size); } } else if (b.pressed) { popup->set_pos(Point2(b.x,b.y)); popup->popup(); } return; } //if (!controls.size()) // return; if (b.button_index!=BUTTON_LEFT) return; if (!b.pressed) { if (drag!=DRAG_NONE) { if (undo_redo) { undo_redo->create_action("Edit Control"); for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); undo_redo->add_do_method(control,"set_pos",control->get_pos()); undo_redo->add_do_method(control,"set_size",control->get_size()); undo_redo->add_undo_method(control,"set_pos",E->get().drag_pos); undo_redo->add_undo_method(control,"set_size",E->get().drag_size); } undo_redo->commit_action(); } drag=DRAG_NONE; } return; } if (controls.size()==1) { //try single control edit Control *control = controls.front()->key(); ERR_FAIL_COND(!current_window); Rect2 rect=control->get_window_rect(); Point2 ofs=Point2();//get_global_pos(); Rect2 draw_rect=Rect2(rect.pos-ofs,rect.size); Point2 click=Point2(b.x,b.y); click = transform.affine_inverse().xform(click); Size2 handle_size=Size2(handle_len,handle_len); drag = DRAG_NONE; if (Rect2(draw_rect.pos-handle_size,handle_size).has_point(click)) drag=DRAG_TOP_LEFT; else if (Rect2(draw_rect.pos+draw_rect.size,handle_size).has_point(click)) drag=DRAG_BOTTOM_RIGHT; else if(Rect2(draw_rect.pos+Point2(draw_rect.size.width,-handle_size.y),handle_size).has_point(click)) drag=DRAG_TOP_RIGHT; else if (Rect2(draw_rect.pos+Point2(-handle_size.x,draw_rect.size.height),handle_size).has_point(click)) drag=DRAG_BOTTOM_LEFT; else if (Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),-handle_size.height),handle_size).has_point(click)) drag=DRAG_TOP; else if( Rect2(draw_rect.pos+Point2(-handle_size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size).has_point(click)) drag=DRAG_LEFT; else if ( Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),draw_rect.size.height),handle_size).has_point(click)) drag=DRAG_BOTTOM; else if( Rect2(draw_rect.pos+Point2(draw_rect.size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size).has_point(click)) drag=DRAG_RIGHT; if (drag!=DRAG_NONE) { drag_from=click; controls[control].drag_pos=control->get_pos(); controls[control].drag_size=control->get_size(); controls[control].drag_limit=drag_from+controls[control].drag_size-control->get_minimum_size(); return; } } //multi control edit Point2 click=Point2(b.x,b.y); Node* scene = get_scene()->get_root_node()->cast_to<EditorNode>()->get_edited_scene(); if (!scene) return; /* if (current_window) { //no window.... ? click-=current_window->get_scroll(); }*/ Control *c=_select_control_at_pos(click, scene); Node* n = c; while ((n && n != scene && n->get_owner() != scene) || (n && !n->is_type("Control"))) { n = n->get_parent(); }; c = n->cast_to<Control>(); if (b.mod.control) { //additive selection if (!c) return; //nothing to add if (current_window && controls.size() && c->get_window()!=current_window) return; //cant multiple select from multiple windows if (!controls.size()) current_window=c->get_window(); if (controls.has(c)) { //already in here, erase it _remove_control(c); update(); return; } //check parents! Control *parent = c->get_parent()->cast_to<Control>(); while(parent) { if (controls.has(parent)) return; //a parent is already selected, so this is pointless parent=parent->get_parent()->cast_to<Control>(); } //check childrens of everything! List<Control*> to_erase; for(ControlMap::Element *E=controls.front();E;E=E->next()) { parent = E->key()->get_parent()->cast_to<Control>(); while(parent) { if (parent==c) { to_erase.push_back(E->key()); break; } parent=parent->get_parent()->cast_to<Control>(); } } while(to_erase.size()) { _remove_control(to_erase.front()->get()); to_erase.pop_front(); } _add_control(c,EditInfo()); update(); } else { //regular selection if (!c) { _clear_controls(); update(); return; } if (!controls.has(c)) { _clear_controls(); current_window=c->get_window(); _add_control(c,EditInfo()); //reselect if (get_scene()->is_editor_hint()) { get_scene()->get_root_node()->call("edit_node",c); } } for(ControlMap::Element *E=controls.front();E;E=E->next()) { EditInfo &ei=E->get(); Control *control=E->key(); ei.drag_pos=control->get_pos(); ei.drag_size=control->get_size(); ei.drag_limit=drag_from+ei.drag_size-control->get_minimum_size(); } drag=DRAG_ALL; drag_from=click; update(); } } if (p_event.type==InputEvent::MOUSE_MOTION) { const InputEventMouseMotion &m=p_event.mouse_motion; if (drag==DRAG_NONE || !current_window) return; for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); Point2 control_drag_pos=E->get().drag_pos; Point2 control_drag_size=E->get().drag_size; Point2 control_drag_limit=E->get().drag_limit; Point2 pos=Point2(m.x,m.y); pos = transform.affine_inverse().xform(pos); switch(drag) { case DRAG_ALL: { control->set_pos( snapify(control_drag_pos+(pos-drag_from)) ); } break; case DRAG_RIGHT: { control->set_size( snapify(Size2(control_drag_size.width+(pos-drag_from).x,control_drag_size.height)) ); } break; case DRAG_BOTTOM: { control->set_size( snapify(Size2(control_drag_size.width,control_drag_size.height+(pos-drag_from).y)) ); } break; case DRAG_BOTTOM_RIGHT: { control->set_size( snapify(control_drag_size+(pos-drag_from)) ); } break; case DRAG_TOP_LEFT: { if(pos.x>control_drag_limit.x) pos.x=control_drag_limit.x; if(pos.y>control_drag_limit.y) pos.y=control_drag_limit.y; Point2 old_size = control->get_size(); Point2 new_pos = snapify(control_drag_pos+(pos-drag_from)); Point2 new_size = old_size + (control->get_pos() - new_pos); control->set_pos( new_pos ); control->set_size( new_size ); } break; case DRAG_TOP: { if(pos.y>control_drag_limit.y) pos.y=control_drag_limit.y; Point2 old_size = control->get_size(); Point2 new_pos = snapify(control_drag_pos+Point2(0,pos.y-drag_from.y)); Point2 new_size = old_size + (control->get_pos() - new_pos); control->set_pos( new_pos ); control->set_size( new_size ); } break; case DRAG_LEFT: { if(pos.x>control_drag_limit.x) pos.x=control_drag_limit.x; Point2 old_size = control->get_size(); Point2 new_pos = snapify(control_drag_pos+Point2(pos.x-drag_from.x,0)); Point2 new_size = old_size + (control->get_pos() - new_pos); control->set_pos( new_pos ); control->set_size( new_size ); } break; case DRAG_TOP_RIGHT: { if(pos.y>control_drag_limit.y) pos.y=control_drag_limit.y; Point2 old_size = control->get_size(); Point2 new_pos = snapify(control_drag_pos+Point2(0,pos.y-drag_from.y)); float new_size_y = Point2( old_size + (control->get_pos() - new_pos)).y; float new_size_x = snapify(control_drag_size+Point2(pos.x-drag_from.x,0)).x; control->set_pos( new_pos ); control->set_size( Point2(new_size_x, new_size_y) ); } break; case DRAG_BOTTOM_LEFT: { if(pos.x>control_drag_limit.x) pos.x=control_drag_limit.x; Point2 old_size = control->get_size(); Point2 new_pos = snapify(control_drag_pos+Point2(pos.x-drag_from.x,0)); float new_size_y = snapify(control_drag_size+Point2(0,pos.y-drag_from.y)).y; float new_size_x = Point2( old_size + (control->get_pos() - new_pos)).x; control->set_pos( new_pos ); control->set_size( Point2(new_size_x, new_size_y) ); } break; default:{} } } } if (p_event.type==InputEvent::KEY) { const InputEventKey &k=p_event.key; if (k.pressed) { if (k.scancode==KEY_UP) _key_move(Vector2(0,-1),k.mod.shift); else if (k.scancode==KEY_DOWN) _key_move(Vector2(0,1),k.mod.shift); else if (k.scancode==KEY_LEFT) _key_move(Vector2(-1,0),k.mod.shift); else if (k.scancode==KEY_RIGHT) _key_move(Vector2(1,0),k.mod.shift); } } } bool ControlEditor::get_remove_list(List<Node*> *p_list) { for(ControlMap::Element *E=controls.front();E;E=E->next()) { p_list->push_back(E->key()); } return !p_list->empty(); } void ControlEditor::_update_scroll(float) { if (updating_scroll) return; if (!current_window) return; Point2 ofs; ofs.x=h_scroll->get_val(); ofs.y=v_scroll->get_val(); // current_window->set_scroll(-ofs); transform=Matrix32(); transform.scale_basis(Size2(zoom,zoom)); transform.elements[2]=-ofs*zoom; RID viewport = editor->get_scene_root()->get_viewport(); VisualServer::get_singleton()->viewport_set_global_canvas_transform(viewport,transform); update(); } void ControlEditor::_notification(int p_what) { if (p_what==NOTIFICATION_PROCESS) { for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); Rect2 r=control->get_window_rect(); if (r != E->get().last_rect ) { update(); E->get().last_rect=r; } } } if (p_what==NOTIFICATION_CHILDREN_CONFIGURED) { get_scene()->connect("node_removed",this,"_node_removed"); } if (p_what==NOTIFICATION_DRAW) { // TODO fetch the viewport? /* if (!control) { h_scroll->hide(); v_scroll->hide(); return; } */ _update_scrollbars(); if (!current_window) return; for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); Rect2 rect=control->get_window_rect(); RID ci=get_canvas_item(); VisualServer::get_singleton()->canvas_item_set_clip(ci,true); Point2 ofs=Point2();//get_global_pos(); Rect2 draw_rect=Rect2(rect.pos-ofs,rect.size); draw_rect.pos = transform.xform(draw_rect.pos); Color light_edit_color=Color(1.0,0.8,0.8); Color dark_edit_color=Color(0.4,0.1,0.1); Size2 handle_size=Size2(handle_len,handle_len); #define DRAW_RECT( m_rect, m_color )\ VisualServer::get_singleton()->canvas_item_add_rect(ci,m_rect,m_color); #define DRAW_EMPTY_RECT( m_rect, m_color )\ DRAW_RECT( Rect2(m_rect.pos,Size2(m_rect.size.width,1)), m_color );\ DRAW_RECT(Rect2(Point2(m_rect.pos.x,m_rect.pos.y+m_rect.size.height-1),Size2(m_rect.size.width,1)), m_color);\ DRAW_RECT(Rect2(m_rect.pos,Size2(1,m_rect.size.height)), m_color);\ DRAW_RECT(Rect2(Point2(m_rect.pos.x+m_rect.size.width-1,m_rect.pos.y),Size2(1,m_rect.size.height)), m_color); #define DRAW_BORDER_RECT( m_rect, m_border_color,m_color )\ DRAW_RECT( m_rect, m_color );\ DRAW_EMPTY_RECT( m_rect, m_border_color ); DRAW_EMPTY_RECT( draw_rect.grow(2), light_edit_color ); DRAW_EMPTY_RECT( draw_rect.grow(1), dark_edit_color ); if (controls.size()==1) { DRAW_BORDER_RECT( Rect2(draw_rect.pos-handle_size,handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+draw_rect.size,handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(draw_rect.size.width,-handle_size.y),handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(-handle_size.x,draw_rect.size.height),handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),-handle_size.height),handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(-handle_size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(Math::floor((draw_rect.size.width-handle_size.x)/2.0),draw_rect.size.height),handle_size), light_edit_color,dark_edit_color ); DRAW_BORDER_RECT( Rect2(draw_rect.pos+Point2(draw_rect.size.width,Math::floor((draw_rect.size.height-handle_size.y)/2.0)),handle_size), light_edit_color,dark_edit_color ); } //DRAW_EMPTY_RECT( Rect2( current_window->get_scroll()-Point2(1,1), get_size()+Size2(2,2)), Color(0.8,0.8,1.0,0.8) ); E->get().last_rect = rect; } } } void ControlEditor::edit(Control *p_control) { drag=DRAG_NONE; _clear_controls(); _add_control(p_control,EditInfo()); current_window=p_control->get_window(); update(); } void ControlEditor::_find_controls_span(Node *p_node, Rect2& r_rect) { if (!editor->get_scene()) return; if (p_node!=editor->get_edited_scene() && p_node->get_owner()!=editor->get_edited_scene()) return; if (p_node->cast_to<Control>()) { Control *c = p_node->cast_to<Control>(); if (c->get_viewport() != editor->get_viewport()->get_viewport()) return; //bye, it's in another viewport if (!c->get_parent_control()) { Rect2 span = c->get_subtree_span_rect(); r_rect.merge(span); } } for(int i=0;i<p_node->get_child_count();i++) { _find_controls_span(p_node->get_child(i),r_rect); } } void ControlEditor::_update_scrollbars() { if (!editor->get_scene()) { h_scroll->hide(); v_scroll->hide(); return; } updating_scroll=true; Size2 size = get_size(); Size2 hmin = h_scroll->get_minimum_size(); Size2 vmin = v_scroll->get_minimum_size(); v_scroll->set_begin( Point2(size.width - vmin.width, 0) ); v_scroll->set_end( Point2(size.width, size.height) ); h_scroll->set_begin( Point2( 0, size.height - hmin.height) ); h_scroll->set_end( Point2(size.width-vmin.width, size.height) ); Rect2 local_rect = Rect2(Point2(),get_size()-Size2(vmin.width,hmin.height)); Rect2 control_rect=local_rect; if (editor->get_edited_scene()) _find_controls_span(editor->get_edited_scene(),control_rect); control_rect.pos*=zoom; control_rect.size*=zoom; /* for(ControlMap::Element *E=controls.front();E;E=E->next()) { Control *control = E->key(); Rect2 r = control->get_window()->get_subtree_span_rect(); if (E==controls.front()) { control_rect = r.merge(local_rect); } else { control_rect = control_rect.merge(r); } } */ Point2 ofs; if (control_rect.size.height <= local_rect.size.height) { v_scroll->hide(); ofs.y=0; } else { v_scroll->show(); v_scroll->set_min(control_rect.pos.y); v_scroll->set_max(control_rect.pos.y+control_rect.size.y); v_scroll->set_page(local_rect.size.y); ofs.y=-v_scroll->get_val(); } if (control_rect.size.width <= local_rect.size.width) { h_scroll->hide(); ofs.x=0; } else { h_scroll->show(); h_scroll->set_min(control_rect.pos.x); h_scroll->set_max(control_rect.pos.x+control_rect.size.x); h_scroll->set_page(local_rect.size.x); ofs.x=-h_scroll->get_val(); } // transform=Matrix32(); transform.elements[2]=ofs*zoom; RID viewport = editor->get_scene_root()->get_viewport(); VisualServer::get_singleton()->viewport_set_global_canvas_transform(viewport,transform); // transform.scale_basis(Vector2(zoom,zoom)); updating_scroll=false; } Point2i ControlEditor::snapify(const Point2i& p_pos) const { bool active=popup->is_item_checked(0); int snap = snap_val->get_text().to_int(); if (!active || snap<1) return p_pos; Point2i pos=p_pos; pos.x-=pos.x%snap; pos.y-=pos.y%snap; return pos; } void ControlEditor::_popup_callback(int p_op) { switch(p_op) { case SNAP_USE: { popup->set_item_checked(0,!popup->is_item_checked(0)); } break; case SNAP_CONFIGURE: { snap_dialog->popup_centered(Size2(200,85)); } break; } } void ControlEditor::_bind_methods() { ObjectTypeDB::bind_method("_input_event",&ControlEditor::_input_event); ObjectTypeDB::bind_method("_node_removed",&ControlEditor::_node_removed); ObjectTypeDB::bind_method("_update_scroll",&ControlEditor::_update_scroll); ObjectTypeDB::bind_method("_popup_callback",&ControlEditor::_popup_callback); ObjectTypeDB::bind_method("_visibility_changed",&ControlEditor::_visibility_changed); } ControlEditor::ControlEditor(EditorNode *p_editor) { editor=p_editor; h_scroll = memnew( HScrollBar ); v_scroll = memnew( VScrollBar ); add_child(h_scroll); add_child(v_scroll); h_scroll->connect("value_changed", this,"_update_scroll",Vector<Variant>(),true); v_scroll->connect("value_changed", this,"_update_scroll",Vector<Variant>(),true); updating_scroll=false; set_focus_mode(FOCUS_ALL); handle_len=10; popup=memnew( PopupMenu ); popup->add_check_item("Use Snap"); popup->add_item("Configure Snap.."); add_child(popup); snap_dialog = memnew( ConfirmationDialog ); snap_dialog->get_ok()->hide(); snap_dialog->get_cancel()->set_text("Close"); add_child(snap_dialog); Label *l = memnew(Label); l->set_text("Snap:"); l->set_pos(Point2(5,5)); snap_dialog->add_child(l); snap_val=memnew(LineEdit); snap_val->set_text("5"); snap_val->set_anchor(MARGIN_RIGHT,ANCHOR_END); snap_val->set_begin(Point2(15,25)); snap_val->set_end(Point2(10,25)); snap_dialog->add_child(snap_val); popup->connect("item_pressed", this,"_popup_callback"); current_window=NULL; zoom=0.5; } void ControlEditorPlugin::edit(Object *p_object) { control_editor->set_undo_redo(&get_undo_redo()); control_editor->edit(p_object->cast_to<Control>()); } bool ControlEditorPlugin::handles(Object *p_object) const { return p_object->is_type("Control"); } void ControlEditorPlugin::make_visible(bool p_visible) { if (p_visible) { control_editor->show(); control_editor->set_process(true); } else { control_editor->hide(); control_editor->set_process(false); } } ControlEditorPlugin::ControlEditorPlugin(EditorNode *p_node) { editor=p_node; control_editor = memnew( ControlEditor(editor) ); editor->get_viewport()->add_child(control_editor); control_editor->set_area_as_parent_rect(); control_editor->hide(); } ControlEditorPlugin::~ControlEditorPlugin() { } #endif
tomasy23/evertonkrosnodart
tools/editor/plugins/control_editor_plugin.cpp
C++
mit
22,889
// // ConvertLambdaBodyExpressionToStatementAction.cs // // Author: // Mansheng Yang <lightyang0@gmail.com> // // Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace ICSharpCode.NRefactory.CSharp.Refactoring { [ContextAction ("Converts expression of lambda body to statement", Description = "Converts expression of lambda body to statement")] public class ConvertLambdaBodyExpressionToStatementAction : SpecializedCodeAction<LambdaExpression> { protected override CodeAction GetAction (RefactoringContext context, LambdaExpression node) { if (!node.ArrowToken.Contains (context.Location)) return null; var bodyExpr = node.Body as Expression; if (bodyExpr == null) return null; return new CodeAction (context.TranslateString ("Convert to lambda statement"), script => { var body = new BlockStatement (); if (RequireReturnStatement (context, node)) { body.Add (new ReturnStatement (bodyExpr.Clone ())); } else { body.Add (new ExpressionStatement (bodyExpr.Clone ())); } script.Replace (bodyExpr, body); }); } static bool RequireReturnStatement (RefactoringContext context, LambdaExpression lambda) { var type = LambdaHelper.GetLambdaReturnType (context, lambda); return type != null && type.ReflectionName != "System.Void"; } } }
praeclarum/Netjs
Netjs/Dependencies/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ConvertLambdaBodyExpressionToStatementAction.cs
C#
mit
2,431
<?php /** * Magento * * NOTICE OF LICENSE * * This source file is subject to the Open Software License (OSL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/osl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@magento.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade Magento to newer * versions in the future. If you wish to customize Magento for your * needs please refer to http://www.magento.com for more information. * * @category Mage * @package Mage_Cms * @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com) * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) */ /** * Cms index controller * * @category Mage * @package Mage_Cms * @author Magento Core Team <core@magentocommerce.com> */ class Mage_Cms_IndexController extends Mage_Core_Controller_Front_Action { /** * Renders CMS Home page * * @param string $coreRoute */ public function indexAction($coreRoute = null) { $pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_HOME_PAGE); if (!Mage::helper('cms/page')->renderPage($this, $pageId)) { $this->_forward('defaultIndex'); } } /** * Default index action (with 404 Not Found headers) * Used if default page don't configure or available * */ public function defaultIndexAction() { $this->getResponse()->setHeader('HTTP/1.1','404 Not Found'); $this->getResponse()->setHeader('Status','404 File not found'); $this->loadLayout(); $this->renderLayout(); } /** * Render CMS 404 Not found page * * @param string $coreRoute */ public function noRouteAction($coreRoute = null) { $this->getResponse()->setHeader('HTTP/1.1','404 Not Found'); $this->getResponse()->setHeader('Status','404 File not found'); $pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_ROUTE_PAGE); if (!Mage::helper('cms/page')->renderPage($this, $pageId)) { $this->_forward('defaultNoRoute'); } } /** * Default no route page action * Used if no route page don't configure or available * */ public function defaultNoRouteAction() { $this->getResponse()->setHeader('HTTP/1.1','404 Not Found'); $this->getResponse()->setHeader('Status','404 File not found'); $this->loadLayout(); $this->renderLayout(); } /** * Render Disable cookies page * */ public function noCookiesAction() { $pageId = Mage::getStoreConfig(Mage_Cms_Helper_Page::XML_PATH_NO_COOKIES_PAGE); if (!Mage::helper('cms/page')->renderPage($this, $pageId)) { $this->_forward('defaultNoCookies');; } } /** * Default no cookies page action * Used if no cookies page don't configure or available * */ public function defaultNoCookiesAction() { $this->loadLayout(); $this->renderLayout(); } }
hansbonini/cloud9-magento
www/app/code/core/Mage/Cms/controllers/IndexController.php
PHP
mit
3,373
<?php /** * PHPUnit * * Copyright (c) 2002-2014, Sebastian Bergmann <sebastian@phpunit.de>. * 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 Sebastian Bergmann nor the names of his * 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. * * @package DbUnit * @author Mike Lively <m@digitalsandwich.com> * @copyright 2002-2014 Sebastian Bergmann <sebastian@phpunit.de> * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @link http://www.phpunit.de/ * @since File available since Release 1.0.0 */ /** * This class facilitates combining database operations. To create a composite * operation pass an array of classes that implement * PHPUnit_Extensions_Database_Operation_IDatabaseOperation and they will be * executed in that order against all data sets. * * @package DbUnit * @author Mike Lively <m@digitalsandwich.com> * @copyright 2010-2014 Mike Lively <m@digitalsandwich.com> * @license http://www.opensource.org/licenses/BSD-3-Clause The BSD 3-Clause License * @version Release: @package_version@ * @link http://www.phpunit.de/ * @since Class available since Release 1.0.0 */ class PHPUnit_Extensions_Database_Operation_Composite implements PHPUnit_Extensions_Database_Operation_IDatabaseOperation { /** * @var array */ protected $operations = array(); /** * Creates a composite operation. * * @param array $operations */ public function __construct(Array $operations) { foreach ($operations as $operation) { if ($operation instanceof PHPUnit_Extensions_Database_Operation_IDatabaseOperation) { $this->operations[] = $operation; } else { throw new InvalidArgumentException("Only database operation instances can be passed to a composite database operation."); } } } public function execute(PHPUnit_Extensions_Database_DB_IDatabaseConnection $connection, PHPUnit_Extensions_Database_DataSet_IDataSet $dataSet) { try { foreach ($this->operations as $operation) { /* @var $operation PHPUnit_Extensions_Database_Operation_IDatabaseOperation */ $operation->execute($connection, $dataSet); } } catch (PHPUnit_Extensions_Database_Operation_Exception $e) { throw new PHPUnit_Extensions_Database_Operation_Exception("COMPOSITE[{$e->getOperation()}]", $e->getQuery(), $e->getArgs(), $e->getTable(), $e->getError()); } } }
drBenway/siteResearch
vendor/phpunit/dbunit/PHPUnit/Extensions/Database/Operation/Composite_1.php
PHP
mit
3,983
export { default, DimmerProps } from './Dimmer';
aabustamante/Semantic-UI-React
src/modules/Dimmer/index.d.ts
TypeScript
mit
49
package keyseq type TernaryTrie struct { root TernaryNode } func NewTernaryTrie() *TernaryTrie { return &TernaryTrie{} } func (t *TernaryTrie) Root() Node { return &t.root } func (t *TernaryTrie) GetList(k KeyList) Node { return Get(t, k) } func (t *TernaryTrie) Get(k Key) Node { return Get(t, KeyList{k}) } func (t *TernaryTrie) Put(k KeyList, v interface{}) Node { return Put(t, k, v) } func (t *TernaryTrie) Size() int { count := 0 EachDepth(t, func(Node) bool { count++ return true }) return count } func (t *TernaryTrie) Balance() { EachDepth(t, func(n Node) bool { n.(*TernaryNode).Balance() return true }) t.root.Balance() } type TernaryNode struct { label Key firstChild *TernaryNode low, high *TernaryNode value interface{} } func NewTernaryNode(l Key) *TernaryNode { return &TernaryNode{label: l} } func (n *TernaryNode) GetList(k KeyList) Node { return n.Get(k[0]) } func (n *TernaryNode) Get(k Key) Node { curr := n.firstChild for curr != nil { switch k.Compare(curr.label) { case 0: // equal return curr case -1: // less curr = curr.low default: //more curr = curr.high } } return nil } func (n *TernaryNode) Dig(k Key) (node Node, isnew bool) { curr := n.firstChild if curr == nil { n.firstChild = NewTernaryNode(k) return n.firstChild, true } for { switch k.Compare(curr.label) { case 0: return curr, false case -1: if curr.low == nil { curr.low = NewTernaryNode(k) return curr.low, true } curr = curr.low default: if curr.high == nil { curr.high = NewTernaryNode(k) return curr.high, true } curr = curr.high } } } func (n *TernaryNode) FirstChild() *TernaryNode { return n.firstChild } func (n *TernaryNode) HasChildren() bool { return n.firstChild != nil } func (n *TernaryNode) Size() int { if n.firstChild == nil { return 0 } count := 0 n.Each(func(Node) bool { count++ return true }) return count } func (n *TernaryNode) Each(proc func(Node) bool) { var f func(*TernaryNode) bool f = func(n *TernaryNode) bool { if n != nil { if !f(n.low) || !proc(n) || !f(n.high) { return false } } return true } f(n.firstChild) } func (n *TernaryNode) RemoveAll() { n.firstChild = nil } func (n *TernaryNode) Label() Key { return n.label } func (n *TernaryNode) Value() interface{} { return n.value } func (n *TernaryNode) SetValue(v interface{}) { n.value = v } func (n *TernaryNode) children() []*TernaryNode { children := make([]*TernaryNode, n.Size()) if n.firstChild == nil { return children } idx := 0 n.Each(func(child Node) bool { children[idx] = child.(*TernaryNode) idx++ return true }) return children } func (n *TernaryNode) Balance() { if n.firstChild == nil { return } children := n.children() for _, child := range children { child.low = nil child.high = nil } n.firstChild = balance(children, 0, len(children)) } func balance(nodes []*TernaryNode, s, e int) *TernaryNode { count := e - s if count <= 0 { return nil } else if count == 1 { return nodes[s] } else if count == 2 { nodes[s].high = nodes[s+1] return nodes[s] } else { mid := (s + e) / 2 n := nodes[mid] n.low = balance(nodes, s, mid) n.high = balance(nodes, mid+1, e) return n } }
dav009/peco
keyseq/ternary.go
GO
mit
3,295
using System; using System.IO; using Foundation; using UIKit; using CoreGraphics; using Dropbox.CoreApi.iOS; namespace DropboxCoreApiSample { public partial class TextViewController : UIViewController { // A TextField with Placeholder CustomUITextView textView; RestClient restClient; string filename; public TextViewController () { View.BackgroundColor = UIColor.White; // Will handle the save to Dropbox process var btnSave = new UIBarButtonItem ("Save", UIBarButtonItemStyle.Plain, WriteFile); btnSave.Enabled = false; // Create the TextField with a Placeholder textView = new CustomUITextView (CGRect.Empty, "Type something nice!"); textView.TranslatesAutoresizingMaskIntoConstraints = false; // If the user has written something, you can save the file textView.Changed += (sender, e) => btnSave.Enabled = textView.Text.Length != 0; // Rest client that will handle the file upload restClient = new RestClient (Session.SharedSession); // Once the file is on Dropbox, notify the user restClient.FileUploaded += (sender, e) => { new UIAlertView ("Saved on Dropbox", "The file was uploaded to Dropbox correctly", null, "OK", null).Show (); #if __UNIFIED__ NavigationController.PopViewController (true); #else NavigationController.PopViewControllerAnimated (true); #endif }; // Handle if something went wrong with the upload of the file restClient.LoadFileFailed += (sender, e) => { // Try to upload the file again var alertView = new UIAlertView ("Hmm...", "Something went wrong when trying to save the file on Dropbox...", null, "Not now", new [] { "Try Again" }); alertView.Clicked += (avSender, avE) => { if (avE.ButtonIndex == 1) restClient.UploadFile (filename, DropboxCredentials.FolderPath, null, Path.GetTempPath () + filename); }; alertView.Show (); }; // Add the view with its constraints View.Add (textView); NavigationItem.RightBarButtonItem = btnSave; AddConstraints (); } void AddConstraints () { var views = new NSDictionary ("textView", textView); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("H:|-0-[textView]-0-|", 0, null, views)); View.AddConstraints (NSLayoutConstraint.FromVisualFormat ("V:|-0-[textView]-0-|", 0, null, views)); } // Process to save the file on Dropbox void WriteFile (object sender, EventArgs e) { // Notify that the user has ended typing textView.EndEditing (true); // Ask for a name to the file var alertView = new UIAlertView ("Save to Dropbox", "Enter a name for the file", null, "Cancel", new [] { "Save" }); alertView.AlertViewStyle = UIAlertViewStyle.PlainTextInput; alertView.Clicked += (avSender, avE) => { // Once we have the name, we need to save the file locally first and then upload it to Dropbox if (avE.ButtonIndex == 1) { filename = alertView.GetTextField (0).Text + ".txt"; var fullPath = Path.GetTempPath () + filename; // Write the file locally File.WriteAllText (fullPath, textView.Text); // Now upload it to Dropbox restClient.UploadFile (filename, DropboxCredentials.FolderPath, null, fullPath); } }; alertView.Show (); } } }
JonDouglas/XamarinComponents
XPlat/DropboxCoreApi/iOS/samples/DropboxCoreApiSample/DropboxCoreApiSample/TextViewController.cs
C#
mit
3,244
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Data; using System.Drawing.Drawing2D; using System.Text; using System.Windows.Forms; using OpenLiveWriter.ApplicationFramework; using OpenLiveWriter.BlogClient; using OpenLiveWriter.Extensibility.BlogClient; using OpenLiveWriter.Localization; using OpenLiveWriter.Localization.Bidi; using OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl; using OpenLiveWriter.CoreServices; namespace OpenLiveWriter.PostEditor.PostPropertyEditing { /* * TODO * Bugs: - Visibility is all screwed up!! - Position of page-relevant labels vs. controls in dialog * Putting focus in a textbox that has a cue banner, causes dirty flag to be marked - Space should trigger View All - F2 during page context shows too many labels - Label visibility not staying in sync with control - Unchecking publish date in dialog doesn't set cue banner in band - Activate main window when dialog is dismissed - Some labels not localized - Labels do not have mnemonics - Clicking on View All should restore a visible but minimized dialog * Horizontal scrollbar sometimes flickers on - Trackback detailed label * Dropdown for Page Parent combo is not the right width * Each Page Parent combo makes its own delayed request - Tags control should share leftover space with category control x Properties dialog should hide and come back * * Questions: * Should Enter dismiss the properties dialog? * Should properties dialog scroll state be remembered between views? */ public partial class PostPropertiesBandControl : UserControl, IBlogPostEditor, IRtlAware, INewCategoryContext { private Blog _targetBlog; private IBlogClientOptions _clientOptions; private const int COL_CATEGORY = 0; private const int COL_TAGS = 1; private const int COL_DATE = 2; private const int COL_PAGEPARENTLABEL = 3; private const int COL_PAGEPARENT = 4; private const int COL_PAGEORDERLABEL = 5; private const int COL_PAGEORDER = 6; private const int COL_FILLER = 7; private const int COL_VIEWALL = 8; private readonly PostPropertiesForm postPropertiesForm; private readonly List<PropertyField> fields = new List<PropertyField>(); private readonly SharedPropertiesController controller; private readonly CategoryContext categoryContext; public PostPropertiesBandControl(CommandManager commandManager) { SetStyle(ControlStyles.UserPaint, true); SetStyle(ControlStyles.DoubleBuffer, true); SetStyle(ControlStyles.AllPaintingInWmPaint, true); SetStyle(ControlStyles.ResizeRedraw, true); InitializeComponent(); categoryContext = new CategoryContext(); controller = new SharedPropertiesController(this, null, categoryDropDown, null, textTags, labelPageOrder, textPageOrder, labelPageParent, comboPageParent, null, datePublishDate, fields, categoryContext); SimpleTextEditorCommandHelper.UseNativeBehaviors(commandManager, textTags, textPageOrder); postPropertiesForm = new PostPropertiesForm(commandManager, categoryContext); if (components == null) components = new Container(); components.Add(postPropertiesForm); postPropertiesForm.Synchronize(controller); commandManager.Add(CommandId.PostProperties, PostProperties_Execute); commandManager.Add(CommandId.ShowCategoryPopup, ShowCategoryPopup_Execute); linkViewAll.KeyDown += (sender, args) => { if (args.KeyValue == ' ') linkViewAll_LinkClicked(sender, new LinkLabelLinkClickedEventArgs(null)); }; // WinLive 180287: We don't want to show or use mnemonics on labels in the post properties band because // they can steal focus from the canvas. linkViewAll.Text = TextHelper.StripAmpersands(Res.Get(StringId.ViewAll)); linkViewAll.UseMnemonic = false; labelPageParent.Text = TextHelper.StripAmpersands(Res.Get(StringId.PropertiesPageParent)); labelPageParent.UseMnemonic = false; labelPageOrder.Text = TextHelper.StripAmpersands(Res.Get(StringId.PropertiesPageOrder)); labelPageOrder.UseMnemonic = false; } private void ShowCategoryPopup_Execute(object sender, EventArgs e) { if (postPropertiesForm.Visible) postPropertiesForm.DisplayCategoryForm(); else categoryDropDown.DisplayCategoryForm(); } protected override void OnLoad(EventArgs args) { base.OnLoad(args); FixCategoryDropDown(); } private void FixCategoryDropDown() { // Exactly align the sizes of the category control and the publish datetime picker control int nonItemHeight = categoryDropDown.Height - categoryDropDown.ItemHeight; categoryDropDown.ItemHeight = datePublishDate.Height - nonItemHeight; categoryDropDown.Height = datePublishDate.Height; datePublishDate.LocationChanged += delegate { // Exactly align the vertical position of the category control and the publish datetime picker control categoryDropDown.Anchor = categoryDropDown.Anchor | AnchorStyles.Top; Padding margin = categoryDropDown.Margin; margin.Top = datePublishDate.Top; categoryDropDown.Margin = margin; }; } private void PostProperties_Execute(object sender, EventArgs e) { if (!Visible) return; if (postPropertiesForm.Visible) postPropertiesForm.Hide(); else postPropertiesForm.Show(FindForm()); } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); Invalidate(); } protected override void OnPaintBackground(PaintEventArgs e) { // Without the height/width checks, minimizing and restoring causes painting to blow up if (!SystemInformation.HighContrast && table.Height > 0 && table.Width > 0 && panelShadow.Height > 0 && panelShadow.Width > 0) { using ( Brush brush = new LinearGradientBrush(table.Bounds, Color.FromArgb(0xDC, 0xE7, 0xF5), Color.White, LinearGradientMode.Vertical)) e.Graphics.FillRectangle(brush, table.Bounds); using ( Brush brush = new LinearGradientBrush(panelShadow.Bounds, Color.FromArgb(208, 208, 208), Color.White, LinearGradientMode.Vertical)) e.Graphics.FillRectangle(brush, panelShadow.Bounds); } else { e.Graphics.Clear(SystemColors.Window); } } private bool categoryVisible = true; private bool CategoryVisible { set { table.ColumnStyles[COL_CATEGORY].SizeType = value ? SizeType.Percent : SizeType.AutoSize; categoryDropDown.Visible = categoryVisible = value; ManageFillerVisibility(); } } private bool tagsVisible = true; private bool TagsVisible { set { table.ColumnStyles[COL_TAGS].SizeType = value ? SizeType.Percent : SizeType.AutoSize; textTags.Visible = tagsVisible = value; ManageFillerVisibility(); } } private void ManageFillerVisibility() { bool shouldShow = !categoryVisible && !tagsVisible; table.ColumnStyles[COL_FILLER].SizeType = shouldShow ? SizeType.Percent : SizeType.AutoSize; } private IBlogPostEditingContext _editorContext; public void Initialize(IBlogPostEditingContext editorContext, IBlogClientOptions clientOptions) { _editorContext = editorContext; _clientOptions = clientOptions; controller.Initialize(editorContext, clientOptions); ((IBlogPostEditor)postPropertiesForm).Initialize(editorContext, clientOptions); ManageLayout(); } private bool IsPage { get { return _editorContext != null && _editorContext.BlogPost != null ? _editorContext.BlogPost.IsPage : false; } } public void OnBlogChanged(Blog newBlog) { _clientOptions = newBlog.ClientOptions; _targetBlog = newBlog; controller.OnBlogChanged(newBlog); ((IBlogPostEditor)postPropertiesForm).OnBlogChanged(newBlog); ManageLayout(); } public void OnBlogSettingsChanged(bool templateChanged) { controller.OnBlogSettingsChanged(templateChanged); ((IBlogPostEditor)postPropertiesForm).OnBlogSettingsChanged(templateChanged); ManageLayout(); } private void ManageLayout() { if (IsPage) { bool showViewAll = _clientOptions.SupportsCommentPolicy || _clientOptions.SupportsPingPolicy || _clientOptions.SupportsAuthor || _clientOptions.SupportsSlug || _clientOptions.SupportsPassword; linkViewAll.Visible = showViewAll; CategoryVisible = false; TagsVisible = false; Visible = showViewAll || _clientOptions.SupportsPageParent || _clientOptions.SupportsPageOrder; } else { bool showViewAll = _clientOptions.SupportsCommentPolicy || _clientOptions.SupportsPingPolicy || _clientOptions.SupportsAuthor || _clientOptions.SupportsSlug || _clientOptions.SupportsPassword || _clientOptions.SupportsExcerpt || _clientOptions.SupportsTrackbacks; bool showTags = (_clientOptions.SupportsKeywords && (_clientOptions.KeywordsAsTags || _clientOptions.SupportsGetKeywords)); Visible = showViewAll || _clientOptions.SupportsCustomDate || showTags || _clientOptions.SupportsCategories; CategoryVisible = _clientOptions.SupportsCategories; TagsVisible = showTags; linkViewAll.Visible = showViewAll; } } public bool IsDirty { get { return controller.IsDirty || ((IBlogPostEditor)postPropertiesForm).IsDirty; } } public bool HasKeywords { get { return postPropertiesForm.HasKeywords; } } public void SaveChanges(BlogPost post, BlogPostSaveOptions options) { controller.SaveChanges(post, options); ((IBlogPostEditor)postPropertiesForm).SaveChanges(post, options); } public bool ValidatePublish() { return controller.ValidatePublish(); } public void OnPublishSucceeded(BlogPost blogPost, PostResult postResult) { controller.OnPublishSucceeded(blogPost, postResult); ((IBlogPostEditor)postPropertiesForm).OnPublishSucceeded(blogPost, postResult); } public void OnClosing(CancelEventArgs e) { controller.OnClosing(e); ((IBlogPostEditor)postPropertiesForm).OnClosing(e); } public void OnPostClosing(CancelEventArgs e) { controller.OnPostClosing(e); ((IBlogPostEditor)postPropertiesForm).OnPostClosing(e); } public void OnClosed() { controller.OnClosed(); ((IBlogPostEditor)postPropertiesForm).OnClosed(); } public void OnPostClosed() { controller.OnPostClosed(); ((IBlogPostEditor)postPropertiesForm).OnPostClosed(); } private void linkViewAll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (e.Button != MouseButtons.Left) return; if (!postPropertiesForm.Visible) postPropertiesForm.Show(FindForm()); else { if (postPropertiesForm.WindowState == FormWindowState.Minimized) postPropertiesForm.WindowState = FormWindowState.Normal; postPropertiesForm.Activate(); } } void IRtlAware.Layout() { } #region Implementation of INewCategoryContext public void NewCategoryAdded(BlogPostCategory category) { controller.NewCategoryAdded(category); } #endregion } }
adilmughal/OpenLiveWriter
src/managed/OpenLiveWriter.PostEditor/PostPropertyEditing/PostPropertiesBandControl.cs
C#
mit
13,831
<?php /** * PHPExcel * * Copyright (c) 2006 - 2007 PHPExcel, Maarten Balliauw * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @copyright Copyright (c) 2006 - 2007 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/gpl.txt GPL */ /** * This file creates a build of PHPExcel */ // Starting build echo date('H:i:s') . " Starting build...\n"; // Specify paths and files to include $aFilesToInclude = array('../changelog.txt', '../install.txt', '../license.txt'); $aPathsToInclude = array('../Classes', '../Tests', '../Documentation'); // Resulting file $strResultingFile = 'LatestBuild.zip'; // Create new ZIP file and open it for writing echo date('H:i:s') . " Creating ZIP archive...\n"; $objZip = new ZipArchive(); // Try opening the ZIP file if ($objZip->open($strResultingFile, ZIPARCHIVE::OVERWRITE) !== true) { throw new Exeption("Could not open " . $strResultingFile . " for writing!"); } // Add files to include foreach ($aFilesToInclude as $strFile) { echo date('H:i:s') . " Adding file $strFile\n"; $objZip->addFile($strFile, cleanFileName($strFile)); } // Add paths to include foreach ($aPathsToInclude as $strPath) { addPathToZIP($strPath, $objZip); } // Set archive comment... echo date('H:i:s') . " Set archive comment...\n"; $objZip->setArchiveComment('PHPExcel - http://www.codeplex.com/PHPExcel'); // Close file echo date('H:i:s') . " Saving ZIP archive...\n"; $objZip->close(); // Finished build echo date('H:i:s') . " Finished build!\n"; /** * Add a specific path's files and folders to a ZIP object * * @param string $strPath Path to add * @param ZipArchive $objZip ZipArchive object */ function addPathToZIP($strPath, $objZip) { echo date('H:i:s') . " Adding path $strPath...\n"; $currentDir = opendir($strPath); while ($strFile = readdir($currentDir)) { if ($strFile != '.' && $strFile != '..') { if (is_file($strPath . '/' . $strFile)) { $objZip->addFile($strPath . '/' . $strFile, cleanFileName($strPath . '/' . $strFile)); } else if (is_dir($strPath . '/' . $strFile)) { if (!eregi('.svn', $strFile)) { addPathToZIP( ($strPath . '/' . $strFile), $objZip ); } } } } } /** * Cleanup a filename * * @param string $strFile Filename * @return string Filename */ function cleanFileName($strFile) { $strFile = str_replace('../', '', $strFile); $strFile = str_replace('WINDOWS', '', $strFile); while (eregi('//', $strFile)) { $strFile = str_replace('//', '/', $strFile); } return $strFile; }
ALTELMA/OfficeEquipmentManager
application/libraries/PHPExcel/branches/v1.1.1/Build/build.php
PHP
mit
3,220
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Bot.Connector { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; /// <summary> /// Attachment View name and size /// </summary> public partial class AttachmentView { /// <summary> /// Initializes a new instance of the AttachmentView class. /// </summary> public AttachmentView() { } /// <summary> /// Initializes a new instance of the AttachmentView class. /// </summary> public AttachmentView(string viewId = default(string), int? size = default(int?)) { ViewId = viewId; Size = size; } /// <summary> /// content type of the attachmnet /// </summary> [JsonProperty(PropertyName = "viewId")] public string ViewId { get; set; } /// <summary> /// Name of the attachment /// </summary> [JsonProperty(PropertyName = "size")] public int? Size { get; set; } } }
dr-em/BotBuilder
CSharp/Library/Microsoft.Bot.Connector/ConnectorAPI/Models/AttachmentView.cs
C#
mit
1,269
'use strict'; var path = require('path'); var fixtures = require('haraka-test-fixtures'); var Connection = fixtures.connection; var Plugin = fixtures.plugin; var _set_up = function(done) { this.backup = {}; // needed for tests this.plugin = new Plugin('auth/auth_vpopmaild'); this.plugin.inherits('auth/auth_base'); // reset the config/root_path this.plugin.config.root_path = path.resolve(__dirname, '../../../config'); this.plugin.cfg = this.plugin.config.get('auth_vpopmaild.ini'); this.connection = Connection.createConnection(); this.connection.capabilities=null; done(); }; exports.hook_capabilities = { setUp : _set_up, 'no TLS': function (test) { var cb = function (rc, msg) { test.expect(3); test.equal(undefined, rc); test.equal(undefined, msg); test.equal(null, this.connection.capabilities); test.done(); }.bind(this); this.plugin.hook_capabilities(cb, this.connection); }, 'with TLS': function (test) { var cb = function (rc, msg) { test.expect(3); test.equal(undefined, rc); test.equal(undefined, msg); test.ok(this.connection.capabilities.length); // console.log(this.connection.capabilities); test.done(); }.bind(this); this.connection.using_tls=true; this.connection.capabilities=[]; this.plugin.hook_capabilities(cb, this.connection); }, 'with TLS, sysadmin': function (test) { var cb = function (rc, msg) { test.expect(3); test.equal(undefined, rc); test.equal(undefined, msg); test.ok(this.connection.capabilities.length); // console.log(this.connection.capabilities); test.done(); }.bind(this); this.connection.using_tls=true; this.connection.capabilities=[]; this.plugin.hook_capabilities(cb, this.connection); }, }; exports.get_vpopmaild_socket = { setUp : _set_up, 'any': function (test) { test.expect(1); var socket = this.plugin.get_vpopmaild_socket('foo@localhost.com'); // console.log(socket); test.ok(socket); socket.end(); test.done(); } }; exports.get_plain_passwd = { setUp : _set_up, 'matt@example.com': function (test) { var cb = function (pass) { test.expect(1); test.ok(pass); test.done(); }; if (this.plugin.cfg['example.com'].sysadmin) { this.plugin.get_plain_passwd('matt@example.com', cb); } else { test.expect(0); test.done(); } } };
slattery/Haraka
tests/plugins/auth/auth_vpopmaild.js
JavaScript
mit
2,773
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Emit; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Symbols; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// The base class for all symbols (namespaces, classes, method, parameters, etc.) that are /// exposed by the compiler. /// </summary> [DebuggerDisplay("{GetDebuggerDisplay(), nq}")] internal abstract partial class Symbol : ISymbolInternal, IFormattable { private ISymbol _lazyISymbol; // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // Changes to the public interface of this class should remain synchronized with the VB version of Symbol. // Do not make any changes to the public interface without making the corresponding change // to the VB version. // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! /// <summary> /// True if this Symbol should be completed by calling ForceComplete. /// Intuitively, true for source entities (from any compilation). /// </summary> internal virtual bool RequiresCompletion { get { return false; } } internal virtual void ForceComplete(SourceLocation locationOpt, CancellationToken cancellationToken) { // must be overridden by source symbols, no-op for other symbols Debug.Assert(!this.RequiresCompletion); } internal virtual bool HasComplete(CompletionPart part) { // must be overridden by source symbols, no-op for other symbols Debug.Assert(!this.RequiresCompletion); return true; } /// <summary> /// Gets the name of this symbol. Symbols without a name return the empty string; null is /// never returned. /// </summary> public virtual string Name { get { return string.Empty; } } /// <summary> /// Gets the name of a symbol as it appears in metadata. Most of the time, this /// is the same as the Name property, with the following exceptions: /// 1) The metadata name of generic types includes the "`1", "`2" etc. suffix that /// indicates the number of type parameters (it does not include, however, names of /// containing types or namespaces). /// 2) The metadata name of explicit interface names have spaces removed, compared to /// the name property. /// </summary> public virtual string MetadataName { get { return this.Name; } } /// <summary> /// Gets the token for this symbol as it appears in metadata. Most of the time this is 0, /// as it is when the symbol is not loaded from metadata. /// </summary> public virtual int MetadataToken => 0; /// <summary> /// Gets the kind of this symbol. /// </summary> public abstract SymbolKind Kind { get; } /// <summary> /// Get the symbol that logically contains this symbol. /// </summary> public abstract Symbol ContainingSymbol { get; } /// <summary> /// Returns the nearest lexically enclosing type, or null if there is none. /// </summary> public virtual NamedTypeSymbol ContainingType { get { Symbol container = this.ContainingSymbol; NamedTypeSymbol containerAsType = container as NamedTypeSymbol; // NOTE: container could be null, so we do not check // whether containerAsType is not null, but // instead check if it did not change after // the cast. if ((object)containerAsType == (object)container) { // this should be relatively uncommon // most symbols that may be contained in a type // know their containing type and can override ContainingType // with a more precise implementation return containerAsType; } // this is recursive, but recursion should be very short // before we reach symbol that definitely knows its containing type. return container.ContainingType; } } /// <summary> /// Gets the nearest enclosing namespace for this namespace or type. For a nested type, /// returns the namespace that contains its container. /// </summary> public virtual NamespaceSymbol ContainingNamespace { get { for (var container = this.ContainingSymbol; (object)container != null; container = container.ContainingSymbol) { var ns = container as NamespaceSymbol; if ((object)ns != null) { return ns; } } return null; } } /// <summary> /// Returns the assembly containing this symbol. If this symbol is shared across multiple /// assemblies, or doesn't belong to an assembly, returns null. /// </summary> public virtual AssemblySymbol ContainingAssembly { get { // Default implementation gets the containers assembly. var container = this.ContainingSymbol; return (object)container != null ? container.ContainingAssembly : null; } } /// <summary> /// For a source assembly, the associated compilation. /// For any other assembly, null. /// For a source module, the DeclaringCompilation of the associated source assembly. /// For any other module, null. /// For any other symbol, the DeclaringCompilation of the associated module. /// </summary> /// <remarks> /// We're going through the containing module, rather than the containing assembly, /// because of /addmodule (symbols in such modules should return null). /// /// Remarks, not "ContainingCompilation" because it isn't transitive. /// </remarks> internal virtual CSharpCompilation DeclaringCompilation { get { switch (this.Kind) { case SymbolKind.ErrorType: return null; case SymbolKind.Assembly: Debug.Assert(!(this is SourceAssemblySymbol), "SourceAssemblySymbol must override DeclaringCompilation"); return null; case SymbolKind.NetModule: Debug.Assert(!(this is SourceModuleSymbol), "SourceModuleSymbol must override DeclaringCompilation"); return null; } var sourceModuleSymbol = this.ContainingModule as SourceModuleSymbol; return (object)sourceModuleSymbol == null ? null : sourceModuleSymbol.DeclaringCompilation; } } Compilation ISymbolInternal.DeclaringCompilation => DeclaringCompilation; string ISymbolInternal.Name => this.Name; string ISymbolInternal.MetadataName => this.MetadataName; ISymbolInternal ISymbolInternal.ContainingSymbol => this.ContainingSymbol; IModuleSymbolInternal ISymbolInternal.ContainingModule => this.ContainingModule; IAssemblySymbolInternal ISymbolInternal.ContainingAssembly => this.ContainingAssembly; ImmutableArray<Location> ISymbolInternal.Locations => this.Locations; INamespaceSymbolInternal ISymbolInternal.ContainingNamespace => this.ContainingNamespace; bool ISymbolInternal.IsImplicitlyDeclared => this.IsImplicitlyDeclared; INamedTypeSymbolInternal ISymbolInternal.ContainingType { get { return this.ContainingType; } } ISymbol ISymbolInternal.GetISymbol() => this.ISymbol; /// <summary> /// Returns the module containing this symbol. If this symbol is shared across multiple /// modules, or doesn't belong to a module, returns null. /// </summary> internal virtual ModuleSymbol ContainingModule { get { // Default implementation gets the containers module. var container = this.ContainingSymbol; return (object)container != null ? container.ContainingModule : null; } } /// <summary> /// The index of this member in the containing symbol. This is an optional /// property, implemented by anonymous type properties only, for comparing /// symbols in flow analysis. /// </summary> /// <remarks> /// Should this be used for tuple fields as well? /// </remarks> internal virtual int? MemberIndexOpt => null; /// <summary> /// The original definition of this symbol. If this symbol is constructed from another /// symbol by type substitution then OriginalDefinition gets the original symbol as it was defined in /// source or metadata. /// </summary> public Symbol OriginalDefinition { get { return OriginalSymbolDefinition; } } protected virtual Symbol OriginalSymbolDefinition { get { return this; } } /// <summary> /// Returns true if this is the original definition of this symbol. /// </summary> public bool IsDefinition { get { return (object)this == (object)OriginalDefinition; } } /// <summary> /// <para> /// Get a source location key for sorting. For performance, it's important that this /// be able to be returned from a symbol without doing any additional allocations (even /// if nothing is cached yet.) /// </para> /// <para> /// Only (original) source symbols and namespaces that can be merged /// need implement this function if they want to do so for efficiency. /// </para> /// </summary> internal virtual LexicalSortKey GetLexicalSortKey() { var locations = this.Locations; var declaringCompilation = this.DeclaringCompilation; Debug.Assert(declaringCompilation != null); // require that it is a source symbol return (locations.Length > 0) ? new LexicalSortKey(locations[0], declaringCompilation) : LexicalSortKey.NotInSource; } /// <summary> /// Gets the locations where this symbol was originally defined, either in source or /// metadata. Some symbols (for example, partial classes) may be defined in more than one /// location. /// </summary> public abstract ImmutableArray<Location> Locations { get; } /// <summary> /// <para> /// Get the syntax node(s) where this symbol was declared in source. Some symbols (for /// example, partial classes) may be defined in more than one location. This property should /// return one or more syntax nodes only if the symbol was declared in source code and also /// was not implicitly declared (see the <see cref="IsImplicitlyDeclared"/> property). /// </para> /// <para> /// Note that for namespace symbol, the declaring syntax might be declaring a nested /// namespace. For example, the declaring syntax node for N1 in "namespace N1.N2 {...}" is /// the entire <see cref="BaseNamespaceDeclarationSyntax"/> for N1.N2. For the global namespace, the declaring /// syntax will be the <see cref="CompilationUnitSyntax"/>. /// </para> /// </summary> /// <returns> /// The syntax node(s) that declared the symbol. If the symbol was declared in metadata or /// was implicitly declared, returns an empty read-only array. /// </returns> /// <remarks> /// To go the opposite direction (from syntax node to symbol), see <see /// cref="CSharpSemanticModel.GetDeclaredSymbol(MemberDeclarationSyntax, CancellationToken)"/>. /// </remarks> public abstract ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get; } /// <summary> /// Helper for implementing <see cref="DeclaringSyntaxReferences"/> for derived classes that store a location but not a /// <see cref="CSharpSyntaxNode"/> or <see cref="SyntaxReference"/>. /// </summary> internal static ImmutableArray<SyntaxReference> GetDeclaringSyntaxReferenceHelper<TNode>(ImmutableArray<Location> locations) where TNode : CSharpSyntaxNode { if (locations.IsEmpty) { return ImmutableArray<SyntaxReference>.Empty; } ArrayBuilder<SyntaxReference> builder = ArrayBuilder<SyntaxReference>.GetInstance(); foreach (Location location in locations) { // Location may be null. See https://github.com/dotnet/roslyn/issues/28862. if (location == null || !location.IsInSource) { continue; } if (location.SourceSpan.Length != 0) { SyntaxToken token = location.SourceTree.GetRoot().FindToken(location.SourceSpan.Start); if (token.Kind() != SyntaxKind.None) { CSharpSyntaxNode node = token.Parent.FirstAncestorOrSelf<TNode>(); if (node != null) { builder.Add(node.GetReference()); } } } else { // Since the location we're interested in can't contain a token, we'll inspect the whole tree, // pruning away branches that don't contain that location. We'll pick the narrowest node of the type // we're looking for. // eg: finding the ParameterSyntax from the empty location of a blank identifier SyntaxNode parent = location.SourceTree.GetRoot(); SyntaxNode found = null; foreach (var descendant in parent.DescendantNodesAndSelf(c => c.Location.SourceSpan.Contains(location.SourceSpan))) { if (descendant is TNode && descendant.Location.SourceSpan.Contains(location.SourceSpan)) { found = descendant; } } if (found is object) { builder.Add(found.GetReference()); } } } return builder.ToImmutableAndFree(); } /// <summary> /// Get this accessibility that was declared on this symbol. For symbols that do not have /// accessibility declared on them, returns <see cref="Accessibility.NotApplicable"/>. /// </summary> public abstract Accessibility DeclaredAccessibility { get; } /// <summary> /// Returns true if this symbol is "static"; i.e., declared with the <c>static</c> modifier or /// implicitly static. /// </summary> public abstract bool IsStatic { get; } /// <summary> /// Returns true if this symbol is "virtual", has an implementation, and does not override a /// base class member; i.e., declared with the <c>virtual</c> modifier. Does not return true for /// members declared as abstract or override. /// </summary> public abstract bool IsVirtual { get; } /// <summary> /// Returns true if this symbol was declared to override a base class member; i.e., declared /// with the <c>override</c> modifier. Still returns true if member was declared to override /// something, but (erroneously) no member to override exists. /// </summary> /// <remarks> /// Even for metadata symbols, <see cref="IsOverride"/> = true does not imply that <see cref="IMethodSymbol.OverriddenMethod"/> will /// be non-null. /// </remarks> public abstract bool IsOverride { get; } /// <summary> /// Returns true if this symbol was declared as requiring an override; i.e., declared with /// the <c>abstract</c> modifier. Also returns true on a type declared as "abstract", all /// interface types, and members of interface types. /// </summary> public abstract bool IsAbstract { get; } /// <summary> /// Returns true if this symbol was declared to override a base class member and was also /// sealed from further overriding; i.e., declared with the <c>sealed</c> modifier. Also set for /// types that do not allow a derived class (declared with <c>sealed</c> or <c>static</c> or <c>struct</c> /// or <c>enum</c> or <c>delegate</c>). /// </summary> public abstract bool IsSealed { get; } /// <summary> /// Returns true if this symbol has external implementation; i.e., declared with the /// <c>extern</c> modifier. /// </summary> public abstract bool IsExtern { get; } /// <summary> /// Returns true if this symbol was automatically created by the compiler, and does not /// have an explicit corresponding source code declaration. /// /// This is intended for symbols that are ordinary symbols in the language sense, /// and may be used by code, but that are simply declared implicitly rather than /// with explicit language syntax. /// /// Examples include (this list is not exhaustive): /// the default constructor for a class or struct that is created if one is not provided, /// the BeginInvoke/Invoke/EndInvoke methods for a delegate, /// the generated backing field for an auto property or a field-like event, /// the "this" parameter for non-static methods, /// the "value" parameter for a property setter, /// the parameters on indexer accessor methods (not on the indexer itself), /// methods in anonymous types, /// anonymous functions /// </summary> public virtual bool IsImplicitlyDeclared { get { return false; } } /// <summary> /// Returns true if this symbol can be referenced by its name in code. Examples of symbols /// that cannot be referenced by name are: /// constructors, destructors, operators, explicit interface implementations, /// accessor methods for properties and events, array types. /// </summary> public bool CanBeReferencedByName { get { switch (this.Kind) { case SymbolKind.Local: case SymbolKind.Label: case SymbolKind.Alias: case SymbolKind.RangeVariable: // never imported, and always references by name. return true; case SymbolKind.Namespace: case SymbolKind.Field: case SymbolKind.ErrorType: case SymbolKind.Parameter: case SymbolKind.TypeParameter: case SymbolKind.Event: break; case SymbolKind.NamedType: if (((NamedTypeSymbol)this).IsSubmissionClass) { return false; } break; case SymbolKind.Property: var property = (PropertySymbol)this; if (property.IsIndexer || property.MustCallMethodsDirectly) { return false; } break; case SymbolKind.Method: var method = (MethodSymbol)this; switch (method.MethodKind) { case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.ReducedExtension: break; case MethodKind.Destructor: // You wouldn't think that destructors would be referenceable by name, but // dev11 only prevents them from being invoked - they can still be assigned // to delegates. return true; case MethodKind.DelegateInvoke: return true; case MethodKind.PropertyGet: case MethodKind.PropertySet: if (!((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly()) { return false; } break; default: return false; } break; case SymbolKind.ArrayType: case SymbolKind.PointerType: case SymbolKind.FunctionPointerType: case SymbolKind.Assembly: case SymbolKind.DynamicType: case SymbolKind.NetModule: case SymbolKind.Discard: return false; default: throw ExceptionUtilities.UnexpectedValue(this.Kind); } // This will eliminate backing fields for auto-props, explicit interface implementations, // indexers, etc. // See the comment on ContainsDroppedIdentifierCharacters for an explanation of why // such names are not referenceable (or see DevDiv #14432). return SyntaxFacts.IsValidIdentifier(this.Name) && !SyntaxFacts.ContainsDroppedIdentifierCharacters(this.Name); } } /// <summary> /// As an optimization, viability checking in the lookup code should use this property instead /// of <see cref="CanBeReferencedByName"/>. The full name check will then be performed in the <see cref="CSharpSemanticModel"/>. /// </summary> /// <remarks> /// This property exists purely for performance reasons. /// </remarks> internal bool CanBeReferencedByNameIgnoringIllegalCharacters { get { if (this.Kind == SymbolKind.Method) { var method = (MethodSymbol)this; switch (method.MethodKind) { case MethodKind.Ordinary: case MethodKind.LocalFunction: case MethodKind.DelegateInvoke: case MethodKind.Destructor: // See comment in CanBeReferencedByName. return true; case MethodKind.PropertyGet: case MethodKind.PropertySet: return ((PropertySymbol)method.AssociatedSymbol).CanCallMethodsDirectly(); default: return false; } } return true; } } /// <summary> /// Perform additional checks after the member has been /// added to the member list of the containing type. /// </summary> internal virtual void AfterAddingTypeMembersChecks(ConversionsBase conversions, BindingDiagnosticBag diagnostics) { } // Note: This is no public "IsNew". This is intentional, because new has no syntactic meaning. // It serves only to remove a warning. Furthermore, it can not be inferred from // metadata. For symbols defined in source, the modifiers in the syntax tree // can be examined. /// <summary> /// Compare two symbol objects to see if they refer to the same symbol. You should always /// use <see cref="operator =="/> and <see cref="operator !="/>, or the <see cref="Equals(object)"/> method, to compare two symbols for equality. /// </summary> public static bool operator ==(Symbol left, Symbol right) { //PERF: this function is often called with // 1) left referencing same object as the right // 2) right being null // The code attempts to check for these conditions before // resorting to .Equals // the condition is expected to be folded when inlining "someSymbol == null" if (right is null) { return left is null; } // this part is expected to disappear when inlining "someSymbol == null" return (object)left == (object)right || right.Equals(left); } /// <summary> /// Compare two symbol objects to see if they refer to the same symbol. You should always /// use == and !=, or the Equals method, to compare two symbols for equality. /// </summary> public static bool operator !=(Symbol left, Symbol right) { //PERF: this function is often called with // 1) left referencing same object as the right // 2) right being null // The code attempts to check for these conditions before // resorting to .Equals // //NOTE: we do not implement this as !(left == right) // since that sometimes results in a worse code // the condition is expected to be folded when inlining "someSymbol != null" if (right is null) { return left is object; } // this part is expected to disappear when inlining "someSymbol != null" return (object)left != (object)right && !right.Equals(left); } public sealed override bool Equals(object obj) { return this.Equals(obj as Symbol, SymbolEqualityComparer.Default.CompareKind); } public bool Equals(Symbol other) { return this.Equals(other, SymbolEqualityComparer.Default.CompareKind); } bool ISymbolInternal.Equals(ISymbolInternal other, TypeCompareKind compareKind) { return this.Equals(other as Symbol, compareKind); } // By default we don't consider the compareKind, and do reference equality. This can be overridden. public virtual bool Equals(Symbol other, TypeCompareKind compareKind) { return (object)this == other; } // By default, we do reference equality. This can be overridden. public override int GetHashCode() { return System.Runtime.CompilerServices.RuntimeHelpers.GetHashCode(this); } public static bool Equals(Symbol first, Symbol second, TypeCompareKind compareKind) { if (first is null) { return second is null; } return first.Equals(second, compareKind); } /// <summary> /// Returns a string representation of this symbol, suitable for debugging purposes, or /// for placing in an error message. /// </summary> /// <remarks> /// This will provide a useful representation, but it would be clearer to call <see cref="ToDisplayString"/> /// directly and provide an explicit format. /// Sealed so that <see cref="ToString"/> and <see cref="ToDisplayString"/> can't get out of sync. /// </remarks> public sealed override string ToString() { return this.ToDisplayString(); } // ---- End of Public Definition --- // Below here can be various useful virtual methods that are useful to the compiler, but we don't // want to expose publicly. // ---- End of Public Definition --- // Must override this in derived classes for visitor pattern. internal abstract TResult Accept<TArgument, TResult>(CSharpSymbolVisitor<TArgument, TResult> visitor, TArgument a); // Prevent anyone else from deriving from this class. internal Symbol() { } /// <summary> /// Build and add synthesized attributes for this symbol. /// </summary> internal virtual void AddSynthesizedAttributes(PEModuleBuilder moduleBuilder, ref ArrayBuilder<SynthesizedAttributeData> attributes) { } /// <summary> /// Convenience helper called by subclasses to add a synthesized attribute to a collection of attributes. /// </summary> internal static void AddSynthesizedAttribute(ref ArrayBuilder<SynthesizedAttributeData> attributes, SynthesizedAttributeData attribute) { if (attribute != null) { if (attributes == null) { attributes = new ArrayBuilder<SynthesizedAttributeData>(1); } attributes.Add(attribute); } } /// <summary> /// <see cref="CharSet"/> effective for this symbol (type or DllImport method). /// Nothing if <see cref="DefaultCharSetAttribute"/> isn't applied on the containing module or it doesn't apply on this symbol. /// </summary> /// <remarks> /// Determined based upon value specified via <see cref="DefaultCharSetAttribute"/> applied on the containing module. /// </remarks> internal CharSet? GetEffectiveDefaultMarshallingCharSet() { Debug.Assert(this.Kind == SymbolKind.NamedType || this.Kind == SymbolKind.Method); return this.ContainingModule.DefaultMarshallingCharSet; } internal bool IsFromCompilation(CSharpCompilation compilation) { Debug.Assert(compilation != null); return compilation == this.DeclaringCompilation; } /// <summary> /// Always prefer <see cref="IsFromCompilation"/>. /// </summary> /// <remarks> /// <para> /// Unfortunately, when determining overriding/hiding/implementation relationships, we don't /// have the "current" compilation available. We could, but that would clutter up the API /// without providing much benefit. As a compromise, we consider all compilations "current". /// </para> /// <para> /// Unlike in VB, we are not allowing retargeting symbols. This method is used as an approximation /// for <see cref="IsFromCompilation"/> when a compilation is not available and that method will never return /// true for retargeting symbols. /// </para> /// </remarks> internal bool Dangerous_IsFromSomeCompilation { get { return this.DeclaringCompilation != null; } } internal virtual bool IsDefinedInSourceTree(SyntaxTree tree, TextSpan? definedWithinSpan, CancellationToken cancellationToken = default(CancellationToken)) { var declaringReferences = this.DeclaringSyntaxReferences; if (this.IsImplicitlyDeclared && declaringReferences.Length == 0) { return this.ContainingSymbol.IsDefinedInSourceTree(tree, definedWithinSpan, cancellationToken); } foreach (var syntaxRef in declaringReferences) { cancellationToken.ThrowIfCancellationRequested(); if (syntaxRef.SyntaxTree == tree && (!definedWithinSpan.HasValue || syntaxRef.Span.IntersectsWith(definedWithinSpan.Value))) { return true; } } return false; } internal static void ForceCompleteMemberByLocation(SourceLocation locationOpt, Symbol member, CancellationToken cancellationToken) { if (locationOpt == null || member.IsDefinedInSourceTree(locationOpt.SourceTree, locationOpt.SourceSpan, cancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); member.ForceComplete(locationOpt, cancellationToken); } } /// <summary> /// Returns the Documentation Comment ID for the symbol, or null if the symbol doesn't /// support documentation comments. /// </summary> public virtual string GetDocumentationCommentId() { // NOTE: we're using a try-finally here because there's a test that specifically // triggers an exception here to confirm that some symbols don't have documentation // comment IDs. We don't care about "leaks" in such cases, but we don't want spew // in the test output. var pool = PooledStringBuilder.GetInstance(); try { StringBuilder builder = pool.Builder; DocumentationCommentIDVisitor.Instance.Visit(this, builder); return builder.Length == 0 ? null : builder.ToString(); } finally { pool.Free(); } } #nullable enable /// <summary> /// Fetches the documentation comment for this element with a cancellation token. /// </summary> /// <param name="preferredCulture">Optionally, retrieve the comments formatted for a particular culture. No impact on source documentation comments.</param> /// <param name="expandIncludes">Optionally, expand <![CDATA[<include>]]> elements. No impact on non-source documentation comments.</param> /// <param name="cancellationToken">Optionally, allow cancellation of documentation comment retrieval.</param> /// <returns>The XML that would be written to the documentation file for the symbol.</returns> public virtual string GetDocumentationCommentXml( CultureInfo? preferredCulture = null, bool expandIncludes = false, CancellationToken cancellationToken = default(CancellationToken)) { return ""; } #nullable disable private static readonly SymbolDisplayFormat s_debuggerDisplayFormat = SymbolDisplayFormat.TestFormat .AddMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier | SymbolDisplayMiscellaneousOptions.IncludeNotNullableReferenceTypeModifier) .WithCompilerInternalOptions(SymbolDisplayCompilerInternalOptions.None); internal virtual string GetDebuggerDisplay() { return $"{this.Kind} {this.ToDisplayString(s_debuggerDisplayFormat)}"; } internal virtual void AddDeclarationDiagnostics(BindingDiagnosticBag diagnostics) { #if DEBUG if (ContainingSymbol is SourceMemberContainerTypeSymbol container) { container.AssertMemberExposure(this, forDiagnostics: true); } #endif if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false || diagnostics.DependenciesBag?.Count > 0) { CSharpCompilation compilation = this.DeclaringCompilation; Debug.Assert(compilation != null); compilation.AddUsedAssemblies(diagnostics.DependenciesBag); if (diagnostics.DiagnosticBag?.IsEmptyWithoutResolution == false) { compilation.DeclarationDiagnostics.AddRange(diagnostics.DiagnosticBag); } } } #region Use-Site Diagnostics /// <summary> /// True if the symbol has a use-site diagnostic with error severity. /// </summary> internal bool HasUseSiteError { get { var info = GetUseSiteInfo(); return info.DiagnosticInfo?.Severity == DiagnosticSeverity.Error; } } /// <summary> /// Returns diagnostic info that should be reported at the use site of the symbol, or default if there is none. /// </summary> internal virtual UseSiteInfo<AssemblySymbol> GetUseSiteInfo() { return default; } protected AssemblySymbol PrimaryDependency { get { AssemblySymbol dependency = this.ContainingAssembly; if (dependency is object && dependency.CorLibrary == dependency) { return null; } return dependency; } } /// <summary> /// Return error code that has highest priority while calculating use site error for this symbol. /// Supposed to be ErrorCode, but it causes inconsistent accessibility error. /// </summary> protected virtual int HighestPriorityUseSiteError { get { return int.MaxValue; } } /// <summary> /// Indicates that this symbol uses metadata that cannot be supported by the language. /// /// Examples include: /// - Pointer types in VB /// - ByRef return type /// - Required custom modifiers /// /// This is distinguished from, for example, references to metadata symbols defined in assemblies that weren't referenced. /// Symbols where this returns true can never be used successfully, and thus should never appear in any IDE feature. /// /// This is set for metadata symbols, as follows: /// Type - if a type is unsupported (e.g., a pointer type, etc.) /// Method - parameter or return type is unsupported /// Field - type is unsupported /// Event - type is unsupported /// Property - type is unsupported /// Parameter - type is unsupported /// </summary> public virtual bool HasUnsupportedMetadata { get { return false; } } /// <summary> /// Merges given diagnostic to the existing result diagnostic. /// </summary> internal bool MergeUseSiteDiagnostics(ref DiagnosticInfo result, DiagnosticInfo info) { if (info == null) { return false; } if (info.Severity == DiagnosticSeverity.Error && (info.Code == HighestPriorityUseSiteError || HighestPriorityUseSiteError == Int32.MaxValue)) { // this error is final, no other error can override it: result = info; return true; } if (result == null || result.Severity == DiagnosticSeverity.Warning && info.Severity == DiagnosticSeverity.Error) { // there could be an error of higher-priority result = info; return false; } // we have a second low-pri error, continue looking for a higher priority one return false; } /// <summary> /// Merges given diagnostic and dependencies to the existing result. /// </summary> internal bool MergeUseSiteInfo(ref UseSiteInfo<AssemblySymbol> result, UseSiteInfo<AssemblySymbol> info) { DiagnosticInfo diagnosticInfo = result.DiagnosticInfo; bool retVal = MergeUseSiteDiagnostics(ref diagnosticInfo, info.DiagnosticInfo); if (diagnosticInfo?.Severity == DiagnosticSeverity.Error) { result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo); return retVal; } var secondaryDependencies = result.SecondaryDependencies; var primaryDependency = result.PrimaryDependency; info.MergeDependencies(ref primaryDependency, ref secondaryDependencies); result = new UseSiteInfo<AssemblySymbol>(diagnosticInfo, primaryDependency, secondaryDependencies); Debug.Assert(!retVal); return retVal; } /// <summary> /// Reports specified use-site diagnostic to given diagnostic bag. /// </summary> /// <remarks> /// This method should be the only method adding use-site diagnostics to a diagnostic bag. /// It performs additional adjustments of the location for unification related diagnostics and /// may be the place where to add more use-site location post-processing. /// </remarks> /// <returns>True if the diagnostic has error severity.</returns> internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, DiagnosticBag diagnostics, Location location) { // Unlike VB the C# Dev11 compiler reports only a single unification error/warning. // By dropping the location we effectively merge all unification use-site errors that have the same error code into a single error. // The error message clearly explains how to fix the problem and reporting the error for each location wouldn't add much value. if (info.Code == (int)ErrorCode.WRN_UnifyReferenceBldRev || info.Code == (int)ErrorCode.WRN_UnifyReferenceMajMin || info.Code == (int)ErrorCode.ERR_AssemblyMatchBadVersion) { location = NoLocation.Singleton; } diagnostics.Add(info, location); return info.Severity == DiagnosticSeverity.Error; } internal static bool ReportUseSiteDiagnostic(DiagnosticInfo info, BindingDiagnosticBag diagnostics, Location location) { return diagnostics.ReportUseSiteDiagnostic(info, location); } /// <summary> /// Derive use-site info from a type symbol. /// </summary> internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeSymbol type) { UseSiteInfo<AssemblySymbol> info = type.GetUseSiteInfo(); if (info.DiagnosticInfo?.Code == (int)ErrorCode.ERR_BogusType) { GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref info); } return MergeUseSiteInfo(ref result, info); } private void GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref UseSiteInfo<AssemblySymbol> info) { switch (this.Kind) { case SymbolKind.Field: case SymbolKind.Method: case SymbolKind.Property: case SymbolKind.Event: info = info.AdjustDiagnosticInfo(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, this)); break; } } private UseSiteInfo<AssemblySymbol> GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo() { var useSiteInfo = new UseSiteInfo<AssemblySymbol>(new CSDiagnosticInfo(ErrorCode.ERR_BogusType, string.Empty)); GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo(ref useSiteInfo); return useSiteInfo; } internal bool DeriveUseSiteInfoFromType(ref UseSiteInfo<AssemblySymbol> result, TypeWithAnnotations type, AllowedRequiredModifierType allowedRequiredModifierType) { return DeriveUseSiteInfoFromType(ref result, type.Type) || DeriveUseSiteInfoFromCustomModifiers(ref result, type.CustomModifiers, allowedRequiredModifierType); } internal bool DeriveUseSiteInfoFromParameter(ref UseSiteInfo<AssemblySymbol> result, ParameterSymbol param) { return DeriveUseSiteInfoFromType(ref result, param.TypeWithAnnotations, AllowedRequiredModifierType.None) || DeriveUseSiteInfoFromCustomModifiers(ref result, param.RefCustomModifiers, this is MethodSymbol method && method.MethodKind == MethodKind.FunctionPointerSignature ? AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute | AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute : AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute); } internal bool DeriveUseSiteInfoFromParameters(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<ParameterSymbol> parameters) { foreach (ParameterSymbol param in parameters) { if (DeriveUseSiteInfoFromParameter(ref result, param)) { return true; } } return false; } [Flags] internal enum AllowedRequiredModifierType { None = 0, System_Runtime_CompilerServices_Volatile = 1, System_Runtime_InteropServices_InAttribute = 1 << 1, System_Runtime_CompilerServices_IsExternalInit = 1 << 2, System_Runtime_CompilerServices_OutAttribute = 1 << 3, } internal bool DeriveUseSiteInfoFromCustomModifiers(ref UseSiteInfo<AssemblySymbol> result, ImmutableArray<CustomModifier> customModifiers, AllowedRequiredModifierType allowedRequiredModifierType) { AllowedRequiredModifierType requiredModifiersFound = AllowedRequiredModifierType.None; bool checkRequiredModifiers = true; foreach (CustomModifier modifier in customModifiers) { NamedTypeSymbol modifierType = ((CSharpCustomModifier)modifier).ModifierSymbol; if (checkRequiredModifiers && !modifier.IsOptional) { AllowedRequiredModifierType current = AllowedRequiredModifierType.None; if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute) != 0 && modifierType.IsWellKnownTypeInAttribute()) { current = AllowedRequiredModifierType.System_Runtime_InteropServices_InAttribute; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile) != 0 && modifierType.SpecialType == SpecialType.System_Runtime_CompilerServices_IsVolatile) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_Volatile; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit) != 0 && modifierType.IsWellKnownTypeIsExternalInit()) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_IsExternalInit; } else if ((allowedRequiredModifierType & AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute) != 0 && modifierType.IsWellKnownTypeOutAttribute()) { current = AllowedRequiredModifierType.System_Runtime_CompilerServices_OutAttribute; } if (current == AllowedRequiredModifierType.None || (current != requiredModifiersFound && requiredModifiersFound != AllowedRequiredModifierType.None)) // At the moment we don't support applying different allowed modreqs to the same target. { if (MergeUseSiteInfo(ref result, GetSymbolSpecificUnsupportedMetadataUseSiteErrorInfo())) { return true; } checkRequiredModifiers = false; } requiredModifiersFound |= current; } // Unbound generic type is valid as a modifier, let's not report any use site diagnostics because of that. if (modifierType.IsUnboundGenericType) { modifierType = modifierType.OriginalDefinition; } if (DeriveUseSiteInfoFromType(ref result, modifierType)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive<T>(ref DiagnosticInfo result, ImmutableArray<T> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) where T : TypeSymbol { foreach (var t in types) { if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeWithAnnotations> types, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var t in types) { if (t.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<CustomModifier> modifiers, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var modifier in modifiers) { if (((CSharpCustomModifier)modifier).ModifierSymbol.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<ParameterSymbol> parameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var parameter in parameters) { if (parameter.TypeWithAnnotations.GetUnificationUseSiteDiagnosticRecursive(ref result, owner, ref checkedTypes) || GetUnificationUseSiteDiagnosticRecursive(ref result, parameter.RefCustomModifiers, owner, ref checkedTypes)) { return true; } } return false; } internal static bool GetUnificationUseSiteDiagnosticRecursive(ref DiagnosticInfo result, ImmutableArray<TypeParameterSymbol> typeParameters, Symbol owner, ref HashSet<TypeSymbol> checkedTypes) { foreach (var typeParameter in typeParameters) { if (GetUnificationUseSiteDiagnosticRecursive(ref result, typeParameter.ConstraintTypesNoUseSiteDiagnostics, owner, ref checkedTypes)) { return true; } } return false; } #endregion /// <summary> /// True if this symbol has been marked with the <see cref="ObsoleteAttribute"/> attribute. /// This property returns <see cref="ThreeState.Unknown"/> if the <see cref="ObsoleteAttribute"/> attribute hasn't been cracked yet. /// </summary> internal ThreeState ObsoleteState { get { switch (ObsoleteKind) { case ObsoleteAttributeKind.None: case ObsoleteAttributeKind.Experimental: return ThreeState.False; case ObsoleteAttributeKind.Uninitialized: return ThreeState.Unknown; default: return ThreeState.True; } } } internal ObsoleteAttributeKind ObsoleteKind { get { var data = this.ObsoleteAttributeData; return (data == null) ? ObsoleteAttributeKind.None : data.Kind; } } /// <summary> /// Returns data decoded from <see cref="ObsoleteAttribute"/> attribute or null if there is no <see cref="ObsoleteAttribute"/> attribute. /// This property returns <see cref="Microsoft.CodeAnalysis.ObsoleteAttributeData.Uninitialized"/> if attribute arguments haven't been decoded yet. /// </summary> internal abstract ObsoleteAttributeData ObsoleteAttributeData { get; } /// <summary> /// Returns true and a <see cref="string"/> from the first <see cref="GuidAttribute"/> on the symbol, /// the string might be null or an invalid guid representation. False, /// if there is no <see cref="GuidAttribute"/> with string argument. /// </summary> internal bool GetGuidStringDefaultImplementation(out string guidString) { foreach (var attrData in this.GetAttributes()) { if (attrData.IsTargetAttribute(this, AttributeDescription.GuidAttribute)) { if (attrData.TryGetGuidAttributeValue(out guidString)) { return true; } } } guidString = null; return false; } public string ToDisplayString(SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayString(ISymbol, format); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null) { return SymbolDisplay.ToDisplayParts(ISymbol, format); } public string ToMinimalDisplayString( SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayString(ISymbol, semanticModel, position, format); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts( SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { return SymbolDisplay.ToMinimalDisplayParts(ISymbol, semanticModel, position, format); } internal static void ReportErrorIfHasConstraints( SyntaxList<TypeParameterConstraintClauseSyntax> constraintClauses, DiagnosticBag diagnostics) { if (constraintClauses.Count > 0) { diagnostics.Add( ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, constraintClauses[0].WhereKeyword.GetLocation()); } } internal static void CheckForBlockAndExpressionBody( CSharpSyntaxNode block, CSharpSyntaxNode expression, CSharpSyntaxNode syntax, BindingDiagnosticBag diagnostics) { if (block != null && expression != null) { diagnostics.Add(ErrorCode.ERR_BlockBodyAndExpressionBody, syntax.GetLocation()); } } [Flags] internal enum ReservedAttributes { DynamicAttribute = 1 << 1, IsReadOnlyAttribute = 1 << 2, IsUnmanagedAttribute = 1 << 3, IsByRefLikeAttribute = 1 << 4, TupleElementNamesAttribute = 1 << 5, NullableAttribute = 1 << 6, NullableContextAttribute = 1 << 7, NullablePublicOnlyAttribute = 1 << 8, NativeIntegerAttribute = 1 << 9, CaseSensitiveExtensionAttribute = 1 << 10, } internal bool ReportExplicitUseOfReservedAttributes(in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, ReservedAttributes reserved) { var attribute = arguments.Attribute; var diagnostics = (BindingDiagnosticBag)arguments.Diagnostics; if ((reserved & ReservedAttributes.DynamicAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.DynamicAttribute)) { // DynamicAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitDynamicAttr, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.IsReadOnlyAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsReadOnlyAttribute)) { } else if ((reserved & ReservedAttributes.IsUnmanagedAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsUnmanagedAttribute)) { } else if ((reserved & ReservedAttributes.IsByRefLikeAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.IsByRefLikeAttribute)) { } else if ((reserved & ReservedAttributes.TupleElementNamesAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.TupleElementNamesAttribute)) { diagnostics.Add(ErrorCode.ERR_ExplicitTupleElementNamesAttribute, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.NullableAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.NullableAttribute)) { // NullableAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitNullableAttribute, arguments.AttributeSyntaxOpt.Location); } else if ((reserved & ReservedAttributes.NullableContextAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullableContextAttribute)) { } else if ((reserved & ReservedAttributes.NullablePublicOnlyAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NullablePublicOnlyAttribute)) { } else if ((reserved & ReservedAttributes.NativeIntegerAttribute) != 0 && reportExplicitUseOfReservedAttribute(attribute, arguments, AttributeDescription.NativeIntegerAttribute)) { } else if ((reserved & ReservedAttributes.CaseSensitiveExtensionAttribute) != 0 && attribute.IsTargetAttribute(this, AttributeDescription.CaseSensitiveExtensionAttribute)) { // ExtensionAttribute should not be set explicitly. diagnostics.Add(ErrorCode.ERR_ExplicitExtension, arguments.AttributeSyntaxOpt.Location); } else { return false; } return true; bool reportExplicitUseOfReservedAttribute(CSharpAttributeData attribute, in DecodeWellKnownAttributeArguments<AttributeSyntax, CSharpAttributeData, AttributeLocation> arguments, in AttributeDescription attributeDescription) { if (attribute.IsTargetAttribute(this, attributeDescription)) { // Do not use '{FullName}'. This is reserved for compiler usage. diagnostics.Add(ErrorCode.ERR_ExplicitReservedAttr, arguments.AttributeSyntaxOpt.Location, attributeDescription.FullName); return true; } return false; } } internal virtual byte? GetNullableContextValue() { return GetLocalNullableContextValue() ?? ContainingSymbol?.GetNullableContextValue(); } internal virtual byte? GetLocalNullableContextValue() { return null; } internal void GetCommonNullableValues(CSharpCompilation compilation, ref MostCommonNullableValueBuilder builder) { switch (this.Kind) { case SymbolKind.NamedType: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(this.GetLocalNullableContextValue()); } break; case SymbolKind.Event: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(((EventSymbol)this).TypeWithAnnotations); } break; case SymbolKind.Field: var field = (FieldSymbol)this; if (field is TupleElementFieldSymbol tupleElement) { field = tupleElement.TupleUnderlyingField; } if (compilation.ShouldEmitNullableAttributes(field)) { builder.AddValue(field.TypeWithAnnotations); } break; case SymbolKind.Method: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(this.GetLocalNullableContextValue()); } break; case SymbolKind.Property: if (compilation.ShouldEmitNullableAttributes(this)) { builder.AddValue(((PropertySymbol)this).TypeWithAnnotations); // Attributes are not emitted for property parameters. } break; case SymbolKind.Parameter: builder.AddValue(((ParameterSymbol)this).TypeWithAnnotations); break; case SymbolKind.TypeParameter: if (this is SourceTypeParameterSymbolBase typeParameter) { builder.AddValue(typeParameter.GetSynthesizedNullableAttributeValue()); foreach (var constraintType in typeParameter.ConstraintTypesNoUseSiteDiagnostics) { builder.AddValue(constraintType); } } break; } } internal bool ShouldEmitNullableContextValue(out byte value) { byte? localValue = GetLocalNullableContextValue(); if (localValue == null) { value = 0; return false; } value = localValue.GetValueOrDefault(); byte containingValue = ContainingSymbol?.GetNullableContextValue() ?? 0; return value != containingValue; } #nullable enable /// <summary> /// True if the symbol is declared outside of the scope of the containing /// symbol /// </summary> internal static bool IsCaptured(Symbol variable, SourceMethodSymbol containingSymbol) { switch (variable.Kind) { case SymbolKind.Field: case SymbolKind.Property: case SymbolKind.Event: // Range variables are not captured, but their underlying parameters // may be. If this is a range underlying parameter it will be a // ParameterSymbol, not a RangeVariableSymbol. case SymbolKind.RangeVariable: return false; case SymbolKind.Local: if (((LocalSymbol)variable).IsConst) { return false; } break; case SymbolKind.Parameter: break; case SymbolKind.Method: if (variable is LocalFunctionSymbol localFunction) { // calling a static local function doesn't require capturing state if (localFunction.IsStatic) { return false; } break; } throw ExceptionUtilities.UnexpectedValue(variable); default: throw ExceptionUtilities.UnexpectedValue(variable.Kind); } // Walk up the containing symbols until we find the target function, in which // case the variable is not captured by the target function, or null, in which // case it is. for (var currentFunction = variable.ContainingSymbol; (object)currentFunction != null; currentFunction = currentFunction.ContainingSymbol) { if (ReferenceEquals(currentFunction, containingSymbol)) { return false; } } return true; } #nullable disable bool ISymbolInternal.IsStatic { get { return this.IsStatic; } } bool ISymbolInternal.IsVirtual { get { return this.IsVirtual; } } bool ISymbolInternal.IsOverride { get { return this.IsOverride; } } bool ISymbolInternal.IsAbstract { get { return this.IsAbstract; } } Accessibility ISymbolInternal.DeclaredAccessibility { get { return this.DeclaredAccessibility; } } public abstract void Accept(CSharpSymbolVisitor visitor); public abstract TResult Accept<TResult>(CSharpSymbolVisitor<TResult> visitor); string IFormattable.ToString(string format, IFormatProvider formatProvider) { return ToString(); } protected abstract ISymbol CreateISymbol(); internal ISymbol ISymbol { get { if (_lazyISymbol is null) { Interlocked.CompareExchange(ref _lazyISymbol, CreateISymbol(), null); } return _lazyISymbol; } } } }
mavasani/roslyn
src/Compilers/CSharp/Portable/Symbols/Symbol.cs
C#
mit
68,726
//= require locastyle/templates/_popover.jst.eco //= require locastyle/templates/_dropdown.jst.eco
diegoeis/locawebstyle
source/assets/javascripts/templates.js
JavaScript
mit
99
// # Mail API // API for sending Mail var Promise = require('bluebird'), pipeline = require('../utils/pipeline'), errors = require('../errors'), mail = require('../mail'), Models = require('../models'), utils = require('./utils'), notifications = require('./notifications'), i18n = require('../i18n'), docName = 'mail', mailer, apiMail; /** * Send mail helper */ function sendMail(object) { if (!(mailer instanceof mail.GhostMailer)) { mailer = new mail.GhostMailer(); } return mailer.send(object.mail[0].message).catch(function (err) { if (mailer.state.usingDirect) { notifications.add( {notifications: [{ type: 'warn', message: [ i18n.t('warnings.index.unableToSendEmail'), i18n.t('common.seeLinkForInstructions', {link: '<a href=\'https://docs.ghost.org/v1.0.0/docs/mail-config\' target=\'_blank\'>Checkout our mail configuration docs!</a>'}) ].join(' ') }]}, {context: {internal: true}} ); } return Promise.reject(new errors.EmailError({err: err})); }); } /** * ## Mail API Methods * * **See:** [API Methods](index.js.html#api%20methods) * @typedef Mail * @param mail */ apiMail = { /** * ### Send * Send an email * * @public * @param {Mail} object details of the email to send * @returns {Promise} */ send: function (object, options) { var tasks; /** * ### Format Response * @returns {Mail} mail */ function formatResponse(data) { delete object.mail[0].options; // Sendmail returns extra details we don't need and that don't convert to JSON delete object.mail[0].message.transport; object.mail[0].status = { message: data.message }; return object; } /** * ### Send Mail */ function send() { return sendMail(object, options); } tasks = [ utils.handlePermissions(docName, 'send'), send, formatResponse ]; return pipeline(tasks, options || {}); }, /** * ### SendTest * Send a test email * * @public * @param {Object} options required property 'to' which contains the recipient address * @returns {Promise} */ sendTest: function (options) { var tasks; /** * ### Model Query */ function modelQuery() { return Models.User.findOne({id: options.context.user}); } /** * ### Generate content */ function generateContent(result) { return mail.utils.generateContent({template: 'test'}).then(function (content) { var payload = { mail: [{ message: { to: result.get('email'), subject: i18n.t('common.api.mail.testGhostEmail'), html: content.html, text: content.text } }] }; return payload; }); } /** * ### Send mail */ function send(payload) { return sendMail(payload, options); } tasks = [ modelQuery, generateContent, send ]; return pipeline(tasks); } }; module.exports = apiMail;
jordanwalsh23/jordanwalsh23.github.io
core/server/api/mail.js
JavaScript
mit
3,802
/** * Lo-Dash 2.4.1 (Custom Build) <http://lodash.com/> * Build: `lodash modularize exports="amd" -o ./compat/` * Copyright 2012-2013 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.5.2 <http://underscorejs.org/LICENSE> * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <http://lodash.com/license> */ define(['../internals/baseEach', '../functions/createCallback', '../objects/isArray'], function(baseEach, createCallback, isArray) { /** * Creates an array of values by running each element in the collection * through the callback. The callback is bound to `thisArg` and invoked with * three arguments; (value, index|key, collection). * * If a property name is provided for `callback` the created "_.pluck" style * callback will return the property value of the given element. * * If an object is provided for `callback` the created "_.where" style callback * will return `true` for elements that have the properties of the given object, * else `false`. * * @static * @memberOf _ * @alias collect * @category Collections * @param {Array|Object|string} collection The collection to iterate over. * @param {Function|Object|string} [callback=identity] The function called * per iteration. If a property name or object is provided it will be used * to create a "_.pluck" or "_.where" style callback, respectively. * @param {*} [thisArg] The `this` binding of `callback`. * @returns {Array} Returns a new array of the results of each `callback` execution. * @example * * _.map([1, 2, 3], function(num) { return num * 3; }); * // => [3, 6, 9] * * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); * // => [3, 6, 9] (property order is not guaranteed across environments) * * var characters = [ * { 'name': 'barney', 'age': 36 }, * { 'name': 'fred', 'age': 40 } * ]; * * // using "_.pluck" callback shorthand * _.map(characters, 'name'); * // => ['barney', 'fred'] */ function map(collection, callback, thisArg) { var index = -1, length = collection ? collection.length : 0, result = Array(typeof length == 'number' ? length : 0); callback = createCallback(callback, thisArg, 3); if (isArray(collection)) { while (++index < length) { result[index] = callback(collection[index], index, collection); } } else { baseEach(collection, function(value, key, collection) { result[++index] = callback(value, key, collection); }); } return result; } return map; });
john-bixly/Morsel
app/vendor/lodash-amd/compat/collections/map.js
JavaScript
mit
2,696
// Copyright 2015-2018 Hans Dembinski // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt // or copy at http://www.boost.org/LICENSE_1_0.txt) //[ guide_histogram_serialization #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/histogram.hpp> #include <boost/histogram/serialization.hpp> // includes serialization code #include <cassert> #include <sstream> int main() { using namespace boost::histogram; auto a = make_histogram(axis::regular<>(3, -1.0, 1.0, "axis 0"), axis::integer<>(0, 2, "axis 1")); a(0.5, 1); std::string buf; // to hold persistent representation // store histogram { std::ostringstream os; boost::archive::text_oarchive oa(os); oa << a; buf = os.str(); } auto b = decltype(a)(); // create a default-constructed second histogram assert(b != a); // b is empty, a is not // load histogram { std::istringstream is(buf); boost::archive::text_iarchive ia(is); ia >> b; } assert(b == a); // now b is equal to a } //]
davehorton/drachtio-server
deps/boost_1_77_0/libs/histogram/examples/guide_histogram_serialization.cpp
C++
mit
1,128
window.Reactable = require('../build/reactable.common');
wemcdonald/reactable
src/reactable.global.js
JavaScript
mit
57
from __future__ import absolute_import import numpy import chainer from chainer import _backend from chainer.backends import _cpu from chainer.configuration import config _ideep_version = None _error = None try: import ideep4py as ideep # NOQA from ideep4py import mdarray # type: ignore # NOQA _ideep_version = 2 if hasattr(ideep, '__version__') else 1 except ImportError as e: _error = e _ideep_version = None class mdarray(object): # type: ignore pass # for type testing class Intel64Device(_backend.Device): """Device for Intel64 (Intel Architecture) backend with iDeep""" xp = numpy name = '@intel64' supported_array_types = (numpy.ndarray, mdarray) __hash__ = _backend.Device.__hash__ def __init__(self): check_ideep_available() super(Intel64Device, self).__init__() @staticmethod def from_array(array): if isinstance(array, mdarray): return Intel64Device() return None def __eq__(self, other): return isinstance(other, Intel64Device) def __repr__(self): return '<{}>'.format(self.__class__.__name__) def send_array(self, array): if isinstance(array, ideep.mdarray): return array if not isinstance(array, numpy.ndarray): array = _cpu._to_cpu(array) # to numpy.ndarray if (isinstance(array, numpy.ndarray) and array.ndim in (1, 2, 4) and 0 not in array.shape): # TODO(kmaehashi): Remove ndim validation once iDeep has fixed. # Currently iDeep only supports (1, 2, 4)-dim arrays. # Note that array returned from `ideep.array` may not be an # iDeep mdarray, e.g., when the dtype is not float32. array = ideep.array(array, itype=ideep.wgt_array) return array def is_array_supported(self, array): return isinstance(array, (numpy.ndarray, mdarray)) # ------------------------------------------------------------------------------ # ideep configuration # ------------------------------------------------------------------------------ _SHOULD_USE_IDEEP = { '==always': {'always': True, 'auto': False, 'never': False}, '>=auto': {'always': True, 'auto': True, 'never': False}, } def is_ideep_available(): """Returns if iDeep is available. Returns: bool: ``True`` if the supported version of iDeep is installed. """ return _ideep_version is not None and _ideep_version == 2 def check_ideep_available(): """Checks if iDeep is available. When iDeep is correctly set up, nothing happens. Otherwise it raises ``RuntimeError``. """ if _ideep_version is None: # If the error is missing shared object, append a message to # redirect to the ideep website. msg = str(_error) if 'cannot open shared object file' in msg: msg += ('\n\nEnsure iDeep requirements are satisfied: ' 'https://github.com/intel/ideep') raise RuntimeError( 'iDeep is not available.\n' 'Reason: {}: {}'.format(type(_error).__name__, msg)) elif _ideep_version != 2: raise RuntimeError( 'iDeep is not available.\n' 'Reason: Unsupported iDeep version ({})'.format(_ideep_version)) def should_use_ideep(level): """Determines if we should use iDeep. This function checks ``chainer.config.use_ideep`` and availability of ``ideep4py`` package. Args: level (str): iDeep use level. It must be either ``'==always'`` or ``'>=auto'``. ``'==always'`` indicates that the ``use_ideep`` config must be ``'always'`` to use iDeep. Returns: bool: ``True`` if the caller should use iDeep. """ if not is_ideep_available(): return False # TODO(niboshi): # Add lowest_version argument and compare with ideep version. # Currently ideep does not provide a way to retrieve its version. if level not in _SHOULD_USE_IDEEP: raise ValueError('invalid iDeep use level: %s ' '(must be either of "==always" or ">=auto")' % repr(level)) flags = _SHOULD_USE_IDEEP[level] use_ideep = config.use_ideep if use_ideep not in flags: raise ValueError('invalid use_ideep configuration: %s ' '(must be either of "always", "auto", or "never")' % repr(use_ideep)) return flags[use_ideep] def inputs_all_ready(inputs, supported_ndim=(2, 4)): """Checks if input arrays are supported for an iDeep primitive. Before calling an iDeep primitive (e.g., ``ideep4py.linear.Forward``), you need to make sure that all input arrays are ready for the primitive by calling this function. Information to be checked includes array types, dimesions and data types. The function checks ``inputs`` info and ``supported_ndim``. Inputs to be tested can be any of ``Variable``, ``numpy.ndarray`` or ``ideep4py.mdarray``. However, all inputs to iDeep primitives must be ``ideep4py.mdarray``. Callers of iDeep primitives are responsible of converting all inputs to ``ideep4py.mdarray``. Args: inputs (sequence of arrays or variables): Inputs to be checked. supported_ndim (tuple of ints): Supported ndim values for the iDeep primitive. Returns: bool: ``True`` if all conditions meet. """ def _is_supported_array_type(a): return isinstance(a, ideep.mdarray) or ideep.check_type([a]) if not is_ideep_available(): return False inputs = [x.data if isinstance(x, chainer.variable.Variable) else x for x in inputs] return (ideep.check_ndim(inputs, supported_ndim) and all([_is_supported_array_type(a) for a in inputs]))
pfnet/chainer
chainer/backends/intel64.py
Python
mit
5,920
package com.prolificinteractive.materialcalendarview; import android.animation.Animator; import android.content.res.Resources; import android.text.TextUtils; import android.util.TypedValue; import android.view.ViewPropertyAnimator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; import android.widget.TextView; import com.prolificinteractive.materialcalendarview.format.TitleFormatter; class TitleChanger { public static final int DEFAULT_ANIMATION_DELAY = 400; public static final int DEFAULT_Y_TRANSLATION_DP = 20; private final TextView title; private TitleFormatter titleFormatter; private final int animDelay; private final int animDuration; private final int translate; private final Interpolator interpolator = new DecelerateInterpolator(2f); private int orientation = MaterialCalendarView.VERTICAL; private long lastAnimTime = 0; private CalendarDay previousMonth = null; public TitleChanger(TextView title) { this.title = title; Resources res = title.getResources(); animDelay = DEFAULT_ANIMATION_DELAY; animDuration = res.getInteger(android.R.integer.config_shortAnimTime) / 2; translate = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, DEFAULT_Y_TRANSLATION_DP, res.getDisplayMetrics() ); } public void change(final CalendarDay currentMonth) { long currentTime = System.currentTimeMillis(); if (currentMonth == null) { return; } if (TextUtils.isEmpty(title.getText()) || (currentTime - lastAnimTime) < animDelay) { doChange(currentTime, currentMonth, false); } if (currentMonth.equals(previousMonth) || (currentMonth.getMonth() == previousMonth.getMonth() && currentMonth.getYear() == previousMonth.getYear())) { return; } doChange(currentTime, currentMonth, true); } private void doChange(final long now, final CalendarDay currentMonth, boolean animate) { title.animate().cancel(); doTranslation(title, 0); title.setAlpha(1); lastAnimTime = now; final CharSequence newTitle = titleFormatter.format(currentMonth); if (!animate) { title.setText(newTitle); } else { final int translation = translate * (previousMonth.isBefore(currentMonth) ? 1 : -1); final ViewPropertyAnimator viewPropertyAnimator = title.animate(); if (orientation == MaterialCalendarView.HORIZONTAL) { viewPropertyAnimator.translationX(translation * -1); } else { viewPropertyAnimator.translationY(translation * -1); } viewPropertyAnimator .alpha(0) .setDuration(animDuration) .setInterpolator(interpolator) .setListener(new AnimatorListener() { @Override public void onAnimationCancel(Animator animator) { doTranslation(title, 0); title.setAlpha(1); } @Override public void onAnimationEnd(Animator animator) { title.setText(newTitle); doTranslation(title, translation); final ViewPropertyAnimator viewPropertyAnimator = title.animate(); if (orientation == MaterialCalendarView.HORIZONTAL) { viewPropertyAnimator.translationX(0); } else { viewPropertyAnimator.translationY(0); } viewPropertyAnimator .alpha(1) .setDuration(animDuration) .setInterpolator(interpolator) .setListener(new AnimatorListener()) .start(); } }).start(); } previousMonth = currentMonth; } private void doTranslation(final TextView title, final int translate) { if (orientation == MaterialCalendarView.HORIZONTAL) { title.setTranslationX(translate); } else { title.setTranslationY(translate); } } public TitleFormatter getTitleFormatter() { return titleFormatter; } public void setTitleFormatter(TitleFormatter titleFormatter) { this.titleFormatter = titleFormatter; } public void setOrientation(int orientation) { this.orientation = orientation; } public int getOrientation() { return orientation; } public void setPreviousMonth(CalendarDay previousMonth) { this.previousMonth = previousMonth; } }
netcosports/material-calendarview
library/src/main/java/com/prolificinteractive/materialcalendarview/TitleChanger.java
Java
mit
5,089
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org http://www.cocos2d-x.org 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. ****************************************************************************/ #include "CCScriptSupport.h" #include "CCScheduler.h" bool CC_DLL cc_assert_script_compatible(const char *msg) { cocos2d::CCScriptEngineProtocol* pEngine = cocos2d::CCScriptEngineManager::sharedManager()->getScriptEngine(); if (pEngine && pEngine->handleAssert(msg)) { return true; } return false; } NS_CC_BEGIN // #pragma mark - // #pragma mark CCScriptHandlerEntry CCScriptHandlerEntry* CCScriptHandlerEntry::create(int nHandler) { CCScriptHandlerEntry* entry = new CCScriptHandlerEntry(nHandler); entry->autorelease(); return entry; } CCScriptHandlerEntry::~CCScriptHandlerEntry(void) { if (m_nHandler != 0) { CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptHandler(m_nHandler); m_nHandler = 0; } } // #pragma mark - // #pragma mark CCSchedulerScriptHandlerEntry CCSchedulerScriptHandlerEntry* CCSchedulerScriptHandlerEntry::create(int nHandler, float fInterval, bool bPaused) { CCSchedulerScriptHandlerEntry* pEntry = new CCSchedulerScriptHandlerEntry(nHandler); pEntry->init(fInterval, bPaused); pEntry->autorelease(); return pEntry; } bool CCSchedulerScriptHandlerEntry::init(float fInterval, bool bPaused) { m_pTimer = new CCTimer(); m_pTimer->initWithScriptHandler(m_nHandler, fInterval); m_pTimer->autorelease(); m_pTimer->retain(); m_bPaused = bPaused; LUALOG("[LUA] ADD script schedule: %d, entryID: %d", m_nHandler, m_nEntryId); return true; } CCSchedulerScriptHandlerEntry::~CCSchedulerScriptHandlerEntry(void) { m_pTimer->release(); LUALOG("[LUA] DEL script schedule %d, entryID: %d", m_nHandler, m_nEntryId); } // #pragma mark - // #pragma mark CCTouchScriptHandlerEntry CCTouchScriptHandlerEntry* CCTouchScriptHandlerEntry::create(int nHandler, bool bIsMultiTouches, int nPriority, bool bSwallowsTouches) { CCTouchScriptHandlerEntry* pEntry = new CCTouchScriptHandlerEntry(nHandler); pEntry->init(bIsMultiTouches, nPriority, bSwallowsTouches); pEntry->autorelease(); return pEntry; } CCTouchScriptHandlerEntry::~CCTouchScriptHandlerEntry(void) { if (m_nHandler != 0) { CCScriptEngineManager::sharedManager()->getScriptEngine()->removeScriptHandler(m_nHandler); LUALOG("[LUA] Remove touch event handler: %d", m_nHandler); m_nHandler = 0; } } bool CCTouchScriptHandlerEntry::init(bool bIsMultiTouches, int nPriority, bool bSwallowsTouches) { m_bIsMultiTouches = bIsMultiTouches; m_nPriority = nPriority; m_bSwallowsTouches = bSwallowsTouches; return true; } // #pragma mark - // #pragma mark CCScriptEngineManager static CCScriptEngineManager* s_pSharedScriptEngineManager = NULL; CCScriptEngineManager::~CCScriptEngineManager(void) { removeScriptEngine(); } void CCScriptEngineManager::setScriptEngine(CCScriptEngineProtocol *pScriptEngine) { removeScriptEngine(); m_pScriptEngine = pScriptEngine; } void CCScriptEngineManager::removeScriptEngine(void) { if (m_pScriptEngine) { delete m_pScriptEngine; m_pScriptEngine = NULL; } } CCScriptEngineManager* CCScriptEngineManager::sharedManager(void) { if (!s_pSharedScriptEngineManager) { s_pSharedScriptEngineManager = new CCScriptEngineManager(); } return s_pSharedScriptEngineManager; } void CCScriptEngineManager::purgeSharedManager(void) { if (s_pSharedScriptEngineManager) { delete s_pSharedScriptEngineManager; s_pSharedScriptEngineManager = NULL; } } NS_CC_END
h-iwata/MultiplayPaint
proj.ios_mac/Photon-iOS_SDK/Demos/etc-bin/cocos2dx/cocos2dx/script_support/CCScriptSupport.cpp
C++
mit
5,005
/** * ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components * @version v20.2.0 * @link http://www.ag-grid.com/ * @license MIT */ "use strict"; var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; var __metadata = (this && this.__metadata) || function (k, v) { if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v); }; Object.defineProperty(exports, "__esModule", { value: true }); var context_1 = require("../context/context"); var logger_1 = require("../logger"); var eventService_1 = require("../eventService"); var events_1 = require("../events"); var gridOptionsWrapper_1 = require("../gridOptionsWrapper"); var columnApi_1 = require("../columnController/columnApi"); var gridApi_1 = require("../gridApi"); var utils_1 = require("../utils"); /** Adds drag listening onto an element. In ag-Grid this is used twice, first is resizing columns, * second is moving the columns and column groups around (ie the 'drag' part of Drag and Drop. */ var DragService = /** @class */ (function () { function DragService() { this.onMouseUpListener = this.onMouseUp.bind(this); this.onMouseMoveListener = this.onMouseMove.bind(this); this.onTouchEndListener = this.onTouchUp.bind(this); this.onTouchMoveListener = this.onTouchMove.bind(this); this.dragEndFunctions = []; this.dragSources = []; } DragService.prototype.init = function () { this.logger = this.loggerFactory.create('DragService'); }; DragService.prototype.destroy = function () { this.dragSources.forEach(this.removeListener.bind(this)); this.dragSources.length = 0; }; DragService.prototype.removeListener = function (dragSourceAndListener) { var element = dragSourceAndListener.dragSource.eElement; var mouseDownListener = dragSourceAndListener.mouseDownListener; element.removeEventListener('mousedown', mouseDownListener); // remove touch listener only if it exists if (dragSourceAndListener.touchEnabled) { var touchStartListener = dragSourceAndListener.touchStartListener; element.removeEventListener('touchstart', touchStartListener, { passive: true }); } }; DragService.prototype.removeDragSource = function (params) { var dragSourceAndListener = utils_1._.find(this.dragSources, function (item) { return item.dragSource === params; }); if (!dragSourceAndListener) { return; } this.removeListener(dragSourceAndListener); utils_1._.removeFromArray(this.dragSources, dragSourceAndListener); }; DragService.prototype.setNoSelectToBody = function (noSelect) { var eDocument = this.gridOptionsWrapper.getDocument(); var eBody = eDocument.querySelector('body'); if (utils_1._.exists(eBody)) { // when we drag the mouse in ag-Grid, this class gets added / removed from the body, so that // the mouse isn't selecting text when dragging. utils_1._.addOrRemoveCssClass(eBody, 'ag-unselectable', noSelect); } }; DragService.prototype.addDragSource = function (params, includeTouch) { if (includeTouch === void 0) { includeTouch = false; } var mouseListener = this.onMouseDown.bind(this, params); params.eElement.addEventListener('mousedown', mouseListener); var touchListener = null; var suppressTouch = this.gridOptionsWrapper.isSuppressTouch(); if (includeTouch && !suppressTouch) { touchListener = this.onTouchStart.bind(this, params); params.eElement.addEventListener('touchstart', touchListener, { passive: false }); } this.dragSources.push({ dragSource: params, mouseDownListener: mouseListener, touchStartListener: touchListener, touchEnabled: includeTouch }); }; // gets called whenever mouse down on any drag source DragService.prototype.onTouchStart = function (params, touchEvent) { var _this = this; this.currentDragParams = params; this.dragging = false; var touch = touchEvent.touches[0]; this.touchLastTime = touch; this.touchStart = touch; touchEvent.preventDefault(); // we temporally add these listeners, for the duration of the drag, they // are removed in touch end handling. params.eElement.addEventListener('touchmove', this.onTouchMoveListener, { passive: true }); params.eElement.addEventListener('touchend', this.onTouchEndListener, { passive: true }); params.eElement.addEventListener('touchcancel', this.onTouchEndListener, { passive: true }); this.dragEndFunctions.push(function () { params.eElement.removeEventListener('touchmove', _this.onTouchMoveListener, { passive: true }); params.eElement.removeEventListener('touchend', _this.onTouchEndListener, { passive: true }); params.eElement.removeEventListener('touchcancel', _this.onTouchEndListener, { passive: true }); }); // see if we want to start dragging straight away if (params.dragStartPixels === 0) { this.onCommonMove(touch, this.touchStart); } }; // gets called whenever mouse down on any drag source DragService.prototype.onMouseDown = function (params, mouseEvent) { var _this = this; // we ignore when shift key is pressed. this is for the range selection, as when // user shift-clicks a cell, this should not be interpreted as the start of a drag. // if (mouseEvent.shiftKey) { return; } if (params.skipMouseEvent) { if (params.skipMouseEvent(mouseEvent)) { return; } } // if there are two elements with parent / child relationship, and both are draggable, // when we drag the child, we should NOT drag the parent. an example of this is row moving // and range selection - row moving should get preference when use drags the rowDrag component. if (mouseEvent._alreadyProcessedByDragService) { return; } mouseEvent._alreadyProcessedByDragService = true; // only interested in left button clicks if (mouseEvent.button !== 0) { return; } this.currentDragParams = params; this.dragging = false; this.mouseEventLastTime = mouseEvent; this.mouseStartEvent = mouseEvent; var eDocument = this.gridOptionsWrapper.getDocument(); // we temporally add these listeners, for the duration of the drag, they // are removed in mouseup handling. eDocument.addEventListener('mousemove', this.onMouseMoveListener); eDocument.addEventListener('mouseup', this.onMouseUpListener); this.dragEndFunctions.push(function () { eDocument.removeEventListener('mousemove', _this.onMouseMoveListener); eDocument.removeEventListener('mouseup', _this.onMouseUpListener); }); //see if we want to start dragging straight away if (params.dragStartPixels === 0) { this.onMouseMove(mouseEvent); } }; // returns true if the event is close to the original event by X pixels either vertically or horizontally. // we only start dragging after X pixels so this allows us to know if we should start dragging yet. DragService.prototype.isEventNearStartEvent = function (currentEvent, startEvent) { // by default, we wait 4 pixels before starting the drag var dragStartPixels = this.currentDragParams.dragStartPixels; var requiredPixelDiff = utils_1._.exists(dragStartPixels) ? dragStartPixels : 4; return utils_1._.areEventsNear(currentEvent, startEvent, requiredPixelDiff); }; DragService.prototype.getFirstActiveTouch = function (touchList) { for (var i = 0; i < touchList.length; i++) { if (touchList[i].identifier === this.touchStart.identifier) { return touchList[i]; } } return null; }; DragService.prototype.onCommonMove = function (currentEvent, startEvent) { if (!this.dragging) { // if mouse hasn't travelled from the start position enough, do nothing if (!this.dragging && this.isEventNearStartEvent(currentEvent, startEvent)) { return; } this.dragging = true; var event_1 = { type: events_1.Events.EVENT_DRAG_STARTED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_1); this.currentDragParams.onDragStart(startEvent); this.setNoSelectToBody(true); } this.currentDragParams.onDragging(currentEvent); }; DragService.prototype.onTouchMove = function (touchEvent) { var touch = this.getFirstActiveTouch(touchEvent.touches); if (!touch) { return; } // this.___statusPanel.setInfoText(Math.random() + ' onTouchMove preventDefault stopPropagation'); // if we don't preview default, then the browser will try and do it's own touch stuff, // like do 'back button' (chrome does this) or scroll the page (eg drag column could be confused // with scroll page in the app) // touchEvent.preventDefault(); this.onCommonMove(touch, this.touchStart); }; // only gets called after a mouse down - as this is only added after mouseDown // and is removed when mouseUp happens DragService.prototype.onMouseMove = function (mouseEvent) { this.onCommonMove(mouseEvent, this.mouseStartEvent); }; DragService.prototype.onTouchUp = function (touchEvent) { var touch = this.getFirstActiveTouch(touchEvent.changedTouches); // i haven't worked this out yet, but there is no matching touch // when we get the touch up event. to get around this, we swap in // the last touch. this is a hack to 'get it working' while we // figure out what's going on, why we are not getting a touch in // current event. if (!touch) { touch = this.touchLastTime; } // if mouse was left up before we started to move, then this is a tap. // we check this before onUpCommon as onUpCommon resets the dragging // let tap = !this.dragging; // let tapTarget = this.currentDragParams.eElement; this.onUpCommon(touch); // if tap, tell user // console.log(`${Math.random()} tap = ${tap}`); // if (tap) { // tapTarget.click(); // } }; DragService.prototype.onMouseUp = function (mouseEvent) { this.onUpCommon(mouseEvent); }; DragService.prototype.onUpCommon = function (eventOrTouch) { if (this.dragging) { this.dragging = false; this.currentDragParams.onDragStop(eventOrTouch); var event_2 = { type: events_1.Events.EVENT_DRAG_STOPPED, api: this.gridApi, columnApi: this.columnApi }; this.eventService.dispatchEvent(event_2); } this.setNoSelectToBody(false); this.mouseStartEvent = null; this.mouseEventLastTime = null; this.touchStart = null; this.touchLastTime = null; this.currentDragParams = null; this.dragEndFunctions.forEach(function (func) { return func(); }); this.dragEndFunctions.length = 0; }; __decorate([ context_1.Autowired('loggerFactory'), __metadata("design:type", logger_1.LoggerFactory) ], DragService.prototype, "loggerFactory", void 0); __decorate([ context_1.Autowired('eventService'), __metadata("design:type", eventService_1.EventService) ], DragService.prototype, "eventService", void 0); __decorate([ context_1.Autowired('gridOptionsWrapper'), __metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper) ], DragService.prototype, "gridOptionsWrapper", void 0); __decorate([ context_1.Autowired('columnApi'), __metadata("design:type", columnApi_1.ColumnApi) ], DragService.prototype, "columnApi", void 0); __decorate([ context_1.Autowired('gridApi'), __metadata("design:type", gridApi_1.GridApi) ], DragService.prototype, "gridApi", void 0); __decorate([ context_1.PostConstruct, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], DragService.prototype, "init", null); __decorate([ context_1.PreDestroy, __metadata("design:type", Function), __metadata("design:paramtypes", []), __metadata("design:returntype", void 0) ], DragService.prototype, "destroy", null); DragService = __decorate([ context_1.Bean('dragService') ], DragService); return DragService; }()); exports.DragService = DragService;
sufuf3/cdnjs
ajax/libs/ag-grid/21.0.0/lib/dragAndDrop/dragService.js
JavaScript
mit
13,765
<?php namespace Kunstmaan\AdminBundle\Helper\Menu; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface; /** * SettingsMenuAdaptor to add the Settings MenuItem to the top menu and build the Settings tree */ class SettingsMenuAdaptor implements MenuAdaptorInterface { /** @var AuthorizationCheckerInterface */ private $authorizationChecker; /** @var bool */ private $isEnabledVersionChecker; /** @var bool */ private $exceptionLoggingEnabled; /** * @param bool $isEnabledVersionChecker */ public function __construct(AuthorizationCheckerInterface $authorizationChecker, $isEnabledVersionChecker, bool $exceptionLoggingEnabled = true) { $this->authorizationChecker = $authorizationChecker; $this->isEnabledVersionChecker = (bool) $isEnabledVersionChecker; $this->exceptionLoggingEnabled = $exceptionLoggingEnabled; } public function adaptChildren(MenuBuilder $menu, array &$children, MenuItem $parent = null, Request $request = null) { if (\is_null($parent)) { $menuItem = new TopMenuItem($menu); $menuItem ->setRoute('KunstmaanAdminBundle_settings') ->setLabel('settings.title') ->setUniqueId('settings') ->setParent($parent) ->setRole('settings'); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); } $children[] = $menuItem; } if (!\is_null($parent) && 'KunstmaanAdminBundle_settings' == $parent->getRoute()) { if ($this->authorizationChecker->isGranted('ROLE_SUPER_ADMIN') && $this->isEnabledVersionChecker) { $menuItem = new MenuItem($menu); $menuItem ->setRoute('KunstmaanAdminBundle_settings_bundle_version') ->setLabel('settings.version.bundle') ->setUniqueId('bundle_versions') ->setParent($parent); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); } $children[] = $menuItem; } if ($this->exceptionLoggingEnabled) { $menuItem = new MenuItem($menu); $menuItem ->setRoute('kunstmaanadminbundle_admin_exception') ->setLabel('settings.exceptions.title') ->setUniqueId('exceptions') ->setParent($parent); if (stripos($request->attributes->get('_route'), $menuItem->getRoute()) === 0) { $menuItem->setActive(true); $parent->setActive(true); } $children[] = $menuItem; } } } }
Kunstmaan/KunstmaanBundlesCMS
src/Kunstmaan/AdminBundle/Helper/Menu/SettingsMenuAdaptor.php
PHP
mit
2,981
/* http://keith-wood.name/calculator.html Catalan initialisation for the jQuery calculator extension Written by Esteve Camps (ecamps at google dot com) June 2010. */ (function($) { // hide the namespace $.calculator.regionalOptions['ca'] = { decimalChar: ',', buttonText: '...', buttonStatus: 'Obrir la calculadora', closeText: 'Tancar', closeStatus: 'Tancar la calculadora', useText: 'Usar', useStatus: 'Usar el valor actual', eraseText: 'Esborrar', eraseStatus: 'Esborrar el valor actual', backspaceText: 'BS', backspaceStatus: 'Esborrar el darrer dígit', clearErrorText: 'CE', clearErrorStatus: 'Esborrar el darrer número', clearText: 'CA', clearStatus: 'Reiniciar el càlcul', memClearText: 'MC', memClearStatus: 'Esborrar la memòria', memRecallText: 'MR', memRecallStatus: 'Recuperar el valor de la memòria', memStoreText: 'MS', memStoreStatus: 'Guardar el valor a la memòria', memAddText: 'M+', memAddStatus: 'Afegir a la memòria', memSubtractText: 'M-', memSubtractStatus: 'Treure de la memòria', base2Text: 'Bin', base2Status: 'Canviar al mode Binari', base8Text: 'Oct', base8Status: 'Canviar al mode Octal', base10Text: 'Dec', base10Status: 'Canviar al mode Decimal', base16Text: 'Hex', base16Status: 'Canviar al mode Hexadecimal', degreesText: 'Deg', degreesStatus: 'Canviar al mode Graus', radiansText: 'Rad', radiansStatus: 'Canviar al mode Radians', isRTL: false}; $.calculator.setDefaults($.calculator.regionalOptions['ca']); })(jQuery);
rsantellan/ventanas-html-proyecto
ventanas/src/AppBundle/Resources/public/admin/vendor/calculator/jquery.calculator-ca.js
JavaScript
mit
1,535
/** * EditorCommands.js * * Released under LGPL License. * Copyright (c) 1999-2015 Ephox Corp. All rights reserved * * License: http://www.tinymce.com/license * Contributing: http://www.tinymce.com/contributing */ /** * This class enables you to add custom editor commands and it contains * overrides for native browser commands to address various bugs and issues. * * @class tinymce.EditorCommands */ define("tinymce/EditorCommands", [ "tinymce/html/Serializer", "tinymce/Env", "tinymce/util/Tools", "tinymce/dom/ElementUtils", "tinymce/dom/RangeUtils", "tinymce/dom/TreeWalker" ], function(Serializer, Env, Tools, ElementUtils, RangeUtils, TreeWalker) { // Added for compression purposes var each = Tools.each, extend = Tools.extend; var map = Tools.map, inArray = Tools.inArray, explode = Tools.explode; var isIE = Env.ie, isOldIE = Env.ie && Env.ie < 11; var TRUE = true, FALSE = false; return function(editor) { var dom, selection, formatter, commands = {state: {}, exec: {}, value: {}}, settings = editor.settings, bookmark; editor.on('PreInit', function() { dom = editor.dom; selection = editor.selection; settings = editor.settings; formatter = editor.formatter; }); /** * Executes the specified command. * * @method execCommand * @param {String} command Command to execute. * @param {Boolean} ui Optional user interface state. * @param {Object} value Optional value for command. * @param {Object} args Optional extra arguments to the execCommand. * @return {Boolean} true/false if the command was found or not. */ function execCommand(command, ui, value, args) { var func, customCommand, state = 0; if (!/^(mceAddUndoLevel|mceEndUndoLevel|mceBeginUndoLevel|mceRepaint)$/.test(command) && (!args || !args.skip_focus)) { editor.focus(); } args = editor.fire('BeforeExecCommand', {command: command, ui: ui, value: value}); if (args.isDefaultPrevented()) { return false; } customCommand = command.toLowerCase(); if ((func = commands.exec[customCommand])) { func(customCommand, ui, value); editor.fire('ExecCommand', {command: command, ui: ui, value: value}); return true; } // Plugin commands each(editor.plugins, function(p) { if (p.execCommand && p.execCommand(command, ui, value)) { editor.fire('ExecCommand', {command: command, ui: ui, value: value}); state = true; return false; } }); if (state) { return state; } // Theme commands if (editor.theme && editor.theme.execCommand && editor.theme.execCommand(command, ui, value)) { editor.fire('ExecCommand', {command: command, ui: ui, value: value}); return true; } // Browser commands try { state = editor.getDoc().execCommand(command, ui, value); } catch (ex) { // Ignore old IE errors } if (state) { editor.fire('ExecCommand', {command: command, ui: ui, value: value}); return true; } return false; } /** * Queries the current state for a command for example if the current selection is "bold". * * @method queryCommandState * @param {String} command Command to check the state of. * @return {Boolean/Number} true/false if the selected contents is bold or not, -1 if it's not found. */ function queryCommandState(command) { var func; // Is hidden then return undefined if (editor._isHidden()) { return; } command = command.toLowerCase(); if ((func = commands.state[command])) { return func(command); } // Browser commands try { return editor.getDoc().queryCommandState(command); } catch (ex) { // Fails sometimes see bug: 1896577 } return false; } /** * Queries the command value for example the current fontsize. * * @method queryCommandValue * @param {String} command Command to check the value of. * @return {Object} Command value of false if it's not found. */ function queryCommandValue(command) { var func; // Is hidden then return undefined if (editor._isHidden()) { return; } command = command.toLowerCase(); if ((func = commands.value[command])) { return func(command); } // Browser commands try { return editor.getDoc().queryCommandValue(command); } catch (ex) { // Fails sometimes see bug: 1896577 } } /** * Adds commands to the command collection. * * @method addCommands * @param {Object} command_list Name/value collection with commands to add, the names can also be comma separated. * @param {String} type Optional type to add, defaults to exec. Can be value or state as well. */ function addCommands(command_list, type) { type = type || 'exec'; each(command_list, function(callback, command) { each(command.toLowerCase().split(','), function(command) { commands[type][command] = callback; }); }); } function addCommand(command, callback, scope) { command = command.toLowerCase(); commands.exec[command] = function(command, ui, value, args) { return callback.call(scope || editor, ui, value, args); }; } /** * Returns true/false if the command is supported or not. * * @method queryCommandSupported * @param {String} command Command that we check support for. * @return {Boolean} true/false if the command is supported or not. */ function queryCommandSupported(command) { command = command.toLowerCase(); if (commands.exec[command]) { return true; } // Browser commands try { return editor.getDoc().queryCommandSupported(command); } catch (ex) { // Fails sometimes see bug: 1896577 } return false; } function addQueryStateHandler(command, callback, scope) { command = command.toLowerCase(); commands.state[command] = function() { return callback.call(scope || editor); }; } function addQueryValueHandler(command, callback, scope) { command = command.toLowerCase(); commands.value[command] = function() { return callback.call(scope || editor); }; } function hasCustomCommand(command) { command = command.toLowerCase(); return !!commands.exec[command]; } // Expose public methods extend(this, { execCommand: execCommand, queryCommandState: queryCommandState, queryCommandValue: queryCommandValue, queryCommandSupported: queryCommandSupported, addCommands: addCommands, addCommand: addCommand, addQueryStateHandler: addQueryStateHandler, addQueryValueHandler: addQueryValueHandler, hasCustomCommand: hasCustomCommand }); // Private methods function execNativeCommand(command, ui, value) { if (ui === undefined) { ui = FALSE; } if (value === undefined) { value = null; } return editor.getDoc().execCommand(command, ui, value); } function isFormatMatch(name) { return formatter.match(name); } function toggleFormat(name, value) { formatter.toggle(name, value ? {value: value} : undefined); editor.nodeChanged(); } function storeSelection(type) { bookmark = selection.getBookmark(type); } function restoreSelection() { selection.moveToBookmark(bookmark); } // Add execCommand overrides addCommands({ // Ignore these, added for compatibility 'mceResetDesignMode,mceBeginUndoLevel': function() {}, // Add undo manager logic 'mceEndUndoLevel,mceAddUndoLevel': function() { editor.undoManager.add(); }, 'Cut,Copy,Paste': function(command) { var doc = editor.getDoc(), failed; // Try executing the native command try { execNativeCommand(command); } catch (ex) { // Command failed failed = TRUE; } // Present alert message about clipboard access not being available if (failed || !doc.queryCommandSupported(command)) { var msg = editor.translate( "Your browser doesn't support direct access to the clipboard. " + "Please use the Ctrl+X/C/V keyboard shortcuts instead." ); if (Env.mac) { msg = msg.replace(/Ctrl\+/g, '\u2318+'); } editor.notificationManager.open({text: msg, type: 'error'}); } }, // Override unlink command unlink: function() { if (selection.isCollapsed()) { var elm = selection.getNode(); if (elm.tagName == 'A') { editor.dom.remove(elm, true); } return; } formatter.remove("link"); }, // Override justify commands to use the text formatter engine 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull,JustifyNone': function(command) { var align = command.substring(7); if (align == 'full') { align = 'justify'; } // Remove all other alignments first each('left,center,right,justify'.split(','), function(name) { if (align != name) { formatter.remove('align' + name); } }); if (align != 'none') { toggleFormat('align' + align); } }, // Override list commands to fix WebKit bug 'InsertUnorderedList,InsertOrderedList': function(command) { var listElm, listParent; execNativeCommand(command); // WebKit produces lists within block elements so we need to split them // we will replace the native list creation logic to custom logic later on // TODO: Remove this when the list creation logic is removed listElm = dom.getParent(selection.getNode(), 'ol,ul'); if (listElm) { listParent = listElm.parentNode; // If list is within a text block then split that block if (/^(H[1-6]|P|ADDRESS|PRE)$/.test(listParent.nodeName)) { storeSelection(); dom.split(listParent, listElm); restoreSelection(); } } }, // Override commands to use the text formatter engine 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { toggleFormat(command); }, // Override commands to use the text formatter engine 'ForeColor,HiliteColor,FontName': function(command, ui, value) { toggleFormat(command, value); }, FontSize: function(command, ui, value) { var fontClasses, fontSizes; // Convert font size 1-7 to styles if (value >= 1 && value <= 7) { fontSizes = explode(settings.font_size_style_values); fontClasses = explode(settings.font_size_classes); if (fontClasses) { value = fontClasses[value - 1] || value; } else { value = fontSizes[value - 1] || value; } } toggleFormat(command, value); }, RemoveFormat: function(command) { formatter.remove(command); }, mceBlockQuote: function() { toggleFormat('blockquote'); }, FormatBlock: function(command, ui, value) { return toggleFormat(value || 'p'); }, mceCleanup: function() { var bookmark = selection.getBookmark(); editor.setContent(editor.getContent({cleanup: TRUE}), {cleanup: TRUE}); selection.moveToBookmark(bookmark); }, mceRemoveNode: function(command, ui, value) { var node = value || selection.getNode(); // Make sure that the body node isn't removed if (node != editor.getBody()) { storeSelection(); editor.dom.remove(node, TRUE); restoreSelection(); } }, mceSelectNodeDepth: function(command, ui, value) { var counter = 0; dom.getParent(selection.getNode(), function(node) { if (node.nodeType == 1 && counter++ == value) { selection.select(node); return FALSE; } }, editor.getBody()); }, mceSelectNode: function(command, ui, value) { selection.select(value); }, mceInsertContent: function(command, ui, value) { var parser, serializer, parentNode, rootNode, fragment, args; var marker, rng, node, node2, bookmarkHtml, merge, data; var textInlineElements = editor.schema.getTextInlineElements(); function trimOrPaddLeftRight(html) { var rng, container, offset; rng = selection.getRng(true); container = rng.startContainer; offset = rng.startOffset; function hasSiblingText(siblingName) { return container[siblingName] && container[siblingName].nodeType == 3; } if (container.nodeType == 3) { if (offset > 0) { html = html.replace(/^&nbsp;/, ' '); } else if (!hasSiblingText('previousSibling')) { html = html.replace(/^ /, '&nbsp;'); } if (offset < container.length) { html = html.replace(/&nbsp;(<br>|)$/, ' '); } else if (!hasSiblingText('nextSibling')) { html = html.replace(/(&nbsp;| )(<br>|)$/, '&nbsp;'); } } return html; } // Removes &nbsp; from a [b] c -> a &nbsp;c -> a c function trimNbspAfterDeleteAndPaddValue() { var rng, container, offset; rng = selection.getRng(true); container = rng.startContainer; offset = rng.startOffset; if (container.nodeType == 3 && rng.collapsed) { if (container.data[offset] === '\u00a0') { container.deleteData(offset, 1); if (!/[\u00a0| ]$/.test(value)) { value += ' '; } } else if (container.data[offset - 1] === '\u00a0') { container.deleteData(offset - 1, 1); if (!/[\u00a0| ]$/.test(value)) { value = ' ' + value; } } } } function markInlineFormatElements(fragment) { if (merge) { for (node = fragment.firstChild; node; node = node.walk(true)) { if (textInlineElements[node.name]) { node.attr('data-mce-new', "true"); } } } } function reduceInlineTextElements() { if (merge) { var root = editor.getBody(), elementUtils = new ElementUtils(dom); each(dom.select('*[data-mce-new]'), function(node) { node.removeAttribute('data-mce-new'); for (var testNode = node.parentNode; testNode && testNode != root; testNode = testNode.parentNode) { if (elementUtils.compare(testNode, node)) { dom.remove(node, true); } } }); } } function moveSelectionToMarker(marker) { var parentEditableFalseElm; function getContentEditableFalseParent(node) { var root = editor.getBody(); for (; node && node !== root; node = node.parentNode) { if (editor.dom.getContentEditable(node) === 'false') { return node; } } return null; } if (!marker) { return; } selection.scrollIntoView(marker); // If marker is in cE=false then move selection to that element instead parentEditableFalseElm = getContentEditableFalseParent(marker); if (parentEditableFalseElm) { dom.remove(marker); selection.select(parentEditableFalseElm); return; } // Move selection before marker and remove it rng = dom.createRng(); // If previous sibling is a text node set the selection to the end of that node node = marker.previousSibling; if (node && node.nodeType == 3) { rng.setStart(node, node.nodeValue.length); // TODO: Why can't we normalize on IE if (!isIE) { node2 = marker.nextSibling; if (node2 && node2.nodeType == 3) { node.appendData(node2.data); node2.parentNode.removeChild(node2); } } } else { // If the previous sibling isn't a text node or doesn't exist set the selection before the marker node rng.setStartBefore(marker); rng.setEndBefore(marker); } // Remove the marker node and set the new range dom.remove(marker); selection.setRng(rng); } if (typeof value != 'string') { merge = value.merge; data = value.data; value = value.content; } // Check for whitespace before/after value if (/^ | $/.test(value)) { value = trimOrPaddLeftRight(value); } // Setup parser and serializer parser = editor.parser; serializer = new Serializer({ validate: settings.validate }, editor.schema); bookmarkHtml = '<span id="mce_marker" data-mce-type="bookmark">&#xFEFF;&#x200B;</span>'; // Run beforeSetContent handlers on the HTML to be inserted args = {content: value, format: 'html', selection: true}; editor.fire('BeforeSetContent', args); value = args.content; // Add caret at end of contents if it's missing if (value.indexOf('{$caret}') == -1) { value += '{$caret}'; } // Replace the caret marker with a span bookmark element value = value.replace(/\{\$caret\}/, bookmarkHtml); // If selection is at <body>|<p></p> then move it into <body><p>|</p> rng = selection.getRng(); var caretElement = rng.startContainer || (rng.parentElement ? rng.parentElement() : null); var body = editor.getBody(); if (caretElement === body && selection.isCollapsed()) { if (dom.isBlock(body.firstChild) && dom.isEmpty(body.firstChild)) { rng = dom.createRng(); rng.setStart(body.firstChild, 0); rng.setEnd(body.firstChild, 0); selection.setRng(rng); } } // Insert node maker where we will insert the new HTML and get it's parent if (!selection.isCollapsed()) { editor.getDoc().execCommand('Delete', false, null); trimNbspAfterDeleteAndPaddValue(); } parentNode = selection.getNode(); // Parse the fragment within the context of the parent node var parserArgs = {context: parentNode.nodeName.toLowerCase(), data: data}; fragment = parser.parse(value, parserArgs); markInlineFormatElements(fragment); // Move the caret to a more suitable location node = fragment.lastChild; if (node.attr('id') == 'mce_marker') { marker = node; for (node = node.prev; node; node = node.walk(true)) { if (node.type == 3 || !dom.isBlock(node.name)) { if (editor.schema.isValidChild(node.parent.name, 'span')) { node.parent.insert(marker, node, node.name === 'br'); } break; } } } editor._selectionOverrides.showBlockCaretContainer(parentNode); // If parser says valid we can insert the contents into that parent if (!parserArgs.invalid) { value = serializer.serialize(fragment); // Check if parent is empty or only has one BR element then set the innerHTML of that parent node = parentNode.firstChild; node2 = parentNode.lastChild; if (!node || (node === node2 && node.nodeName === 'BR')) { dom.setHTML(parentNode, value); } else { selection.setContent(value); } } else { // If the fragment was invalid within that context then we need // to parse and process the parent it's inserted into // Insert bookmark node and get the parent selection.setContent(bookmarkHtml); parentNode = selection.getNode(); rootNode = editor.getBody(); // Opera will return the document node when selection is in root if (parentNode.nodeType == 9) { parentNode = node = rootNode; } else { node = parentNode; } // Find the ancestor just before the root element while (node !== rootNode) { parentNode = node; node = node.parentNode; } // Get the outer/inner HTML depending on if we are in the root and parser and serialize that value = parentNode == rootNode ? rootNode.innerHTML : dom.getOuterHTML(parentNode); value = serializer.serialize( parser.parse( // Need to replace by using a function since $ in the contents would otherwise be a problem value.replace(/<span (id="mce_marker"|id=mce_marker).+?<\/span>/i, function() { return serializer.serialize(fragment); }) ) ); // Set the inner/outer HTML depending on if we are in the root or not if (parentNode == rootNode) { dom.setHTML(rootNode, value); } else { dom.setOuterHTML(parentNode, value); } } reduceInlineTextElements(); moveSelectionToMarker(dom.get('mce_marker')); editor.fire('SetContent', args); editor.addVisual(); }, mceInsertRawHTML: function(command, ui, value) { selection.setContent('tiny_mce_marker'); editor.setContent( editor.getContent().replace(/tiny_mce_marker/g, function() { return value; }) ); }, mceToggleFormat: function(command, ui, value) { toggleFormat(value); }, mceSetContent: function(command, ui, value) { editor.setContent(value); }, 'Indent,Outdent': function(command) { var intentValue, indentUnit, value; // Setup indent level intentValue = settings.indentation; indentUnit = /[a-z%]+$/i.exec(intentValue); intentValue = parseInt(intentValue, 10); if (!queryCommandState('InsertUnorderedList') && !queryCommandState('InsertOrderedList')) { // If forced_root_blocks is set to false we don't have a block to indent so lets create a div if (!settings.forced_root_block && !dom.getParent(selection.getNode(), dom.isBlock)) { formatter.apply('div'); } each(selection.getSelectedBlocks(), function(element) { if (dom.getContentEditable(element) === "false") { return; } if (element.nodeName != "LI") { var indentStyleName = editor.getParam('indent_use_margin', false) ? 'margin' : 'padding'; indentStyleName += dom.getStyle(element, 'direction', true) == 'rtl' ? 'Right' : 'Left'; if (command == 'outdent') { value = Math.max(0, parseInt(element.style[indentStyleName] || 0, 10) - intentValue); dom.setStyle(element, indentStyleName, value ? value + indentUnit : ''); } else { value = (parseInt(element.style[indentStyleName] || 0, 10) + intentValue) + indentUnit; dom.setStyle(element, indentStyleName, value); } } }); } else { execNativeCommand(command); } }, mceRepaint: function() { }, InsertHorizontalRule: function() { editor.execCommand('mceInsertContent', false, '<hr />'); }, mceToggleVisualAid: function() { editor.hasVisual = !editor.hasVisual; editor.addVisual(); }, mceReplaceContent: function(command, ui, value) { editor.execCommand('mceInsertContent', false, value.replace(/\{\$selection\}/g, selection.getContent({format: 'text'}))); }, mceInsertLink: function(command, ui, value) { var anchor; if (typeof value == 'string') { value = {href: value}; } anchor = dom.getParent(selection.getNode(), 'a'); // Spaces are never valid in URLs and it's a very common mistake for people to make so we fix it here. value.href = value.href.replace(' ', '%20'); // Remove existing links if there could be child links or that the href isn't specified if (!anchor || !value.href) { formatter.remove('link'); } // Apply new link to selection if (value.href) { formatter.apply('link', value, anchor); } }, selectAll: function() { var root = dom.getRoot(), rng; if (selection.getRng().setStart) { rng = dom.createRng(); rng.setStart(root, 0); rng.setEnd(root, root.childNodes.length); selection.setRng(rng); } else { // IE will render it's own root level block elements and sometimes // even put font elements in them when the user starts typing. So we need to // move the selection to a more suitable element from this: // <body>|<p></p></body> to this: <body><p>|</p></body> rng = selection.getRng(); if (!rng.item) { rng.moveToElementText(root); rng.select(); } } }, "delete": function() { execNativeCommand("Delete"); // Check if body is empty after the delete call if so then set the contents // to an empty string and move the caret to any block produced by that operation // this fixes the issue with root blocks not being properly produced after a delete call on IE var body = editor.getBody(); if (dom.isEmpty(body)) { editor.setContent(''); if (body.firstChild && dom.isBlock(body.firstChild)) { editor.selection.setCursorLocation(body.firstChild, 0); } else { editor.selection.setCursorLocation(body, 0); } } }, mceNewDocument: function() { editor.setContent(''); }, InsertLineBreak: function(command, ui, value) { // We load the current event in from EnterKey.js when appropriate to heed // certain event-specific variations such as ctrl-enter in a list var evt = value; var brElm, extraBr, marker; var rng = selection.getRng(true); new RangeUtils(dom).normalize(rng); var offset = rng.startOffset; var container = rng.startContainer; // Resolve node index if (container.nodeType == 1 && container.hasChildNodes()) { var isAfterLastNodeInContainer = offset > container.childNodes.length - 1; container = container.childNodes[Math.min(offset, container.childNodes.length - 1)] || container; if (isAfterLastNodeInContainer && container.nodeType == 3) { offset = container.nodeValue.length; } else { offset = 0; } } var parentBlock = dom.getParent(container, dom.isBlock); var parentBlockName = parentBlock ? parentBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 var containerBlock = parentBlock ? dom.getParent(parentBlock.parentNode, dom.isBlock) : null; var containerBlockName = containerBlock ? containerBlock.nodeName.toUpperCase() : ''; // IE < 9 & HTML5 // Enter inside block contained within a LI then split or insert before/after LI var isControlKey = evt && evt.ctrlKey; if (containerBlockName == 'LI' && !isControlKey) { parentBlock = containerBlock; parentBlockName = containerBlockName; } // Walks the parent block to the right and look for BR elements function hasRightSideContent() { var walker = new TreeWalker(container, parentBlock), node; var nonEmptyElementsMap = editor.schema.getNonEmptyElements(); while ((node = walker.next())) { if (nonEmptyElementsMap[node.nodeName.toLowerCase()] || node.length > 0) { return true; } } } if (container && container.nodeType == 3 && offset >= container.nodeValue.length) { // Insert extra BR element at the end block elements if (!isOldIE && !hasRightSideContent()) { brElm = dom.create('br'); rng.insertNode(brElm); rng.setStartAfter(brElm); rng.setEndAfter(brElm); extraBr = true; } } brElm = dom.create('br'); rng.insertNode(brElm); // Rendering modes below IE8 doesn't display BR elements in PRE unless we have a \n before it var documentMode = dom.doc.documentMode; if (isOldIE && parentBlockName == 'PRE' && (!documentMode || documentMode < 8)) { brElm.parentNode.insertBefore(dom.doc.createTextNode('\r'), brElm); } // Insert temp marker and scroll to that marker = dom.create('span', {}, '&nbsp;'); brElm.parentNode.insertBefore(marker, brElm); selection.scrollIntoView(marker); dom.remove(marker); if (!extraBr) { rng.setStartAfter(brElm); rng.setEndAfter(brElm); } else { rng.setStartBefore(brElm); rng.setEndBefore(brElm); } selection.setRng(rng); editor.undoManager.add(); return TRUE; } }); // Add queryCommandState overrides addCommands({ // Override justify commands 'JustifyLeft,JustifyCenter,JustifyRight,JustifyFull': function(command) { var name = 'align' + command.substring(7); var nodes = selection.isCollapsed() ? [dom.getParent(selection.getNode(), dom.isBlock)] : selection.getSelectedBlocks(); var matches = map(nodes, function(node) { return !!formatter.matchNode(node, name); }); return inArray(matches, TRUE) !== -1; }, 'Bold,Italic,Underline,Strikethrough,Superscript,Subscript': function(command) { return isFormatMatch(command); }, mceBlockQuote: function() { return isFormatMatch('blockquote'); }, Outdent: function() { var node; if (settings.inline_styles) { if ((node = dom.getParent(selection.getStart(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { return TRUE; } if ((node = dom.getParent(selection.getEnd(), dom.isBlock)) && parseInt(node.style.paddingLeft, 10) > 0) { return TRUE; } } return ( queryCommandState('InsertUnorderedList') || queryCommandState('InsertOrderedList') || (!settings.inline_styles && !!dom.getParent(selection.getNode(), 'BLOCKQUOTE')) ); }, 'InsertUnorderedList,InsertOrderedList': function(command) { var list = dom.getParent(selection.getNode(), 'ul,ol'); return list && ( command === 'insertunorderedlist' && list.tagName === 'UL' || command === 'insertorderedlist' && list.tagName === 'OL' ); } }, 'state'); // Add queryCommandValue overrides addCommands({ 'FontSize,FontName': function(command) { var value = 0, parent; if ((parent = dom.getParent(selection.getNode(), 'span'))) { if (command == 'fontsize') { value = parent.style.fontSize; } else { value = parent.style.fontFamily.replace(/, /g, ',').replace(/[\'\"]/g, '').toLowerCase(); } } return value; } }, 'value'); // Add undo manager logic addCommands({ Undo: function() { editor.undoManager.undo(); }, Redo: function() { editor.undoManager.redo(); } }); }; });
michalgraczyk/calculus
web/js/tiny_mce/js/tinymce/classes/EditorCommands.js
JavaScript
mit
29,362
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using Perspex.Media; using TheArtOfDev.HtmlRenderer.Adapters; using TheArtOfDev.HtmlRenderer.Adapters.Entities; namespace TheArtOfDev.HtmlRenderer.Perspex.Adapters { /// <summary> /// Adapter for Perspex Font. /// </summary> internal sealed class FontAdapter : RFont { public RFontStyle Style { get; } #region Fields and Consts /// <summary> /// the size of the font /// </summary> private readonly double _size; /// <summary> /// the vertical offset of the font underline location from the top of the font. /// </summary> private readonly double _underlineOffset = -1; /// <summary> /// Cached font height. /// </summary> private readonly double _height = -1; /// <summary> /// Cached font whitespace width. /// </summary> private double _whitespaceWidth = -1; #endregion /// <summary> /// Init. /// </summary> public FontAdapter(string fontFamily, double size, RFontStyle style) { Style = style; Name = fontFamily; _size = size; //TODO: Somehow get proper line spacing and underlinePosition var lineSpacing = 1; var underlinePosition = 0; _height = 96d / 72d * _size * lineSpacing; _underlineOffset = 96d / 72d * _size * (lineSpacing + underlinePosition); } public string Name { get; set; } public override double Size { get { return _size; } } public override double UnderlineOffset { get { return _underlineOffset; } } public override double Height { get { return _height; } } public override double LeftPadding { get { return _height / 6f; } } public override double GetWhitespaceWidth(RGraphics graphics) { if (_whitespaceWidth < 0) { _whitespaceWidth = graphics.MeasureString(" ", this).Width; } return _whitespaceWidth; } public FontStyle FontStyle => Style.HasFlag(RFontStyle.Italic) ? FontStyle.Italic : FontStyle.Normal; public FontWeight Weight => Style.HasFlag(RFontStyle.Bold) ? FontWeight.Bold : FontWeight.Normal; } }
danwalmsley/Perspex
src/Perspex.HtmlRenderer/Adapters/FontAdapter.cs
C#
mit
2,736
<?php /** * WPSEO plugin file. * * @package WPSEO\Internals\Options */ /** * Option: wpseo. */ class WPSEO_Option_Wpseo extends WPSEO_Option { /** * @var string Option name. */ public $option_name = 'wpseo'; /** * @var array Array of defaults for the option. * Shouldn't be requested directly, use $this->get_defaults(); */ protected $defaults = array( // Non-form fields, set via (ajax) function. 'ms_defaults_set' => false, // Non-form field, should only be set via validation routine. 'version' => '', // Leave default as empty to ensure activation/upgrade works. // Form fields. 'disableadvanced_meta' => true, 'onpage_indexability' => true, 'baiduverify' => '', // Text field. 'googleverify' => '', // Text field. 'msverify' => '', // Text field. 'yandexverify' => '', 'site_type' => '', // List of options. 'has_multiple_authors' => '', 'environment_type' => '', 'content_analysis_active' => true, 'keyword_analysis_active' => true, 'enable_admin_bar_menu' => true, 'enable_cornerstone_content' => true, 'enable_xml_sitemap' => true, 'enable_text_link_counter' => true, 'show_onboarding_notice' => false, 'first_activated_on' => false, 'recalibration_beta' => false, ); /** * @var array Sub-options which should not be overloaded with multi-site defaults. */ public $ms_exclude = array( /* Privacy. */ 'baiduverify', 'googleverify', 'msverify', 'yandexverify', ); /** @var array Possible values for the site_type option. */ protected $site_types = array( '', 'blog', 'shop', 'news', 'smallBusiness', 'corporateOther', 'personalOther', ); /** @var array Possible environment types. */ protected $environment_types = array( '', 'production', 'staging', 'development', ); /** @var array Possible has_multiple_authors options. */ protected $has_multiple_authors_options = array( '', true, false, ); /** * @var string Name for an option higher in the hierarchy to override setting access. */ protected $override_option_name = 'wpseo_ms'; /** * Add the actions and filters for the option. * * @todo [JRF => testers] Check if the extra actions below would run into problems if an option * is updated early on and if so, change the call to schedule these for a later action on add/update * instead of running them straight away. * * @return \WPSEO_Option_Wpseo */ protected function __construct() { parent::__construct(); /* Clear the cache on update/add. */ add_action( 'add_option_' . $this->option_name, array( 'WPSEO_Utils', 'clear_cache' ) ); add_action( 'update_option_' . $this->option_name, array( 'WPSEO_Utils', 'clear_cache' ) ); /** * Filter the `wpseo` option defaults. * * @param array $defaults Array the defaults for the `wpseo` option attributes. */ $this->defaults = apply_filters( 'wpseo_option_wpseo_defaults', $this->defaults ); } /** * Get the singleton instance of this class. * * @return object */ public static function get_instance() { if ( ! ( self::$instance instanceof self ) ) { self::$instance = new self(); } return self::$instance; } /** * Add filters to make sure that the option is merged with its defaults before being returned. * * @return void */ public function add_option_filters() { parent::add_option_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_option_filter_hook(); if ( has_filter( $hookname, $callback ) === false ) { add_filter( $hookname, $callback, $priority ); } } /** * Remove the option filters. * Called from the clean_up methods to make sure we retrieve the original old option. * * @return void */ public function remove_option_filters() { parent::remove_option_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_option_filter_hook(); remove_filter( $hookname, $callback, $priority ); } /** * Add filters to make sure that the option default is returned if the option is not set. * * @return void */ public function add_default_filters() { parent::add_default_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_default_option_filter_hook(); if ( has_filter( $hookname, $callback ) === false ) { add_filter( $hookname, $callback, $priority ); } } /** * Remove the default filters. * Called from the validate() method to prevent failure to add new options. * * @return void */ public function remove_default_filters() { parent::remove_default_filters(); list( $hookname, $callback, $priority ) = $this->get_verify_features_default_option_filter_hook(); remove_filter( $hookname, $callback, $priority ); } /** * Validate the option. * * @param array $dirty New value for the option. * @param array $clean Clean value for the option, normally the defaults. * @param array $old Old value of the option. * * @return array Validated clean value for the option to be saved to the database. */ protected function validate_option( $dirty, $clean, $old ) { foreach ( $clean as $key => $value ) { switch ( $key ) { case 'version': $clean[ $key ] = WPSEO_VERSION; break; /* Verification strings. */ case 'baiduverify': case 'googleverify': case 'msverify': case 'yandexverify': $this->validate_verification_string( $key, $dirty, $old, $clean ); break; /* * Boolean dismiss warnings - not fields - may not be in form * (and don't need to be either as long as the default is false). */ case 'ms_defaults_set': if ( isset( $dirty[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::validate_bool( $dirty[ $key ] ); } elseif ( isset( $old[ $key ] ) ) { $clean[ $key ] = WPSEO_Utils::validate_bool( $old[ $key ] ); } break; case 'site_type': $clean[ $key ] = $old[ $key ]; if ( isset( $dirty[ $key ] ) && in_array( $dirty[ $key ], $this->site_types, true ) ) { $clean[ $key ] = $dirty[ $key ]; } break; case 'environment_type': $clean[ $key ] = $old[ $key ]; if ( isset( $dirty[ $key ] ) && in_array( $dirty[ $key ], $this->environment_types, true ) ) { $clean[ $key ] = $dirty[ $key ]; } break; case 'has_multiple_authors': $clean[ $key ] = $old[ $key ]; if ( isset( $dirty[ $key ] ) && in_array( $dirty[ $key ], $this->has_multiple_authors_options, true ) ) { $clean[ $key ] = $dirty[ $key ]; } break; case 'first_activated_on': $clean[ $key ] = false; if ( isset( $dirty[ $key ] ) ) { if ( $dirty[ $key ] === false || WPSEO_Utils::validate_int( $dirty[ $key ] ) ) { $clean[ $key ] = $dirty[ $key ]; } } break; /* * Boolean (checkbox) fields. */ /* * Covers: * 'disableadvanced_meta' * 'yoast_tracking' */ default: $clean[ $key ] = ( isset( $dirty[ $key ] ) ? WPSEO_Utils::validate_bool( $dirty[ $key ] ) : false ); break; } } return $clean; } /** * Verifies that the feature variables are turned off if the network is configured so. * * @param mixed $options Value of the option to be returned. Typically an array. * * @return mixed Filtered $options value. */ public function verify_features_against_network( $options = array() ) { if ( ! is_array( $options ) || empty( $options ) ) { return $options; } // For the feature variables, set their values to off in case they are disabled. $feature_vars = array( 'disableadvanced_meta' => false, 'onpage_indexability' => false, 'content_analysis_active' => false, 'keyword_analysis_active' => false, 'enable_admin_bar_menu' => false, 'enable_cornerstone_content' => false, 'enable_xml_sitemap' => false, 'enable_text_link_counter' => false, ); // We can reuse this logic from the base class with the above defaults to parse with the correct feature values. $options = $this->prevent_disabled_options_update( $options, $feature_vars ); return $options; } /** * Gets the filter hook name and callback for adjusting the retrieved option value against the network-allowed features. * * @return array Array where the first item is the hook name, the second is the hook callback, * and the third is the hook priority. */ protected function get_verify_features_option_filter_hook() { return array( "option_{$this->option_name}", array( $this, 'verify_features_against_network' ), 11, ); } /** * Gets the filter hook name and callback for adjusting the default option value against the network-allowed features. * * @return array Array where the first item is the hook name, the second is the hook callback, * and the third is the hook priority. */ protected function get_verify_features_default_option_filter_hook() { return array( "default_option_{$this->option_name}", array( $this, 'verify_features_against_network' ), 11, ); } /** * Clean a given option value. * * @param array $option_value Old (not merged with defaults or filtered) option value to * clean according to the rules for this option. * @param string $current_version Optional. Version from which to upgrade, if not set, * version specific upgrades will be disregarded. * @param array $all_old_option_values Optional. Only used when importing old options to have * access to the real old values, in contrast to the saved ones. * * @return array Cleaned option. */ protected function clean_option( $option_value, $current_version = null, $all_old_option_values = null ) { return $option_value; } }
mandino/hotelmilosantabarbara.com
wp-content/plugins/wordpress-seo/inc/options/class-wpseo-option-wpseo.php
PHP
mit
10,210
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.test.utility.events; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.eclipse.persistence.tools.workbench.utility.AbstractModel; import org.eclipse.persistence.tools.workbench.utility.ClassTools; import org.eclipse.persistence.tools.workbench.utility.CollectionTools; import org.eclipse.persistence.tools.workbench.utility.events.CollectionChangeListener; import org.eclipse.persistence.tools.workbench.utility.events.ListChangeEvent; import org.eclipse.persistence.tools.workbench.utility.events.ListChangeListener; import org.eclipse.persistence.tools.workbench.utility.events.ReflectiveChangeListener; import org.eclipse.persistence.tools.workbench.utility.iterators.CloneListIterator; public class ReflectiveListChangeListenerTests extends TestCase { public static Test suite() { return new TestSuite(ReflectiveListChangeListenerTests.class); } public ReflectiveListChangeListenerTests(String name) { super(name); } private ListChangeListener buildZeroArgumentListener(Object target) { return ReflectiveChangeListener.buildListChangeListener(target, "itemAddedZeroArgument", "itemRemovedZeroArgument", "itemReplacedZeroArgument", "listChangedZeroArgument"); } private ListChangeListener buildSingleArgumentListener(Object target) { return ReflectiveChangeListener.buildListChangeListener(target, "itemAddedSingleArgument", "itemRemovedSingleArgument", "itemReplacedSingleArgument", "listChangedSingleArgument"); } public void testItemAddedZeroArgument() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.addString(string); assertTrue(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemAddedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.addString(string); assertTrue(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemAddedSingleArgument() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.addString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertTrue(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemAddedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.addString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertTrue(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedZeroArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertTrue(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertTrue(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedSingleArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertTrue(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemRemovedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.removeString(string); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertTrue(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedZeroArgument() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertTrue(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertTrue(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedSingleArgument() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertTrue(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testItemReplacedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String oldString = "foo"; String newString = "bar"; testModel.addString(oldString); Target target = new Target(testModel, TestModel.STRINGS_LIST, newString, 0, oldString); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.replaceString(oldString, newString); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertTrue(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testListChangedZeroArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(this.buildZeroArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertTrue(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testListChangedZeroArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildZeroArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertTrue(target.listChangedZeroArgumentFlag); assertFalse(target.listChangedSingleArgumentFlag); } public void testListChangedSingleArgument() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(this.buildSingleArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertTrue(target.listChangedSingleArgumentFlag); } public void testListChangedSingleArgumentNamedList() { TestModel testModel = new TestModel(); String string = "foo"; testModel.addString(string); Target target = new Target(testModel, TestModel.STRINGS_LIST, null, -1); testModel.addListChangeListener(TestModel.STRINGS_LIST, this.buildSingleArgumentListener(target)); testModel.replaceAllStrings(new String[] {"bar", "baz"}); assertFalse(target.itemAddedZeroArgumentFlag); assertFalse(target.itemAddedSingleArgumentFlag); assertFalse(target.itemRemovedZeroArgumentFlag); assertFalse(target.itemRemovedSingleArgumentFlag); assertFalse(target.itemReplacedZeroArgumentFlag); assertFalse(target.itemReplacedSingleArgumentFlag); assertFalse(target.listChangedZeroArgumentFlag); assertTrue(target.listChangedSingleArgumentFlag); } public void testBogusDoubleArgument1() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); boolean exCaught = false; try { ListChangeListener listener = ReflectiveChangeListener.buildListChangeListener(target, "listChangedDoubleArgument"); fail("bogus listener: " + listener); } catch (RuntimeException ex) { if (ex.getCause().getClass() == NoSuchMethodException.class) { exCaught = true; } } assertTrue(exCaught); } public void testBogusDoubleArgument2() throws Exception { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); Method method = ClassTools.method(target, "listChangedDoubleArgument", new Class[] {ListChangeEvent.class, Object.class}); boolean exCaught = false; try { ListChangeListener listener = ReflectiveChangeListener.buildListChangeListener(target, method); fail("bogus listener: " + listener); } catch (RuntimeException ex) { if (ex.getMessage().equals(method.toString())) { exCaught = true; } } assertTrue(exCaught); } public void testListenerMismatch() { TestModel testModel = new TestModel(); String string = "foo"; Target target = new Target(testModel, TestModel.STRINGS_LIST, string, 0); // build a LIST change listener and hack it so we // can add it as a COLLECTION change listener Object listener = ReflectiveChangeListener.buildListChangeListener(target, "itemAddedSingleArgument"); testModel.addCollectionChangeListener((CollectionChangeListener) listener); boolean exCaught = false; try { testModel.changeCollection(); fail("listener mismatch: " + listener); } catch (IllegalArgumentException ex) { exCaught = true; } assertTrue(exCaught); } private class TestModel extends AbstractModel { private List strings = new ArrayList(); public static final String STRINGS_LIST = "strings"; TestModel() { super(); } ListIterator strings() { return new CloneListIterator(this.strings); } void addString(String string) { this.addItemToList(string, this.strings, STRINGS_LIST); } void removeString(String string) { this.removeItemFromList(this.strings.indexOf(string), this.strings, STRINGS_LIST); } void replaceString(String oldString, String newString) { this.setItemInList(this.strings.indexOf(oldString), newString, this.strings, STRINGS_LIST); } void replaceAllStrings(String[] newStrings) { this.strings.clear(); CollectionTools.addAll(this.strings, newStrings); this.fireListChanged(STRINGS_LIST); } void changeCollection() { this.fireCollectionChanged("bogus collection"); } } private class Target { TestModel testModel; String listName; String string; int index; String replacedString; boolean itemAddedZeroArgumentFlag = false; boolean itemAddedSingleArgumentFlag = false; boolean itemRemovedZeroArgumentFlag = false; boolean itemRemovedSingleArgumentFlag = false; boolean itemReplacedZeroArgumentFlag = false; boolean itemReplacedSingleArgumentFlag = false; boolean listChangedZeroArgumentFlag = false; boolean listChangedSingleArgumentFlag = false; Target(TestModel testModel, String listName, String string, int index) { super(); this.testModel = testModel; this.listName = listName; this.string = string; this.index = index; } Target(TestModel testModel, String listName, String string, int index, String replacedString) { this(testModel, listName, string, index); this.replacedString = replacedString; } void itemAddedZeroArgument() { this.itemAddedZeroArgumentFlag = true; } void itemAddedSingleArgument(ListChangeEvent e) { this.itemAddedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertEquals(this.string, e.items().next()); assertEquals(this.index, e.getIndex()); } void itemRemovedZeroArgument() { this.itemRemovedZeroArgumentFlag = true; } void itemRemovedSingleArgument(ListChangeEvent e) { this.itemRemovedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertEquals(this.string, e.items().next()); assertEquals(this.index, e.getIndex()); } void itemReplacedZeroArgument() { this.itemReplacedZeroArgumentFlag = true; } void itemReplacedSingleArgument(ListChangeEvent e) { this.itemReplacedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertEquals(this.string, e.items().next()); assertEquals(this.replacedString, e.replacedItems().next()); assertEquals(this.index, e.getIndex()); } void listChangedZeroArgument() { this.listChangedZeroArgumentFlag = true; } void listChangedSingleArgument(ListChangeEvent e) { this.listChangedSingleArgumentFlag = true; assertSame(this.testModel, e.getSource()); assertEquals(this.listName, e.getListName()); assertFalse(e.items().hasNext()); assertEquals(this.index, e.getIndex()); } void listChangedDoubleArgument(ListChangeEvent e, Object o) { fail("bogus event: " + e); } } }
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench.test/utility/source/org/eclipse/persistence/tools/workbench/test/utility/events/ReflectiveListChangeListenerTests.java
Java
epl-1.0
22,586
/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/ package org.eclipse.persistence.tools.workbench.test.mappingsmodel.query; import org.eclipse.persistence.tools.workbench.test.mappingsmodel.ModelProblemsTestCase; import org.eclipse.persistence.tools.workbench.mappingsmodel.ProblemConstants; import org.eclipse.persistence.tools.workbench.mappingsmodel.db.MWColumn; import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.relational.MWUserDefinedQueryKey; import junit.framework.Test; import junit.framework.TestSuite; public class MWUserDefinedQueryKeyTests extends ModelProblemsTestCase { public static Test suite() { return new TestSuite(MWUserDefinedQueryKeyTests.class); } /** * Constructor for MWQueryableTests. * @param name */ public MWUserDefinedQueryKeyTests(String name){ super(name); } public void testFieldExistsProblem() { String problem = ProblemConstants.DESCRIPTOR_QUERY_KEY_NO_COLUMN_SPECIFIED; MWUserDefinedQueryKey qKey = getPersonDescriptor().addQueryKey("qKey", (MWColumn)getPersonDescriptor().getPrimaryTable().columns().next()); assertTrue("The query key should not have the problem: " + problem, !hasProblem(problem, getPersonDescriptor())); qKey.setColumn(null); assertTrue("The query key should have the problem: " + problem, hasProblem(problem, getPersonDescriptor())); } }
RallySoftware/eclipselink.runtime
utils/eclipselink.utils.workbench.test/mappingsplugin/source/org/eclipse/persistence/tools/workbench/test/mappingsmodel/query/MWUserDefinedQueryKeyTests.java
Java
epl-1.0
2,104
/******************************************************************************* * Copyright (c) 2006, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation * ******************************************************************************/ package org.eclipse.persistence.jpa.jpql.parser; /** * The query BNF for a function expression returning a numeric value. * <p> * JPA 1.0: * <div><b>BNF:</b> <code>functions_returning_numerics::= LENGTH(string_primary) | * LOCATE(string_primary, string_primary[, simple_arithmetic_expression]) | * ABS(simple_arithmetic_expression) | SQRT(simple_arithmetic_expression) | * MOD(simple_arithmetic_expression, simple_arithmetic_expression) | * SIZE(collection_valued_path_expression)</code><p></div> * * JPA 2.0: * <div><b>BNF:</b> <code>functions_returning_numerics::= LENGTH(string_primary) | * LOCATE(string_primary, string_primary[, simple_arithmetic_expression]) | * ABS(simple_arithmetic_expression) | SQRT(simple_arithmetic_expression) | * MOD(simple_arithmetic_expression, simple_arithmetic_expression) | * SIZE(collection_valued_path_expression) | * INDEX(identification_variable)</code><p></div> * * @version 2.4 * @since 2.3 * @author Pascal Filion */ @SuppressWarnings("nls") public final class FunctionsReturningNumericsBNF extends JPQLQueryBNF { /** * The unique identifier of this BNF rule. */ public static final String ID = "functions_returning_numerics"; /** * Creates a new <code>FunctionsReturningNumericsBNF</code>. */ public FunctionsReturningNumericsBNF() { super(ID); } /** * {@inheritDoc} */ @Override protected void initialize() { super.initialize(); registerExpressionFactory(LengthExpressionFactory.ID); registerExpressionFactory(LocateExpressionFactory.ID); registerExpressionFactory(AbsExpressionFactory.ID); registerExpressionFactory(SqrtExpressionFactory.ID); registerExpressionFactory(ModExpressionFactory.ID); registerExpressionFactory(SizeExpressionFactory.ID); } }
RallySoftware/eclipselink.runtime
jpa/org.eclipse.persistence.jpa.jpql/src/org/eclipse/persistence/jpa/jpql/parser/FunctionsReturningNumericsBNF.java
Java
epl-1.0
3,120
<?php /** * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 * @package kernel */ $tpl = eZTemplate::factory(); $Module = $Params['Module']; $roleID = $Params['RoleID']; $ini = eZINI::instance( 'module.ini' ); $modules = $ini->variable( 'ModuleSettings', 'ModuleList' ); sort( $modules ); $role = eZRole::fetch( 0, $roleID ); if ( $role === null ) { $role = eZRole::fetch( $roleID ); if ( $role ) { if ( $role->attribute( 'version' ) == '0' ) { $temporaryRole = $role->createTemporaryVersion(); unset( $role ); $role = $temporaryRole; } } else { return $Module->handleError( eZError::KERNEL_NOT_AVAILABLE, 'kernel' ); } } $http = eZHTTPTool::instance(); $tpl->setVariable( 'module', $Module ); $role->turnOffCaching(); $tpl->setVariable( 'role', $role ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); if ( $http->hasPostVariable( 'NewName' ) && $role->attribute( 'name' ) != $http->postVariable( 'NewName' ) ) { $role->setAttribute( 'name' , $http->postVariable( 'NewName' ) ); $role->store(); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } $showModules = true; $showFunctions = false; $showLimitations = false; $noFunctions = false; $noLimitations = false; if ( $http->hasPostVariable( 'Apply' ) ) { $originalRole = eZRole::fetch( $role->attribute( 'version' ) ); $originalRoleName = $originalRole->attribute( 'name' ); $originalRoleID = $originalRole->attribute( 'id' ); // Who changes which role(s) should be logged. if ( $http->hasSessionVariable( 'RoleWasChanged' ) and $http->sessionVariable( 'RoleWasChanged' ) === true ) { eZAudit::writeAudit( 'role-change', array( 'Role ID' => $originalRoleID, 'Role name' => $originalRoleName, 'Comment' => 'Changed the current role: kernel/role/edit.php' ) ); $http->removeSessionVariable( 'RoleWasChanged' ); } $originalRole->revertFromTemporaryVersion(); eZContentCacheManager::clearAllContentCache(); $Module->redirectTo( $Module->functionURI( 'view' ) . '/' . $originalRoleID . '/'); /* Clean up policy cache */ eZUser::cleanupCache(); } if ( $http->hasPostVariable( 'Discard' ) ) { $http->removeSessionVariable( 'RoleWasChanged' ); $role = eZRole::fetch( $roleID ) ; $originalRole = eZRole::fetch( $role->attribute( 'version') ); $role->removeThis(); if ( $originalRole != null && $originalRole->attribute( 'is_new' ) == 1 ) { $originalRole->remove(); } $Module->redirectTo( $Module->functionURI( 'list' ) . '/' ); } if ( $http->hasPostVariable( 'ChangeRoleName' ) ) { $role->setAttribute( 'name', $http->postVariable( 'NewName' ) ); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } if ( $http->hasPostVariable( 'AddModule' ) ) { if ( $http->hasPostVariable( 'Modules' ) ) $currentModule = $http->postVariable( 'Modules' ); else if ( $http->hasPostVariable( 'CurrentModule' ) ) $currentModule = $http->postVariable( 'CurrentModule' ); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => '*' ) ); } if ( $http->hasPostVariable( 'AddFunction' ) ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'ModuleFunction' ); eZDebugSetting::writeDebug( 'kernel-role-edit', $currentModule, 'currentModule'); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction ) ); } if ( $http->hasPostVariable( 'AddLimitation' ) ) { $policy = false; if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $hasNodeLimitation = false; $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); if ( $policy ) { $limitationList = eZPolicyLimitation::fetchByPolicyID( $policy->attribute( 'id' ) ); foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( $limitationIdentifier != 'Node' and $limitationIdentifier != 'Subtree' ) eZPolicyLimitation::removeByID( $limitationID ); if ( $limitationIdentifier == 'Node' ) { $nodeLimitationValues = eZPolicyLimitationValue::fetchList( $limitationID ); if ( $nodeLimitationValues != null ) $hasNodeLimitation = true; else eZPolicyLimitation::removeByID( $limitationID ); } if ( $limitationIdentifier == 'Subtree' ) { $nodeLimitationValues = eZPolicyLimitationValue::fetchList( $limitationID ); if ( $nodeLimitationValues == null ) eZPolicyLimitation::removeByID( $limitationID ); } } // if ( !$hasNodeLimitation ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'CurrentFunction' ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $currentFunctionLimitations = $functions[ $currentFunction ]; foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] ) and $functionLimitation['name'] != 'Node' and $functionLimitation['name'] != 'Subtree' ) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); if ( !in_array( '-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } } } } if ( !$policy ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'CurrentFunction' ); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '' ) ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $currentFunctionLimitations = $functions[ $currentFunction ]; eZDebugSetting::writeDebug( 'kernel-role-edit', $currentFunctionLimitations, 'currentFunctionLimitations' ); $db = eZDB::instance(); $db->begin(); foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] ) ) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $limitationValues, 'limitationValues' ); if ( !in_array('-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } $db->commit(); } } if ( $http->hasPostVariable( 'RemovePolicy' ) ) { $policyID = $http->postVariable( 'RolePolicy' ) ; eZDebugSetting::writeDebug( 'kernel-role-edit', $policyID, 'trying to remove policy' ); eZPolicy::removeByID( $policyID ); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } if ( $http->hasPostVariable( 'RemovePolicies' ) and $http->hasPostVariable( 'DeleteIDArray' ) ) { $db = eZDB::instance(); $db->begin(); foreach( $http->postVariable( 'DeleteIDArray' ) as $deleteID) { eZDebugSetting::writeDebug( 'kernel-role-edit', $deleteID, 'trying to remove policy' ); eZPolicy::removeByID( $deleteID ); } $db->commit(); // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); } if ( $http->hasPostVariable( 'CustomFunction' ) ) { if ( $http->hasPostVariable( 'Modules' ) ) $currentModule = $http->postVariable( 'Modules' ); else if ( $http->hasPostVariable( 'CurrentModule' ) ) $currentModule = $http->postVariable( 'CurrentModule' ); if ( $currentModule != '*' ) { $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $functionNames = array_keys( $functions ); } else { $functionNames = array(); } $showModules = false; $showFunctions = true; if ( count( $functionNames ) < 1 ) { $showModules = true; $showFunctions = false; $showLimitations = false; $noFunctions = true; } $tpl->setVariable( 'current_module', $currentModule ); $tpl->setVariable( 'functions', $functionNames ); $tpl->setVariable( 'no_functions', $noFunctions ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step 2: select function' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep2.tpl' ); return; } if ( $http->hasPostVariable( 'DiscardFunction' ) ) { $showModules = true; $showFunctions = false; } if ( $http->hasPostVariable( 'SelectButton' ) or $http->hasPostVariable( 'BrowseCancelButton' ) or $http->hasPostVariable( 'Limitation' ) or $http->hasPostVariable( 'SelectedNodeIDArray' ) or $http->hasPostVariable( 'BrowseLimitationNodeButton' ) or $http->hasPostVariable( 'DeleteNodeButton' ) or $http->hasPostVariable( 'BrowseLimitationSubtreeButton' ) or $http->hasPostVariable( 'DeleteSubtreeButton' ) ) { $db = eZDB::instance(); $db->begin(); if ( $http->hasPostVariable( 'DeleteNodeButton' ) and $http->hasSessionVariable( 'BrowsePolicyID' ) ) { if ( $http->hasPostVariable( 'DeleteNodeIDArray' ) ) { $deletedIDList = $http->postVariable( 'DeleteNodeIDArray' ); foreach ( $deletedIDList as $deletedID ) { eZPolicyLimitationValue::removeByValue( $deletedID, $http->sessionVariable( 'BrowsePolicyID' ) ); } } } if ( $http->hasPostVariable( 'DeleteSubtreeButton' ) and $http->hasSessionVariable( 'BrowsePolicyID' ) ) { if ( $http->hasPostVariable( 'DeleteSubtreeIDArray' ) ) { $deletedIDList = $http->postVariable( 'DeleteSubtreeIDArray' ); foreach ( $deletedIDList as $deletedID ) { $subtree = eZContentObjectTreeNode::fetch( $deletedID , false, false); $path = $subtree['path_string']; eZPolicyLimitationValue::removeByValue( $path, $http->sessionVariable( 'BrowsePolicyID' ) ); } } } if ( $http->hasPostVariable( 'Limitation' ) and $http->hasSessionVariable( 'BrowsePolicyID' ) ) $http->removeSessionVariable( 'BrowsePolicyID' ); if ( $http->hasSessionVariable( 'BrowseCurrentModule' ) ) $currentModule = $http->sessionVariable( 'BrowseCurrentModule' ); if ( $http->hasPostVariable( 'CurrentModule' ) ) $currentModule = $http->postVariable( 'CurrentModule' ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $functionNames = array_keys( $functions ); $showModules = false; $showFunctions = false; $showLimitations = true; $nodeList = array(); $nodeIDList = array(); $subtreeList = array(); $subtreeIDList = array(); // Check for temporary node and subtree policy limitation if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policyID = $http->sessionVariable( 'BrowsePolicyID' ); // Fetch node limitations $nodeLimitation = eZPolicyLimitation::fetchByIdentifier( $policyID, 'Node' ); if ( $nodeLimitation != null ) { $nodeLimitationID = $nodeLimitation->attribute('id'); $nodeLimitationValues = eZPolicyLimitationValue::fetchList( $nodeLimitationID ); foreach ( $nodeLimitationValues as $nodeLimitationValue ) { $nodeID = $nodeLimitationValue->attribute( 'value' ); $nodeIDList[] = $nodeID; $node = eZContentObjectTreeNode::fetch( $nodeID ); $nodeList[] = $node; } } // Fetch subtree limitations $subtreeLimitation = eZPolicyLimitation::fetchByIdentifier( $policyID, 'Subtree' ); if ( $subtreeLimitation != null ) { $subtreeLimitationID = $subtreeLimitation->attribute('id'); $subtreeLimitationValues = eZPolicyLimitationValue::fetchList( $subtreeLimitationID ); foreach ( $subtreeLimitationValues as $subtreeLimitationValue ) { $subtreePath = $subtreeLimitationValue->attribute( 'value' ); $subtreeObject = eZContentObjectTreeNode::fetchByPath( $subtreePath ); if ( $subtreeObject ) { $subtreeID = $subtreeObject->attribute( 'node_id' ); $subtreeIDList[] = $subtreeID; $subtree = eZContentObjectTreeNode::fetch( $subtreeID ); $subtreeList[] = $subtree; } } } } if ( $http->hasSessionVariable( 'BrowseCurrentFunction' ) ) $currentFunction = $http->sessionVariable( 'BrowseCurrentFunction' ); if ( $http->hasPostVariable( 'CurrentFunction' ) ) $currentFunction = $http->postVariable( 'CurrentFunction' ); if ( $http->hasPostVariable( 'ModuleFunction' ) ) $currentFunction = $http->postVariable( 'ModuleFunction' ); $currentFunctionLimitations = array(); foreach( $functions[ $currentFunction ] as $key => $limitation ) { if( count( $limitation[ 'values' ] == 0 ) && array_key_exists( 'class', $limitation ) ) { $obj = new $limitation['class']( array() ); $limitationValueList = call_user_func_array ( array( $obj , $limitation['function']) , $limitation['parameter'] ); $limitationValueArray = array(); foreach( $limitationValueList as $limitationValue ) { $limitationValuePair = array(); $limitationValuePair['Name'] = $limitationValue[ 'name' ]; $limitationValuePair['value'] = $limitationValue[ 'id' ]; $limitationValueArray[] = $limitationValuePair; } $limitation[ 'values' ] = $limitationValueArray; } $currentFunctionLimitations[ $key ] = $limitation; } if ( count( $currentFunctionLimitations ) < 1 ) { $showModules = false; $showFunctions = true; $showLimitations = false; $noLimitations = true; } if ( $http->hasPostVariable( 'BrowseLimitationSubtreeButton' ) || $http->hasPostVariable( 'BrowseLimitationNodeButton' ) ) { // Store other limitations if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); $limitationList = eZPolicyLimitation::fetchByPolicyID( $policy->attribute( 'id' ) ); foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( $limitationIdentifier != 'Node' and $limitationIdentifier != 'Subtree' ) eZPolicyLimitation::removeByID( $limitationID ); } foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] ) and $functionLimitation['name'] != 'Node' and $functionLimitation['name'] != 'Subtree' ) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $limitationValues, 'limitationValues'); if ( !in_array('-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } } else { $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '') ); $http->setSessionVariable( 'BrowsePolicyID', $policy->attribute('id') ); foreach ( $currentFunctionLimitations as $functionLimitation ) { if ( $http->hasPostVariable( $functionLimitation['name'] )) { $limitationValues = $http->postVariable( $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $limitationValues, 'limitationValues'); if ( !in_array( '-1', $limitationValues ) ) { $policyLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), $functionLimitation['name'] ); eZDebugSetting::writeDebug( 'kernel-role-edit', $policyLimitation, 'policyLimitationCreated' ); foreach ( $limitationValues as $limitationValue ) { eZPolicyLimitationValue::createNew( $policyLimitation->attribute( 'id' ), $limitationValue ); } } } } } $db->commit(); $http->setSessionVariable( 'BrowseCurrentModule', $currentModule ); $http->setSessionVariable( 'BrowseCurrentFunction', $currentFunction ); if ( $http->hasPostVariable( 'BrowseLimitationSubtreeButton' ) ) { eZContentBrowse::browse( array( 'action_name' => 'FindLimitationSubtree', 'from_page' => '/role/edit/' . $roleID . '/' ), $Module ); } elseif ( $http->hasPostVariable( 'BrowseLimitationNodeButton' ) ) { eZContentBrowse::browse( array( 'action_name' => 'FindLimitationNode', 'from_page' => '/role/edit/' . $roleID . '/' ), $Module ); } return; } if ( $http->hasPostVariable( 'SelectedNodeIDArray' ) and $http->postVariable( 'BrowseActionName' ) == 'FindLimitationNode' and !$http->hasPostVariable( 'BrowseCancelButton' ) ) { $selectedNodeIDList = $http->postVariable( 'SelectedNodeIDArray' ); if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); $limitationList = eZPolicyLimitation::fetchByPolicyID( $policy->attribute( 'id' ) ); // Remove other limitations. When the policy is applied to node, no other constraints needed. // Removes limitations only from a DropList if it is specified in the module. if ( isset( $currentFunctionLimitations['Node']['DropList'] ) ) { $dropList = $currentFunctionLimitations['Node']['DropList']; foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( in_array( $limitationIdentifier, $dropList ) ) { eZPolicyLimitation::removeByID( $limitationID ); } } } else { foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); if ( $limitationIdentifier != 'Node' and $limitationIdentifier != 'Subtree' ) eZPolicyLimitation::removeByID( $limitationID ); } } } else { $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '') ); $http->setSessionVariable( 'BrowsePolicyID', $policy->attribute('id') ); } $nodeLimitation = eZPolicyLimitation::fetchByIdentifier( $policy->attribute('id'), 'Node' ); if ( $nodeLimitation == null ) $nodeLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), 'Node' ); foreach ( $selectedNodeIDList as $nodeID ) { if ( !in_array( $nodeID, $nodeIDList ) ) { $nodeLimitationValue = eZPolicyLimitationValue::createNew( $nodeLimitation->attribute( 'id' ), $nodeID ); $node = eZContentObjectTreeNode::fetch( $nodeID ); $nodeList[] = $node; } } } if ( $http->hasPostVariable( 'SelectedNodeIDArray' ) and $http->postVariable( 'BrowseActionName' ) == 'FindLimitationSubtree' and !$http->hasPostVariable( 'BrowseCancelButton' ) ) { $selectedSubtreeIDList = $http->postVariable( 'SelectedNodeIDArray' ); if ( $http->hasSessionVariable( 'BrowsePolicyID' ) ) { $policy = eZPolicy::fetch( $http->sessionVariable( 'BrowsePolicyID' ) ); } else { $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction, 'Limitation' => '') ); $http->setSessionVariable( 'BrowsePolicyID', $policy->attribute('id') ); } $subtreeLimitation = eZPolicyLimitation::fetchByIdentifier( $policy->attribute('id'), 'Subtree' ); if ( $subtreeLimitation == null ) $subtreeLimitation = eZPolicyLimitation::createNew( $policy->attribute('id'), 'Subtree' ); foreach ( $selectedSubtreeIDList as $nodeID ) { if ( !in_array( $nodeID, $subtreeIDList ) ) { $subtree = eZContentObjectTreeNode::fetch( $nodeID ); $pathString = $subtree->attribute( 'path_string' ); $policyLimitationValue = eZPolicyLimitationValue::createNew( $subtreeLimitation->attribute( 'id' ), $pathString ); $subtreeList[] = $subtree; } } } if ( $http->hasPostVariable( 'Limitation' ) && count( $currentFunctionLimitations ) == 0 ) { $currentModule = $http->postVariable( 'CurrentModule' ); $currentFunction = $http->postVariable( 'ModuleFunction' ); eZDebugSetting::writeDebug( 'kernel-role-edit', $currentModule, 'currentModule' ); $policy = eZPolicy::createNew( $roleID, array( 'ModuleName'=> $currentModule, 'FunctionName' => $currentFunction ) ); } else { $db->commit(); $currentLimitationList = array(); foreach ( $currentFunctionLimitations as $currentFunctionLimitation ) { $limitationName = $currentFunctionLimitation['name']; $currentLimitationList[$limitationName] = '-1'; } if ( isset( $policyID ) ) { $limitationList = eZPolicyLimitation::fetchByPolicyID( $policyID ); foreach ( $limitationList as $limitation ) { $limitationID = $limitation->attribute( 'id' ); $limitationIdentifier = $limitation->attribute( 'identifier' ); $limitationValues = eZPolicyLimitationValue::fetchList( $limitationID ); $valueList = array(); foreach ( $limitationValues as $limitationValue ) { $value = $limitationValue->attribute( 'value' ); $valueList[] = $value; } $currentLimitationList[$limitationIdentifier] = $valueList; } } $tpl->setVariable( 'current_function', $currentFunction ); $tpl->setVariable( 'function_limitations', $currentFunctionLimitations ); $tpl->setVariable( 'no_limitations', $noLimitations ); $tpl->setVariable( 'current_module', $currentModule ); $tpl->setVariable( 'functions', $functionNames ); $tpl->setVariable( 'node_list', $nodeList ); $tpl->setVariable( 'subtree_list', $subtreeList ); $tpl->setVariable( 'current_limitation_list', $currentLimitationList ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step three: set function limitations' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep3.tpl' ); return; } $db->commit(); } if ( $http->hasPostVariable( 'DiscardLimitation' ) || $http->hasPostVariable( 'Step2') ) { $currentModule = $http->postVariable( 'CurrentModule' ); $mod = eZModule::exists( $currentModule ); $functions = $mod->attribute( 'available_functions' ); $functionNames = array_keys( $functions ); $showModules = false; $showFunctions = true; $tpl->setVariable( 'current_module', $currentModule ); $tpl->setVariable( 'functions', $functionNames ); $tpl->setVariable( 'no_functions', false ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step two: select function' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep2.tpl' ); return; } if ( $http->hasPostVariable( 'CreatePolicy' ) || $http->hasPostVariable( 'Step1' ) ) { // Set flag for audit. If true audit will be processed $http->setSessionVariable( 'RoleWasChanged', true ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); $tpl->setVariable( 'modules', $modules ); $moduleList = array(); foreach( $modules as $module ) { $moduleList[] = eZModule::exists( $module ); } $tpl->setVariable( 'module_list', $moduleList ); $tpl->setVariable( 'role', $role ); $tpl->setVariable( 'module', $Module ); $Result = array(); $Result['path'] = array( array( 'url' => false , 'text' => ezpI18n::tr( 'kernel/role', 'Create new policy, step one: select module' ) ) ); $Result['content'] = $tpl->fetch( 'design:role/createpolicystep1.tpl' ); return; } // Set flag for audit. If true audit will be processed // Cancel button was pressed if ( $http->hasPostVariable( 'CancelPolicyButton' ) ) $http->setSessionVariable( 'RoleWasChanged', false ); $policies = $role->attribute( 'policies' ); $tpl->setVariable( 'no_functions', $noFunctions ); $tpl->setVariable( 'no_limitations', $noLimitations ); $tpl->setVariable( 'show_modules', $showModules ); $tpl->setVariable( 'show_limitations', $showLimitations ); $tpl->setVariable( 'show_functions', $showFunctions ); $tpl->setVariable( 'policies', $policies ); $tpl->setVariable( 'modules', $modules ); $tpl->setVariable( 'module', $Module ); $tpl->setVariable( 'role', $role ); $tpl->setVariable( 'step', 0 ); $Module->setTitle( 'Edit ' . $role->attribute( 'name' ) ); $Result = array(); $Result['path'] = array( array( 'text' => 'Role', 'url' => 'role/list' ), array( 'text' => $role->attribute( 'name' ), 'url' => false ) ); $Result['content'] = $tpl->fetch( 'design:role/edit.tpl' ); ?>
CG77/ezpublish-legacy
kernel/role/edit.php
PHP
gpl-2.0
30,498
<?php /** * @file * Contains \Drupal\user\Form\UserPasswordForm. */ namespace Drupal\user\Form; use Drupal\Core\Field\Plugin\Field\FieldType\EmailItem; use Drupal\Core\Form\FormBase; use Drupal\Core\Language\Language; use Drupal\Core\Language\LanguageManager; use Drupal\user\UserStorageControllerInterface; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\DependencyInjection\ContainerInterface; /** * Provides a user password reset form. */ class UserPasswordForm extends FormBase { /** * The user storage controller. * * @var \Drupal\user\UserStorageControllerInterface */ protected $userStorageController; /** * The language manager. * * @var \Drupal\Core\Language\LanguageManager */ protected $languageManager; /** * Constructs a UserPasswordForm object. * * @param \Drupal\user\UserStorageControllerInterface $user_storage_controller * The user storage controller. * @param \Drupal\Core\Language\LanguageManager $language_manager * The language manager. */ public function __construct(UserStorageControllerInterface $user_storage_controller, LanguageManager $language_manager) { $this->userStorageController = $user_storage_controller; $this->languageManager = $language_manager; } /** * {@inheritdoc} */ public static function create(ContainerInterface $container) { return new static( $container->get('entity.manager')->getStorageController('user'), $container->get('language_manager') ); } /** * {@inheritdoc} */ public function getFormId() { return 'user_pass'; } /** * {@inheritdoc} * * @param \Symfony\Component\HttpFoundation\Request $request * The request object. */ public function buildForm(array $form, array &$form_state) { $form['name'] = array( '#type' => 'textfield', '#title' => $this->t('Username or e-mail address'), '#size' => 60, '#maxlength' => max(USERNAME_MAX_LENGTH, EMAIL_MAX_LENGTH), '#required' => TRUE, '#attributes' => array( 'autocorrect' => 'off', 'autocapitalize' => 'off', 'spellcheck' => 'false', 'autofocus' => 'autofocus', ), ); // Allow logged in users to request this also. $user = $this->currentUser(); if ($user->isAuthenticated()) { $form['name']['#type'] = 'value'; $form['name']['#value'] = $user->getEmail(); $form['mail'] = array( '#prefix' => '<p>', '#markup' => $this->t('Password reset instructions will be mailed to %email. You must log out to use the password reset link in the e-mail.', array('%email' => $user->getEmail())), '#suffix' => '</p>', ); } else { $form['name']['#default_value'] = $this->getRequest()->query->get('name'); } $form['actions'] = array('#type' => 'actions'); $form['actions']['submit'] = array('#type' => 'submit', '#value' => $this->t('E-mail new password')); return $form; } /** * {@inheritdoc} */ public function validateForm(array &$form, array &$form_state) { $name = trim($form_state['values']['name']); // Try to load by email. $users = $this->userStorageController->loadByProperties(array('mail' => $name, 'status' => '1')); if (empty($users)) { // No success, try to load by name. $users = $this->userStorageController->loadByProperties(array('name' => $name, 'status' => '1')); } $account = reset($users); if ($account && $account->id()) { form_set_value(array('#parents' => array('account')), $account, $form_state); } else { $this->setFormError('name', $form_state, $this->t('Sorry, %name is not recognized as a username or an e-mail address.', array('%name' => $name))); } } /** * {@inheritdoc} */ public function submitForm(array &$form, array &$form_state) { $langcode = $this->languageManager->getCurrentLanguage()->id; $account = $form_state['values']['account']; // Mail one time login URL and instructions using current language. $mail = _user_mail_notify('password_reset', $account, $langcode); if (!empty($mail)) { watchdog('user', 'Password reset instructions mailed to %name at %email.', array('%name' => $account->getUsername(), '%email' => $account->getEmail())); drupal_set_message($this->t('Further instructions have been sent to your e-mail address.')); } $form_state['redirect_route']['route_name'] = 'user.page'; } }
allgood2386/lexrants-me
core/modules/user/lib/Drupal/user/Form/UserPasswordForm.php
PHP
gpl-2.0
4,512
<?php /** * This is a helper class for WordPress that allows format HTML tags, including inputs, textareas, etc * * @author Rinat Khaziev * @version 0.1 */ class Html_Helper { function __construct() { } /** * Render multiple choice checkboxes * * @param string $name * @param string $description * @param array $data */ function checkboxes( $name = '', $description = '', $data = array(), $checked = array() ) { if ( $name != '' ) { $name = filter_var( $name, FILTER_SANITIZE_STRING ); if ( $description ); echo $this->element( 'p', __( $description ) ); echo '<input type="hidden" name="' . esc_attr( $name ) .'" value="" />'; foreach ( (array) $data as $item ) { $is_checked_attr = in_array( $item, (array) $checked ) ? ' checked="true" ' : ''; $item = filter_var( $item, FILTER_SANITIZE_STRING ); echo '<div class="sm-input-wrapper">'; echo '<input type="checkbox" name="' . esc_attr( $name ) . '[]" value="' . esc_attr( $item ) . '" id="' .esc_attr( $name ) . esc_attr( $item ) . '" ' . $is_checked_attr . ' />'; echo '<label for="' .esc_attr( $name ) . esc_attr( $item ) . '">' . esc_attr ( $item ) . '</label>'; echo '</div>'; } } } function _checkbox( $name = '', $description = '', $value = '', $atts, $checked = array() ) { // Generate unique id to make label clickable $rnd_id = uniqid( 'uniq-label-id-' ); return '<div class="checkbox-option-wrapper"><input type="checkbox" id="' . esc_attr( $rnd_id ) . '" value="'. esc_attr( $value ) . '" name="' . esc_attr( $name ) . '" '.$this->_format_attributes( $atts ) . ' /><label for="' . esc_attr( $rnd_id ) . '">' . esc_html ($description ) . '</label></div>'; } function _radio( $name = '', $description = '', $value = '', $atts, $checked = array() ) { // Generate unique id to make label clickable $rnd_id = uniqid( 'uniq-label-id-' ); return '<div class="checkbox-option-wrapper"><input type="radio" id="' . esc_attr( $rnd_id ) . '" value="'. esc_attr( $value ) . '" name="' . esc_attr( $name ) . '" '.$this->_format_attributes( $atts ) . ' /><label for="' . esc_attr( $rnd_id ) . '">' . esc_html ($description ) . '</label></div>'; } /** * This method supports unlimited arguments, * each argument represents html value */ function table_row() { $data = func_get_args(); $ret = ''; foreach ( $data as $cell ) $ret .= $this->element( 'td', $cell, null, false ); return "<tr>" . $ret . "</tr>\n"; } /** * easy wrapper method * * @param unknown $type (select|input) * @param string $name * @param mixed $data */ function input( $type, $name, $data = null, $attrs = array() ) { switch ( $type ) { case 'select': return $this->_select( $name, $data, $attrs ); break; case 'text': case 'hidden': case 'submit': case 'file': case 'checkbox': return $this->_text( $name, $type, $data, $attrs ) ; break; case 'radio': return $this->_radio( $name, $data, $attrs ) ; default: return; } } /** * This is a private method to render inputs * * @access private */ function _text( $name = '', $type='text', $data = '', $attrs = array() ) { return '<input type="' . esc_attr( $type ) . '" value="'. esc_attr( $data ) . '" name="' . esc_attr( $name ) . '" '.$this->_format_attributes( $attrs ) . ' />'; } /** * * * @access private */ function _select( $name, $data = array(), $attrs ) { $ret = ''; foreach ( (array) $data as $key => $value ) { $attrs_to_pass = array( 'value' => $key ); if ( isset( $attrs[ 'default' ] ) && $key == $attrs[ 'default' ] ) $attrs_to_pass[ 'selected' ] = 'selected'; $ret .= $this->element( 'option', $value, $attrs_to_pass, false ); } return '<select name="' . esc_attr( $name ) . '">' . $ret . '</select>'; } function table_head( $data = array(), $params = null ) { echo '<table><thead>'; foreach ( $data as $th ) { echo '<th>' . esc_html( $th ) . '</th>'; } echo '</thead><tbody>'; } function table_foot() { echo '</tbody></table>'; } function form_start( $attrs = array() ) { echo '<form' . $this->_format_attributes( $attrs ) .'>'; } function form_end() { echo '</form>'; } /** * Renders html element * * @param string $tag one of allowed tags * @param string content innerHTML content of tag * @param array $params additional attributes * @param bool $escape escape innerHTML or not, defaults to true * @return string rendered html tag */ function element( $tag, $content, $params = array(), $escape = true ) { $allowed = apply_filters( 'hh_allowed_html_elements' , array( 'div', 'p', 'span', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'td', 'option', 'label', 'textarea', 'select', 'option' ) ); $attr_string = $this->_format_attributes( $params ); if ( in_array( $tag, $allowed ) ) return "<{$tag} {$attr_string}>" . ( $escape ? esc_html ( $content ) : $content ) . "</{$tag}>"; } /** * Formats and returns string of allowed html attrs * * @param array $attrs * @return string attributes */ function _format_attributes( $attrs = array() ) { $attr_string = ''; foreach ( (array) $attrs as $attr => $value ) { if ( in_array( $attr, $this->_allowed_html_attrs() ) ) $attr_string .= " {$attr}='" . esc_attr ( $value ) . "'"; } return $attr_string; } /** * Validates and returns url as A HTML element * * @param string $url any valid url * @param string $title * @param unknown $params array of html attributes * @return string html link */ function a( $url, $title = '', $params = array() ) { $attr_string = $this->_format_attributes( $params ); if ( filter_var( trim( $url ), FILTER_VALIDATE_URL ) ) return '<a href="' . esc_url( trim( $url ) ) . '" ' . $attr_string . '>' . ( $title != '' ? esc_html ( $title ) : esc_url( trim( $url ) ) ) . '</a>'; } /** * Returns allowed HTML attributes */ function _allowed_html_attrs() { return apply_filters( 'hh_allowed_html_attributes', array( 'href', 'class', 'id', 'value', 'action', 'name', 'method', 'selected', 'checked', 'for', 'multiple' ) ); } }
Luckynumberseven/project2
wp-content/plugins/frontend-uploader/lib/php/class-html-helper.php
PHP
gpl-2.0
6,132
<?php /** * @package EasyBlog * @copyright Copyright (C) 2010 Stack Ideas Private Limited. All rights reserved. * @license GNU/GPL, see LICENSE.php * * EasyBlog is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined('_JEXEC') or die('Restricted access'); ?> <!-- Post item wrapper --> <div id="entry-<?php echo $row->id; ?>" class="blog-post micro-photo clearfix prel<?php echo (!empty($row->team)) ? ' teamblog-post' : '' ;?>" itemscope itemtype="http://schema.org/Blog"> <div class="blog-post-in"> <div class="blog-head"> <!-- @template: Admin tools --> <?php echo $this->fetch( 'blog.admin.tool.php' , array( 'row' => $row ) ); ?> <?php if( $system->config->get( 'layout_avatar' ) && $this->getParam( 'show_avatar_frontpage' ) ){ ?> <!-- @template: Avatar --> <?php echo $this->fetch( 'blog.avatar.php' , array( 'row' => $row ) ); ?> <?php } ?> <div class="blog-head-in"> <!-- Post title --> <div class="blog-photo"> <h2 id="title-<?php echo $row->id; ?>" class="blog-title<?php echo ($row->isFeatured) ? ' featured' : '';?> rip mbs" itemprop="name"> <a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id='.$row->id); ?>" title="<?php echo $this->escape( $row->title );?>" itemprop="url"><?php echo $row->title; ?></a> <?php if( $row->isFeatured ) { ?> <!-- Show a featured tag if the entry is featured --> <sup class="tag-featured"><?php echo Jtext::_('COM_EASYBLOG_FEATURED_FEATURED'); ?></sup> <?php } ?> </h2> </div> <!-- Post metadata --> <?php echo $this->fetch( 'blog.meta.php' , array( 'row' => $row, 'postedText' => JText::_( 'COM_EASYBLOG_PHOTO_UPLOADED' ) ) ); ?> </div> <div class="clear"></div> </div> <!-- Content wrappings --> <div class="blog-content clearfix"> <!-- @Trigger onAfterDisplayTitle --> <?php echo $row->event->afterDisplayTitle; ?> <!-- Post content --> <div class="blog-text clearfix prel"> <!-- @Trigger: onBeforeDisplayContent --> <?php echo $row->event->beforeDisplayContent; ?> <!-- Load social buttons --> <?php if( in_array( $system->config->get( 'main_socialbutton_position' ) , array( 'top' , 'left' , 'right' ) ) ){ ?> <?php echo EasyBlogHelper::showSocialButton( $row , true ); ?> <?php } ?> <!-- Photo items --> <?php if( $row->images ){ ?> <?php foreach( $row->images as $image ){ ?> <p class="photo-source"> <span> <a href="<?php echo EasyBlogRouter::_('index.php?option=com_easyblog&view=entry&id='.$row->id); ?>"><img src="<?php echo $image;?>" /></a> </span> </p> <?php } ?> <?php } ?> <!-- Post content --> <?php echo $row->text; ?> <!-- @Trigger: onAfterDisplayContent --> <?php echo $row->event->afterDisplayContent; ?> <!-- Copyright text --> <?php if( $system->config->get( 'layout_copyrights' ) && !empty($row->copyrights) ) { ?> <?php echo $this->fetch( 'blog.copyright.php' , array( 'row' => $row ) ); ?> <?php } ?> <!-- Maps --> <?php if( $system->config->get( 'main_locations_blog_frontpage' ) ){ ?> <?php echo EasyBlogHelper::getHelper( 'Maps' )->getHTML( true , $row->address, $row->latitude , $row->longitude , $system->config->get( 'main_locations_blog_map_width') , $system->config->get( 'main_locations_blog_map_height' ), JText::sprintf( 'COM_EASYBLOG_LOCATIONS_BLOG_POSTED_FROM' , $row->address ), 'post_map_canvas_' . $row->id );?> <?php } ?> </div> <?php if( $this->getParam( 'show_last_modified' ) ){ ?> <!-- Modified date --> <span class="blog-modified-date"> <?php echo JText::_( 'COM_EASYBLOG_LAST_MODIFIED' ); ?> <?php echo JText::_( 'COM_EASYBLOG_ON' ); ?> <time datetime="<?php echo $this->formatDate( '%Y-%m-%d' , $row->modified ); ?>"> <span><?php echo $this->formatDate( $system->config->get('layout_dateformat') , $row->modified ); ?></span> </time> </span> <?php } ?> <?php if( $this->getparam( 'show_tags' , true ) && $this->getParam( 'show_tags_frontpage' , true ) ){ ?> <?php echo $this->fetch( 'tags.item.php' , array( 'tags' => $row->tags ) ); ?> <?php } ?> <!-- Load bottom social buttons --> <?php if( $system->config->get( 'main_socialbutton_position' ) == 'bottom' ){ ?> <?php echo EasyBlogHelper::showSocialButton( $row , true ); ?> <?php } ?> <!-- Standard facebook like button needs to be at the bottom --> <?php if( $system->config->get('main_facebook_like') && $system->config->get('main_facebook_like_layout') == 'standard' && $system->config->get( 'integrations_facebook_show_in_listing') ) : ?> <?php echo $this->fetch( 'facebook.standard.php' , array( 'facebook' => $row->facebookLike ) ); ?> <?php endif; ?> <?php if( $system->config->get( 'layout_showcomment' ) && EasyBlogHelper::getHelper( 'Comment')->isBuiltin() ){ ?> <!-- Recent comment listings on the frontpage --> <?php echo $this->fetch( 'blog.item.comment.list.php' , array( 'row' => $row ) ); ?> <?php } ?> </div> <!-- Bottom metadata --> <?php echo $this->fetch( 'blog.meta.bottom.php' , array( 'row' => $row ) ); ?> </div> </div>
david-strejc/octopus
components/com_easyblog/themes/nomad/blog.item.photo.php
PHP
gpl-2.0
5,596
#include "gtest/gtest.h" #include "llt_mockcpp.h" #include <stdio.h> #include <stdlib.h> //½¨ÒéÕâÑùÒýÓ㬱ÜÃâÏÂÃæÓùؼü×ÖʱÐèÒª¼Óǰ׺ testing:: using namespace testing; #ifdef __cplusplus extern "C" { #endif extern unsigned int uttest_OM_AcpuCallBackMsgProc_case1(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case2(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case3(void); extern unsigned int uttest_OM_AcpuCallBackMsgProc_case4(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case1(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case2(void); extern unsigned int uttest_OM_AcpuCallBackFidInit_case3(void); extern void OM_Log1(char *cFileName, unsigned int ulLineNum, unsigned int enModuleId, unsigned int enSubModId, unsigned int enLevel, char *pcString, int lPara1); extern unsigned int VOS_RegisterPIDInfo(unsigned int ulPID, void* pfnInitFun, void* pfnMsgFun); extern unsigned int VOS_RegisterMsgTaskPrio(unsigned int ulFID, unsigned int TaskPrio); #ifdef __cplusplus } #endif #ifndef VOS_OK #define VOS_OK 0 #endif #ifndef VOS_ERR #define VOS_ERR 1 #endif TEST(OM_AcpuCallBackMsgProc1, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case1(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc2, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case2(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc3, UT) { MOCKER(OM_Log1) .expects(once()); uttest_OM_AcpuCallBackMsgProc_case3(); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackMsgProc4, UT) { uttest_OM_AcpuCallBackMsgProc_case4(); } TEST(OM_AcpuCallBackFidInit1, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue(VOS_ERR)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case1()); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackFidInit2, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue((unsigned int)VOS_OK)); MOCKER(VOS_RegisterMsgTaskPrio) .stubs() .will(returnValue((unsigned int)VOS_ERR)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case2()); GlobalMockObject::reset(); } TEST(OM_AcpuCallBackFidInit3, UT) { MOCKER(VOS_RegisterPIDInfo) .stubs() .will(returnValue((unsigned int)VOS_OK)); MOCKER(VOS_RegisterMsgTaskPrio) .stubs() .will(returnValue((unsigned int)VOS_OK)); EXPECT_EQ(VOS_OK, uttest_OM_AcpuCallBackFidInit_case3()); GlobalMockObject::reset(); }
slade87/ALE21-Kernel
drivers/hisi/modem_hi6xxx/oam/comm/acore/om/uttest_omappoutside.cpp
C++
gpl-2.0
2,725
/* SESC: Super ESCalar simulator Copyright (C) 2005 University of California, Santa Cruz Contributed by Jose Renau This file is part of SESC. SESC is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. SESC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with SESC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include <stdio.h> #include <ctype.h> #include <math.h> //#include "nanassert.h" //#include "Snippets.h" //#include "SescConf.h" #include "nanassert.h" #include "SescConf.h" #include "Snippets.h" extern "C" { #include "cacti42_areadef.h" #include "cacti_interface.h" #include "cacti42_def.h" #include "cacti42_io.h" } #ifdef SESC_SESCTHERM #include "ThermTrace.h" ThermTrace *sescTherm=0; #endif /*------------------------------------------------------------------------------*/ #include <vector> static double tech; static int res_memport; static double wattch2cactiFactor = 1; double getEnergy(int size ,int bsize ,int assoc ,int rdPorts ,int wrPorts ,int subBanks ,int useTag ,int bits ,xcacti_flp *xflp ); double getEnergy(const char *,xcacti_flp *); //extern "C" void output_data(result_type *result, arearesult_type *arearesult, // area_type *arearesult_subbanked, // parameter_type *parameters, double *NSubbanks); /* extern "C" void output_data(result_type *result, arearesult_type *arearesult, parameter_type *parameters); extern "C" total_result_type cacti_interface( int cache_size, int line_size, int associativity, int rw_ports, int excl_read_ports, int excl_write_ports, int single_ended_read_ports, int banks, double tech_node, int output_width, int specific_tag, int tag_width, int access_mode, int pure_sram); extern "C" void xcacti_power_flp(const result_type *result, const arearesult_type *arearesult, const area_type *arearesult_subbanked, const parameter_type *parameters, xcacti_flp *xflp); */ void iterate(); int getInstQueueSize(const char* proc) { // get the clusters int min = SescConf->getRecordMin(proc,"cluster") ; int max = SescConf->getRecordMax(proc,"cluster") ; int total = 0; int num = 0; for(int i = min ; i <= max ; i++){ const char* cc = SescConf->getCharPtr(proc,"cluster",i) ; if(SescConf->checkInt(cc,"winSize")){ int sz = SescConf->getInt(cc,"winSize") ; total += sz; num++; } } // check if(!num){ fprintf(stderr,"no clusters\n"); exit(-1); } return total/num; } #ifdef SESC_SESCTHERM static void update_layout_bank(const char *blockName, xcacti_flp *xflp, const ThermTrace::FLPUnit *flp) { double dx; double dy; double a; // +------------------------------+ // | bank ctrl | // +------------------------------+ // | tag | de | data | // | array | co | array | // | | de | | // +------------------------------+ // | tag_ctrl | data_ctrl | // +------------------------------+ const char *flpSec = SescConf->getCharPtr("","floorplan"); size_t max = SescConf->getRecordMax(flpSec,"blockDescr"); max++; char cadena[1024]; //-------------------------------- // Find top block bank_ctrl dy = flp->delta_y*(xflp->bank_ctrl_a/xflp->total_a); if (xflp->bank_ctrl_e) { // Only if bankCtrl consumes energy sprintf(cadena, "%sBankCtrl %g %g %g %g", blockName, flp->delta_x, dy, flp->x, flp->y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sBankCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } double tag_start_y = dy + flp->y; //-------------------------------- // Find lower blocks tag_ctrl and data_ctrl dy = flp->delta_y*((3*xflp->tag_ctrl_a+3*xflp->data_ctrl_a)/xflp->total_a); a = xflp->tag_ctrl_a+xflp->data_ctrl_a; dx = flp->delta_x*(xflp->tag_ctrl_a/a); double tag_end_y = flp->y+flp->delta_y-dy; if (xflp->tag_array_e) { // Only if tag consumes energy sprintf(cadena,"%sTagCtrl %g %g %g %g", blockName, dx/3, dy, flp->x+dx/3, tag_end_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sTagCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } sprintf(cadena,"%sDataCtrl %g %g %g %g", blockName, (flp->delta_x-dx)/3, dy, flp->x+dx+(flp->delta_x-dx)/3, tag_end_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDataCtrlEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; //-------------------------------- // Find middle blocks tag array, decode, and data array a = xflp->tag_array_a+xflp->data_array_a+xflp->decode_a; dy = tag_end_y - tag_start_y; if (xflp->tag_array_e) { dx = flp->delta_x*(xflp->tag_array_a/a); sprintf(cadena, "%sTagArray %g %g %g %g", blockName, dx, dy, flp->x, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sTagArrayEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } double x = flp->x + dx; dx = flp->delta_x*((xflp->decode_a)/a); sprintf(cadena, "%sDecode %g %g %g %g", blockName, dx, dy, x, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDecodeEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; dx = flp->delta_x*((xflp->data_array_a)/a); sprintf(cadena, "%sDataArray %g %g %g %g", blockName, dx, dy, flp->x+flp->delta_x-dx, tag_start_y); SescConf->updateRecord(flpSec, "blockDescr", strdup(cadena) , max); sprintf(cadena,"%sDataArrayEnergy", blockName); SescConf->updateRecord(flpSec, "blockMatch", strdup(cadena) , max); max++; } static void update_sublayout(const char *blockName, xcacti_flp *xflp, const ThermTrace::FLPUnit *flp, int id) { if(id==1) { update_layout_bank(blockName,xflp,flp); }else if ((id % 2) == 0) { // even number ThermTrace::FLPUnit flp1 = *flp; ThermTrace::FLPUnit flp2 = *flp; if (flp->delta_x > flp->delta_y) { // x-axe is bigger flp1.delta_x = flp->delta_x/2; flp2.delta_x = flp->delta_x/2; flp2.x = flp->x+flp->delta_x/2; }else{ // y-axe is bigger flp1.delta_y = flp->delta_x/2; flp2.delta_y = flp->delta_y/2; flp2.y = flp->y + flp->delta_y/2; } update_sublayout(blockName, xflp, &flp1, id/2); update_sublayout(blockName, xflp, &flp2, id/2); }else{ MSG("Invalid number of banks to partition. Please use power of two"); exit(-1); I(0); // In } } void update_layout(const char *blockName, xcacti_flp *xflp) { const ThermTrace::FLPUnit *flp = sescTherm->findBlock(blockName); I(flp); if (flp == 0) { MSG("Error: blockName[%s] not found in blockDescr",blockName); exit(-1); return; // no match found } update_sublayout(blockName, xflp, flp, xflp->NSubbanks*xflp->assoc); } #endif void iterate() { std::vector<char *> sections; std::vector<char *>::iterator it; SescConf->getAllSections(sections) ; char line[100] ; for(it = sections.begin();it != sections.end(); it++) { const char *block = *it; if (!SescConf->checkCharPtr(block,"deviceType")) continue; const char *name = SescConf->getCharPtr(block,"deviceType") ; if(strcasecmp(name,"vbus")==0){ SescConf->updateRecord(block,"busEnergy",0.0) ; // FIXME: compute BUS energy }else if (strcasecmp(name,"niceCache") == 0) { // No energy for ideal caches (DRAM bank) SescConf->updateRecord(block, "RdHitEnergy" ,0.0); SescConf->updateRecord(block, "RdMissEnergy" ,0.0); SescConf->updateRecord(block, "WrHitEnergy" ,0.0); SescConf->updateRecord(block, "WrMissEnergy" ,0.0); }else if(strstr(name,"cache") || strstr(name,"tlb") || strstr(name,"mem") || strstr(name,"dir") || !strcmp(name,"revLVIDTable") ) { xcacti_flp xflp; double eng = getEnergy(block, &xflp); #ifdef SESC_SESCTHERM2 if (SescConf->checkCharPtr(block,"blockName")) { const char *blockName = SescConf->getCharPtr(block,"blockName"); MSG("%s (block=%s) has blockName %s",name, block, blockName); update_layout(blockName, &xflp); } #else // write it SescConf->updateRecord(block, "RdHitEnergy" ,eng); SescConf->updateRecord(block, "RdMissEnergy" ,eng * 2); // Rd miss + lineFill SescConf->updateRecord(block, "WrHitEnergy" ,eng); SescConf->updateRecord(block, "WrMissEnergy" ,eng * 2); // Wr miss + lineFill #endif } } } char * strfy(int v){ char *t = new char[10] ; sprintf(t,"%d",v); return t ; } char *strfy(double v){ char *t = new char[10] ; sprintf(t,"%lf",v); return t ; } double getEnergy(int size ,int bsize ,int assoc ,int rdPorts ,int wrPorts ,int subBanks ,int useTag ,int bits ,xcacti_flp *xflp ) { int nsets = size/(bsize*assoc); int fully_assoc, associativity; int rwPorts = 0; double ret; if (nsets == 0) { printf("Invalid cache parameters size[%d], bsize[%d], assoc[%d]\n", size, bsize, assoc); exit(0); } if (subBanks == 0) { printf("Invalid cache subbanks parameters\n"); exit(0); } if ((size/subBanks)<64) { printf("size %d: subBanks %d: assoc %d : nset %d\n",size,subBanks,assoc,nsets); size =64*subBanks; } if (rdPorts>1) { wrPorts = rdPorts-2; rdPorts = 2; } if ((rdPorts+wrPorts+rwPorts) < 1) { rdPorts = 0; wrPorts = 0; rwPorts = 1; } if (bsize*8 < bits) bsize = bits/8; BITOUT = bits; if (size == bsize * assoc) { fully_assoc = 1; }else{ fully_assoc = 0; } size = roundUpPower2(size); if (fully_assoc) { associativity = size/bsize; }else{ associativity = assoc; } if (associativity >= 32) associativity = size/bsize; nsets = size/(bsize*associativity); total_result_type result2; printf("\n\n\n########################################################"); printf("\nInput to Cacti_Interface..."); printf("\n size = %d, bsize = %d, assoc = %d, rports = %d, wports = %d", size, bsize, associativity, rdPorts, wrPorts); printf("\n subBanks = %d, tech = %f, bits = %d", subBanks, tech, bits); result2 = cacti_interface(size, bsize, associativity, rwPorts, rdPorts, wrPorts, 0, subBanks, tech, bits, 0, 0, // custom tag 0, useTag); #ifdef DEBUG //output_data(&result,&arearesult,&arearesult_subbanked,&parameters); output_data(&result2.result,&result2.area,&result2.params); #endif //xcacti_power_flp(&result,&arearesult,&arearesult_subbanked,&parameters, xflp); xcacti_power_flp(&result2.result, &result2.area, &result2.arearesult_subbanked, &result2.params, xflp); //return wattch2cactiFactor * 1e9*(result.total_power_without_routing/subBanks + result.total_routing_power); return wattch2cactiFactor * 1e9*(result2.result.total_power_without_routing.readOp.dynamic / subBanks + result2.result.total_routing_power.readOp.dynamic); } double getEnergy(const char *section, xcacti_flp *xflp) { // set the input int cache_size = SescConf->getInt(section,"size") ; int block_size = SescConf->getInt(section,"bsize") ; int assoc = SescConf->getInt(section,"assoc") ; int write_ports = 0 ; int read_ports = SescConf->getInt(section,"numPorts"); int readwrite_ports = 1; int subbanks = 1; int bits = 32; if(SescConf->checkInt(section,"subBanks")) subbanks = SescConf->getInt(section,"subBanks"); if(SescConf->checkInt(section,"bits")) bits = SescConf->getInt(section,"bits"); printf("Module [%s]...\n", section); return getEnergy(cache_size ,block_size ,assoc ,read_ports ,readwrite_ports ,subbanks ,1 ,bits ,xflp); } void processBranch(const char *proc) { // FIXME: add thermal block to branch predictor // get the branch const char* bpred = SescConf->getCharPtr(proc,"bpred") ; // get the type const char* type = SescConf->getCharPtr(bpred,"type") ; xcacti_flp xflp; double bpred_power=0; // switch based on the type if(!strcmp(type,"Taken") || !strcmp(type,"Oracle") || !strcmp(type,"NotTaken") || !strcmp(type,"Static")) { // No tables bpred_power= 0; }else if(!strcmp(type,"2bit")) { int size = SescConf->getInt(bpred,"size") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); bpred_power= 0; }else if(!strcmp(type,"2level")) { int size = SescConf->getInt(bpred,"l2size") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); }else if(!strcmp(type,"ogehl")) { int mTables = SescConf->getInt(bpred,"mtables") ; int size = SescConf->getInt(bpred,"tsize") ; I(0); // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp) * mTables; }else if(!strcmp(type,"hybrid")) { int size = SescConf->getInt(bpred,"localSize") ; // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power = getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: update layout #endif size = SescConf->getInt(bpred,"metaSize"); // 32 = 8bytes line * 4 predictions per byte (assume 2bit counter) bpred_power += getEnergy(size/32, 8, 1, 1, 0, 1, 0, 8, &xflp); }else{ MSG("Unknown energy for branch predictor type [%s]", type); exit(-1); } #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure const char *bpredBlockName = SescConf->getCharPtr(bpred, "blockName"); update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"bpredEnergy",bpred_power) ; #endif int btbSize = SescConf->getInt(bpred,"btbSize"); int btbAssoc = SescConf->getInt(bpred,"btbAssoc"); double btb_power = 0; if (btbSize) { btb_power = getEnergy(btbSize*8, 8, btbAssoc, 1, 0, 1, 1, 64, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"btbEnergy",btb_power) ; #endif }else{ SescConf->updateRecord(proc,"btbEnergy",0.0) ; } double ras_power =0; int ras_size = SescConf->getInt(bpred,"rasSize"); if (ras_size) { ras_power = getEnergy(ras_size*8, 8, 1, 1, 0, 1, 0, 64, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure (all bpred may share a block) update_layout(bpredBlockName, &xflp); #else SescConf->updateRecord(proc,"rasEnergy",ras_power) ; #endif }else{ SescConf->updateRecord(proc,"rasEnergy",0.0) ; } } void processorCore() { const char *proc = SescConf->getCharPtr("","cpucore",0) ; fprintf(stderr,"proc = [%s]\n",proc); xcacti_flp xflp; //---------------------------------------------- // Branch Predictor processBranch(proc); //---------------------------------------------- // Register File int issueWidth= SescConf->getInt(proc,"issueWidth"); int size = SescConf->getInt(proc,"intRegs"); int banks = 1; int rdPorts = 2*issueWidth; int wrPorts = issueWidth; int bits = 32; int bytes = 8; if(SescConf->checkInt(proc,"bits")) { bits = SescConf->getInt(proc,"bits"); bytes = bits/8; if (bits*8 != bytes) { fprintf(stderr,"Not valid number of bits for the processor core [%d]\n",bits); exit(-2); } } if(SescConf->checkInt(proc,"intRegBanks")) banks = SescConf->getInt(proc,"intRegBanks"); if(SescConf->checkInt(proc,"intRegRdPorts")) rdPorts = SescConf->getInt(proc,"intRegRdPorts"); if(SescConf->checkInt(proc,"intRegWrPorts")) wrPorts = SescConf->getInt(proc,"intRegWrPorts"); double regEnergy = getEnergy(size*bytes, bytes, 1, rdPorts, wrPorts, banks, 0, bits, &xflp); printf("\nRegister [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*bytes, banks, rdPorts+wrPorts, regEnergy); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(proc,"IntRegBlockName"); I(blockName); update_layout(blockName, &xflp); blockName = SescConf->getCharPtr(proc,"fpRegBlockName"); I(blockName); update_layout(blockName , &xflp); // FIXME: different energy for FP register #else SescConf->updateRecord(proc,"wrRegEnergy",regEnergy); SescConf->updateRecord(proc,"rdRegEnergy",regEnergy); #endif //---------------------------------------------- // Load/Store Queue size = SescConf->getInt(proc,"maxLoads"); banks = 1; rdPorts = res_memport; wrPorts = res_memport; if(SescConf->checkInt(proc,"lsqBanks")) banks = SescConf->getInt(proc,"lsqBanks"); regEnergy = getEnergy(size*2*bytes,2*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure blockName = SescConf->getCharPtr(proc,"LSQBlockName"); I(blockName); update_layout(lsqBlockName, &xflp); #else SescConf->updateRecord(proc,"ldqRdWrEnergy",regEnergy); #endif printf("\nLoad Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*2*bytes, banks, 2*res_memport, regEnergy); size = SescConf->getInt(proc,"maxStores"); regEnergy = getEnergy(size*4*bytes,4*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); #ifdef SESC_SESCTHERM2 // FIXME: partition energies per structure blockName = SescConf->getCharPtr(proc,"LSQBlockName"); I(blockName); update_layout(lsqBlockName, &xflp); #else SescConf->updateRecord(proc,"stqRdWrEnergy",regEnergy); #endif printf("\nStore Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*4*bytes, banks, 2*res_memport, regEnergy); #ifdef SESC_INORDER size = size/4; regEnergy = getEnergy(size*4*bytes,4*bytes,size,rdPorts,wrPorts,banks,1, 2*bits, &xflp); printf("\nStore Inorder Queue [%d bytes] banks[%d] ports[%d] Energy[%g]\n" ,size*4*bytes, banks, 2*res_memport, regEnergy); SescConf->updateRecord(proc,"stqRdWrEnergyInOrder",regEnergy); #ifdef SESC_SESCTHERM I(0); exit(-1); // Not supported #endif #endif //---------------------------------------------- // Reorder Buffer size = SescConf->getInt(proc,"robSize"); banks = size/64; if (banks == 0) { banks = 1; }else{ banks = roundUpPower2(banks); } // Retirement should hit another bank rdPorts = 1; // continuous possitions wrPorts = 1; regEnergy = getEnergy(size*2,2*issueWidth,1,rdPorts,wrPorts,banks,0,16*issueWidth, &xflp); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(proc,"robBlockName"); I(blockName); update_layout(blockName, &xflp); // FIXME: partition energies per structure #else SescConf->updateRecord(proc,"robEnergy",regEnergy); #endif printf("\nROB [%d bytes] banks[%d] ports[%d] Energy[%g]\n",size*2, banks, 2*rdPorts, regEnergy); //---------------------------------------------- // Rename Table { double bitsPerEntry = log(SescConf->getInt(proc,"intRegs"))/log(2); size = roundUpPower2(static_cast<unsigned int>(32*bitsPerEntry/8)); banks = 1; rdPorts = 2*issueWidth; wrPorts = issueWidth; regEnergy = getEnergy(size,1,1,rdPorts,wrPorts,banks,0,1, &xflp); #ifdef SESC_SESCTHERM2 update_layout("IntRAT", &xflp); //FIXME: create a IntRATblockName // FIXME: partition energies per structure #endif printf("\nrename [%d bytes] banks[%d] Energy[%g]\n",size, banks, regEnergy); regEnergy += getEnergy(size,1,1,rdPorts/2+1,wrPorts/2+1,banks,0,1, &xflp); #ifdef SESC_SESCTHERM2 update_layout("IntRAT", &xflp); // FIXME: partition energies per structure #else // unified FP+Int RAT energy counter SescConf->updateRecord(proc,"renameEnergy",regEnergy); #endif } //---------------------------------------------- // Window Energy & Window + DDIS { int min = SescConf->getRecordMin(proc,"cluster") ; int max = SescConf->getRecordMax(proc,"cluster") ; I(min==0); for(int i = min ; i <= max ; i++) { const char *cluster = SescConf->getCharPtr(proc,"cluster",i) ; // TRADITIONAL COLLAPSING ISSUE LOGIC // Recalculate windowRdWrEnergy using CACTI (keep select and wake) size = SescConf->getInt(cluster,"winSize"); banks = 1; rdPorts = SescConf->getInt(cluster,"wakeUpNumPorts"); wrPorts = issueWidth; int robSize = SescConf->getInt(proc,"robSize"); float entryBits = 4*(log(robSize)/log(2)); // src1, src2, dest, instID entryBits += 7; // opcode entryBits += 1; // ready bit int tableBits = static_cast<int>(entryBits * size); int tableBytes; if (tableBits < 8) { tableBits = 8; tableBytes = 1; }else{ tableBytes = tableBits/8; } int assoc= roundUpPower2(static_cast<unsigned int>(entryBits/8)); tableBytes = roundUpPower2(tableBytes); regEnergy = getEnergy(tableBytes,tableBytes/assoc,assoc,rdPorts,wrPorts,banks,1,static_cast<int>(entryBits), &xflp); printf("\nWindow [%d bytes] assoc[%d] banks[%d] ports[%d] Energy[%g]\n" ,tableBytes, assoc, banks, rdPorts+wrPorts, regEnergy); #ifdef SESC_SESCTHERM2 const char *blockName = SescConf->getCharPtr(cluster,"blockName"); I(blockName); update_layout(blockName, &xflp); #else // unified FP+Int RAT energy counter SescConf->updateRecord(cluster,"windowRdWrEnergy" ,regEnergy,0); #endif } } } void cacti_setup() { const char *technology = SescConf->getCharPtr("","technology"); fprintf(stderr,"technology = [%s]\n",technology); tech = SescConf->getInt(technology,"tech"); fprintf(stderr, "tech : %9.0fnm\n" , tech); tech /= 1000; #ifdef SESC_SESCTHERM sescTherm = new ThermTrace(0); // No input trace, just read conf #endif const char *proc = SescConf->getCharPtr("","cpucore",0); const char *l1Cache = SescConf->getCharPtr(proc,"dataSource"); const char *l1CacheSpace = strstr(l1Cache," "); char *l1Section = strdup(l1Cache); if (l1CacheSpace) l1Section[l1CacheSpace - l1Cache] = 0; res_memport = SescConf->getInt(l1Section,"numPorts"); xcacti_flp xflp; double l1Energy = getEnergy(l1Section, &xflp); double WattchL1Energy = SescConf->getDouble("","wattchDataCacheEnergy"); if (WattchL1Energy) { wattch2cactiFactor = WattchL1Energy/l1Energy; fprintf(stderr,"wattch2cacti Factor %g\n", wattch2cactiFactor); }else{ fprintf(stderr,"-----WARNING: No wattch correction factor\n"); } processorCore(); iterate(); }
dilawar/sesc
src_without_LF/libpower/cacti/cacti_setup.cpp
C++
gpl-2.0
23,999
/* * Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /* * @test * @summary It tests (almost) all keytool behaviors with NSS. * @library /test/lib /test/jdk/sun/security/pkcs11 * @modules java.base/sun.security.tools.keytool * java.base/sun.security.util * java.base/sun.security.x509 * @run main/othervm/timeout=600 NssTest */ public class NssTest { public static void main(String[] args) throws Exception { Path libPath = PKCS11Test.getNSSLibPath("softokn3"); if (libPath == null) { return; } System.out.println("Using NSS lib at " + libPath); copyFiles(); System.setProperty("nss", ""); System.setProperty("nss.lib", String.valueOf(libPath)); PKCS11Test.loadNSPR(libPath.getParent().toString()); KeyToolTest.main(args); } private static void copyFiles() throws IOException { Path srcPath = Paths.get(System.getProperty("test.src")); Files.copy(srcPath.resolve("p11-nss.txt"), Paths.get("p11-nss.txt")); Path dbPath = srcPath.getParent().getParent() .resolve("pkcs11").resolve("nss").resolve("db"); Files.copy(dbPath.resolve("cert8.db"), Paths.get("cert8.db")); Files.copy(dbPath.resolve("key3.db"), Paths.get("key3.db")); Files.copy(dbPath.resolve("secmod.db"), Paths.get("secmod.db")); } }
md-5/jdk10
test/jdk/sun/security/tools/keytool/NssTest.java
Java
gpl-2.0
2,505
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ChapterMarker.cs" company="HandBrake Project (http://handbrake.fr)"> // This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License. // </copyright> // <summary> // A Movie Chapter // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace HandBrake.ApplicationServices.Services.Encode.Model.Models { using System; using HandBrake.ApplicationServices.Utilities; /// <summary> /// A Movie Chapter /// </summary> public class ChapterMarker : PropertyChangedBase { /// <summary> /// Backing field for chapter name /// </summary> private string chapterName; /// <summary> /// Initializes a new instance of the <see cref="ChapterMarker"/> class. /// </summary> public ChapterMarker() { } /// <summary> /// Initializes a new instance of the <see cref="ChapterMarker"/> class. /// </summary> /// <param name="number"> /// The number. /// </param> /// <param name="name"> /// The name. /// </param> /// <param name="duration"> /// The duration. /// </param> public ChapterMarker(int number, string name, TimeSpan duration) { this.ChapterName = name; this.ChapterNumber = number; this.Duration = duration; } /// <summary> /// Initializes a new instance of the <see cref="ChapterMarker"/> class. /// Copy Constructor /// </summary> /// <param name="chapter"> /// The chapter. /// </param> public ChapterMarker(ChapterMarker chapter) { this.ChapterName = chapter.ChapterName; this.ChapterNumber = chapter.ChapterNumber; this.Duration = chapter.Duration; } /// <summary> /// Gets or sets The number of this Chapter, in regards to it's parent Title /// </summary> public int ChapterNumber { get; set; } /// <summary> /// Gets or sets the duration. /// </summary> public TimeSpan Duration { get; set; } /// <summary> /// Gets or sets ChapterName. /// </summary> public string ChapterName { get { return this.chapterName; } set { this.chapterName = value; this.NotifyOfPropertyChange(() => this.ChapterName); } } } }
Rodeo314/hb-saintdev
win/CS/HandBrake.ApplicationServices/Services/Encode/Model/Models/ChapterMarker.cs
C#
gpl-2.0
2,905
// clang-format off /* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator https://www.lammps.org/, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "nstencil_half_multi_3d_tri.h" #include "neigh_list.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ NStencilHalfMulti3dTri::NStencilHalfMulti3dTri(LAMMPS *lmp) : NStencil(lmp) {} /* ---------------------------------------------------------------------- */ void NStencilHalfMulti3dTri::set_stencil_properties() { int n = ncollections; int i, j; // Cross collections: use full stencil, looking one way through hierarchy // smaller -> larger => use full stencil in larger bin // larger -> smaller => no nstencil required // If cut offs are same, use half stencil for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { if(cutcollectionsq[i][i] > cutcollectionsq[j][j]) continue; flag_skip_multi[i][j] = false; if(cutcollectionsq[i][i] == cutcollectionsq[j][j]){ flag_half_multi[i][j] = true; bin_collection_multi[i][j] = i; } else { flag_half_multi[i][j] = false; bin_collection_multi[i][j] = j; } } } } /* ---------------------------------------------------------------------- create stencils based on bin geometry and cutoff ------------------------------------------------------------------------- */ void NStencilHalfMulti3dTri::create() { int icollection, jcollection, bin_collection, i, j, k, ns; int n = ncollections; double cutsq; for (icollection = 0; icollection < n; icollection++) { for (jcollection = 0; jcollection < n; jcollection++) { if (flag_skip_multi[icollection][jcollection]) { nstencil_multi[icollection][jcollection] = 0; continue; } ns = 0; sx = stencil_sx_multi[icollection][jcollection]; sy = stencil_sy_multi[icollection][jcollection]; sz = stencil_sz_multi[icollection][jcollection]; mbinx = stencil_mbinx_multi[icollection][jcollection]; mbiny = stencil_mbiny_multi[icollection][jcollection]; mbinz = stencil_mbinz_multi[icollection][jcollection]; bin_collection = bin_collection_multi[icollection][jcollection]; cutsq = cutcollectionsq[icollection][jcollection]; if (flag_half_multi[icollection][jcollection]) { for (k = 0; k <= sz; k++) for (j = -sy; j <= sy; j++) for (i = -sx; i <= sx; i++) if (bin_distance_multi(i,j,k,bin_collection) < cutsq) stencil_multi[icollection][jcollection][ns++] = k*mbiny*mbinx + j*mbinx + i; } else { for (k = -sz; k <= sz; k++) for (j = -sy; j <= sy; j++) for (i = -sx; i <= sx; i++) if (bin_distance_multi(i,j,k,bin_collection) < cutsq) stencil_multi[icollection][jcollection][ns++] = k*mbiny*mbinx + j*mbinx + i; } nstencil_multi[icollection][jcollection] = ns; } } }
akohlmey/lammps
src/nstencil_half_multi_3d_tri.cpp
C++
gpl-2.0
3,559
<?php /** * File containing the eZXHTMLXMLOutput class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version //autogentag// * @package kernel */ class eZXHTMLXMLOutput extends eZXMLOutputHandler { public $OutputTags = array( 'section' => array( 'quickRender' => true, 'initHandler' => 'initHandlerSection', 'renderHandler' => 'renderChildrenOnly' ), 'embed' => array( 'initHandler' => 'initHandlerEmbed', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification', 'xhtml:id' => 'id', 'object_id' => false, 'node_id' => false, 'show_path' => false ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'embed-inline' => array( 'initHandler' => 'initHandlerEmbed', 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'class' => 'classification', 'xhtml:id' => 'id', 'object_id' => false, 'node_id' => false, 'show_path' => false ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'table' => array( 'initHandler' => 'initHandlerTable', 'leavingHandler' => 'leavingHandlerTable', 'renderHandler' => 'renderAll', 'contentVarName' => 'rows', 'attrNamesTemplate' => array( 'class' => 'classification', 'width' => 'width' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'tr' => array( //'quickRender' => array( 'tr', "\n" ), 'initHandler' => 'initHandlerTr', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'td' => array( 'initHandler' => 'initHandlerTd', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'xhtml:width' => 'width', 'xhtml:colspan' => 'colspan', 'xhtml:rowspan' => 'rowspan', 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'th' => array( 'initHandler' => 'initHandlerTd', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'xhtml:width' => 'width', 'xhtml:colspan' => 'colspan', 'xhtml:rowspan' => 'rowspan', 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'ol' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'ul' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'li' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'header' => array( 'initHandler' => 'initHandlerHeader', 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'paragraph' => array( //'quickRender' => array( 'p', "\n" ), 'renderHandler' => 'renderParagraph', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'line' => array( //'quickRender' => array( '', "<br/>" ), 'renderHandler' => 'renderLine' ), 'literal' => array( 'renderHandler' => 'renderAll', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'strong' => array( 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'emphasize' => array( 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'link' => array( 'initHandler' => 'initHandlerLink', 'renderHandler' => 'renderInline', 'attrNamesTemplate' => array( 'xhtml:id' => 'id', 'xhtml:title' => 'title', 'url_id' => false, 'object_id' => false, 'node_id' => false, 'show_path' => false, 'ezurl_id' => false, 'anchor_name' => false, 'class' => 'classification' ), 'attrDesignKeys' => array( 'class' => 'classification' ) ), 'anchor' => array( 'renderHandler' => 'renderInline' ), 'custom' => array( 'initHandler' => 'initHandlerCustom', 'renderHandler' => 'renderCustom', 'attrNamesTemplate' => array( 'name' => false ) ), '#text' => array( 'quickRender' => true, 'renderHandler' => 'renderText' ) ); function eZXHTMLXMLOutput( &$xmlData, $aliasedType, $contentObjectAttribute = null ) { $this->eZXMLOutputHandler( $xmlData, $aliasedType, $contentObjectAttribute ); $ini = eZINI::instance('ezxml.ini'); if ( $ini->variable( 'ezxhtml', 'RenderParagraphInTableCells' ) == 'disabled' ) $this->RenderParagraphInTableCells = false; } function initHandlerSection( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array(); if( !isset( $parentParams['section_level'] ) ) $parentParams['section_level'] = 0; else $parentParams['section_level']++; // init header counter for current level and for the next level if needed $level = $parentParams['section_level']; if ( $level != 0 ) { if ( !isset( $this->HeaderCount[$level] ) ) $this->HeaderCount[$level] = 0; if ( !isset( $this->HeaderCount[$level + 1] ) ) $this->HeaderCount[$level + 1] = 0; } return $ret; } function initHandlerHeader( $element, &$attributes, &$siblingParams, &$parentParams ) { $level = $parentParams['section_level']; $this->HeaderCount[$level]++; // headers auto-numbering $i = 1; $headerAutoName = ''; while ( $i <= $level ) { if ( $i > 1 ) $headerAutoName .= "_"; $headerAutoName .= $this->HeaderCount[$i]; $i++; } $levelNumber = str_replace( "_", ".", $headerAutoName ); if ( $this->ObjectAttributeID ) $headerAutoName = $this->ObjectAttributeID . '_' . $headerAutoName; $ret = array( 'tpl_vars' => array( 'level' => $level, 'header_number' => $levelNumber, 'toc_anchor_name' => $headerAutoName ) ); return $ret; } function initHandlerLink( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array(); // Set link parameters for rendering children of link tag $href=''; if ( $element->getAttribute( 'url_id' ) != null ) { $linkID = $element->getAttribute( 'url_id' ); if ( isset( $this->LinkArray[$linkID] ) ) $href = $this->LinkArray[$linkID]; } elseif ( $element->getAttribute( 'node_id' ) != null ) { $nodeID = $element->getAttribute( 'node_id' ); $node = isset( $this->NodeArray[$nodeID] ) ? $this->NodeArray[$nodeID] : null; if ( $node != null ) { $view = $element->getAttribute( 'view' ); if ( $view ) $href = 'content/view/' . $view . '/' . $nodeID; else $href = $node->attribute( 'url_alias' ); } else { eZDebug::writeWarning( "Node #$nodeID doesn't exist", "XML output handler: link" ); } } elseif ( $element->getAttribute( 'object_id' ) != null ) { $objectID = $element->getAttribute( 'object_id' ); if ( isset( $this->ObjectArray["$objectID"] ) ) { $object = $this->ObjectArray["$objectID"]; $node = $object->attribute( 'main_node' ); if ( $node ) { $nodeID = $node->attribute( 'node_id' ); $view = $element->getAttribute( 'view' ); if ( $view ) $href = 'content/view/' . $view . '/' . $nodeID; else $href = $node->attribute( 'url_alias' ); } else { eZDebug::writeWarning( "Object #$objectID doesn't have assigned nodes", "XML output handler: link" ); } } else { eZDebug::writeWarning( "Object #$objectID doesn't exist", "XML output handler: link" ); } } elseif ( $element->getAttribute( 'href' ) != null ) { $href = $element->getAttribute( 'href' ); } if ( $element->getAttribute( 'anchor_name' ) != null ) { $href .= '#' . $element->getAttribute( 'anchor_name' ); } if ( $href !== false ) { $attributes['href'] = $href; $parentParams['link_parameters'] = $attributes; } return $ret; } function initHandlerEmbed( $element, &$attributes, &$siblingParams, &$parentParams ) { // default return value in case of errors $ret = array( 'no_render' => true ); $tplSuffix = ''; $objectID = $element->getAttribute( 'object_id' ); if ( $objectID && !empty( $this->ObjectArray["$objectID"] ) ) { $object = $this->ObjectArray["$objectID"]; } else { $nodeID = $element->getAttribute( 'node_id' ); if ( $nodeID ) { if ( isset( $this->NodeArray[$nodeID] ) ) { $node = $this->NodeArray[$nodeID]; $objectID = $node->attribute( 'contentobject_id' ); $object = $node->object(); $tplSuffix = '_node'; } else { eZDebug::writeWarning( "Node #$nodeID doesn't exist", "XML output handler: embed" ); return $ret; } } } if ( !isset( $object ) || !$object || !( $object instanceof eZContentObject ) ) { eZDebug::writeWarning( "Can't fetch object #$objectID", "XML output handler: embed" ); return $ret; } if ( $object->attribute( 'status' ) != eZContentObject::STATUS_PUBLISHED ) { eZDebug::writeWarning( "Object #$objectID is not published", "XML output handler: embed" ); return $ret; } if ( eZINI::instance()->variable( 'SiteAccessSettings', 'ShowHiddenNodes' ) !== 'true' ) { if ( isset( $node ) ) { // embed with a node ID if ( $node->attribute( 'is_invisible' ) ) { eZDebug::writeNotice( "Node #{$nodeID} is invisible", "XML output handler: embed" ); return $ret; } } else { // embed with an object id // checking if at least a location is visible $oneVisible = false; foreach( $object->attribute( 'assigned_nodes' ) as $assignedNode ) { if ( !$assignedNode->attribute( 'is_invisible' ) ) { $oneVisible = true; break; } } if ( !$oneVisible ) { eZDebug::writeNotice( "None of the object #{$objectID}'s location(s) is visible", "XML output handler: embed" ); return $ret; } } } if ( $object->attribute( 'can_read' ) || $object->attribute( 'can_view_embed' ) ) { $templateName = $element->nodeName . $tplSuffix; } else { $templateName = $element->nodeName . '_denied'; } $objectParameters = array(); $excludeAttrs = array( 'view', 'class', 'node_id', 'object_id' ); foreach ( $attributes as $attrName => $value ) { if ( !in_array( $attrName, $excludeAttrs ) ) { if ( strpos( $attrName, ':' ) !== false ) $attrName = substr( $attrName, strpos( $attrName, ':' ) + 1 ); $objectParameters[$attrName] = $value; unset( $attributes[$attrName] ); } } if ( isset( $parentParams['link_parameters'] ) ) $linkParameters = $parentParams['link_parameters']; else $linkParameters = array(); $ret = array( 'template_name' => $templateName, 'tpl_vars' => array( 'object' => $object, 'link_parameters' => $linkParameters, 'object_parameters' => $objectParameters ), 'design_keys' => array( 'class_identifier' => $object->attribute( 'class_identifier' ) ) ); if ( $tplSuffix == '_node') $ret['tpl_vars']['node'] = $node; return $ret; } function initHandlerTable( $element, &$attributes, &$siblingParams, &$parentParams ) { // Backing up the section_level, headings' level should be restarted inside tables. // @see http://issues.ez.no/11536 $this->SectionLevelStack[] = $parentParams['section_level']; $parentParams['section_level'] = 0; // Numbers of rows and cols are lower by 1 for back-compatibility. $rowCount = self::childTagCount( $element ) -1; $lastRow = $element->lastChild; while ( $lastRow && !( $lastRow instanceof DOMElement && $lastRow->nodeName == 'tr' ) ) { $lastRow = $lastRow->previousSibling; } $colCount = self::childTagCount( $lastRow ); if ( $colCount ) $colCount--; $ret = array( 'tpl_vars' => array( 'col_count' => $colCount, 'row_count' => $rowCount ) ); return $ret; } function leavingHandlerTable( $element, &$attributes, &$siblingParams, &$parentParams ) { // Restoring the section_level as it was before entering the table. // @see http://issues.ez.no/11536 $parentParams['section_level'] = array_pop($this->SectionLevelStack); } function initHandlerTr( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array(); if( !isset( $siblingParams['table_row_count'] ) ) $siblingParams['table_row_count'] = 0; else $siblingParams['table_row_count']++; $parentParams['table_row_count'] = $siblingParams['table_row_count']; // Number of cols is lower by 1 for back-compatibility. $colCount = self::childTagCount( $element ); if ( $colCount ) $colCount--; $ret = array( 'tpl_vars' => array( 'row_count' => $parentParams['table_row_count'], 'col_count' => $colCount ) ); // Allow overrides based on table class $parent = $element->parentNode; if ( $parent instanceof DOMElement && $parent->hasAttribute('class') ) $ret['design_keys'] = array( 'table_classification' => $parent->getAttribute('class') ); return $ret; } function initHandlerTd( $element, &$attributes, &$siblingParams, &$parentParams ) { if( !isset( $siblingParams['table_col_count'] ) ) $siblingParams['table_col_count'] = 0; else $siblingParams['table_col_count']++; $ret = array( 'tpl_vars' => array( 'col_count' => &$siblingParams['table_col_count'], 'row_count' => &$parentParams['table_row_count'] ) ); // Allow overrides based on table class $parent = $element->parentNode->parentNode; if ( $parent instanceof DOMElement && $parent->hasAttribute('class') ) $ret['design_keys'] = array( 'table_classification' => $parent->getAttribute('class') ); if ( !$this->RenderParagraphInTableCells && self::childTagCount( $element ) == 1 ) { // paragraph will not be rendered so its align attribute needs to // be taken into account at the td/th level // Looking for the paragraph with align attribute foreach( $element->childNodes as $c ) { if ( $c instanceof DOMElement ) { if ( $c->hasAttribute( 'align' ) ) { $attributes['align'] = $c->getAttribute( 'align' ); } break ; } } } return $ret; } function initHandlerCustom( $element, &$attributes, &$siblingParams, &$parentParams ) { $ret = array( 'template_name' => $attributes['name'] ); return $ret; } // Render handlers function renderParagraph( $element, $childrenOutput, $vars ) { // don't render if inside 'li' or inside 'td'/'th' (by option) $parent = $element->parentNode; if ( ( $parent->nodeName == 'li' && self::childTagCount( $parent ) == 1 ) || ( in_array( $parent->nodeName, array( 'td', 'th' ) ) && !$this->RenderParagraphInTableCells && self::childTagCount( $parent ) == 1 ) ) { return $childrenOutput; } // Break paragraph by block tags (like table, ol, ul, header and paragraphs) $tagText = ''; $lastTagInline = null; $inlineContent = ''; foreach( $childrenOutput as $key => $childOutput ) { if ( $childOutput[0] === true )// is inline { if( $childOutput[1] === ' ' ) { if ( isset( $childrenOutput[$key+1] ) && $childrenOutput[$key+1][0] === false ) continue; else if ( isset( $childrenOutput[ $key - 1 ] ) && $childrenOutput[ $key - 1 ][0] === false ) continue; } $inlineContent .= $childOutput[1]; } // Only render paragraph if current tag is block and previous was an inline tag // OR if current one is inline and it's the last item in the child list if ( ( $childOutput[0] === false && $lastTagInline === true ) || ( $childOutput[0] === true && !isset( $childrenOutput[ $key + 1 ] ) ) ) { $tagText .= $this->renderTag( $element, $inlineContent, $vars ); $inlineContent = ''; } if ( $childOutput[0] === false )// is block $tagText .= $childOutput[1]; $lastTagInline = $childOutput[0]; } return array( false, $tagText ); } /* Count child elemnts, ignoring whitespace and text * * @param DOMElement $parent * @return int */ protected static function childTagCount( DOMElement $parent ) { $count = 0; foreach( $parent->childNodes as $child ) { if ( $child instanceof DOMElement ) $count++; } return $count; } function renderInline( $element, $childrenOutput, $vars ) { $renderedArray = array(); $lastTagInline = null; $inlineContent = ''; foreach( $childrenOutput as $key=>$childOutput ) { if ( $childOutput[0] === true )// is inline $inlineContent .= $childOutput[1]; // Only render tag if current tag is block and previous was an inline tag // OR if current one is inline and it's the last item in the child list if ( ( $childOutput[0] === false && $lastTagInline === true ) || ( $childOutput[0] === true && !isset( $childrenOutput[ $key + 1 ] ) ) ) { $tagText = $this->renderTag( $element, $inlineContent, $vars ); $renderedArray[] = array( true, $tagText ); $inlineContent = ''; } if ( $childOutput[0] === false )// is block $renderedArray[] = array( false, $childOutput[1] ); $lastTagInline = $childOutput[0]; } return $renderedArray; } function renderLine( $element, $childrenOutput, $vars ) { $renderedArray = array(); $lastTagInline = null; $inlineContent = ''; foreach( $childrenOutput as $key=>$childOutput ) { if ( $childOutput[0] === true )// is inline $inlineContent .= $childOutput[1]; // Render line tag only if the last part of childrenOutput is inline and the next tag // within the same paragraph is 'line' too. if ( $childOutput[0] === false && $lastTagInline === true ) { $renderedArray[] = array( true, $inlineContent ); $inlineContent = ''; } elseif ( $childOutput[0] === true && !isset( $childrenOutput[ $key + 1 ] ) ) { $next = $element->nextSibling; // Make sure we get next element that is an element (ignoring whitespace) while ( $next && !$next instanceof DOMElement ) { $next = $next->nextSibling; } if ( $next && $next->nodeName == 'line' ) { $tagText = $this->renderTag( $element, $inlineContent, $vars ); $renderedArray[] = array( true, $tagText ); } else $renderedArray[] = array( true, $inlineContent ); } if ( $childOutput[0] === false )// is block $renderedArray[] = array( false, $childOutput[1] ); $lastTagInline = $childOutput[0]; } return $renderedArray; } function renderCustom( $element, $childrenOutput, $vars ) { if ( $this->XMLSchema->isInline( $element ) ) { $ret = $this->renderInline( $element, $childrenOutput, $vars ); } else { $ret = $this->renderAll( $element, $childrenOutput, $vars ); } return $ret; } function renderChildrenOnly( $element, $childrenOutput, $vars ) { $tagText = ''; foreach( $childrenOutput as $childOutput ) { $tagText .= $childOutput[1]; } return array( false, $tagText ); } function renderText( $element, $childrenOutput, $vars ) { if ( $element->parentNode->nodeName != 'literal' ) { if ( trim( $element->textContent ) === '' && ( ( $element->previousSibling && $element->previousSibling->nodeName === 'line' ) || ( $element->nextSibling && $element->nextSibling->nodeName === 'line' ) ) ) { // spaces before or after a line element are irrelevant return array( true, '' ); } $text = htmlspecialchars( $element->textContent ); $text = str_replace( array( '&amp;nbsp;', "\xC2\xA0" ), '&nbsp;', $text); // Get rid of linebreak and spaces stored in xml file $text = str_replace( "\n", '', $text ); if ( $this->AllowMultipleSpaces ) $text = str_replace( ' ', ' &nbsp;', $text ); else $text = preg_replace( "# +#", " ", $text ); if ( $this->AllowNumericEntities ) $text = preg_replace( '/&amp;#([0-9]+);/', '&#\1;', $text ); } else { $text = $element->textContent; } return array( true, $text ); } /// Array of parameters for rendering tags that are children of 'link' tag public $LinkParameters = array(); public $HeaderCount = array(); /** * Stack of section levels saved when entering tables. * @var array */ protected $SectionLevelStack = array(); public $RenderParagraphInTableCells = true; } ?>
guillaumelecerf/ezpublish-legacy
kernel/classes/datatypes/ezxmltext/handlers/output/ezxhtmlxmloutput.php
PHP
gpl-2.0
27,406
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.alarm.filter; import org.opennms.web.filter.NoSubstringFilter; public class NegativeEventParmLikeFilter extends NoSubstringFilter { public static final String TYPE = "noparmmatchany"; public NegativeEventParmLikeFilter(String value) { super(TYPE, "eventParms", "eventParms", value + "(string,text)"); } @Override public String getTextDescription() { String strippedType = getValue().replace("(string,text)", ""); String[] parms = strippedType.split("="); StringBuffer buffer = new StringBuffer(parms[0] + " is not \""); buffer.append(parms[parms.length - 1]); buffer.append("\""); return buffer.toString(); } @Override public String getDescription() { return TYPE + "=" + getValueString().replace("(string,text)", ""); } }
vishwaAbhinav/OpenNMS
opennms-webapp/src/main/java/org/opennms/web/alarm/filter/NegativeEventParmLikeFilter.java
Java
gpl-2.0
2,058
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.3 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2013 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM is distributed in the hope that it will be useful, but | | WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | | See the GNU Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * * @package CRM * @copyright CiviCRM LLC (c) 2004-2013 * $Id$ * */ class CRM_Core_I18n_SchemaStructure_3_4_0 { static function &columns() { static $result = NULL; if (!$result) { $result = array( 'civicrm_option_group' => array( 'label' => "varchar(255)", 'description' => "varchar(255)", ), 'civicrm_contact_type' => array( 'label' => "varchar(64)", 'description' => "text", ), 'civicrm_premiums' => array( 'premiums_intro_title' => "varchar(255)", 'premiums_intro_text' => "text", ), 'civicrm_product' => array( 'name' => "varchar(255)", 'description' => "text", 'options' => "text", ), 'civicrm_membership_type' => array( 'name' => "varchar(128)", 'description' => "varchar(255)", ), 'civicrm_membership_status' => array( 'label' => "varchar(128)", ), 'civicrm_participant_status_type' => array( 'label' => "varchar(255)", ), 'civicrm_tell_friend' => array( 'title' => "varchar(255)", 'intro' => "text", 'suggested_message' => "text", 'thankyou_title' => "varchar(255)", 'thankyou_text' => "text", ), 'civicrm_price_set' => array( 'title' => "varchar(255)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_batch' => array( 'label' => "varchar(64)", 'description' => "text", ), 'civicrm_custom_group' => array( 'title' => "varchar(64)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_custom_field' => array( 'label' => "varchar(255)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_dashboard' => array( 'label' => "varchar(255)", ), 'civicrm_option_value' => array( 'label' => "varchar(255)", 'description' => "text", ), 'civicrm_contribution_page' => array( 'title' => "varchar(255)", 'intro_text' => "text", 'pay_later_text' => "text", 'pay_later_receipt' => "text", 'thankyou_title' => "varchar(255)", 'thankyou_text' => "text", 'thankyou_footer' => "text", 'for_organization' => "text", 'receipt_from_name' => "varchar(255)", 'receipt_text' => "text", 'footer_text' => "text", 'honor_block_title' => "varchar(255)", 'honor_block_text' => "text", ), 'civicrm_membership_block' => array( 'new_title' => "varchar(255)", 'new_text' => "text", 'renewal_title' => "varchar(255)", 'renewal_text' => "text", ), 'civicrm_price_field' => array( 'label' => "varchar(255)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_price_field_value' => array( 'label' => "varchar(255)", 'description' => "text", ), 'civicrm_uf_group' => array( 'title' => "varchar(64)", 'help_pre' => "text", 'help_post' => "text", ), 'civicrm_uf_field' => array( 'help_post' => "text", 'help_pre' => "text", 'label' => "varchar(255)", ), 'civicrm_event' => array( 'title' => "varchar(255)", 'summary' => "text", 'description' => "text", 'registration_link_text' => "varchar(255)", 'event_full_text' => "text", 'fee_label' => "varchar(255)", 'intro_text' => "text", 'footer_text' => "text", 'confirm_title' => "varchar(255)", 'confirm_text' => "text", 'confirm_footer_text' => "text", 'confirm_email_text' => "text", 'confirm_from_name' => "varchar(255)", 'thankyou_title' => "varchar(255)", 'thankyou_text' => "text", 'thankyou_footer_text' => "text", 'pay_later_text' => "text", 'pay_later_receipt' => "text", 'waitlist_text' => "text", 'approval_req_text' => "text", 'template_title' => "varchar(255)", ), ); } return $result; } static function &indices() { static $result = NULL; if (!$result) { $result = array( 'civicrm_price_set' => array( 'UI_title' => array( 'name' => 'UI_title', 'field' => array( 'title', ), 'unique' => 1, ), ), 'civicrm_custom_group' => array( 'UI_title_extends' => array( 'name' => 'UI_title_extends', 'field' => array( 'title', 'extends', ), 'unique' => 1, ), ), 'civicrm_custom_field' => array( 'UI_label_custom_group_id' => array( 'name' => 'UI_label_custom_group_id', 'field' => array( 'label', 'custom_group_id', ), 'unique' => 1, ), ), ); } return $result; } static function &tables() { static $result = NULL; if (!$result) { $result = array_keys(self::columns()); } return $result; } }
tomlagier/NoblePower
wp-content/plugins/civicrm/civicrm/CRM/Core/I18n/SchemaStructure_3_4_0.php
PHP
gpl-2.0
7,148
<?php // phpcs:ignoreFile -- compatibility library for PHP 5-7.1 if (class_exists('ParagonIE_Sodium_Core_ChaCha20_IetfCtx', false)) { return; } /** * Class ParagonIE_Sodium_Core32_ChaCha20_IetfCtx */ class ParagonIE_Sodium_Core32_ChaCha20_IetfCtx extends ParagonIE_Sodium_Core32_ChaCha20_Ctx { /** * ParagonIE_Sodium_Core_ChaCha20_IetfCtx constructor. * * @internal You should not use this directly from another application * * @param string $key ChaCha20 key. * @param string $iv Initialization Vector (a.k.a. nonce). * @param string $counter The initial counter value. * Defaults to 4 0x00 bytes. * @throws InvalidArgumentException * @throws SodiumException * @throws TypeError */ public function __construct($key = '', $iv = '', $counter = '') { if (self::strlen($iv) !== 12) { throw new InvalidArgumentException('ChaCha20 expects a 96-bit nonce in IETF mode.'); } parent::__construct($key, self::substr($iv, 0, 8), $counter); if (!empty($counter)) { $this->container[12] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($counter, 0, 4)); } $this->container[13] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 0, 4)); $this->container[14] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 4, 4)); $this->container[15] = ParagonIE_Sodium_Core32_Int32::fromReverseString(self::substr($iv, 8, 4)); } }
tstephen/srp-digital
wp-content/plugins/wordfence/crypto/vendor/paragonie/sodium_compat/src/Core32/ChaCha20/IetfCtx.php
PHP
gpl-2.0
1,562
#ifndef NETWORK_RULES_HPP #define NETWORK_RULES_HPP #include <map> #include "ReactionRule.hpp" #include "generator.hpp" class NetworkRules { public: typedef ReactionRule reaction_rule_type; typedef SpeciesTypeID species_id_type; typedef abstract_limited_generator<reaction_rule_type> reaction_rule_generator; typedef reaction_rule_type::identifier_type identifier_type; public: virtual identifier_type add_reaction_rule(ReactionRule const&) = 0; virtual void remove_reaction_rule(ReactionRule const&) = 0; virtual reaction_rule_generator* query_reaction_rule(species_id_type const& r1) const = 0; virtual reaction_rule_generator* query_reaction_rule(species_id_type const& r1, species_id_type const& r2) const = 0; virtual ~NetworkRules() = 0; }; #endif /* NETWORK_RULES_HPP */
navoj/ecell4
ecell4/egfrd/legacy/NetworkRules.hpp
C++
gpl-2.0
821
""" color scheme source data """ schemes = {'classic': [(255, 237, 237), (255, 224, 224), (255, 209, 209), (255, 193, 193), (255, 176, 176), (255, 159, 159), (255, 142, 142), (255, 126, 126), (255, 110, 110), (255, 94, 94), (255, 81, 81), (255, 67, 67), (255, 56, 56), (255, 46, 46), (255, 37, 37), (255, 29, 29), (255, 23, 23), (255, 18, 18), (255, 14, 14), (255, 11, 11), (255, 8, 8), (255, 6, 6), (255, 5, 5), (255, 3, 3), (255, 2, 2), (255, 2, 2), (255, 1, 1), (255, 1, 1), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 0, 0), (255, 1, 0), (255, 4, 0), (255, 6, 0), (255, 10, 0), (255, 14, 0), (255, 18, 0), (255, 22, 0), (255, 26, 0), (255, 31, 0), (255, 36, 0), (255, 41, 0), (255, 45, 0), (255, 51, 0), (255, 57, 0), (255, 62, 0), (255, 68, 0), (255, 74, 0), (255, 81, 0), (255, 86, 0), (255, 93, 0), (255, 99, 0), (255, 105, 0), (255, 111, 0), (255, 118, 0), (255, 124, 0), (255, 131, 0), (255, 137, 0), (255, 144, 0), (255, 150, 0), (255, 156, 0), (255, 163, 0), (255, 169, 0), (255, 175, 0), (255, 181, 0), (255, 187, 0), (255, 192, 0), (255, 198, 0), (255, 203, 0), (255, 208, 0), (255, 213, 0), (255, 218, 0), (255, 222, 0), (255, 227, 0), (255, 232, 0), (255, 235, 0), (255, 238, 0), (255, 242, 0), (255, 245, 0), (255, 247, 0), (255, 250, 0), (255, 251, 0), (253, 252, 0), (250, 252, 1), (248, 252, 2), (244, 252, 2), (241, 252, 3), (237, 252, 3), (233, 252, 3), (229, 252, 4), (225, 252, 4), (220, 252, 5), (216, 252, 5), (211, 252, 6), (206, 252, 7), (201, 252, 7), (197, 252, 8), (191, 251, 8), (185, 249, 9), (180, 247, 9), (174, 246, 10), (169, 244, 11), (164, 242, 11), (158, 240, 12), (151, 238, 13), (146, 236, 14), (140, 233, 14), (134, 231, 15), (128, 228, 16), (122, 226, 17), (116, 223, 18), (110, 221, 19), (105, 218, 20), (99, 216, 21), (93, 214, 22), (88, 211, 23), (82, 209, 24), (76, 207, 25), (71, 204, 26), (66, 202, 28), (60, 200, 30), (55, 198, 31), (50, 196, 33), (45, 194, 34), (40, 191, 35), (36, 190, 37), (31, 188, 39), (27, 187, 40), (23, 185, 43), (19, 184, 44), (15, 183, 46), (12, 182, 48), (9, 181, 51), (6, 181, 53), (3, 180, 55), (1, 180, 57), (0, 180, 60), (0, 180, 62), (0, 180, 65), (0, 181, 68), (0, 182, 70), (0, 182, 74), (0, 183, 77), (0, 184, 80), (0, 184, 84), (0, 186, 88), (0, 187, 92), (0, 188, 95), (0, 190, 99), (0, 191, 104), (0, 193, 108), (0, 194, 112), (0, 196, 116), (0, 198, 120), (0, 200, 125), (0, 201, 129), (0, 203, 134), (0, 205, 138), (0, 207, 143), (0, 209, 147), (0, 211, 151), (0, 213, 156), (0, 215, 160), (0, 216, 165), (0, 219, 171), (0, 222, 178), (0, 224, 184), (0, 227, 190), (0, 229, 197), (0, 231, 203), (0, 233, 209), (0, 234, 214), (0, 234, 220), (0, 234, 225), (0, 234, 230), (0, 234, 234), (0, 234, 238), (0, 234, 242), (0, 234, 246), (0, 234, 248), (0, 234, 251), (0, 234, 254), (0, 234, 255), (0, 232, 255), (0, 228, 255), (0, 224, 255), (0, 219, 255), (0, 214, 254), (0, 208, 252), (0, 202, 250), (0, 195, 247), (0, 188, 244), (0, 180, 240), (0, 173, 236), (0, 164, 232), (0, 156, 228), (0, 147, 222), (0, 139, 218), (0, 130, 213), (0, 122, 208), (0, 117, 205), (0, 112, 203), (0, 107, 199), (0, 99, 196), (0, 93, 193), (0, 86, 189), (0, 78, 184), (0, 71, 180), (0, 65, 175), (0, 58, 171), (0, 52, 167), (0, 46, 162), (0, 40, 157), (0, 35, 152), (0, 30, 147), (0, 26, 142), (0, 22, 136), (0, 18, 131), (0, 15, 126), (0, 12, 120), (0, 9, 115), (1, 8, 110), (1, 6, 106), (1, 5, 101), (2, 4, 97), (3, 4, 92), (4, 5, 89), (5, 5, 85), (6, 6, 82), (7, 7, 79), (8, 8, 77), (10, 10, 77), (12, 12, 77), (14, 14, 76), (16, 16, 74), (19, 19, 73), (21, 21, 72), (24, 24, 71), (26, 26, 69), (29, 29, 70), (32, 32, 69), (35, 35, 68), (37, 37, 67), (40, 40, 67), (42, 42, 65), (44, 44, 65), (46, 46, 64), (48, 48, 63), (49, 50, 62), (51, 51, 61), (53, 52, 61)], 'fire': [(255, 255, 255), (255, 255, 253), (255, 255, 250), (255, 255, 247), (255, 255, 244), (255, 255, 241), (255, 255, 238), (255, 255, 234), (255, 255, 231), (255, 255, 227), (255, 255, 223), (255, 255, 219), (255, 255, 214), (255, 255, 211), (255, 255, 206), (255, 255, 202), (255, 255, 197), (255, 255, 192), (255, 255, 187), (255, 255, 183), (255, 255, 178), (255, 255, 172), (255, 255, 167), (255, 255, 163), (255, 255, 157), (255, 255, 152), (255, 255, 147), (255, 255, 142), (255, 255, 136), (255, 255, 132), (255, 255, 126), (255, 255, 121), (255, 255, 116), (255, 255, 111), (255, 255, 106), (255, 255, 102), (255, 255, 97), (255, 255, 91), (255, 255, 87), (255, 255, 82), (255, 255, 78), (255, 255, 74), (255, 255, 70), (255, 255, 65), (255, 255, 61), (255, 255, 57), (255, 255, 53), (255, 255, 50), (255, 255, 46), (255, 255, 43), (255, 255, 39), (255, 255, 38), (255, 255, 34), (255, 255, 31), (255, 255, 29), (255, 255, 26), (255, 255, 25), (255, 254, 23), (255, 251, 22), (255, 250, 22), (255, 247, 23), (255, 245, 23), (255, 242, 24), (255, 239, 24), (255, 236, 25), (255, 232, 25), (255, 229, 26), (255, 226, 26), (255, 222, 27), (255, 218, 27), (255, 215, 28), (255, 210, 28), (255, 207, 29), (255, 203, 29), (255, 199, 30), (255, 194, 30), (255, 190, 31), (255, 186, 31), (255, 182, 32), (255, 176, 32), (255, 172, 33), (255, 168, 34), (255, 163, 34), (255, 159, 35), (255, 154, 35), (255, 150, 36), (255, 145, 36), (255, 141, 37), (255, 136, 37), (255, 132, 38), (255, 128, 39), (255, 124, 39), (255, 119, 40), (255, 115, 40), (255, 111, 41), (255, 107, 41), (255, 103, 42), (255, 99, 42), (255, 95, 43), (255, 92, 44), (255, 89, 44), (255, 85, 45), (255, 81, 45), (255, 79, 46), (255, 76, 47), (255, 72, 47), (255, 70, 48), (255, 67, 48), (255, 65, 49), (255, 63, 50), (255, 60, 50), (255, 59, 51), (255, 57, 51), (255, 55, 52), (255, 55, 53), (255, 53, 53), (253, 54, 54), (253, 54, 54), (251, 55, 55), (250, 56, 56), (248, 56, 56), (247, 57, 57), (246, 57, 57), (244, 58, 58), (242, 59, 59), (240, 59, 59), (239, 60, 60), (238, 61, 61), (235, 61, 61), (234, 62, 62), (232, 62, 62), (229, 63, 63), (228, 64, 64), (226, 64, 64), (224, 65, 65), (222, 66, 66), (219, 66, 66), (218, 67, 67), (216, 67, 67), (213, 68, 68), (211, 69, 69), (209, 69, 69), (207, 70, 70), (205, 71, 71), (203, 71, 71), (200, 72, 72), (199, 73, 73), (196, 73, 73), (194, 74, 74), (192, 74, 74), (190, 75, 75), (188, 76, 76), (186, 76, 76), (183, 77, 77), (181, 78, 78), (179, 78, 78), (177, 79, 79), (175, 80, 80), (173, 80, 80), (170, 81, 81), (169, 82, 82), (166, 82, 82), (165, 83, 83), (162, 83, 83), (160, 84, 84), (158, 85, 85), (156, 85, 85), (154, 86, 86), (153, 87, 87), (150, 87, 87), (149, 88, 88), (147, 89, 89), (146, 90, 90), (144, 91, 91), (142, 92, 92), (142, 94, 94), (141, 95, 95), (140, 96, 96), (139, 98, 98), (138, 99, 99), (136, 100, 100), (135, 101, 101), (135, 103, 103), (134, 104, 104), (133, 105, 105), (133, 107, 107), (132, 108, 108), (131, 109, 109), (132, 111, 111), (131, 112, 112), (130, 113, 113), (130, 114, 114), (130, 116, 116), (130, 117, 117), (130, 118, 118), (129, 119, 119), (130, 121, 121), (130, 122, 122), (130, 123, 123), (130, 124, 124), (131, 126, 126), (131, 127, 127), (130, 128, 128), (131, 129, 129), (132, 131, 131), (132, 132, 132), (133, 133, 133), (134, 134, 134), (135, 135, 135), (136, 136, 136), (138, 138, 138), (139, 139, 139), (140, 140, 140), (141, 141, 141), (142, 142, 142), (143, 143, 143), (144, 144, 144), (145, 145, 145), (147, 147, 147), (148, 148, 148), (149, 149, 149), (150, 150, 150), (151, 151, 151), (152, 152, 152), (153, 153, 153), (154, 154, 154), (155, 155, 155), (156, 156, 156), (157, 157, 157), (158, 158, 158), (159, 159, 159), (160, 160, 160), (160, 160, 160), (161, 161, 161), (162, 162, 162), (163, 163, 163), (164, 164, 164), (165, 165, 165), (166, 166, 166), (167, 167, 167), (167, 167, 167), (168, 168, 168), (169, 169, 169), (170, 170, 170), (170, 170, 170), (171, 171, 171), (172, 172, 172), (173, 173, 173), (173, 173, 173), (174, 174, 174), (175, 175, 175), (175, 175, 175), (176, 176, 176), (176, 176, 176), (177, 177, 177), (177, 177, 177)], 'omg': [(255, 255, 255), (255, 254, 254), (255, 253, 253), (255, 251, 251), (255, 250, 250), (255, 249, 249), (255, 247, 247), (255, 246, 246), (255, 244, 244), (255, 242, 242), (255, 241, 241), (255, 239, 239), (255, 237, 237), (255, 235, 235), (255, 233, 233), (255, 231, 231), (255, 229, 229), (255, 227, 227), (255, 226, 226), (255, 224, 224), (255, 222, 222), (255, 220, 220), (255, 217, 217), (255, 215, 215), (255, 213, 213), (255, 210, 210), (255, 208, 208), (255, 206, 206), (255, 204, 204), (255, 202, 202), (255, 199, 199), (255, 197, 197), (255, 194, 194), (255, 192, 192), (255, 189, 189), (255, 188, 188), (255, 185, 185), (255, 183, 183), (255, 180, 180), (255, 178, 178), (255, 176, 176), (255, 173, 173), (255, 171, 171), (255, 169, 169), (255, 167, 167), (255, 164, 164), (255, 162, 162), (255, 160, 160), (255, 158, 158), (255, 155, 155), (255, 153, 153), (255, 151, 151), (255, 149, 149), (255, 147, 147), (255, 145, 145), (255, 143, 143), (255, 141, 141), (255, 139, 139), (255, 137, 137), (255, 136, 136), (255, 134, 134), (255, 132, 132), (255, 131, 131), (255, 129, 129), (255, 128, 128), (255, 127, 127), (255, 127, 127), (255, 126, 126), (255, 125, 125), (255, 125, 125), (255, 124, 124), (255, 123, 122), (255, 123, 122), (255, 122, 121), (255, 122, 121), (255, 121, 120), (255, 120, 119), (255, 119, 118), (255, 119, 118), (255, 118, 116), (255, 117, 116), (255, 117, 115), (255, 115, 114), (255, 115, 114), (255, 114, 113), (255, 114, 112), (255, 113, 111), (255, 113, 111), (255, 112, 110), (255, 111, 108), (255, 111, 108), (255, 110, 107), (255, 110, 107), (255, 109, 105), (255, 109, 105), (255, 108, 104), (255, 107, 104), (255, 107, 102), (255, 106, 102), (255, 106, 101), (255, 105, 101), (255, 104, 99), (255, 104, 99), (255, 103, 98), (255, 103, 98), (255, 102, 97), (255, 102, 96), (255, 101, 96), (255, 101, 96), (255, 100, 94), (255, 100, 94), (255, 99, 93), (255, 99, 92), (255, 98, 91), (255, 98, 91), (255, 97, 90), (255, 97, 89), (255, 96, 89), (255, 96, 89), (255, 95, 88), (255, 95, 88), (255, 94, 86), (255, 93, 86), (255, 93, 85), (255, 93, 85), (255, 92, 85), (255, 92, 84), (255, 91, 83), (255, 91, 83), (255, 90, 82), (255, 90, 82), (255, 89, 81), (255, 89, 82), (255, 89, 80), (255, 89, 80), (255, 89, 79), (255, 89, 79), (255, 88, 79), (255, 88, 79), (255, 87, 78), (255, 87, 78), (255, 87, 78), (255, 87, 77), (255, 87, 77), (255, 86, 77), (255, 86, 77), (255, 85, 76), (255, 85, 76), (255, 85, 75), (255, 85, 76), (255, 85, 75), (255, 85, 76), (255, 84, 75), (255, 84, 75), (255, 84, 75), (255, 84, 75), (255, 85, 75), (255, 84, 75), (255, 84, 75), (255, 83, 74), (255, 83, 75), (255, 83, 75), (255, 84, 75), (255, 83, 75), (255, 83, 75), (255, 83, 75), (255, 83, 75), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 76), (255, 83, 77), (255, 84, 78), (255, 83, 78), (255, 84, 79), (255, 84, 78), (255, 84, 79), (255, 83, 79), (255, 84, 80), (255, 83, 80), (255, 84, 81), (255, 85, 82), (255, 85, 82), (255, 85, 83), (255, 85, 83), (255, 85, 84), (255, 85, 84), (255, 86, 85), (255, 86, 85), (255, 87, 87), (254, 89, 89), (254, 91, 92), (253, 92, 93), (252, 94, 96), (251, 96, 98), (251, 97, 100), (249, 99, 103), (249, 100, 105), (248, 102, 108), (247, 104, 111), (246, 105, 113), (245, 107, 116), (244, 109, 119), (243, 110, 122), (242, 112, 125), (241, 113, 127), (240, 115, 130), (239, 117, 134), (238, 118, 136), (237, 120, 140), (236, 121, 142), (235, 123, 145), (234, 124, 148), (233, 126, 151), (232, 127, 154), (232, 129, 157), (230, 130, 159), (230, 132, 162), (229, 133, 165), (228, 135, 168), (227, 136, 170), (227, 138, 173), (226, 139, 176), (225, 140, 178), (224, 142, 181), (223, 143, 183), (223, 144, 185), (223, 146, 188), (222, 147, 190), (221, 148, 192), (221, 150, 195), (220, 151, 197), (219, 152, 199), (219, 153, 201), (219, 154, 202), (219, 156, 205), (218, 157, 207), (217, 158, 208), (217, 159, 210), (217, 160, 211), (217, 161, 213), (216, 162, 214), (216, 163, 216), (216, 164, 217), (215, 165, 218), (216, 166, 219), (215, 166, 220), (215, 167, 222), (215, 168, 223), (215, 169, 223), (215, 170, 224), (215, 170, 225)], 'pbj': [(41, 10, 89), (41, 10, 89), (42, 10, 89), (42, 10, 89), (42, 10, 88), (43, 10, 88), (43, 9, 88), (43, 9, 88), (44, 9, 88), (44, 9, 88), (45, 10, 89), (46, 10, 88), (46, 9, 88), (47, 9, 88), (47, 9, 88), (47, 9, 88), (48, 8, 88), (48, 8, 87), (49, 8, 87), (49, 8, 87), (49, 7, 87), (50, 7, 87), (50, 7, 87), (51, 7, 86), (51, 6, 86), (53, 7, 86), (53, 7, 86), (54, 7, 86), (54, 6, 85), (55, 6, 85), (55, 6, 85), (56, 5, 85), (56, 5, 85), (57, 5, 84), (57, 5, 84), (58, 4, 84), (59, 4, 84), (59, 5, 84), (60, 4, 84), (60, 4, 84), (61, 4, 84), (61, 4, 83), (62, 3, 83), (63, 3, 83), (63, 3, 83), (64, 3, 82), (64, 3, 82), (65, 3, 82), (66, 3, 82), (67, 4, 82), (68, 4, 82), (69, 4, 82), (69, 4, 81), (70, 4, 81), (71, 4, 81), (71, 4, 80), (72, 4, 80), (73, 4, 80), (73, 4, 79), (75, 5, 80), (76, 5, 80), (77, 5, 79), (77, 5, 79), (78, 5, 79), (79, 5, 78), (80, 5, 78), (80, 5, 78), (80, 5, 77), (81, 5, 77), (83, 6, 76), (83, 6, 76), (84, 6, 76), (85, 6, 75), (86, 6, 75), (87, 6, 74), (88, 6, 74), (88, 6, 73), (89, 6, 73), (91, 7, 73), (92, 7, 73), (93, 7, 72), (94, 7, 72), (94, 7, 71), (95, 7, 71), (96, 7, 70), (96, 7, 70), (97, 7, 69), (99, 9, 70), (100, 9, 69), (101, 10, 69), (102, 10, 68), (103, 11, 67), (104, 11, 67), (105, 12, 66), (106, 13, 66), (107, 14, 66), (108, 15, 65), (109, 16, 64), (110, 16, 64), (111, 17, 63), (112, 18, 62), (113, 18, 61), (114, 19, 61), (115, 20, 60), (118, 22, 60), (119, 22, 59), (120, 22, 58), (120, 23, 58), (121, 24, 57), (122, 25, 56), (124, 26, 55), (125, 27, 54), (127, 29, 54), (128, 30, 54), (130, 31, 53), (131, 32, 52), (132, 33, 51), (133, 34, 50), (134, 35, 49), (135, 36, 48), (137, 38, 48), (138, 39, 47), (140, 40, 46), (141, 41, 46), (142, 42, 45), (143, 42, 44), (144, 43, 43), (145, 44, 42), (146, 45, 42), (149, 47, 41), (150, 48, 41), (151, 49, 40), (152, 50, 39), (153, 51, 38), (154, 52, 38), (155, 53, 37), (157, 55, 36), (159, 57, 36), (160, 57, 35), (160, 58, 34), (162, 59, 33), (163, 60, 33), (164, 61, 32), (165, 62, 31), (167, 63, 30), (168, 65, 30), (169, 66, 29), (170, 67, 29), (172, 68, 28), (173, 69, 27), (174, 70, 26), (175, 71, 26), (176, 71, 25), (178, 73, 25), (179, 74, 24), (180, 75, 24), (181, 76, 23), (182, 77, 23), (183, 78, 23), (184, 79, 22), (186, 80, 22), (187, 81, 21), (188, 82, 21), (189, 83, 21), (190, 83, 20), (191, 84, 20), (192, 85, 19), (192, 86, 19), (193, 87, 18), (194, 87, 18), (196, 89, 18), (196, 90, 18), (197, 90, 18), (198, 90, 18), (199, 91, 18), (200, 92, 18), (201, 93, 18), (202, 93, 18), (203, 94, 18), (204, 96, 19), (204, 96, 19), (205, 97, 19), (206, 98, 19), (207, 99, 19), (208, 99, 19), (209, 100, 19), (210, 100, 19), (211, 100, 19), (212, 102, 20), (213, 103, 20), (214, 103, 20), (214, 104, 20), (215, 105, 20), (215, 105, 20), (216, 106, 20), (217, 107, 20), (218, 107, 20), (219, 108, 20), (220, 109, 21), (221, 109, 21), (222, 110, 21), (222, 111, 21), (223, 111, 21), (224, 112, 21), (225, 113, 21), (226, 113, 21), (227, 114, 21), (227, 114, 21), (228, 115, 22), (229, 116, 22), (229, 116, 22), (230, 117, 22), (231, 117, 22), (231, 118, 22), (232, 119, 22), (233, 119, 22), (234, 120, 22), (234, 120, 22), (235, 121, 22), (236, 121, 22), (237, 122, 23), (237, 122, 23), (238, 123, 23), (239, 124, 23), (239, 124, 23), (240, 125, 23), (240, 125, 23), (241, 126, 23), (241, 126, 23), (242, 127, 23), (243, 127, 23), (243, 128, 23), (244, 128, 24), (244, 128, 24), (245, 129, 24), (246, 129, 24), (246, 130, 24), (247, 130, 24), (247, 131, 24), (248, 131, 24), (249, 131, 24), (249, 132, 24), (250, 132, 24), (250, 133, 24), (250, 133, 24), (250, 133, 24), (251, 134, 24), (251, 134, 25), (252, 135, 25), (252, 135, 25), (253, 135, 25), (253, 136, 25), (253, 136, 25), (254, 136, 25), (254, 136, 25), (255, 137, 25)], 'pgaitch': [(255, 254, 165), (255, 254, 164), (255, 253, 163), (255, 253, 162), (255, 253, 161), (255, 252, 160), (255, 252, 159), (255, 252, 157), (255, 251, 156), (255, 251, 155), (255, 251, 153), (255, 250, 152), (255, 250, 150), (255, 250, 149), (255, 249, 148), (255, 249, 146), (255, 249, 145), (255, 248, 143), (255, 248, 141), (255, 248, 139), (255, 247, 138), (255, 247, 136), (255, 246, 134), (255, 246, 132), (255, 246, 130), (255, 245, 129), (255, 245, 127), (255, 245, 125), (255, 244, 123), (255, 244, 121), (255, 243, 119), (255, 243, 117), (255, 242, 114), (255, 242, 112), (255, 241, 111), (255, 241, 109), (255, 240, 107), (255, 240, 105), (255, 239, 102), (255, 239, 100), (255, 238, 99), (255, 238, 97), (255, 237, 95), (255, 237, 92), (255, 236, 90), (255, 237, 89), (255, 236, 87), (255, 235, 84), (255, 235, 82), (255, 234, 80), (255, 233, 79), (255, 233, 77), (255, 232, 74), (255, 231, 72), (255, 230, 70), (255, 230, 69), (255, 229, 67), (255, 228, 65), (255, 227, 63), (255, 226, 61), (255, 225, 60), (255, 225, 58), (255, 224, 56), (255, 223, 54), (255, 222, 52), (255, 222, 51), (255, 221, 49), (255, 220, 47), (255, 219, 46), (255, 218, 44), (255, 216, 43), (255, 215, 42), (255, 214, 41), (255, 213, 39), (255, 212, 39), (255, 211, 37), (255, 209, 36), (255, 208, 34), (255, 208, 33), (255, 206, 33), (255, 205, 32), (255, 204, 30), (255, 202, 29), (255, 201, 29), (255, 199, 28), (254, 199, 28), (254, 199, 27), (253, 198, 27), (252, 197, 27), (251, 196, 27), (250, 195, 26), (249, 195, 26), (248, 194, 26), (248, 193, 26), (247, 192, 26), (246, 192, 25), (245, 191, 26), (244, 190, 26), (243, 189, 25), (241, 188, 25), (240, 187, 25), (239, 187, 25), (238, 186, 25), (236, 185, 25), (236, 184, 26), (235, 183, 26), (233, 182, 25), (232, 181, 25), (230, 181, 26), (229, 180, 26), (228, 179, 25), (227, 178, 25), (226, 177, 26), (224, 176, 26), (222, 176, 25), (221, 175, 25), (220, 173, 26), (219, 172, 26), (217, 171, 25), (215, 170, 25), (214, 170, 26), (212, 169, 26), (211, 167, 25), (209, 166, 25), (208, 166, 26), (206, 165, 26), (204, 163, 26), (203, 162, 26), (202, 161, 25), (200, 161, 26), (198, 159, 26), (197, 158, 26), (195, 157, 26), (193, 157, 27), (192, 155, 27), (190, 154, 27), (189, 153, 27), (187, 152, 28), (186, 151, 28), (184, 150, 28), (182, 149, 28), (181, 148, 29), (179, 147, 29), (177, 146, 29), (175, 144, 29), (174, 144, 30), (172, 142, 30), (170, 141, 30), (169, 140, 30), (167, 139, 31), (165, 138, 31), (164, 137, 31), (162, 136, 31), (161, 135, 32), (159, 134, 32), (157, 133, 32), (154, 132, 32), (153, 131, 33), (151, 130, 33), (150, 129, 33), (148, 127, 33), (147, 127, 34), (145, 126, 34), (143, 124, 34), (141, 123, 34), (140, 122, 35), (139, 121, 35), (137, 120, 35), (135, 119, 35), (134, 118, 36), (132, 117, 36), (130, 116, 36), (129, 115, 36), (127, 113, 36), (126, 113, 37), (124, 112, 37), (122, 111, 37), (121, 110, 37), (120, 109, 38), (118, 108, 38), (116, 107, 38), (115, 105, 38), (113, 104, 38), (112, 104, 39), (110, 103, 39), (108, 102, 39), (107, 101, 39), (106, 100, 40), (104, 99, 40), (102, 98, 40), (101, 96, 40), (99, 96, 40), (99, 96, 41), (97, 94, 41), (96, 93, 41), (94, 92, 41), (92, 91, 41), (92, 90, 42), (90, 90, 42), (89, 89, 42), (87, 87, 42), (86, 86, 42), (85, 86, 43), (84, 85, 43), (83, 84, 43), (81, 83, 43), (80, 82, 43), (80, 82, 44), (78, 80, 44), (77, 80, 44), (75, 79, 44), (75, 78, 44), (74, 78, 45), (73, 76, 45), (71, 75, 45), (71, 75, 45), (70, 74, 45), (69, 74, 46), (68, 73, 46), (67, 72, 46), (66, 71, 46), (65, 71, 46), (64, 69, 46), (64, 69, 47), (63, 68, 47), (62, 67, 47), (61, 67, 47), (60, 66, 47), (59, 65, 47), (59, 65, 48), (59, 64, 48), (58, 63, 48), (57, 63, 48), (56, 62, 48), (56, 62, 48), (55, 61, 48), (55, 61, 49), (55, 60, 49), (55, 60, 49), (54, 59, 49), (53, 58, 49), (53, 57, 49), (52, 57, 49), (52, 57, 50), (52, 56, 50), (52, 56, 50), (52, 56, 50), (52, 55, 50), (51, 54, 50), (51, 53, 50), (51, 53, 50), (51, 52, 50), (51, 53, 51), (51, 53, 51), (51, 52, 51), (51, 52, 51)]} def valid_schemes(): return schemes.keys()
ashmastaflash/IDCOAS
integration/heatmaps/heatmap/colorschemes.py
Python
gpl-2.0
33,688
<?php /** * File containing the ezpOauthBadRequestException class. * * @copyright Copyright (C) eZ Systems AS. All rights reserved. * @license For full copyright and license information view LICENSE file distributed with this source code. * @version 2014.11.1 * @package kernel */ /** * This is the base exception for triggering BAD REQUEST response. * * @package oauth */ abstract class ezpOauthBadRequestException extends ezpOauthException { public function __construct( $message ) { parent::__construct( $message ); } } ?>
CG77/ezpublish-legacy
kernel/private/rest/classes/exceptions/bad_request.php
PHP
gpl-2.0
558
class Organization::Public::Piece::AllGroupsController < Sys::Controller::Public::Base def pre_dispatch @piece = Organization::Piece::AllGroup.where(id: Page.current_piece.id).first render :text => '' unless @piece @item = Page.current_item end def index sys_group_codes = @piece.content.root_sys_group.children.pluck(:code) @groups = @piece.content.groups.public.where(sys_group_code: sys_group_codes) end end
tao-k/zomeki
app/controllers/organization/public/piece/all_groups_controller.rb
Ruby
gpl-3.0
441
package org.ovirt.engine.ui.uicommonweb.models.templates; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.compat.Version; import org.ovirt.engine.ui.uicommonweb.builders.BuilderExecutor; import org.ovirt.engine.ui.uicommonweb.builders.vm.CommentVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.CommonVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.CoreVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.HwOnlyVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.KernelParamsVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.NameAndDescriptionVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.builders.vm.SerialNumberPolicyVmBaseToUnitBuilder; import org.ovirt.engine.ui.uicommonweb.models.vms.UnitVmModel; import org.ovirt.engine.ui.uicommonweb.models.vms.instancetypes.ExistingNonClusterModelBehavior; public class ExistingBlankTemplateModelBehavior extends ExistingNonClusterModelBehavior { private VmTemplate template; public ExistingBlankTemplateModelBehavior(VmTemplate template) { super(template); this.template = template; } @Override protected void postBuild() { getModel().getBaseTemplate().setIsAvailable(false); getModel().getTemplateVersionName().setIsAvailable(false); getModel().getVmType().setIsChangeable(true); getModel().getEmulatedMachine().setIsAvailable(false); getModel().getCustomCpu().setIsAvailable(false); getModel().getOSType().setIsAvailable(false); updateCustomPropertySheet(latestCluster()); getModel().getCustomPropertySheet().deserialize(template.getCustomProperties()); updateTimeZone(template.getTimeZone()); getModel().getVmInitEnabled().setEntity(template.getVmInit() != null); getModel().getVmInitModel().init(template); } @Override protected Version getClusterCompatibilityVersion() { return latestCluster(); } @Override protected void buildModel(VmBase vmBase, BuilderExecutor.BuilderExecutionFinished<VmBase, UnitVmModel> callback) { new BuilderExecutor<>(callback, new NameAndDescriptionVmBaseToUnitBuilder(), new CommentVmBaseToUnitBuilder(), new CommonVmBaseToUnitBuilder( new HwOnlyVmBaseToUnitBuilder().withEveryFeatureSupported(), new CoreVmBaseToUnitBuilder( new KernelParamsVmBaseToUnitBuilder(), new SerialNumberPolicyVmBaseToUnitBuilder().withEveryFeatureSupported() ).withEveryFeatureSupported())) .build(vmBase, getModel()); } public VmTemplate getVmTemplate() { return template; } }
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/templates/ExistingBlankTemplateModelBehavior.java
Java
gpl-3.0
2,954
using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; using System.ComponentModel.Design; using Microsoft.Win32; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.OLE.Interop; using Microsoft.VisualStudio.Shell; using System.Reflection; using System.IO; using dnlib.DotNet; namespace ICSharpCode.ILSpy.AddIn { /// <summary> /// This is the class that implements the package exposed by this assembly. /// /// The minimum requirement for a class to be considered a valid package for Visual Studio /// is to implement the IVsPackage interface and register itself with the shell. /// This package uses the helper classes defined inside the Managed Package Framework (MPF) /// to do it: it derives from the Package class that provides the implementation of the /// IVsPackage interface and uses the registration attributes defined in the framework to /// register itself and its components with the shell. /// </summary> // This attribute tells the PkgDef creation utility (CreatePkgDef.exe) that this class is // a package. [PackageRegistration(UseManagedResourcesOnly = true)] // This attribute is used to register the information needed to show this package // in the Help/About dialog of Visual Studio. [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // This attribute is needed to let the shell know that this package exposes some menus. [ProvideMenuResource("Menus.ctmenu", 1)] [Guid(GuidList.guidILSpyAddInPkgString)] [ProvideAutoLoad(VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_string)] public sealed class ILSpyAddInPackage : Package { /// <summary> /// Default constructor of the package. /// Inside this method you can place any initialization code that does not require /// any Visual Studio service because at this point the package object is created but /// not sited yet inside Visual Studio environment. The place to do all the other /// initialization is the Initialize method. /// </summary> public ILSpyAddInPackage() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString())); } ///////////////////////////////////////////////////////////////////////////// // Overridden Package Implementation #region Package Members /// <summary> /// Initialization of the package; this method is called right after the package is sited, so this is the place /// where you can put all the initialization code that rely on services provided by VisualStudio. /// </summary> protected override void Initialize() { Debug.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString())); base.Initialize(); // Add our command handlers for menu (commands must exist in the .vsct file) OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService; if (null != mcs) { // Create the command for the menu item. CommandID menuCommandID = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)PkgCmdIDList.cmdidOpenReferenceInILSpy); MenuCommand menuItem = new MenuCommand(OpenReferenceInILSpyCallback, menuCommandID); mcs.AddCommand(menuItem); // Create the command for the menu item. CommandID menuCommandID2 = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)PkgCmdIDList.cmdidOpenProjectOutputInILSpy); MenuCommand menuItem2 = new MenuCommand(OpenProjectOutputInILSpyCallback, menuCommandID2); mcs.AddCommand(menuItem2); // Create the command for the menu item. CommandID menuCommandID3 = new CommandID(GuidList.guidILSpyAddInCmdSet, (int)PkgCmdIDList.cmdidOpenILSpy); MenuCommand menuItem3 = new MenuCommand(OpenILSpyCallback, menuCommandID3); mcs.AddCommand(menuItem3); } } #endregion /// <summary> /// This function is the callback used to execute a command when the a menu item is clicked. /// See the Initialize method to see how the menu item is associated to this function using /// the OleMenuCommandService service and the MenuCommand class. /// </summary> private void OpenReferenceInILSpyCallback(object sender, EventArgs e) { var explorer = ((EnvDTE80.DTE2)GetGlobalService(typeof(EnvDTE.DTE))).ToolWindows.SolutionExplorer; var items =(object[]) explorer.SelectedItems; foreach (EnvDTE.UIHierarchyItem item in items) { dynamic reference = item.Object; string path = null; if (reference.PublicKeyToken != "") { var token = Utils.HexStringToBytes(reference.PublicKeyToken); path = GacInterop.FindAssemblyInNetGac(new AssemblyNameInfo() { Name = reference.Identity, Version = new Version(reference.Version), PublicKeyOrToken = new PublicKeyToken(token), Culture = string.Empty }); } if (path == null) path = reference.Path; OpenAssemblyInILSpy(path); } } private void OpenProjectOutputInILSpyCallback(object sender, EventArgs e) { var explorer = ((EnvDTE80.DTE2)GetGlobalService(typeof(EnvDTE.DTE))).ToolWindows.SolutionExplorer; var items = (object[])explorer.SelectedItems; foreach (EnvDTE.UIHierarchyItem item in items) { EnvDTE.Project project = (EnvDTE.Project)item.Object; EnvDTE.Configuration config = project.ConfigurationManager.ActiveConfiguration; string projectPath = Path.GetDirectoryName(project.FileName); string outputPath = config.Properties.Item("OutputPath").Value.ToString(); string assemblyFileName = project.Properties.Item("OutputFileName").Value.ToString(); OpenAssemblyInILSpy(Path.Combine(projectPath, outputPath, assemblyFileName)); } } private void OpenILSpyCallback(object sender, EventArgs e) { Process.Start(GetILSpyPath()); } private string GetILSpyPath() { var basePath = Path.GetDirectoryName(typeof(ILSpyAddInPackage).Assembly.Location); return Path.Combine(basePath, "dnSpy.exe"); } private void OpenAssemblyInILSpy(string assemblyFileName) { if (!File.Exists(assemblyFileName)) { ShowMessage("Could not find assembly '{0}', please ensure the project and all references were built correctly!", assemblyFileName); return; } Process.Start(GetILSpyPath(), Utils.ArgumentArrayToCommandLine(assemblyFileName)); } private void ShowMessage(string format, params object[] items) { IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell)); Guid clsid = Guid.Empty; int result; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure( uiShell.ShowMessageBox( 0, ref clsid, "ILSpy.AddIn", string.Format(CultureInfo.CurrentCulture, format, items), string.Empty, 0, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST, OLEMSGICON.OLEMSGICON_INFO, 0, // false out result ) ); } } }
UlyssesWu/dnSpy
ILSpy.AddIn/ILSpyAddInPackage.cs
C#
gpl-3.0
6,884
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.os.storage; import android.os.Parcel; import android.os.Parcelable; import android.util.DebugUtils; import android.util.TimeUtils; import com.android.internal.util.IndentingPrintWriter; import com.android.internal.util.Preconditions; import java.util.Objects; /** * Metadata for a storage volume which may not be currently present. * * @hide */ public class VolumeRecord implements Parcelable { public static final String EXTRA_FS_UUID = "android.os.storage.extra.FS_UUID"; public static final int USER_FLAG_INITED = 1 << 0; public static final int USER_FLAG_SNOOZED = 1 << 1; public final int type; public final String fsUuid; public String partGuid; public String nickname; public int userFlags; public long createdMillis; public long lastTrimMillis; public long lastBenchMillis; public VolumeRecord(int type, String fsUuid) { this.type = type; this.fsUuid = Preconditions.checkNotNull(fsUuid); } public VolumeRecord(Parcel parcel) { type = parcel.readInt(); fsUuid = parcel.readString(); partGuid = parcel.readString(); nickname = parcel.readString(); userFlags = parcel.readInt(); createdMillis = parcel.readLong(); lastTrimMillis = parcel.readLong(); lastBenchMillis = parcel.readLong(); } public int getType() { return type; } public String getFsUuid() { return fsUuid; } public String getNickname() { return nickname; } public boolean isInited() { return (userFlags & USER_FLAG_INITED) != 0; } public boolean isSnoozed() { return (userFlags & USER_FLAG_SNOOZED) != 0; } public void dump(IndentingPrintWriter pw) { pw.println("VolumeRecord:"); pw.increaseIndent(); pw.printPair("type", DebugUtils.valueToString(VolumeInfo.class, "TYPE_", type)); pw.printPair("fsUuid", fsUuid); pw.printPair("partGuid", partGuid); pw.println(); pw.printPair("nickname", nickname); pw.printPair("userFlags", DebugUtils.flagsToString(VolumeRecord.class, "USER_FLAG_", userFlags)); pw.println(); pw.printPair("createdMillis", TimeUtils.formatForLogging(createdMillis)); pw.printPair("lastTrimMillis", TimeUtils.formatForLogging(lastTrimMillis)); pw.printPair("lastBenchMillis", TimeUtils.formatForLogging(lastBenchMillis)); pw.decreaseIndent(); pw.println(); } @Override public VolumeRecord clone() { final Parcel temp = Parcel.obtain(); try { writeToParcel(temp, 0); temp.setDataPosition(0); return CREATOR.createFromParcel(temp); } finally { temp.recycle(); } } @Override public boolean equals(Object o) { if (o instanceof VolumeRecord) { return Objects.equals(fsUuid, ((VolumeRecord) o).fsUuid); } else { return false; } } @Override public int hashCode() { return fsUuid.hashCode(); } public static final Creator<VolumeRecord> CREATOR = new Creator<VolumeRecord>() { @Override public VolumeRecord createFromParcel(Parcel in) { return new VolumeRecord(in); } @Override public VolumeRecord[] newArray(int size) { return new VolumeRecord[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel parcel, int flags) { parcel.writeInt(type); parcel.writeString(fsUuid); parcel.writeString(partGuid); parcel.writeString(nickname); parcel.writeInt(userFlags); parcel.writeLong(createdMillis); parcel.writeLong(lastTrimMillis); parcel.writeLong(lastBenchMillis); } }
syslover33/ctank
java/android-sdk-linux_r24.4.1_src/sources/android-23/android/os/storage/VolumeRecord.java
Java
gpl-3.0
4,577
#include "AtomicMaker.h" #include <string> void AtomicMaker::readParam(std::istream& in) { read<Boundary>(in, "boundary", boundary_); readParamComposite(in, random_); read<int>(in, "nMolecule", nMolecule_); } void AtomicMaker::writeConfig(std::ostream& out) { Vector r; Vector v; int iMol; out << "BOUNDARY" << std::endl; out << std::endl; out << boundary_ << std::endl; out << std::endl; out << "MOLECULES" << std::endl; out << std::endl; out << "species " << 0 << std::endl; out << "nMolecule " << nMolecule_ << std::endl; out << std::endl; for (iMol = 0; iMol < nMolecule_; ++iMol) { out << "molecule " << iMol << std::endl; boundary_.randomPosition(random_, r); out << r << std::endl; out << std::endl; } } int main() { AtomicMaker obj; obj.readParam(std::cin); obj.writeConfig(std::cout); }
jmysona/testing2
src/draft/tools/atomicMaker/AtomicMaker.cpp
C++
gpl-3.0
898
/* * Copyright (c) 2002-2005 The Regents of The University of Michigan * 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 holders 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. * * Authors: Nathan Binkert */ /* @file * Simple object for creating a simple pcap style packet trace */ #include "dev/net/etherdump.hh" #include <sys/time.h> #include <algorithm> #include <string> #include "base/logging.hh" #include "base/output.hh" #include "sim/core.hh" using std::string; EtherDump::EtherDump(const Params *p) : SimObject(p), stream(simout.create(p->file, true)->stream()), maxlen(p->maxlen) { } #define DLT_EN10MB 1 // Ethernet (10Mb) #define TCPDUMP_MAGIC 0xa1b2c3d4 #define PCAP_VERSION_MAJOR 2 #define PCAP_VERSION_MINOR 4 struct pcap_file_header { uint32_t magic; uint16_t version_major; uint16_t version_minor; int32_t thiszone; // gmt to local correction uint32_t sigfigs; // accuracy of timestamps uint32_t snaplen; // max length saved portion of each pkt uint32_t linktype; // data link type (DLT_*) }; struct pcap_pkthdr { uint32_t seconds; uint32_t microseconds; uint32_t caplen; // length of portion present uint32_t len; // length this packet (off wire) }; void EtherDump::init() { struct pcap_file_header hdr; hdr.magic = TCPDUMP_MAGIC; hdr.version_major = PCAP_VERSION_MAJOR; hdr.version_minor = PCAP_VERSION_MINOR; hdr.thiszone = 0; hdr.snaplen = 1500; hdr.sigfigs = 0; hdr.linktype = DLT_EN10MB; stream->write(reinterpret_cast<char *>(&hdr), sizeof(hdr)); stream->flush(); } void EtherDump::dumpPacket(EthPacketPtr &packet) { pcap_pkthdr pkthdr; pkthdr.seconds = curTick() / SimClock::Int::s; pkthdr.microseconds = (curTick() / SimClock::Int::us) % ULL(1000000); pkthdr.caplen = std::min(packet->length, maxlen); pkthdr.len = packet->length; stream->write(reinterpret_cast<char *>(&pkthdr), sizeof(pkthdr)); stream->write(reinterpret_cast<char *>(packet->data), pkthdr.caplen); stream->flush(); } EtherDump * EtherDumpParams::create() { return new EtherDump(this); }
vineodd/PIMSim
GEM5Simulation/gem5/src/dev/net/etherdump.cc
C++
gpl-3.0
3,646
namespace ArdupilotMega.Antenna { partial class Tracker { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Tracker)); this.CMB_interface = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.CMB_baudrate = new System.Windows.Forms.ComboBox(); this.CMB_serialport = new System.Windows.Forms.ComboBox(); this.TRK_pantrim = new System.Windows.Forms.TrackBar(); this.TXT_panrange = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.TXT_tiltrange = new System.Windows.Forms.TextBox(); this.TRK_tilttrim = new System.Windows.Forms.TrackBar(); this.label2 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.CHK_revpan = new System.Windows.Forms.CheckBox(); this.CHK_revtilt = new System.Windows.Forms.CheckBox(); this.TXT_pwmrangepan = new System.Windows.Forms.TextBox(); this.TXT_pwmrangetilt = new System.Windows.Forms.TextBox(); this.label8 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label11 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.BUT_connect = new ArdupilotMega.Controls.MyButton(); this.LBL_pantrim = new System.Windows.Forms.Label(); this.LBL_tilttrim = new System.Windows.Forms.Label(); this.BUT_find = new ArdupilotMega.Controls.MyButton(); this.TXT_centerpan = new System.Windows.Forms.TextBox(); this.TXT_centertilt = new System.Windows.Forms.TextBox(); this.label13 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.TRK_pantrim)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.TRK_tilttrim)).BeginInit(); this.SuspendLayout(); // // CMB_interface // this.CMB_interface.FormattingEnabled = true; this.CMB_interface.Items.AddRange(new object[] { resources.GetString("CMB_interface.Items"), resources.GetString("CMB_interface.Items1")}); resources.ApplyResources(this.CMB_interface, "CMB_interface"); this.CMB_interface.Name = "CMB_interface"; this.CMB_interface.SelectedIndexChanged += new System.EventHandler(this.CMB_interface_SelectedIndexChanged); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // CMB_baudrate // this.CMB_baudrate.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CMB_baudrate.FormattingEnabled = true; this.CMB_baudrate.Items.AddRange(new object[] { resources.GetString("CMB_baudrate.Items"), resources.GetString("CMB_baudrate.Items1"), resources.GetString("CMB_baudrate.Items2"), resources.GetString("CMB_baudrate.Items3"), resources.GetString("CMB_baudrate.Items4"), resources.GetString("CMB_baudrate.Items5"), resources.GetString("CMB_baudrate.Items6"), resources.GetString("CMB_baudrate.Items7")}); resources.ApplyResources(this.CMB_baudrate, "CMB_baudrate"); this.CMB_baudrate.Name = "CMB_baudrate"; // // CMB_serialport // this.CMB_serialport.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.CMB_serialport.FormattingEnabled = true; resources.ApplyResources(this.CMB_serialport, "CMB_serialport"); this.CMB_serialport.Name = "CMB_serialport"; // // TRK_pantrim // resources.ApplyResources(this.TRK_pantrim, "TRK_pantrim"); this.TRK_pantrim.Maximum = 360; this.TRK_pantrim.Minimum = -360; this.TRK_pantrim.Name = "TRK_pantrim"; this.TRK_pantrim.TickFrequency = 5; this.TRK_pantrim.Scroll += new System.EventHandler(this.TRK_pantrim_Scroll); // // TXT_panrange // resources.ApplyResources(this.TXT_panrange, "TXT_panrange"); this.TXT_panrange.Name = "TXT_panrange"; this.TXT_panrange.TextChanged += new System.EventHandler(this.TXT_panrange_TextChanged); // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // label4 // resources.ApplyResources(this.label4, "label4"); this.label4.Name = "label4"; // // label5 // resources.ApplyResources(this.label5, "label5"); this.label5.Name = "label5"; // // label6 // resources.ApplyResources(this.label6, "label6"); this.label6.Name = "label6"; // // TXT_tiltrange // resources.ApplyResources(this.TXT_tiltrange, "TXT_tiltrange"); this.TXT_tiltrange.Name = "TXT_tiltrange"; this.TXT_tiltrange.TextChanged += new System.EventHandler(this.TXT_tiltrange_TextChanged); // // TRK_tilttrim // resources.ApplyResources(this.TRK_tilttrim, "TRK_tilttrim"); this.TRK_tilttrim.Maximum = 180; this.TRK_tilttrim.Minimum = -180; this.TRK_tilttrim.Name = "TRK_tilttrim"; this.TRK_tilttrim.TickFrequency = 5; this.TRK_tilttrim.Scroll += new System.EventHandler(this.TRK_tilttrim_Scroll); // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // label7 // resources.ApplyResources(this.label7, "label7"); this.label7.Name = "label7"; // // CHK_revpan // resources.ApplyResources(this.CHK_revpan, "CHK_revpan"); this.CHK_revpan.Name = "CHK_revpan"; this.CHK_revpan.UseVisualStyleBackColor = true; this.CHK_revpan.CheckedChanged += new System.EventHandler(this.CHK_revpan_CheckedChanged); // // CHK_revtilt // resources.ApplyResources(this.CHK_revtilt, "CHK_revtilt"); this.CHK_revtilt.Name = "CHK_revtilt"; this.CHK_revtilt.UseVisualStyleBackColor = true; this.CHK_revtilt.CheckedChanged += new System.EventHandler(this.CHK_revtilt_CheckedChanged); // // TXT_pwmrangepan // resources.ApplyResources(this.TXT_pwmrangepan, "TXT_pwmrangepan"); this.TXT_pwmrangepan.Name = "TXT_pwmrangepan"; // // TXT_pwmrangetilt // resources.ApplyResources(this.TXT_pwmrangetilt, "TXT_pwmrangetilt"); this.TXT_pwmrangetilt.Name = "TXT_pwmrangetilt"; // // label8 // resources.ApplyResources(this.label8, "label8"); this.label8.Name = "label8"; // // label9 // resources.ApplyResources(this.label9, "label9"); this.label9.Name = "label9"; // // label10 // resources.ApplyResources(this.label10, "label10"); this.label10.Name = "label10"; // // label11 // resources.ApplyResources(this.label11, "label11"); this.label11.Name = "label11"; // // label12 // resources.ApplyResources(this.label12, "label12"); this.label12.Name = "label12"; // // BUT_connect // resources.ApplyResources(this.BUT_connect, "BUT_connect"); this.BUT_connect.Name = "BUT_connect"; this.BUT_connect.UseVisualStyleBackColor = true; this.BUT_connect.Click += new System.EventHandler(this.BUT_connect_Click); // // LBL_pantrim // resources.ApplyResources(this.LBL_pantrim, "LBL_pantrim"); this.LBL_pantrim.Name = "LBL_pantrim"; // // LBL_tilttrim // resources.ApplyResources(this.LBL_tilttrim, "LBL_tilttrim"); this.LBL_tilttrim.Name = "LBL_tilttrim"; // // BUT_find // resources.ApplyResources(this.BUT_find, "BUT_find"); this.BUT_find.Name = "BUT_find"; this.BUT_find.UseVisualStyleBackColor = true; this.BUT_find.Click += new System.EventHandler(this.BUT_find_Click); // // TXT_centerpan // resources.ApplyResources(this.TXT_centerpan, "TXT_centerpan"); this.TXT_centerpan.Name = "TXT_centerpan"; this.TXT_centerpan.TextChanged += new System.EventHandler(this.TXT_centerpan_TextChanged); // // TXT_centertilt // resources.ApplyResources(this.TXT_centertilt, "TXT_centertilt"); this.TXT_centertilt.Name = "TXT_centertilt"; this.TXT_centertilt.TextChanged += new System.EventHandler(this.TXT_centertilt_TextChanged); // // label13 // resources.ApplyResources(this.label13, "label13"); this.label13.Name = "label13"; // // label14 // resources.ApplyResources(this.label14, "label14"); this.label14.Name = "label14"; // // Tracker // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.label14); this.Controls.Add(this.label13); this.Controls.Add(this.TXT_centertilt); this.Controls.Add(this.TXT_centerpan); this.Controls.Add(this.BUT_find); this.Controls.Add(this.LBL_tilttrim); this.Controls.Add(this.LBL_pantrim); this.Controls.Add(this.label12); this.Controls.Add(this.label10); this.Controls.Add(this.label11); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.TXT_pwmrangetilt); this.Controls.Add(this.TXT_pwmrangepan); this.Controls.Add(this.CHK_revtilt); this.Controls.Add(this.CHK_revpan); this.Controls.Add(this.label7); this.Controls.Add(this.label2); this.Controls.Add(this.label5); this.Controls.Add(this.label6); this.Controls.Add(this.TXT_tiltrange); this.Controls.Add(this.TRK_tilttrim); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.TXT_panrange); this.Controls.Add(this.TRK_pantrim); this.Controls.Add(this.CMB_baudrate); this.Controls.Add(this.BUT_connect); this.Controls.Add(this.CMB_serialport); this.Controls.Add(this.label1); this.Controls.Add(this.CMB_interface); this.Name = "Tracker"; ((System.ComponentModel.ISupportInitialize)(this.TRK_pantrim)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.TRK_tilttrim)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ComboBox CMB_interface; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox CMB_baudrate; private ArdupilotMega.Controls.MyButton BUT_connect; private System.Windows.Forms.ComboBox CMB_serialport; private System.Windows.Forms.TrackBar TRK_pantrim; private System.Windows.Forms.TextBox TXT_panrange; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.TextBox TXT_tiltrange; private System.Windows.Forms.TrackBar TRK_tilttrim; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label7; private System.Windows.Forms.CheckBox CHK_revpan; private System.Windows.Forms.CheckBox CHK_revtilt; private System.Windows.Forms.TextBox TXT_pwmrangepan; private System.Windows.Forms.TextBox TXT_pwmrangetilt; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label11; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label LBL_pantrim; private System.Windows.Forms.Label LBL_tilttrim; private Controls.MyButton BUT_find; private System.Windows.Forms.TextBox TXT_centerpan; private System.Windows.Forms.TextBox TXT_centertilt; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label14; } }
trunet/ardupilot
Tools/ArdupilotMegaPlanner/Antenna/Tracker.Designer.cs
C#
gpl-3.0
15,376
#!/usr/bin/python # # GEOMTERY.OUT to OpenDX # # Created: April 2009 (AVK) # Modified: February 2012 (AVK) # import math import sys def r3minv(a, b): t1 = a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) + \ a[0][1] * (a[1][2] * a[2][0] - a[1][0] * a[2][2]) + \ a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) if math.fabs(t1) < 1e-40: print "r3mv: singular matrix" sys.exit(0) t1 = 1.0/t1 b[0][0] = t1 * (a[1][1] * a[2][2] - a[1][2] * a[2][1]) b[0][1] = t1 * (a[0][2] * a[2][1] - a[0][1] * a[2][2]) b[0][2] = t1 * (a[0][1] * a[1][2] - a[0][2] * a[1][1]) b[1][0] = t1 * (a[1][2] * a[2][0] - a[1][0] * a[2][2]) b[1][1] = t1 * (a[0][0] * a[2][2] - a[0][2] * a[2][0]) b[1][2] = t1 * (a[0][2] * a[1][0] - a[0][0] * a[1][2]) b[2][0] = t1 * (a[1][0] * a[2][1] - a[1][1] * a[2][0]) b[2][1] = t1 * (a[0][1] * a[2][0] - a[0][0] * a[2][1]) b[2][2] = t1 * (a[0][0] * a[1][1] - a[0][1] * a[1][0]) return # # angular part of site-centered orbital # current implementation is for d-orbitals only # class Orbital: def __init__(self,coefs): self.pos=[] self.tri=[] self.coefs=coefs self.make() # real spherical harmonics def Rlm(self,l,m,theta,phi): if l==2 and m==-2: return -math.sqrt(15.0/(16*math.pi))*math.sin(2*phi)*math.sin(theta)**2 if l==2 and m==-1: return -math.sqrt(15.0/(16*math.pi))*math.sin(phi)*math.sin(2*theta) if l==2 and m==0: return math.sqrt(5/(64*math.pi))*(1+3*math.cos(2*theta)) if l==2 and m==1: return -math.sqrt(15.0/(16*math.pi))*math.cos(phi)*math.sin(2*theta) if l==2 and m==2: return math.sqrt(15.0/(16*math.pi))*math.cos(2*phi)*math.sin(theta)**2 def val(self,theta,phi): v=0 for m in range(5): v+=self.coefs[m]*self.Rlm(2,m-2,theta,phi) return v def make(self): raw_pos=[] raw_con=[] n=30 for t in range(n): theta=math.pi*t/(n-1) for p in range(n): phi=2*math.pi*p/(n-1) v=5.5*self.val(theta,phi) x=v*math.sin(theta)*math.cos(phi) y=v*math.sin(theta)*math.sin(phi) z=v*math.cos(theta) raw_pos.append([x,y,z]) for t in range(n): for p in range(n): i1=t i2=(t+1)%n j1=p j2=(p+1)%n n1=i1*n+j1 n2=i1*n+j2 n3=i2*n+j2 n4=i2*n+j1 raw_con.append([n1,n2,n3]) raw_con.append([n1,n3,n4]) # find equal positions eq_pos=[-1 for i in range(n*n)] l=0 for i in range(n*n): if eq_pos[i]==-1: eq_pos[i]=l self.pos.append(raw_pos[i]) for j in range(i+1,n*n): if abs(raw_pos[i][0]-raw_pos[j][0])<1e-10 and \ abs(raw_pos[i][1]-raw_pos[j][1])<1e-10 and \ abs(raw_pos[i][2]-raw_pos[j][2])<1e-10: eq_pos[j]=l l+=1 npos=l # substitute positions in triangles by non-equal positions for i in range(2*n*n): raw_con[i][0]=eq_pos[raw_con[i][0]] raw_con[i][1]=eq_pos[raw_con[i][1]] raw_con[i][2]=eq_pos[raw_con[i][2]] eq_con=[-1 for i in range(2*n*n)] # mark degenerate triangles for i in range(2*n*n): if raw_con[i][0]==raw_con[i][1] or raw_con[i][0]==raw_con[i][2] or \ raw_con[i][1]==raw_con[i][2]: eq_con[i]=-2 # find equal triangles l=0 for i in range(2*n*n): if eq_con[i]==-1: eq_con[i]=l self.tri.append(raw_con[i]) for j in range(i+1,2*n*n): if raw_con[i][0]==raw_con[j][0] and raw_con[i][1]==raw_con[j][1] and \ raw_con[i][2]==raw_con[j][2]: eq_con[j]=l l+=1 # # species-specific variables # class Species: def __init__(self, label): self.label = label self.R = 1.0 self.color = [0.5, 0.5, 0.5] self.visible = True # # atom-specific variables # class Atom: def __init__(self, species, posc, posl): self.species = species self.posc = posc self.posl = posl self.nghbr = [] self.orbital = 0 # # geometry-specific variables # class Geometry: def __init__(self): self.avec = [] self.speciesList = {} self.atomList = [] # read 'GEOMETRY.OUT' self.readGeometry() # make a list of nearest neighbours for each atom self.findNeighbours() # print basic info self.printGeometry() def readGeometry(self): fin = open("GEOMETRY.OUT","r") while True : line = fin.readline() if not line: break line = line.strip(" \n") if line == "avec": for i in range(3): s1 = fin.readline().strip(" \n").split() self.avec.append([float(s1[0]), float(s1[1]), float(s1[2])]) if line == "atoms": # get number of species s1 = fin.readline().strip(" \n").split() nspecies = int(s1[0]) # go over species for i in range(nspecies): # construct label from species file name s1 = fin.readline().strip(" \n").split() label = s1[0][1:s1[0].find(".in")] # crate new species sp = Species(label) # put species to the list self.speciesList[label] = sp # get number of atoms for current species s1 = fin.readline().strip(" \n").split() natoms = int(s1[0]) # go over atoms for j in range(natoms): s1 = fin.readline().strip(" \n").split() posl = [float(s1[0]), float(s1[1]), float(s1[2])] posc = [0, 0, 0] for l in range(3): for x in range(3): posc[x] += posl[l] * self.avec[l][x] # create new atom self.atomList.append(Atom(sp, posc, posl)) fin.close() def printGeometry(self): print "lattice vectors" print " a1 : %12.6f %12.6f %12.6f"%(self.avec[0][0], self.avec[0][1], self.avec[0][2]) print " a2 : %12.6f %12.6f %12.6f"%(self.avec[1][0], self.avec[1][1], self.avec[1][2]) print " a3 : %12.6f %12.6f %12.6f"%(self.avec[2][0], self.avec[2][1], self.avec[2][2]) print "atoms" for i in range(len(self.atomList)): print "%4i (%2s) at position %12.6f %12.6f %12.6f"%\ (i, self.atomList[i].species.label, self.atomList[i].posc[0],\ self.atomList[i].posc[1], self.atomList[i].posc[2]) def findNeighbours(self): for iat in range(len(self.atomList)): xi = self.atomList[iat].posc nn = [] # add nearest neigbours for jat in range(len(self.atomList)): xj = self.atomList[jat].posc for i1 in range(-4,5): for i2 in range(-4,5): for i3 in range(-4,5): t = [0, 0, 0] for x in range(3): t[x] = i1 * self.avec[0][x] + i2 * self.avec[1][x] + i3 * self.avec[2][x] r = [0, 0, 0] for x in range(3): r[x] = xj[x] + t[x] - xi[x] d = math.sqrt(r[0]**2 + r[1]**2 + r[2]**2) if (d <= 10.0): nn.append([jat, r, d]) # sort by distance for i in range(len(nn) - 1): for j in range(i+1, len(nn)): if nn[j][2] < nn[i][2]: nn[i], nn[j] = nn[j], nn[i] self.atomList[iat].nghbr = nn[:] # # cell (not necessarily primitive) with atoms and bonds # class Cell: def __init__(self, geometry, box): self.geometry = geometry self.box = box self.bonds = [] self.atoms = [] self.bondList = [] return def hide(self, label): print " " print "hiding", label self.geometry.speciesList[label].visible = False return def atomSphere(self, label, color, R): self.geometry.speciesList[label].color = color self.geometry.speciesList[label].R = R return def bond(self, label1, label2, length, extend): self.bondList.append([label1, label2, length, extend]) return def atomOrbital(self, ias, fname, iorb): fin = open(fname, "r") f1 = [] for i in range(5): s1 = fin.readline().strip(" \n").split() if i == (iorb - 1): for j in range(5): f1.append(float(s1[j])) self.geometry.atomList[ias].orbital = Orbital(f1) return def write(self): self.fillBox() self.makeBonds() self.writeAtoms() self.writeBonds() #self.writeOrbitals() # def inBox(self, p, box): # n=[0,0,0] # a=box[0] # b=box[1] # c=box[2] # i=0 # # n[0]=a[1]*b[2]-a[2]*b[1] # n[1]=a[2]*b[0]-a[0]*b[2] # n[2]=a[0]*b[1]-a[1]*b[0] # d1=n[0]*p[0]+n[1]*p[1]+n[2]*p[2] # d2=n[0]*(p[0]-c[0])+n[1]*(p[1]-c[1])+n[2]*(p[2]-c[2]) # if cmp(d1,0)*cmp(d2,0)==-1 or abs(d1) < 1e-4 or abs(d2) < 1e-4: # i+=1; # # n[0]=a[1]*c[2]-a[2]*c[1] # n[1]=a[2]*c[0]-a[0]*c[2] # n[2]=a[0]*c[1]-a[1]*c[0] # d1=n[0]*p[0]+n[1]*p[1]+n[2]*p[2] # d2=n[0]*(p[0]-b[0])+n[1]*(p[1]-b[1])+n[2]*(p[2]-b[2]) # if cmp(d1,0)*cmp(d2,0)==-1 or abs(d1) < 1e-4 or abs(d2) < 1e-4: # i+=1; # # n[0]=b[1]*c[2]-b[2]*c[1] # n[1]=b[2]*c[0]-b[0]*c[2] # n[2]=b[0]*c[1]-b[1]*c[0] # d1=n[0]*p[0]+n[1]*p[1]+n[2]*p[2] # d2=n[0]*(p[0]-a[0])+n[1]*(p[1]-a[1])+n[2]*(p[2]-a[2]) # if cmp(d1,0)*cmp(d2,0)==-1 or abs(d1) < 1e-4 or abs(d2) < 1e-4: # i+=1; # # if i==3: return True # else: return False def inBox(self, r, imv): # coorinates in the inits of box vectors rb = [0, 0, 0] for i in range(3): for j in range(3): rb[i] += imv[i][j] * r[j] if (rb[0] >= -0.5 and rb[0] <= 0.5) and \ (rb[1] >= -0.5 and rb[1] <= 0.5) and \ (rb[2] >= -0.5 and rb[2] <= 0.5): return True else: return False def fillBox(self): print " " print "populating the box" print " box parameters" print " center : %12.6f %12.6f %12.6f"%(self.box[0][0], self.box[0][1], self.box[0][2]) print " v1 : %12.6f %12.6f %12.6f"%(self.box[1][0], self.box[1][1], self.box[1][2]) print " v2 : %12.6f %12.6f %12.6f"%(self.box[2][0], self.box[2][1], self.box[2][2]) print " v3 : %12.6f %12.6f %12.6f"%(self.box[3][0], self.box[3][1], self.box[3][2]) mv = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] for i in range(3): for x in range(3): mv[x][i] = self.box[1+i][x] imv = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] r3minv(mv, imv) for ias in range(len(self.geometry.atomList)): if self.geometry.atomList[ias].species.visible: for i1 in range(-4, 5): for i2 in range(-4, 5): for i3 in range(-4, 5): # absolute position (position in the unit cell + translation) r = [0, 0, 0] for x in range(3): r[x] = self.geometry.atomList[ias].posc[x] + \ i1 * self.geometry.avec[0][x] + \ i2 * self.geometry.avec[1][x] + \ i3 * self.geometry.avec[2][x] # position with respect to the center of the box r0 = [0, 0, 0] for x in range(3): r0[x] = r[x] - self.box[0][x] if self.inBox(r0, imv): self.atoms.append([ias, r]) return def writeAtoms(self): print " " print "writing ATOMS.dx" fout = open("ATOMS.dx", "w+") fout.write("object 1 class array type float rank 0 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): ias = self.atoms[i][0] fout.write("%f\n"%self.geometry.atomList[ias].species.R) fout.write("attribute \"dep\" string \"positions\"\n") fout.write("#\n") fout.write("object 2 class array type float rank 1 shape 3 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): ias = self.atoms[i][0] color = self.geometry.atomList[ias].species.color fout.write("%f %f %f\n"%(color[0], color[1], color[2])) fout.write("attribute \"dep\" string \"positions\"\n") fout.write("#\n") fout.write("object 3 class array type float rank 1 shape 3 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): ias = self.atoms[i][0] pos = self.atoms[i][1] fout.write("%f %f %f # %s\n"%(pos[0], pos[1], pos[2], self.geometry.atomList[ias].species.label)) fout.write("attribute \"dep\" string \"positions\"\n") fout.write("#\n") fout.write("object \"atoms\" class field\n") fout.write("component \"data\" value 1\n") fout.write("component \"colors\" value 2\n") fout.write("component \"positions\" value 3\n") fout.write("attribute \"name\" string \"cell\"") fout.close() return def index_in_atoms(self, r): for i in range(len(self.atoms)): if math.fabs(r[0] - self.atoms[i][1][0]) < 1e-10 and \ math.fabs(r[1] - self.atoms[i][1][1]) < 1e-10 and \ math.fabs(r[2] - self.atoms[i][1][2]) < 1e-10: return i return -1 def makeBonds(self): for ibond in range(len(self.bondList)): lbl1 = self.bondList[ibond][0] lbl2 = self.bondList[ibond][1] length = self.bondList[ibond][2] extend = self.bondList[ibond][3] # go over all atoms in the box for i in range(len(self.atoms)): ias = self.atoms[i][0] if self.geometry.atomList[ias].species.label == lbl1: # go over nearest neigbours of atom ias for j in range(len(self.geometry.atomList[ias].nghbr)): jas = self.geometry.atomList[ias].nghbr[j][0] if (self.geometry.atomList[jas].species.label == lbl2) and \ (self.geometry.atomList[ias].nghbr[j][2] <= length): # absolute position of neigbour: position of central atom + connecting vector rj = [0, 0, 0] for x in range(3): rj[x] = self.atoms[i][1][x] + self.geometry.atomList[ias].nghbr[j][1][x] # index of this neigbour in the list of atoms in the box idx = self.index_in_atoms(rj) if idx!=-1: self.bonds.append([i, idx]) elif extend: self.atoms.append([jas, rj]) self.bonds.append([i, len(self.atoms)-1]) return def writeBonds(self): print " " print "writing BONDS.dx" fout = open("BONDS.dx","w+") fout.write("object 1 class array type float rank 1 shape 3 items %i data follows\n"%len(self.atoms)) for i in range(len(self.atoms)): pos = self.atoms[i][1] fout.write("%f %f %f\n"%(pos[0], pos[1], pos[2])) fout.write("#\n") fout.write("object 2 class array type int rank 1 shape 2 items %i data follows\n"%len(self.bonds)) for i in range(len(self.bonds)): fout.write("%i %i\n"%(self.bonds[i][0], self.bonds[i][1])) fout.write("attribute \"element type\" string \"lines\"\n") fout.write("attribute \"ref\" string \"positions\"\n") fout.write("#\n") fout.write("object \"atom_connect\" class field\n") fout.write("component \"positions\" value 1\n") fout.write("component \"connections\" value 2\n") fout.write("end\n") fout.close() return def writeOrbitals(self): print " " print "writing ORBITALS.dx" fout=open("ORBITALS.dx","w+") iorb=0 for iat in range(len(self.atomList)): print self.atomList[iat].orbital if self.atomList[iat].orbital != 0: iorb+=1 r0=self.atomList[iat].posc fout.write("object %i class array type float rank 1 shape 3 items %i data follows\n"%\ ((iorb-1)*2+1,len(self.atomList[iat].orbital.pos))) for i in range(len(self.atomList[iat].orbital.pos)): r=[0,0,0] for x in range(3): r[x]=r0[x]+self.atomList[iat].orbital.pos[i][x] fout.write("%f %f %f\n"%(r[0],r[1],r[2])) fout.write("#\n") fout.write("object %i class array type int rank 1 shape 3 items %i data follows\n"%\ ((iorb-1)*2+2,len(self.atomList[iat].orbital.tri))) for i in range(len(self.atomList[iat].orbital.tri)): fout.write("%i %i %i\n"%(self.atomList[iat].orbital.tri[i][0],\ self.atomList[iat].orbital.tri[i][1],\ self.atomList[iat].orbital.tri[i][2])) fout.write("attribute \"ref\" string \"positions\"\n") fout.write("attribute \"element type\" string \"triangles\"\n") fout.write("attribute \"dep\" string \"connections\"\n") fout.write("#\n") fout.write("object \"orbital%i\" class field\n"%iorb) fout.write("component \"positions\" value %i\n"%((iorb-1)*2+1)) fout.write("component \"connections\" value %i\n"%((iorb-1)*2+2)) fout.write("#\n") norb=iorb fout.write("object \"orbital\" class group\n") for iorb in range(norb): fout.write(" member %i value \"orbital%i\"\n"%(iorb,iorb+1)) fout.write("end\n") fout.close() # # # print " " print "GEOMTERY.OUT to OpenDX" print " " # # get the geometry # geometry = Geometry() # # 3D box (center point + 3 non-collinear vectors) # example: # box=[[0,0,0],[10,0,0],[0,10,0],[0,0,10]] box = [[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]] #geometry.avec[0],geometry.avec[1],geometry.avec[2]] # # cell with user-defined shape # cell = Cell(geometry, box) # # cell.hide(label) # hides species with a given label # example: # cell.hide("Ca") #cell.hide("Y") # # cell.atomSphere(label,color,radius) # sets [r,g,b] color and radius of species with a given label # example: red Mn sphere with radius 1.0 # cell.atomSphere("Mn",[1.0,0.0,0.0],1.0) cell.atomSphere("La", [0.0, 1.0, 0.0], 1.0) cell.atomSphere("Cu", [1.0, 0.0, 0.0], 1.0) cell.atomSphere("O", [0.0, 0.0, 1.0], 1.0) # # cell.bond(label1,label2,d,extend) # defines a bond with a maximum length 'd' from species 'label1' to species 'label2' # if extend is True, the bond can go outside the box # example: Mn-O bond # cell.bond("Mn","O",5,True) cell.bond("Cu", "O", 5, True) # # cell.atomOrbital(j, file_name, i) # defines angular part of the site-centered orbital i for atom j; # the orbital coefficients are taken from file file_name # example: #cell.atomOrbital(4, "Cu1_mtrx.txt", 1) # # write to .dx files # cell.write()
rgvanwesep/exciting-plus-rgvw-mod
utilities/geometry2dx__mtrx.py
Python
gpl-3.0
20,319
#Copyright (C) 2014 Marc Herndon # #This program is free software; you can redistribute it and/or #modify it under the terms of the GNU General Public License, #version 2, as published by the Free Software Foundation. # #This program is distributed in the hope that it will be useful, #but WITHOUT ANY WARRANTY; without even the implied warranty of #MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #GNU General Public License for more details. # #You should have received a copy of the GNU General Public License #along with this program; if not, write to the Free Software #Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. """ This module contains the definition of the `Attribute` class, used to represent individual SMART attributes associated with a `Device`. """ class Attribute(object): """ Contains all of the information associated with a single SMART attribute in a `Device`'s SMART table. This data is intended to exactly mirror that obtained through smartctl. """ def __init__(self, num, name, flags, value, worst, thresh, attr_type, updated, when_failed, raw): self.num = num """**(str):** Attribute's ID as a decimal value (1-255).""" self.name = name """ **(str):** Attribute's name, as reported by smartmontools' drive.db. """ self.flags = flags """**(str):** Attribute flags as a hexadecimal value (ie: 0x0032).""" self.value = value """**(str):** Attribute's current normalized value.""" self.worst = worst """**(str):** Worst recorded normalized value for this attribute.""" self.thresh = thresh """**(str):** Attribute's failure threshold.""" self.type = attr_type """**(str):** Attribute's type, generally 'pre-fail' or 'old-age'.""" self.updated = updated """ **(str):** When is this attribute updated? Generally 'Always' or 'Offline' """ self.when_failed = when_failed """ **(str):** When did this attribute cross below `pySMART.attribute.Attribute.thresh`? Reads '-' when not failed. Generally either 'FAILING_NOW' or 'In_the_Past' otherwise. """ self.raw = raw """**(str):** Attribute's current raw (non-normalized) value.""" def __repr__(self): """Define a basic representation of the class object.""" return "<SMART Attribute %r %s/%s raw:%s>" % ( self.name, self.value, self.thresh, self.raw) def __str__(self): """ Define a formatted string representation of the object's content. In the interest of not overflowing 80-character lines this does not print the value of `pySMART.attribute.Attribute.flags_hex`. """ return "{0:>3} {1:24}{2:4}{3:4}{4:4}{5:9}{6:8}{7:12}{8}".format( self.num, self.name, self.value, self.worst, self.thresh, self.type, self.updated, self.when_failed, self.raw) __all__ = ['Attribute']
scith/htpc-manager_ynh
sources/libs/pySMART/attribute.py
Python
gpl-3.0
3,070
define([ 'angular' , './view-rubberband-controller' , './view-rubberband-directive' ], function( angular , Controller , directive ) { "use strict"; return angular.module('mtk.viewRubberband', []) .controller('ViewRubberbandController', Controller) .directive('mtkViewRubberband', directive) ; });
jeroenbreen/metapolator
app/lib/ui/metapolator/view-rubberband/view-rubberband.js
JavaScript
gpl-3.0
354
from .main import Sabnzbd def start(): return Sabnzbd() config = [{ 'name': 'sabnzbd', 'groups': [ { 'tab': 'downloaders', 'list': 'download_providers', 'name': 'sabnzbd', 'label': 'Sabnzbd', 'description': 'Use <a href="http://sabnzbd.org/" target="_blank">SABnzbd</a> (0.7+) to download NZBs.', 'wizard': True, 'options': [ { 'name': 'enabled', 'default': 0, 'type': 'enabler', 'radio_group': 'nzb', }, { 'name': 'host', 'default': 'localhost:8080', }, { 'name': 'api_key', 'label': 'Api Key', 'description': 'Used for all calls to Sabnzbd.', }, { 'name': 'category', 'label': 'Category', 'description': 'The category CP places the nzb in. Like <strong>movies</strong> or <strong>couchpotato</strong>', }, { 'name': 'priority', 'label': 'Priority', 'type': 'dropdown', 'default': '0', 'advanced': True, 'values': [('Paused', -2), ('Low', -1), ('Normal', 0), ('High', 1), ('Forced', 2)], 'description': 'Add to the queue with this priority.', }, { 'name': 'manual', 'default': False, 'type': 'bool', 'advanced': True, 'description': 'Disable this downloader for automated searches, but use it when I manually send a release.', }, { 'name': 'remove_complete', 'advanced': True, 'label': 'Remove NZB', 'default': False, 'type': 'bool', 'description': 'Remove the NZB from history after it completed.', }, { 'name': 'delete_failed', 'default': True, 'advanced': True, 'type': 'bool', 'description': 'Delete a release after the download has failed.', }, ], } ], }]
jerbob92/CouchPotatoServer
couchpotato/core/downloaders/sabnzbd/__init__.py
Python
gpl-3.0
2,548
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. *****************************************************************************/ // sync_reset.cpp -- test for // // Original Author: John Aynsley, Doulos, Inc. // // MODIFICATION LOG - modifiers, enter your name, affiliation, date and // // $Log: sync_reset.cpp,v $ // Revision 1.2 2011/05/08 19:18:46 acg // Andy Goodrich: remove extraneous + prefixes from git diff. // // sync_reset_on/off #define SC_INCLUDE_DYNAMIC_PROCESSES #include <systemc> using namespace sc_core; using std::cout; using std::endl; struct M2: sc_module { M2(sc_module_name _name) { SC_THREAD(ticker); SC_THREAD(calling); SC_THREAD(target1); t1 = sc_get_current_process_handle(); sc_spawn_options opt; opt.spawn_method(); opt.dont_initialize(); opt.set_sensitivity( &t1.reset_event() ); sc_spawn(sc_bind( &M2::reset_handler, this ), "reset_handler", &opt); SC_THREAD(target2); t2 = sc_get_current_process_handle(); SC_METHOD(target3); sensitive << ev; t3 = sc_get_current_process_handle(); count = 1; f0 = f1 = f2 = f3 = f4 = f5 = f6 = f7 = f8 = f9 = 0; f10 = f11 = f12 = f13 = f14 = f15 = f16 = f17 = f18 = f19 = 0; f20 = f21 = f22 = f23 = f24 = f25 = f26 = f27 = f28 = f29 = 0; f30 = f31 = f32 = f33 = f34 = f35 = f36 = f37 = f38 = f39 = 0; f40 = f41 = f42 = f43 = f44 = f45 = f46 = f47 = f48 = f49 = 0; } sc_process_handle t1, t2, t3; sc_event ev; int count; int f0, f1, f2, f3, f4, f5, f6, f7, f8, f9; int f10, f11, f12, f13, f14, f15, f16, f17, f18, f19; int f20, f21, f22, f23, f24, f25, f26, f27, f28, f29; int f30, f31, f32, f33, f34, f35, f36, f37, f38, f39; int f40, f41, f42, f43, f44, f45, f46, f47, f48, f49; void ticker() { for (;;) { wait(10, SC_NS); sc_assert( !sc_is_unwinding() ); ev.notify(); } } void calling() { count = 1; wait(15, SC_NS); // Target runs at 10 NS count = 2; t1.sync_reset_on(); // Target does not run at 15 NS wait(10, SC_NS); // Target is reset at 20 NS count = 3; wait(10, SC_NS); // Target is reset again at 30 NS count = 4; t1.sync_reset_off(); // Target does not run at 35 NS wait(10, SC_NS); // Target runs at 40 NS count = 5; t1.sync_reset_off(); // Double sync_reset_off wait(10, SC_NS); // Target runs at 50 NS count = 6; t1.sync_reset_on(); t1.disable(); wait(10, SC_NS); // Target does not run at 60 NS count = 7; t1.enable(); // Target does not run at 65 NS wait(10, SC_NS); // Target reset at 70 NS count = 8; t1.disable(); wait(10, SC_NS); // Target does not run at 80 NS count = 9; t1.sync_reset_off(); wait(10, SC_NS); // Target still disabled at 90 NS count = 10; t1.enable(); wait(10, SC_NS); // Target runs at 100 NS count = 11; t1.suspend(); wait(10, SC_NS); // Target does not run at 110 NS count = 12; wait(10, SC_NS); // Target still suspended at 120 NS count = 13; t1.resume(); // Target runs at 125 NS wait(1, SC_NS); count = 14; wait(9, SC_NS); // Target runs again at 130 NS count = 15; t1.sync_reset_on(); // Double sync_reset_on wait(10, SC_NS); // Target reset at 140 NS count = 16; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 150 NS count = 17; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 160 NS count = 18; t1.sync_reset_on(); wait(10, SC_NS); // Target reset at 170 NS count = 19; t1.reset(); // Target reset at 175 NS wait(SC_ZERO_TIME); count = 20; wait(1, SC_NS); t1.reset(); // Target reset at 176 NS count = 21; t1.reset(); // Target reset at 176 NS wait(1, SC_NS); count = 22; wait(8, SC_NS); // Target reset at 180 NS count = 23; wait(10, SC_NS); // Target reset at 190 NS count = 24; t1.sync_reset_off(); wait(10, SC_NS); // Target runs at 200 NS count = 25; wait(10, SC_NS); // Target runs at 210 NS count = 26; t1.reset(); wait(SC_ZERO_TIME); // Target reset at 215 t1.disable(); // Close it down wait(sc_time(300, SC_NS) - sc_time_stamp()); count = 27; t2.resume(); wait(SC_ZERO_TIME); count = 28; wait(15, SC_NS); count = 29; t2.sync_reset_on(); wait(10, SC_NS); t2.sync_reset_off(); t2.suspend(); wait(sc_time(405, SC_NS) - sc_time_stamp()); count = 30; t3.resume(); wait(SC_ZERO_TIME); count = 31; wait(10, SC_NS); count = 32; t3.sync_reset_on(); wait(10, SC_NS); sc_stop(); } void target1() { //cout << "Target1 called/reset at " << sc_time_stamp() << " count = " << count << endl; switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(0, SC_NS) ); f0=1; break; case 2: sc_assert( sc_time_stamp() == sc_time(20, SC_NS) ); f1=1; break; case 3: sc_assert( sc_time_stamp() == sc_time(30, SC_NS) ); f2=1; break; case 7: sc_assert( sc_time_stamp() == sc_time(70, SC_NS) ); f3=1; break; case 15: sc_assert( sc_time_stamp() == sc_time(140, SC_NS) ); f4=1; break; case 18: sc_assert( sc_time_stamp() == sc_time(170, SC_NS) ); f5=1; break; case 19: sc_assert( sc_time_stamp() == sc_time(175, SC_NS) ); f6=1; break; case 20: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f7=1; break; case 21: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f8=1; break; case 22: sc_assert( sc_time_stamp() == sc_time(180, SC_NS) ); f9=1; break; case 23: sc_assert( sc_time_stamp() == sc_time(190, SC_NS) ); f10=1; break; case 26: sc_assert( sc_time_stamp() == sc_time(215, SC_NS) ); f11=1; break; default: sc_assert( false ); break; } for (;;) { try { wait(ev); //cout << "Target1 awoke at " << sc_time_stamp() << " count = " << count << endl; sc_assert( !sc_is_unwinding() ); switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(10, SC_NS) ); f12=1; break; case 4: sc_assert( sc_time_stamp() == sc_time(40, SC_NS) ); f13=1; break; case 5: sc_assert( sc_time_stamp() == sc_time(50, SC_NS) ); f14=1; break; case 10: sc_assert( sc_time_stamp() == sc_time(100, SC_NS) ); f15=1; break; case 13: sc_assert( sc_time_stamp() == sc_time(125, SC_NS) ); f16=1; break; case 14: sc_assert( sc_time_stamp() == sc_time(130, SC_NS) ); f17=1; break; case 16: sc_assert( sc_time_stamp() == sc_time(150, SC_NS) ); f18=1; break; case 17: sc_assert( sc_time_stamp() == sc_time(160, SC_NS) ); f19=1; break; case 24: sc_assert( sc_time_stamp() == sc_time(200, SC_NS) ); f20=1; break; case 25: sc_assert( sc_time_stamp() == sc_time(210, SC_NS) ); f21=1; break; default: sc_assert( false ); break; } } catch (const sc_unwind_exception& ex) { sc_assert( sc_is_unwinding() ); sc_assert( ex.is_reset() ); throw ex; } } } void reset_handler() { //cout << "reset_handler awoke at " << sc_time_stamp() << " count = " << count << endl; sc_assert( !sc_is_unwinding() ); switch (count) { case 2: sc_assert( sc_time_stamp() == sc_time(20, SC_NS) ); f22=1; break; case 3: sc_assert( sc_time_stamp() == sc_time(30, SC_NS) ); f23=1; break; case 7: sc_assert( sc_time_stamp() == sc_time(70, SC_NS) ); f24=1; break; case 15: sc_assert( sc_time_stamp() == sc_time(140, SC_NS) ); f27=1; break;; case 18: sc_assert( sc_time_stamp() == sc_time(170, SC_NS) ); f28=1; break; case 19: sc_assert( sc_time_stamp() == sc_time(175, SC_NS) ); f29=1; break; case 21: sc_assert( sc_time_stamp() == sc_time(176, SC_NS) ); f31=1; break; case 22: sc_assert( sc_time_stamp() == sc_time(180, SC_NS) ); f32=1; break; case 23: sc_assert( sc_time_stamp() == sc_time(190, SC_NS) ); f33=1; break; case 26: sc_assert( sc_time_stamp() == sc_time(215, SC_NS) ); f34=1; break; default: sc_assert( false ); break; } } void target2() { if (sc_delta_count() == 0) t2.suspend(); // Hack to work around not being able to call suspend during elab switch (count) { case 27: sc_assert( sc_time_stamp() == sc_time(300, SC_NS) ); f35=1; break; case 29: sc_assert( sc_time_stamp() == sc_time(320, SC_NS) ); f37=1; break; default: sc_assert( false ); break; } while(1) { try { wait(10, SC_NS); } catch (const sc_unwind_exception& e) { switch (count) { case 29: sc_assert( sc_time_stamp() == sc_time(320, SC_NS) ); f38=1; break; default: sc_assert( false ); break; } throw e; } switch (count) { case 28: sc_assert( sc_time_stamp() == sc_time(310, SC_NS) ); f36=1; break; default: sc_assert( false ); break; } } } void target3() { if (sc_delta_count() == 0) t3.suspend(); // Hack to work around not being able to call suspend during elab switch (count) { case 1: sc_assert( sc_time_stamp() == sc_time(0, SC_NS) ); break; case 30: sc_assert( sc_time_stamp() == sc_time(405, SC_NS) ); f39=1; break; case 31: sc_assert( sc_time_stamp() == sc_time(410, SC_NS) ); f40=1; break; case 32: sc_assert( sc_time_stamp() == sc_time(420, SC_NS) ); f41=1; break; default: sc_assert( false ); break; } } SC_HAS_PROCESS(M2); }; int sc_main(int argc, char* argv[]) { M2 m("m"); sc_start(); sc_assert(m.f0); sc_assert(m.f1); sc_assert(m.f2); sc_assert(m.f3); sc_assert(m.f4); sc_assert(m.f5); sc_assert(m.f6); sc_assert(m.f7); sc_assert(m.f8); sc_assert(m.f9); sc_assert(m.f10); sc_assert(m.f11); sc_assert(m.f12); sc_assert(m.f13); sc_assert(m.f14); sc_assert(m.f15); sc_assert(m.f16); sc_assert(m.f17); sc_assert(m.f18); sc_assert(m.f19); sc_assert(m.f20); sc_assert(m.f21); sc_assert(m.f22); sc_assert(m.f23); sc_assert(m.f24); sc_assert(m.f27); sc_assert(m.f28); sc_assert(m.f29); sc_assert(m.f31); sc_assert(m.f32); sc_assert(m.f33); sc_assert(m.f34); sc_assert(m.f35); sc_assert(m.f36); sc_assert(m.f37); sc_assert(m.f38); sc_assert(m.f39); sc_assert(m.f40); sc_assert(m.f41); cout << endl << "Success" << endl; return 0; }
vineodd/PIMSim
GEM5Simulation/gem5/src/systemc/tests/systemc/1666-2011-compliance/sync_reset/sync_reset.cpp
C++
gpl-3.0
11,660
// UK lang variables tinyMCE.addI18n('pt.codehighlighting',{ codehighlighting_desc : "Code Highlighting", codehighlighting_title : "Code Highlighting", codehighlighting_langaugepicker : "Choose the language", codehighlighting_pagecode : "Paste your code here", codehighlighting_button_desc: "Insert code", codehighlighting_nogutter : "No Gutter", codehighlighting_collapse : "Collapse", codehighlighting_nocontrols : "No Controls", codehighlighting_showcolumns : "Show Columns" });
ahilles107/Newscoop
newscoop/js/tinymce/plugins/codehighlighting/langs/pt.js
JavaScript
gpl-3.0
494
// Copyright 2008 the V8 project authors. 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. var a = [0,1,2,3]; assertEquals(0, a.length = 0); assertEquals('undefined', typeof a[0]); assertEquals('undefined', typeof a[1]); assertEquals('undefined', typeof a[2]); assertEquals('undefined', typeof a[3]); var a = [0,1,2,3]; assertEquals(2, a.length = 2); assertEquals(0, a[0]); assertEquals(1, a[1]); assertEquals('undefined', typeof a[2]); assertEquals('undefined', typeof a[3]); var a = new Array(); a[0] = 0; a[1000] = 1000; a[1000000] = 1000000; a[2000000] = 2000000; assertEquals(2000001, a.length); assertEquals(0, a.length = 0); assertEquals(0, a.length); assertEquals('undefined', typeof a[0]); assertEquals('undefined', typeof a[1000]); assertEquals('undefined', typeof a[1000000]); assertEquals('undefined', typeof a[2000000]); var a = new Array(); a[0] = 0; a[1000] = 1000; a[1000000] = 1000000; a[2000000] = 2000000; assertEquals(2000001, a.length); assertEquals(2000, a.length = 2000); assertEquals(2000, a.length); assertEquals(0, a[0]); assertEquals(1000, a[1000]); assertEquals('undefined', typeof a[1000000]); assertEquals('undefined', typeof a[2000000]); var a = new Array(); a[Math.pow(2,31)-1] = 0; a[Math.pow(2,30)-1] = 0; assertEquals(Math.pow(2,31), a.length); var a = new Array(); a[0] = 0; a[1000] = 1000; a[Math.pow(2,30)-1] = Math.pow(2,30)-1; a[Math.pow(2,31)-1] = Math.pow(2,31)-1; a[Math.pow(2,32)-2] = Math.pow(2,32)-2; assertEquals(Math.pow(2,30)-1, a[Math.pow(2,30)-1]); assertEquals(Math.pow(2,31)-1, a[Math.pow(2,31)-1]); assertEquals(Math.pow(2,32)-2, a[Math.pow(2,32)-2]); assertEquals(Math.pow(2,32)-1, a.length); assertEquals(Math.pow(2,30) + 1, a.length = Math.pow(2,30)+1); // not a smi! assertEquals(Math.pow(2,30)+1, a.length); assertEquals(0, a[0]); assertEquals(1000, a[1000]); assertEquals(Math.pow(2,30)-1, a[Math.pow(2,30)-1]); assertEquals('undefined', typeof a[Math.pow(2,31)-1]); assertEquals('undefined', typeof a[Math.pow(2,32)-2], "top"); var a = new Array(); assertEquals(Object(12), a.length = new Number(12)); assertEquals(12, a.length); Number.prototype.valueOf = function() { return 10; } var n = new Number(100); assertEquals(n, a.length = n); assertEquals(10, a.length); n.valueOf = function() { return 20; } assertEquals(n, a.length = n); assertEquals(20, a.length); var o = { length: -23 }; Array.prototype.pop.apply(o); assertEquals(4294967272, o.length); // Check case of compiled stubs. var a = []; for (var i = 0; i < 7; i++) { assertEquals(3, a.length = 3); var t = 239; t = a.length = 7; assertEquals(7, t); } (function () { "use strict"; var frozen_object = Object.freeze({__proto__:[]}); assertThrows(function () { frozen_object.length = 10 }); })();
victorzhao/miniblink49
v8_4_5/test/mjsunit/array-length.js
JavaScript
gpl-3.0
4,264
// // DO NOT REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. // // @Authors: // christiank // dinwiggy // // Copyright 2004-2010 by OM International // // This file is part of OpenPetra.org. // // OpenPetra.org is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // OpenPetra.org is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with OpenPetra.org. If not, see <http://www.gnu.org/licenses/>. // using System; using System.Data; using System.Windows.Forms; using Ict.Common; using Ict.Common.Controls; using Ict.Common.Remoting.Client; using Ict.Common.Verification; using Ict.Petra.Client.App.Core; using Ict.Petra.Client.App.Core.RemoteObjects; using Ict.Petra.Client.MPartner; using Ict.Petra.Shared; using Ict.Petra.Shared.Interfaces.MPartner; using Ict.Petra.Shared.MCommon; using Ict.Petra.Shared.MCommon.Data; using Ict.Petra.Shared.MPartner.Partner.Data; using Ict.Petra.Shared.MPersonnel; using Ict.Petra.Shared.MPersonnel.Personnel.Data; using Ict.Petra.Shared.MPersonnel.Person; using Ict.Petra.Shared.MPersonnel.Validation; namespace Ict.Petra.Client.MPartner.Gui { public partial class TUC_IndividualData_PreviousExperience { /// <summary>holds a reference to the Proxy System.Object of the Serverside UIConnector</summary> private IPartnerUIConnectorsPartnerEdit FPartnerEditUIConnector; #region Properties /// <summary>used for passing through the Clientside Proxy for the UIConnector</summary> public IPartnerUIConnectorsPartnerEdit PartnerEditUIConnector { get { return FPartnerEditUIConnector; } set { FPartnerEditUIConnector = value; } } #endregion #region Events /// <summary>todoComment</summary> public event TRecalculateScreenPartsEventHandler RecalculateScreenParts; #endregion /// <summary> /// todoComment /// </summary> public void SpecialInitUserControl(IndividualDataTDS AMainDS) { FMainDS = AMainDS; LoadDataOnDemand(); } /// <summary> /// add a new batch /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void NewRecord(System.Object sender, EventArgs e) { this.CreateNewPmPastExperience(); } // Sets the key for a new row private void NewRowManual(ref PmPastExperienceRow ARow) { ARow.PartnerKey = FMainDS.PPerson[0].PartnerKey; ARow.Key = Convert.ToInt32(TRemote.MCommon.WebConnectors.GetNextSequence(TSequenceNames.seq_past_experience)); } /// <summary> /// Performs checks to determine whether a deletion of the current /// row is permissable /// </summary> /// <param name="ARowToDelete">the currently selected row to be deleted</param> /// <param name="ADeletionQuestion">can be changed to a context-sensitive deletion confirmation question</param> /// <returns>true if user is permitted and able to delete the current row</returns> private bool PreDeleteManual(PmPastExperienceRow ARowToDelete, ref string ADeletionQuestion) { /*Code to execute before the delete can take place*/ ADeletionQuestion = Catalog.GetString("Are you sure you want to delete the current row?"); ADeletionQuestion += String.Format("{0}{0}({1} {2}, {3} {4})", Environment.NewLine, lblLocation.Text, txtLocation.Text, lblRole.Text, txtRole.Text); return true; } /// <summary> /// Code to be run after the deletion process /// </summary> /// <param name="ARowToDelete">the row that was/was to be deleted</param> /// <param name="AAllowDeletion">whether or not the user was permitted to delete</param> /// <param name="ADeletionPerformed">whether or not the deletion was performed successfully</param> /// <param name="ACompletionMessage">if specified, is the deletion completion message</param> private void PostDeleteManual(PmPastExperienceRow ARowToDelete, bool AAllowDeletion, bool ADeletionPerformed, string ACompletionMessage) { if (ADeletionPerformed) { DoRecalculateScreenParts(); } } private void DoRecalculateScreenParts() { OnRecalculateScreenParts(new TRecalculateScreenPartsEventArgs() { ScreenPart = TScreenPartEnum.spCounters }); } private void ShowDetailsManual(PmPastExperienceRow ARow) { // In theory, the next Method call could be done in Methods NewRowManual; however, NewRowManual runs before // the Row is actually added and this would result in the Count to be one too less, so we do the Method call here, short // of a non-existing 'AfterNewRowManual' Method.... DoRecalculateScreenParts(); } /// <summary> /// Gets the data from all controls on this UserControl. /// The data is stored in the DataTables/DataColumns to which the Controls /// are mapped. /// </summary> public void GetDataFromControls2() { // Get data out of the Controls only if there is at least one row of data (Note: Column Headers count as one row) if (grdDetails.Rows.Count > 1) { GetDataFromControls(); } } /// <summary> /// This Method is needed for UserControls who get dynamicly loaded on TabPages. /// Since we don't have controls on this UserControl that need adjusting after resizing /// on 'Large Fonts (120 DPI)', we don't need to do anything here. /// </summary> public void AdjustAfterResizing() { } /// <summary> /// called for HereFlag event for work location check box /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void HereFlagChanged(object sender, EventArgs e) { if (this.chkHereFlag.Checked) { chkSimilarOrgFlag.Enabled = false; chkSimilarOrgFlag.Checked = true; } else { chkSimilarOrgFlag.Enabled = true; chkSimilarOrgFlag.Checked = false; } } /// <summary> /// Loads Previous Experience Data from Petra Server into FMainDS, if not already loaded. /// </summary> /// <returns>true if successful, otherwise false.</returns> private Boolean LoadDataOnDemand() { Boolean ReturnValue; try { // Make sure that Typed DataTables are already there at Client side if (FMainDS.PmPastExperience == null) { FMainDS.Tables.Add(new PmPastExperienceTable()); FMainDS.InitVars(); } if (TClientSettings.DelayedDataLoading && (FMainDS.PmPastExperience.Rows.Count == 0)) { FMainDS.Merge(FPartnerEditUIConnector.GetDataPersonnelIndividualData(TIndividualDataItemEnum.idiPreviousExperiences)); // Make DataRows unchanged if (FMainDS.PmPastExperience.Rows.Count > 0) { if (FMainDS.PmPastExperience.Rows[0].RowState != DataRowState.Added) { FMainDS.PmPastExperience.AcceptChanges(); } } } if (FMainDS.PmPastExperience.Rows.Count != 0) { ReturnValue = true; } else { ReturnValue = false; } } catch (System.NullReferenceException) { return false; } catch (Exception) { throw; } return ReturnValue; } private void OnRecalculateScreenParts(TRecalculateScreenPartsEventArgs e) { if (RecalculateScreenParts != null) { RecalculateScreenParts(this, e); } } private void ValidateDataDetailsManual(PmPastExperienceRow ARow) { TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection; TSharedPersonnelValidation_Personnel.ValidatePreviousExperienceManual(this, ARow, ref VerificationResultCollection, FValidationControlsDict); } } }
tpokorra/openpetra.js
csharp/ICT/Petra/Client/MPartner/Gui/UC_IndividualData_PreviousExperience.ManualCode.cs
C#
gpl-3.0
9,535
/* * This file is part of the PulseView project. * * Copyright (C) 2012 Joel Holdsworth <joel@airwebreathe.org.uk> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see <http://www.gnu.org/licenses/>. */ #ifndef PULSEVIEW_PV_DATA_ANALOGSEGMENT_HPP #define PULSEVIEW_PV_DATA_ANALOGSEGMENT_HPP #include "segment.hpp" #include <utility> #include <vector> #include <QObject> using std::enable_shared_from_this; using std::pair; namespace AnalogSegmentTest { struct Basic; } namespace pv { namespace data { class Analog; class AnalogSegment : public Segment, public enable_shared_from_this<Segment> { Q_OBJECT public: struct EnvelopeSample { float min; float max; }; struct EnvelopeSection { uint64_t start; unsigned int scale; uint64_t length; EnvelopeSample *samples; }; private: struct Envelope { uint64_t length; uint64_t data_length; EnvelopeSample *samples; }; private: static const unsigned int ScaleStepCount = 10; static const int EnvelopeScalePower; static const int EnvelopeScaleFactor; static const float LogEnvelopeScaleFactor; static const uint64_t EnvelopeDataUnit; public: AnalogSegment(Analog& owner, uint32_t segment_id, uint64_t samplerate); virtual ~AnalogSegment(); void append_interleaved_samples(const float *data, size_t sample_count, size_t stride); float get_sample(int64_t sample_num) const; void get_samples(int64_t start_sample, int64_t end_sample, float* dest) const; const pair<float, float> get_min_max() const; float* get_iterator_value_ptr(SegmentDataIterator* it); void get_envelope_section(EnvelopeSection &s, uint64_t start, uint64_t end, float min_length) const; private: void reallocate_envelope(Envelope &e); void append_payload_to_envelope_levels(); private: Analog& owner_; struct Envelope envelope_levels_[ScaleStepCount]; float min_value_, max_value_; friend struct AnalogSegmentTest::Basic; }; } // namespace data } // namespace pv #endif // PULSEVIEW_PV_DATA_ANALOGSEGMENT_HPP
uwehermann/pulseview
pv/data/analogsegment.hpp
C++
gpl-3.0
2,563
package org.ovirt.engine.ui.uicommonweb.models.providers; import org.ovirt.engine.core.common.action.AddExternalSubnetParameters; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.businessentities.network.NetworkView; import org.ovirt.engine.core.common.businessentities.network.ProviderNetwork; import org.ovirt.engine.ui.frontend.Frontend; import org.ovirt.engine.ui.uicommonweb.UICommand; import org.ovirt.engine.ui.uicommonweb.help.HelpTag; import org.ovirt.engine.ui.uicommonweb.models.EntityModel; import org.ovirt.engine.ui.uicommonweb.models.Model; import org.ovirt.engine.ui.uicommonweb.models.SearchableListModel; import org.ovirt.engine.ui.uicompat.ConstantsManager; import org.ovirt.engine.ui.uicompat.FrontendActionAsyncResult; import org.ovirt.engine.ui.uicompat.IFrontendActionAsyncCallback; public class NewExternalSubnetModel extends Model { private EntityModel<NetworkView> network; private ExternalSubnetModel subnetModel; private final SearchableListModel sourceModel; public NewExternalSubnetModel(NetworkView network, SearchableListModel sourceModel) { this.sourceModel = sourceModel; setNetwork(new EntityModel<NetworkView>()); getNetwork().setEntity(network); setSubnetModel(new ExternalSubnetModel()); getSubnetModel().setExternalNetwork(network.getProvidedBy()); setTitle(ConstantsManager.getInstance().getConstants().newExternalSubnetTitle()); setHelpTag(HelpTag.new_external_subnet); setHashName("new_external_subnet"); //$NON-NLS-1$ initCommands(); } protected void initCommands() { UICommand okCommand = UICommand.createDefaultOkUiCommand("OnSave", this); //$NON-NLS-1$ getCommands().add(okCommand); UICommand cancelCommand = UICommand.createCancelUiCommand("Cancel", this); //$NON-NLS-1$ getCommands().add(cancelCommand); } public EntityModel<NetworkView> getNetwork() { return network; } private void setNetwork(EntityModel<NetworkView> network) { this.network = network; } public ExternalSubnetModel getSubnetModel() { return subnetModel; } private void setSubnetModel(ExternalSubnetModel subnetModel) { this.subnetModel = subnetModel; } private void onSave() { if (!validate()) { return; } // Save changes. flush(); startProgress(null); ProviderNetwork providedBy = getNetwork().getEntity().getProvidedBy(); Frontend.getInstance().runAction(VdcActionType.AddSubnetToProvider, new AddExternalSubnetParameters(getSubnetModel().getSubnet(), providedBy.getProviderId(), providedBy.getExternalId()), new IFrontendActionAsyncCallback() { @Override public void executed(FrontendActionAsyncResult result) { VdcReturnValueBase returnValue = result.getReturnValue(); stopProgress(); if (returnValue != null && returnValue.getSucceeded()) { cancel(); } } }, this, true); } public void flush() { getSubnetModel().flush(); } private void cancel() { sourceModel.setWindow(null); } @Override public void executeCommand(UICommand command) { super.executeCommand(command); if ("OnSave".equals(command.getName())) { //$NON-NLS-1$ onSave(); } else if ("Cancel".equals(command.getName())) { //$NON-NLS-1$ cancel(); } } public boolean validate() { return getSubnetModel().validate(); } }
jtux270/translate
ovirt/3.6_source/frontend/webadmin/modules/uicommonweb/src/main/java/org/ovirt/engine/ui/uicommonweb/models/providers/NewExternalSubnetModel.java
Java
gpl-3.0
3,910
<?php /* * This file is part of Phraseanet * * (c) 2005-2016 Alchemy * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ use Guzzle\Http\Url; class media_adapter extends media_abstract { /** * Constructor * * Enforces Url to de defined * * @param int $width * @param int $height * @param Url $url */ public function __construct($width, $height, Url $url) { parent::__construct($width, $height, $url); } }
nmaillat/Phraseanet
lib/classes/media/adapter.php
PHP
gpl-3.0
556
<?php /** * File: table_easywi_statistics.php. * Author: Ulrich Block * Date: 17.10.15 * Contact: <ulrich.block@easy-wi.com> * * This file is part of Easy-WI. * * Easy-WI is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Easy-WI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Easy-WI. If not, see <http://www.gnu.org/licenses/>. * * Diese Datei ist Teil von Easy-WI. * * Easy-WI ist Freie Software: Sie koennen es unter den Bedingungen * der GNU General Public License, wie von der Free Software Foundation, * Version 3 der Lizenz oder (nach Ihrer Wahl) jeder spaeteren * veroeffentlichten Version, weiterverbreiten und/oder modifizieren. * * Easy-WI wird in der Hoffnung, dass es nuetzlich sein wird, aber * OHNE JEDE GEWAEHELEISTUNG, bereitgestellt; sogar ohne die implizite * Gewaehrleistung der MARKTFAEHIGKEIT oder EIGNUNG FUER EINEN BESTIMMTEN ZWECK. * Siehe die GNU General Public License fuer weitere Details. * * Sie sollten eine Kopie der GNU General Public License zusammen mit diesem * Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>. */ $defined['easywi_statistics'] = array( 'gameMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterServerAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterSlotsAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverSlotsInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverSlotsActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverSlotsUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverNoPassword' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverNoTag' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'gameserverNotRunning' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterDBAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlDBInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlDBActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'mysqlDBSpaceUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'ticketsCompleted' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'ticketsInProcess' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'ticketsNew' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'userAmount' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'userAmountActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualMasterVserverAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'virtualActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterServerAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterSlotsAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverSlotsInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverSlotsActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverSlotsUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverTrafficAllowed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverTrafficUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'voiceserverCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterCrashed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterSpaceAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webMasterVhostAvailable' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceInstalled' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceSpaceGiven' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceSpaceGivenActive' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'webspaceSpaceUsed' => array("Type"=>"int(10) unsigned","Null"=>"YES","Key"=>"","Default"=>"0","Extra"=>""), 'userID' => array("Type"=>"int(10) unsigned","Null"=>"NO","Key"=>"PRI","Default"=>"0","Extra"=>""), 'statDate' => array("Type"=>"date","Null"=>"NO","Key"=>"PRI","Default"=>"2015-01-01","Extra"=>""), 'countUpdates' => array("Type"=>"int(10) unsigned","Null"=>"NO","Key"=>"","Default"=>"0","Extra"=>"") );
TR-Host/easy-wi-mirror
web/stuff/data/table_easywi_statistics.php
PHP
gpl-3.0
8,010
/* Copyright © 2001-2014, Canal TP and/or its affiliates. All rights reserved. This file is part of Navitia, the software to build cool stuff with public transport. Hope you'll enjoy and contribute to this project, powered by Canal TP (www.canaltp.fr). Help us simplify mobility and open public transport: a non ending quest to the responsive locomotion way of traveling! LICENCE: This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Stay tuned using twitter @navitia IRC #navitia on freenode https://groups.google.com/d/forum/navitia www.navitia.io */ #include "calendar.h" #include "ptreferential/ptreferential.h" #include "type/data.h" namespace navitia { namespace calendar { type::Indexes Calendar::get_calendars(const std::string& filter, const std::vector<std::string>& forbidden_uris, const type::Data &d, const boost::gregorian::date_period filter_period, const boost::posix_time::ptime){ type::Indexes to_return; to_return = ptref::make_query(type::Type_e::Calendar, filter, forbidden_uris, d); if (to_return.empty() || (filter_period.begin().is_not_a_date())) { return to_return; } type::Indexes indexes; for (type::idx_t idx : to_return) { navitia::type::Calendar* cal = d.pt_data->calendars[idx]; for (const boost::gregorian::date_period per : cal->active_periods) { if (filter_period.begin() == filter_period.end()) { if (per.contains(filter_period.begin())) { indexes.insert(cal->idx); break; } } else { if (filter_period.intersects(per)) { indexes.insert(cal->idx); break; } } } } return indexes; } } }
TeXitoi/navitia
source/calendar/calendar.cpp
C++
agpl-3.0
2,441
# -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2012 OpenERP S.A (<http://www.openerp.com>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## { 'name' : 'Portal', 'version': '1.0', 'depends': [ 'base', 'share', 'auth_signup', ], 'author': 'OpenERP SA', 'category': 'Portal', 'description': """ Customize access to your OpenERP database to external users by creating portals. ================================================================================ A portal defines a specific user menu and access rights for its members. This menu can ben seen by portal members, public users and any other user that have the access to technical features (e.g. the administrator). Also, each portal member is linked to a specific partner. The module also associates user groups to the portal users (adding a group in the portal automatically adds it to the portal users, etc). That feature is very handy when used in combination with the module 'share'. """, 'website': 'http://www.openerp.com', 'data': [ 'portal_data.xml', 'portal_view.xml', 'wizard/portal_wizard_view.xml', 'wizard/share_wizard_view.xml', 'security/ir.model.access.csv', ], 'demo': ['portal_demo.xml'], 'css': ['static/src/css/portal.css'], 'auto_install': True, 'installable': True, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
poiesisconsulting/openerp-restaurant
portal/__openerp__.py
Python
agpl-3.0
2,288
define(['angular'], function(angular) { 'use strict'; return angular.module('superdesk.services.storage', []) /** * LocalStorage wrapper * * it stores data as json to keep its type */ .service('storage', function() { /** * Get item from storage * * @param {string} key * @returns {mixed} */ this.getItem = function(key) { return angular.fromJson(localStorage.getItem(key)); }; /** * Set storage item * * @param {string} key * @param {mixed} data */ this.setItem = function(key, data) { localStorage.setItem(key, angular.toJson(data)); }; /** * Remove item from storage * * @param {string} key */ this.removeItem = function(key) { localStorage.removeItem(key); }; /** * Remove all items from storage */ this.clear = function() { localStorage.clear(); }; }); });
plamut/superdesk
client/app/scripts/superdesk/services/storage.js
JavaScript
agpl-3.0
1,250
<?php /* * StatusNet - the distributed open-source microblogging tool * Copyright (C) 2008-2010, StatusNet, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ if (!defined('STATUSNET')) { exit(1); } /** * Utility class to wrap basic oEmbed lookups. * * Blacklisted hosts will use an alternate lookup method: * - Twitpic * * Whitelisted hosts will use known oEmbed API endpoints: * - Flickr, YFrog * * Sites that provide discovery links will use them directly; a bug * in use of discovery links with query strings is worked around. * * Others will fall back to oohembed (unless disabled). * The API endpoint can be configured or disabled through config * as 'oohembed'/'endpoint'. */ class oEmbedHelper { protected static $apiMap = array( 'flickr.com' => 'http://www.flickr.com/services/oembed/', 'yfrog.com' => 'http://www.yfrog.com/api/oembed', 'youtube.com' => 'http://www.youtube.com/oembed', 'viddler.com' => 'http://lab.viddler.com/services/oembed/', 'qik.com' => 'http://qik.com/api/oembed.json', 'revision3.com' => 'http://revision3.com/api/oembed/', 'hulu.com' => 'http://www.hulu.com/api/oembed.json', 'vimeo.com' => 'http://www.vimeo.com/api/oembed.json', 'my.opera.com' => 'http://my.opera.com/service/oembed', ); protected static $functionMap = array( 'twitpic.com' => 'oEmbedHelper::twitPic', ); /** * Perform or fake an oEmbed lookup for the given resource. * * Some known hosts are whitelisted with API endpoints where we * know they exist but autodiscovery data isn't available. * If autodiscovery links are missing and we don't recognize the * host, we'll pass it to noembed.com's public service which * will either proxy or fake info on a lot of sites. * * A few hosts are blacklisted due to known problems with oohembed, * in which case we'll look up the info another way and return * equivalent data. * * Throws exceptions on failure. * * @param string $url * @param array $params * @return object */ public static function getObject($url, $params=array()) { $host = parse_url($url, PHP_URL_HOST); if (substr($host, 0, 4) == 'www.') { $host = substr($host, 4); } common_log(LOG_INFO, 'Checking for oEmbed data for ' . $url); // You can fiddle with the order of discovery -- either skipping // some types or re-ordering them. $order = common_config('oembed', 'order'); foreach ($order as $method) { switch ($method) { case 'built-in': common_log(LOG_INFO, 'Considering built-in oEmbed methods...'); // Blacklist: systems with no oEmbed API of their own, which are // either missing from or broken on noembed.com's proxy. // we know how to look data up in another way... if (array_key_exists($host, self::$functionMap)) { common_log(LOG_INFO, 'We have a built-in method for ' . $host); $func = self::$functionMap[$host]; return call_user_func($func, $url, $params); } break; case 'well-known': common_log(LOG_INFO, 'Considering well-known oEmbed endpoints...'); // Whitelist: known API endpoints for sites that don't provide discovery... if (array_key_exists($host, self::$apiMap)) { $api = self::$apiMap[$host]; common_log(LOG_INFO, 'Using well-known endpoint "' . $api . '" for "' . $host . '"'); break 2; } break; case 'discovery': try { common_log(LOG_INFO, 'Trying to discover an oEmbed endpoint using link headers.'); $api = self::discover($url); common_log(LOG_INFO, 'Found API endpoint ' . $api . ' for URL ' . $url); break 2; } catch (Exception $e) { common_log(LOG_INFO, 'Could not find an oEmbed endpoint using link headers.'); // Just ignore it! } break; case 'service': $api = common_config('oembed', 'endpoint'); common_log(LOG_INFO, 'Using service API endpoint ' . $api); break 2; break; } } if (empty($api)) { // TRANS: Server exception thrown in oEmbed action if no API endpoint is available. throw new ServerException(_('No oEmbed API endpoint available.')); } return self::getObjectFrom($api, $url, $params); } /** * Perform basic discovery. * @return string */ static function discover($url) { // @fixme ideally skip this for non-HTML stuff! $body = self::http($url); return self::discoverFromHTML($url, $body); } /** * Partially ripped from OStatus' FeedDiscovery class. * * @param string $url source URL, used to resolve relative links * @param string $body HTML body text * @return mixed string with URL or false if no target found */ static function discoverFromHTML($url, $body) { // DOMDocument::loadHTML may throw warnings on unrecognized elements, // and notices on unrecognized namespaces. $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE)); $dom = new DOMDocument(); $ok = $dom->loadHTML($body); error_reporting($old); if (!$ok) { throw new oEmbedHelper_BadHtmlException(); } // Ok... now on to the links! $feeds = array( 'application/json+oembed' => false, ); $nodes = $dom->getElementsByTagName('link'); for ($i = 0; $i < $nodes->length; $i++) { $node = $nodes->item($i); if ($node->hasAttributes()) { $rel = $node->attributes->getNamedItem('rel'); $type = $node->attributes->getNamedItem('type'); $href = $node->attributes->getNamedItem('href'); if ($rel && $type && $href) { $rel = array_filter(explode(" ", $rel->value)); $type = trim($type->value); $href = trim($href->value); if (in_array('alternate', $rel) && array_key_exists($type, $feeds) && empty($feeds[$type])) { // Save the first feed found of each type... $feeds[$type] = $href; } } } } // Return the highest-priority feed found foreach ($feeds as $type => $url) { if ($url) { return $url; } } throw new oEmbedHelper_DiscoveryException(); } /** * Actually do an oEmbed lookup to a particular API endpoint. * * @param string $api oEmbed API endpoint URL * @param string $url target URL to look up info about * @param array $params * @return object */ static function getObjectFrom($api, $url, $params=array()) { $params['url'] = $url; $params['format'] = 'json'; $data = self::json($api, $params); return self::normalize($data); } /** * Normalize oEmbed format. * * @param object $orig * @return object */ static function normalize($orig) { $data = clone($orig); if (empty($data->type)) { throw new Exception('Invalid oEmbed data: no type field.'); } if ($data->type == 'image') { // YFrog does this. $data->type = 'photo'; } if (isset($data->thumbnail_url)) { if (!isset($data->thumbnail_width)) { // !?!?! $data->thumbnail_width = common_config('attachments', 'thumb_width'); $data->thumbnail_height = common_config('attachments', 'thumb_height'); } } return $data; } /** * Using a local function for twitpic lookups, as oohembed's adapter * doesn't return a valid result: * http://code.google.com/p/oohembed/issues/detail?id=19 * * This code fetches metadata from Twitpic's own API, and attempts * to guess proper thumbnail size from the original's size. * * @todo respect maxwidth and maxheight params * * @param string $url * @param array $params * @return object */ static function twitPic($url, $params=array()) { $matches = array(); if (preg_match('!twitpic\.com/(\w+)!', $url, $matches)) { $id = $matches[1]; } else { throw new Exception("Invalid twitpic URL"); } // Grab metadata from twitpic's API... // http://dev.twitpic.com/docs/2/media_show $data = self::json('http://api.twitpic.com/2/media/show.json', array('id' => $id)); $oembed = (object)array('type' => 'photo', 'url' => 'http://twitpic.com/show/full/' . $data->short_id, 'width' => $data->width, 'height' => $data->height); if (!empty($data->message)) { $oembed->title = $data->message; } // Thumbnail is cropped and scaled to 150x150 box: // http://dev.twitpic.com/docs/thumbnails/ $thumbSize = 150; $oembed->thumbnail_url = 'http://twitpic.com/show/thumb/' . $data->short_id; $oembed->thumbnail_width = $thumbSize; $oembed->thumbnail_height = $thumbSize; return $oembed; } /** * Fetch some URL and return JSON data. * * @param string $url * @param array $params query-string params * @return object */ static protected function json($url, $params=array()) { $data = self::http($url, $params); return json_decode($data); } /** * Hit some web API and return data on success. * @param string $url * @param array $params * @return string */ static protected function http($url, $params=array()) { $client = HTTPClient::start(); if ($params) { $query = http_build_query($params, null, '&'); if (strpos($url, '?') === false) { $url .= '?' . $query; } else { $url .= '&' . $query; } } $response = $client->get($url); if ($response->isOk()) { return $response->getBody(); } else { throw new Exception('Bad HTTP response code: ' . $response->getStatus()); } } } class oEmbedHelper_Exception extends Exception { public function __construct($message = "", $code = 0, $previous = null) { parent::__construct($message, $code); } } class oEmbedHelper_BadHtmlException extends oEmbedHelper_Exception { function __construct($previous=null) { return parent::__construct('Bad HTML in discovery data.', 0, $previous); } } class oEmbedHelper_DiscoveryException extends oEmbedHelper_Exception { function __construct($previous=null) { return parent::__construct('No oEmbed discovery data.', 0, $previous); } }
gayathri6/stepstream_salute
lib_old/oembedhelper.php
PHP
agpl-3.0
12,206
// Copyright (c) 2013-2017 The btcsuite developers // Use of this source code is governed by an ISC // license that can be found in the LICENSE file. package netsync import ( "container/list" "net" "sync" "sync/atomic" "time" "github.com/btcsuite/btcd/blockchain" "github.com/btcsuite/btcd/chaincfg" "github.com/btcsuite/btcd/chaincfg/chainhash" "github.com/btcsuite/btcd/database" "github.com/btcsuite/btcd/mempool" peerpkg "github.com/btcsuite/btcd/peer" "github.com/btcsuite/btcd/wire" "github.com/btcsuite/btcutil" ) const ( // minInFlightBlocks is the minimum number of blocks that should be // in the request queue for headers-first mode before requesting // more. minInFlightBlocks = 10 // maxRejectedTxns is the maximum number of rejected transactions // hashes to store in memory. maxRejectedTxns = 1000 // maxRequestedBlocks is the maximum number of requested block // hashes to store in memory. maxRequestedBlocks = wire.MaxInvPerMsg // maxRequestedTxns is the maximum number of requested transactions // hashes to store in memory. maxRequestedTxns = wire.MaxInvPerMsg ) // zeroHash is the zero value hash (all zeros). It is defined as a convenience. var zeroHash chainhash.Hash // newPeerMsg signifies a newly connected peer to the block handler. type newPeerMsg struct { peer *peerpkg.Peer } // blockMsg packages a bitcoin block message and the peer it came from together // so the block handler has access to that information. type blockMsg struct { block *btcutil.Block peer *peerpkg.Peer reply chan struct{} } // invMsg packages a bitcoin inv message and the peer it came from together // so the block handler has access to that information. type invMsg struct { inv *wire.MsgInv peer *peerpkg.Peer } // headersMsg packages a bitcoin headers message and the peer it came from // together so the block handler has access to that information. type headersMsg struct { headers *wire.MsgHeaders peer *peerpkg.Peer } // donePeerMsg signifies a newly disconnected peer to the block handler. type donePeerMsg struct { peer *peerpkg.Peer } // txMsg packages a bitcoin tx message and the peer it came from together // so the block handler has access to that information. type txMsg struct { tx *btcutil.Tx peer *peerpkg.Peer reply chan struct{} } // getSyncPeerMsg is a message type to be sent across the message channel for // retrieving the current sync peer. type getSyncPeerMsg struct { reply chan int32 } // processBlockResponse is a response sent to the reply channel of a // processBlockMsg. type processBlockResponse struct { isOrphan bool err error } // processBlockMsg is a message type to be sent across the message channel // for requested a block is processed. Note this call differs from blockMsg // above in that blockMsg is intended for blocks that came from peers and have // extra handling whereas this message essentially is just a concurrent safe // way to call ProcessBlock on the internal block chain instance. type processBlockMsg struct { block *btcutil.Block flags blockchain.BehaviorFlags reply chan processBlockResponse } // isCurrentMsg is a message type to be sent across the message channel for // requesting whether or not the sync manager believes it is synced with the // currently connected peers. type isCurrentMsg struct { reply chan bool } // pauseMsg is a message type to be sent across the message channel for // pausing the sync manager. This effectively provides the caller with // exclusive access over the manager until a receive is performed on the // unpause channel. type pauseMsg struct { unpause <-chan struct{} } // headerNode is used as a node in a list of headers that are linked together // between checkpoints. type headerNode struct { height int32 hash *chainhash.Hash } // peerSyncState stores additional information that the SyncManager tracks // about a peer. type peerSyncState struct { syncCandidate bool requestQueue []*wire.InvVect requestedTxns map[chainhash.Hash]struct{} requestedBlocks map[chainhash.Hash]struct{} } // SyncManager is used to communicate block related messages with peers. The // SyncManager is started as by executing Start() in a goroutine. Once started, // it selects peers to sync from and starts the initial block download. Once the // chain is in sync, the SyncManager handles incoming block and header // notifications and relays announcements of new blocks to peers. type SyncManager struct { peerNotifier PeerNotifier started int32 shutdown int32 chain *blockchain.BlockChain txMemPool *mempool.TxPool chainParams *chaincfg.Params progressLogger *blockProgressLogger msgChan chan interface{} wg sync.WaitGroup quit chan struct{} // These fields should only be accessed from the blockHandler thread rejectedTxns map[chainhash.Hash]struct{} requestedTxns map[chainhash.Hash]struct{} requestedBlocks map[chainhash.Hash]struct{} syncPeer *peerpkg.Peer peerStates map[*peerpkg.Peer]*peerSyncState // The following fields are used for headers-first mode. headersFirstMode bool headerList *list.List startHeader *list.Element nextCheckpoint *chaincfg.Checkpoint } // resetHeaderState sets the headers-first mode state to values appropriate for // syncing from a new peer. func (sm *SyncManager) resetHeaderState(newestHash *chainhash.Hash, newestHeight int32) { sm.headersFirstMode = false sm.headerList.Init() sm.startHeader = nil // When there is a next checkpoint, add an entry for the latest known // block into the header pool. This allows the next downloaded header // to prove it links to the chain properly. if sm.nextCheckpoint != nil { node := headerNode{height: newestHeight, hash: newestHash} sm.headerList.PushBack(&node) } } // findNextHeaderCheckpoint returns the next checkpoint after the passed height. // It returns nil when there is not one either because the height is already // later than the final checkpoint or some other reason such as disabled // checkpoints. func (sm *SyncManager) findNextHeaderCheckpoint(height int32) *chaincfg.Checkpoint { checkpoints := sm.chain.Checkpoints() if len(checkpoints) == 0 { return nil } // There is no next checkpoint if the height is already after the final // checkpoint. finalCheckpoint := &checkpoints[len(checkpoints)-1] if height >= finalCheckpoint.Height { return nil } // Find the next checkpoint. nextCheckpoint := finalCheckpoint for i := len(checkpoints) - 2; i >= 0; i-- { if height >= checkpoints[i].Height { break } nextCheckpoint = &checkpoints[i] } return nextCheckpoint } // startSync will choose the best peer among the available candidate peers to // download/sync the blockchain from. When syncing is already running, it // simply returns. It also examines the candidates for any which are no longer // candidates and removes them as needed. func (sm *SyncManager) startSync() { // Return now if we're already syncing. if sm.syncPeer != nil { return } // Once the segwit soft-fork package has activated, we only // want to sync from peers which are witness enabled to ensure // that we fully validate all blockchain data. segwitActive, err := sm.chain.IsDeploymentActive(chaincfg.DeploymentSegwit) if err != nil { log.Errorf("Unable to query for segwit soft-fork state: %v", err) return } best := sm.chain.BestSnapshot() var bestPeer *peerpkg.Peer for peer, state := range sm.peerStates { if !state.syncCandidate { continue } if segwitActive && !peer.IsWitnessEnabled() { log.Debugf("peer %v not witness enabled, skipping", peer) continue } // Remove sync candidate peers that are no longer candidates due // to passing their latest known block. NOTE: The < is // intentional as opposed to <=. While technically the peer // doesn't have a later block when it's equal, it will likely // have one soon so it is a reasonable choice. It also allows // the case where both are at 0 such as during regression test. if peer.LastBlock() < best.Height { state.syncCandidate = false continue } // TODO(davec): Use a better algorithm to choose the best peer. // For now, just pick the first available candidate. bestPeer = peer } // Start syncing from the best peer if one was selected. if bestPeer != nil { // Clear the requestedBlocks if the sync peer changes, otherwise // we may ignore blocks we need that the last sync peer failed // to send. sm.requestedBlocks = make(map[chainhash.Hash]struct{}) locator, err := sm.chain.LatestBlockLocator() if err != nil { log.Errorf("Failed to get block locator for the "+ "latest block: %v", err) return } log.Infof("Syncing to block height %d from peer %v", bestPeer.LastBlock(), bestPeer.Addr()) // When the current height is less than a known checkpoint we // can use block headers to learn about which blocks comprise // the chain up to the checkpoint and perform less validation // for them. This is possible since each header contains the // hash of the previous header and a merkle root. Therefore if // we validate all of the received headers link together // properly and the checkpoint hashes match, we can be sure the // hashes for the blocks in between are accurate. Further, once // the full blocks are downloaded, the merkle root is computed // and compared against the value in the header which proves the // full block hasn't been tampered with. // // Once we have passed the final checkpoint, or checkpoints are // disabled, use standard inv messages learn about the blocks // and fully validate them. Finally, regression test mode does // not support the headers-first approach so do normal block // downloads when in regression test mode. if sm.nextCheckpoint != nil && best.Height < sm.nextCheckpoint.Height && sm.chainParams != &chaincfg.RegressionNetParams { bestPeer.PushGetHeadersMsg(locator, sm.nextCheckpoint.Hash) sm.headersFirstMode = true log.Infof("Downloading headers for blocks %d to "+ "%d from peer %s", best.Height+1, sm.nextCheckpoint.Height, bestPeer.Addr()) } else { bestPeer.PushGetBlocksMsg(locator, &zeroHash) } sm.syncPeer = bestPeer } else { log.Warnf("No sync peer candidates available") } } // isSyncCandidate returns whether or not the peer is a candidate to consider // syncing from. func (sm *SyncManager) isSyncCandidate(peer *peerpkg.Peer) bool { // Typically a peer is not a candidate for sync if it's not a full node, // however regression test is special in that the regression tool is // not a full node and still needs to be considered a sync candidate. if sm.chainParams == &chaincfg.RegressionNetParams { // The peer is not a candidate if it's not coming from localhost // or the hostname can't be determined for some reason. host, _, err := net.SplitHostPort(peer.Addr()) if err != nil { return false } if host != "127.0.0.1" && host != "localhost" { return false } } else { // The peer is not a candidate for sync if it's not a full // node. Additionally, if the segwit soft-fork package has // activated, then the peer must also be upgraded. segwitActive, err := sm.chain.IsDeploymentActive(chaincfg.DeploymentSegwit) if err != nil { log.Errorf("Unable to query for segwit "+ "soft-fork state: %v", err) } nodeServices := peer.Services() if nodeServices&wire.SFNodeNetwork != wire.SFNodeNetwork || (segwitActive && !peer.IsWitnessEnabled()) { return false } } // Candidate if all checks passed. return true } // handleNewPeerMsg deals with new peers that have signalled they may // be considered as a sync peer (they have already successfully negotiated). It // also starts syncing if needed. It is invoked from the syncHandler goroutine. func (sm *SyncManager) handleNewPeerMsg(peer *peerpkg.Peer) { // Ignore if in the process of shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { return } log.Infof("New valid peer %s (%s)", peer, peer.UserAgent()) // Initialize the peer state isSyncCandidate := sm.isSyncCandidate(peer) sm.peerStates[peer] = &peerSyncState{ syncCandidate: isSyncCandidate, requestedTxns: make(map[chainhash.Hash]struct{}), requestedBlocks: make(map[chainhash.Hash]struct{}), } // Start syncing by choosing the best candidate if needed. if isSyncCandidate && sm.syncPeer == nil { sm.startSync() } } // handleDonePeerMsg deals with peers that have signalled they are done. It // removes the peer as a candidate for syncing and in the case where it was // the current sync peer, attempts to select a new best peer to sync from. It // is invoked from the syncHandler goroutine. func (sm *SyncManager) handleDonePeerMsg(peer *peerpkg.Peer) { state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received done peer message for unknown peer %s", peer) return } // Remove the peer from the list of candidate peers. delete(sm.peerStates, peer) log.Infof("Lost peer %s", peer) // Remove requested transactions from the global map so that they will // be fetched from elsewhere next time we get an inv. for txHash := range state.requestedTxns { delete(sm.requestedTxns, txHash) } // Remove requested blocks from the global map so that they will be // fetched from elsewhere next time we get an inv. // TODO: we could possibly here check which peers have these blocks // and request them now to speed things up a little. for blockHash := range state.requestedBlocks { delete(sm.requestedBlocks, blockHash) } // Attempt to find a new peer to sync from if the quitting peer is the // sync peer. Also, reset the headers-first state if in headers-first // mode so if sm.syncPeer == peer { sm.syncPeer = nil if sm.headersFirstMode { best := sm.chain.BestSnapshot() sm.resetHeaderState(&best.Hash, best.Height) } sm.startSync() } } // handleTxMsg handles transaction messages from all peers. func (sm *SyncManager) handleTxMsg(tmsg *txMsg) { peer := tmsg.peer state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received tx message from unknown peer %s", peer) return } // NOTE: BitcoinJ, and possibly other wallets, don't follow the spec of // sending an inventory message and allowing the remote peer to decide // whether or not they want to request the transaction via a getdata // message. Unfortunately, the reference implementation permits // unrequested data, so it has allowed wallets that don't follow the // spec to proliferate. While this is not ideal, there is no check here // to disconnect peers for sending unsolicited transactions to provide // interoperability. txHash := tmsg.tx.Hash() // Ignore transactions that we have already rejected. Do not // send a reject message here because if the transaction was already // rejected, the transaction was unsolicited. if _, exists = sm.rejectedTxns[*txHash]; exists { log.Debugf("Ignoring unsolicited previously rejected "+ "transaction %v from %s", txHash, peer) return } // Process the transaction to include validation, insertion in the // memory pool, orphan handling, etc. acceptedTxs, err := sm.txMemPool.ProcessTransaction(tmsg.tx, true, true, mempool.Tag(peer.ID())) // Remove transaction from request maps. Either the mempool/chain // already knows about it and as such we shouldn't have any more // instances of trying to fetch it, or we failed to insert and thus // we'll retry next time we get an inv. delete(state.requestedTxns, *txHash) delete(sm.requestedTxns, *txHash) if err != nil { // Do not request this transaction again until a new block // has been processed. sm.rejectedTxns[*txHash] = struct{}{} sm.limitMap(sm.rejectedTxns, maxRejectedTxns) // When the error is a rule error, it means the transaction was // simply rejected as opposed to something actually going wrong, // so log it as such. Otherwise, something really did go wrong, // so log it as an actual error. if _, ok := err.(mempool.RuleError); ok { log.Debugf("Rejected transaction %v from %s: %v", txHash, peer, err) } else { log.Errorf("Failed to process transaction %v: %v", txHash, err) } // Convert the error into an appropriate reject message and // send it. code, reason := mempool.ErrToRejectErr(err) peer.PushRejectMsg(wire.CmdTx, code, reason, txHash, false) return } sm.peerNotifier.AnnounceNewTransactions(acceptedTxs) } // current returns true if we believe we are synced with our peers, false if we // still have blocks to check func (sm *SyncManager) current() bool { if !sm.chain.IsCurrent() { return false } // if blockChain thinks we are current and we have no syncPeer it // is probably right. if sm.syncPeer == nil { return true } // No matter what chain thinks, if we are below the block we are syncing // to we are not current. if sm.chain.BestSnapshot().Height < sm.syncPeer.LastBlock() { return false } return true } // handleBlockMsg handles block messages from all peers. func (sm *SyncManager) handleBlockMsg(bmsg *blockMsg) { peer := bmsg.peer state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received block message from unknown peer %s", peer) return } // If we didn't ask for this block then the peer is misbehaving. blockHash := bmsg.block.Hash() if _, exists = state.requestedBlocks[*blockHash]; !exists { // The regression test intentionally sends some blocks twice // to test duplicate block insertion fails. Don't disconnect // the peer or ignore the block when we're in regression test // mode in this case so the chain code is actually fed the // duplicate blocks. if sm.chainParams != &chaincfg.RegressionNetParams { log.Warnf("Got unrequested block %v from %s -- "+ "disconnecting", blockHash, peer.Addr()) peer.Disconnect() return } } // When in headers-first mode, if the block matches the hash of the // first header in the list of headers that are being fetched, it's // eligible for less validation since the headers have already been // verified to link together and are valid up to the next checkpoint. // Also, remove the list entry for all blocks except the checkpoint // since it is needed to verify the next round of headers links // properly. isCheckpointBlock := false behaviorFlags := blockchain.BFNone if sm.headersFirstMode { firstNodeEl := sm.headerList.Front() if firstNodeEl != nil { firstNode := firstNodeEl.Value.(*headerNode) if blockHash.IsEqual(firstNode.hash) { behaviorFlags |= blockchain.BFFastAdd if firstNode.hash.IsEqual(sm.nextCheckpoint.Hash) { isCheckpointBlock = true } else { sm.headerList.Remove(firstNodeEl) } } } } // Remove block from request maps. Either chain will know about it and // so we shouldn't have any more instances of trying to fetch it, or we // will fail the insert and thus we'll retry next time we get an inv. delete(state.requestedBlocks, *blockHash) delete(sm.requestedBlocks, *blockHash) // Process the block to include validation, best chain selection, orphan // handling, etc. _, isOrphan, err := sm.chain.ProcessBlock(bmsg.block, behaviorFlags) if err != nil { // When the error is a rule error, it means the block was simply // rejected as opposed to something actually going wrong, so log // it as such. Otherwise, something really did go wrong, so log // it as an actual error. if _, ok := err.(blockchain.RuleError); ok { log.Infof("Rejected block %v from %s: %v", blockHash, peer, err) } else { log.Errorf("Failed to process block %v: %v", blockHash, err) } if dbErr, ok := err.(database.Error); ok && dbErr.ErrorCode == database.ErrCorruption { panic(dbErr) } // Convert the error into an appropriate reject message and // send it. code, reason := mempool.ErrToRejectErr(err) peer.PushRejectMsg(wire.CmdBlock, code, reason, blockHash, false) return } // Meta-data about the new block this peer is reporting. We use this // below to update this peer's lastest block height and the heights of // other peers based on their last announced block hash. This allows us // to dynamically update the block heights of peers, avoiding stale // heights when looking for a new sync peer. Upon acceptance of a block // or recognition of an orphan, we also use this information to update // the block heights over other peers who's invs may have been ignored // if we are actively syncing while the chain is not yet current or // who may have lost the lock announcment race. var heightUpdate int32 var blkHashUpdate *chainhash.Hash // Request the parents for the orphan block from the peer that sent it. if isOrphan { // We've just received an orphan block from a peer. In order // to update the height of the peer, we try to extract the // block height from the scriptSig of the coinbase transaction. // Extraction is only attempted if the block's version is // high enough (ver 2+). header := &bmsg.block.MsgBlock().Header if blockchain.ShouldHaveSerializedBlockHeight(header) { coinbaseTx := bmsg.block.Transactions()[0] cbHeight, err := blockchain.ExtractCoinbaseHeight(coinbaseTx) if err != nil { log.Warnf("Unable to extract height from "+ "coinbase tx: %v", err) } else { log.Debugf("Extracted height of %v from "+ "orphan block", cbHeight) heightUpdate = cbHeight blkHashUpdate = blockHash } } orphanRoot := sm.chain.GetOrphanRoot(blockHash) locator, err := sm.chain.LatestBlockLocator() if err != nil { log.Warnf("Failed to get block locator for the "+ "latest block: %v", err) } else { peer.PushGetBlocksMsg(locator, orphanRoot) } } else { // When the block is not an orphan, log information about it and // update the chain state. sm.progressLogger.LogBlockHeight(bmsg.block) // Update this peer's latest block height, for future // potential sync node candidacy. best := sm.chain.BestSnapshot() heightUpdate = best.Height blkHashUpdate = &best.Hash // Clear the rejected transactions. sm.rejectedTxns = make(map[chainhash.Hash]struct{}) } // Update the block height for this peer. But only send a message to // the server for updating peer heights if this is an orphan or our // chain is "current". This avoids sending a spammy amount of messages // if we're syncing the chain from scratch. if blkHashUpdate != nil && heightUpdate != 0 { peer.UpdateLastBlockHeight(heightUpdate) if isOrphan || sm.current() { go sm.peerNotifier.UpdatePeerHeights(blkHashUpdate, heightUpdate, peer) } } // Nothing more to do if we aren't in headers-first mode. if !sm.headersFirstMode { return } // This is headers-first mode, so if the block is not a checkpoint // request more blocks using the header list when the request queue is // getting short. if !isCheckpointBlock { if sm.startHeader != nil && len(state.requestedBlocks) < minInFlightBlocks { sm.fetchHeaderBlocks() } return } // This is headers-first mode and the block is a checkpoint. When // there is a next checkpoint, get the next round of headers by asking // for headers starting from the block after this one up to the next // checkpoint. prevHeight := sm.nextCheckpoint.Height prevHash := sm.nextCheckpoint.Hash sm.nextCheckpoint = sm.findNextHeaderCheckpoint(prevHeight) if sm.nextCheckpoint != nil { locator := blockchain.BlockLocator([]*chainhash.Hash{prevHash}) err := peer.PushGetHeadersMsg(locator, sm.nextCheckpoint.Hash) if err != nil { log.Warnf("Failed to send getheaders message to "+ "peer %s: %v", peer.Addr(), err) return } log.Infof("Downloading headers for blocks %d to %d from "+ "peer %s", prevHeight+1, sm.nextCheckpoint.Height, sm.syncPeer.Addr()) return } // This is headers-first mode, the block is a checkpoint, and there are // no more checkpoints, so switch to normal mode by requesting blocks // from the block after this one up to the end of the chain (zero hash). sm.headersFirstMode = false sm.headerList.Init() log.Infof("Reached the final checkpoint -- switching to normal mode") locator := blockchain.BlockLocator([]*chainhash.Hash{blockHash}) err = peer.PushGetBlocksMsg(locator, &zeroHash) if err != nil { log.Warnf("Failed to send getblocks message to peer %s: %v", peer.Addr(), err) return } } // fetchHeaderBlocks creates and sends a request to the syncPeer for the next // list of blocks to be downloaded based on the current list of headers. func (sm *SyncManager) fetchHeaderBlocks() { // Nothing to do if there is no start header. if sm.startHeader == nil { log.Warnf("fetchHeaderBlocks called with no start header") return } // Build up a getdata request for the list of blocks the headers // describe. The size hint will be limited to wire.MaxInvPerMsg by // the function, so no need to double check it here. gdmsg := wire.NewMsgGetDataSizeHint(uint(sm.headerList.Len())) numRequested := 0 for e := sm.startHeader; e != nil; e = e.Next() { node, ok := e.Value.(*headerNode) if !ok { log.Warn("Header list node type is not a headerNode") continue } iv := wire.NewInvVect(wire.InvTypeBlock, node.hash) haveInv, err := sm.haveInventory(iv) if err != nil { log.Warnf("Unexpected failure when checking for "+ "existing inventory during header block "+ "fetch: %v", err) } if !haveInv { syncPeerState := sm.peerStates[sm.syncPeer] sm.requestedBlocks[*node.hash] = struct{}{} syncPeerState.requestedBlocks[*node.hash] = struct{}{} // If we're fetching from a witness enabled peer // post-fork, then ensure that we receive all the // witness data in the blocks. if sm.syncPeer.IsWitnessEnabled() { iv.Type = wire.InvTypeWitnessBlock } gdmsg.AddInvVect(iv) numRequested++ } sm.startHeader = e.Next() if numRequested >= wire.MaxInvPerMsg { break } } if len(gdmsg.InvList) > 0 { sm.syncPeer.QueueMessage(gdmsg, nil) } } // handleHeadersMsg handles block header messages from all peers. Headers are // requested when performing a headers-first sync. func (sm *SyncManager) handleHeadersMsg(hmsg *headersMsg) { peer := hmsg.peer _, exists := sm.peerStates[peer] if !exists { log.Warnf("Received headers message from unknown peer %s", peer) return } // The remote peer is misbehaving if we didn't request headers. msg := hmsg.headers numHeaders := len(msg.Headers) if !sm.headersFirstMode { log.Warnf("Got %d unrequested headers from %s -- "+ "disconnecting", numHeaders, peer.Addr()) peer.Disconnect() return } // Nothing to do for an empty headers message. if numHeaders == 0 { return } // Process all of the received headers ensuring each one connects to the // previous and that checkpoints match. receivedCheckpoint := false var finalHash *chainhash.Hash for _, blockHeader := range msg.Headers { blockHash := blockHeader.BlockHash() finalHash = &blockHash // Ensure there is a previous header to compare against. prevNodeEl := sm.headerList.Back() if prevNodeEl == nil { log.Warnf("Header list does not contain a previous" + "element as expected -- disconnecting peer") peer.Disconnect() return } // Ensure the header properly connects to the previous one and // add it to the list of headers. node := headerNode{hash: &blockHash} prevNode := prevNodeEl.Value.(*headerNode) if prevNode.hash.IsEqual(&blockHeader.PrevBlock) { node.height = prevNode.height + 1 e := sm.headerList.PushBack(&node) if sm.startHeader == nil { sm.startHeader = e } } else { log.Warnf("Received block header that does not "+ "properly connect to the chain from peer %s "+ "-- disconnecting", peer.Addr()) peer.Disconnect() return } // Verify the header at the next checkpoint height matches. if node.height == sm.nextCheckpoint.Height { if node.hash.IsEqual(sm.nextCheckpoint.Hash) { receivedCheckpoint = true log.Infof("Verified downloaded block "+ "header against checkpoint at height "+ "%d/hash %s", node.height, node.hash) } else { log.Warnf("Block header at height %d/hash "+ "%s from peer %s does NOT match "+ "expected checkpoint hash of %s -- "+ "disconnecting", node.height, node.hash, peer.Addr(), sm.nextCheckpoint.Hash) peer.Disconnect() return } break } } // When this header is a checkpoint, switch to fetching the blocks for // all of the headers since the last checkpoint. if receivedCheckpoint { // Since the first entry of the list is always the final block // that is already in the database and is only used to ensure // the next header links properly, it must be removed before // fetching the blocks. sm.headerList.Remove(sm.headerList.Front()) log.Infof("Received %v block headers: Fetching blocks", sm.headerList.Len()) sm.progressLogger.SetLastLogTime(time.Now()) sm.fetchHeaderBlocks() return } // This header is not a checkpoint, so request the next batch of // headers starting from the latest known header and ending with the // next checkpoint. locator := blockchain.BlockLocator([]*chainhash.Hash{finalHash}) err := peer.PushGetHeadersMsg(locator, sm.nextCheckpoint.Hash) if err != nil { log.Warnf("Failed to send getheaders message to "+ "peer %s: %v", peer.Addr(), err) return } } // haveInventory returns whether or not the inventory represented by the passed // inventory vector is known. This includes checking all of the various places // inventory can be when it is in different states such as blocks that are part // of the main chain, on a side chain, in the orphan pool, and transactions that // are in the memory pool (either the main pool or orphan pool). func (sm *SyncManager) haveInventory(invVect *wire.InvVect) (bool, error) { switch invVect.Type { case wire.InvTypeWitnessBlock: fallthrough case wire.InvTypeBlock: // Ask chain if the block is known to it in any form (main // chain, side chain, or orphan). return sm.chain.HaveBlock(&invVect.Hash) case wire.InvTypeWitnessTx: fallthrough case wire.InvTypeTx: // Ask the transaction memory pool if the transaction is known // to it in any form (main pool or orphan). if sm.txMemPool.HaveTransaction(&invVect.Hash) { return true, nil } // Check if the transaction exists from the point of view of the // end of the main chain. entry, err := sm.chain.FetchUtxoEntry(&invVect.Hash) if err != nil { return false, err } return entry != nil && !entry.IsFullySpent(), nil } // The requested inventory is is an unsupported type, so just claim // it is known to avoid requesting it. return true, nil } // handleInvMsg handles inv messages from all peers. // We examine the inventory advertised by the remote peer and act accordingly. func (sm *SyncManager) handleInvMsg(imsg *invMsg) { peer := imsg.peer state, exists := sm.peerStates[peer] if !exists { log.Warnf("Received inv message from unknown peer %s", peer) return } // Attempt to find the final block in the inventory list. There may // not be one. lastBlock := -1 invVects := imsg.inv.InvList for i := len(invVects) - 1; i >= 0; i-- { if invVects[i].Type == wire.InvTypeBlock { lastBlock = i break } } // If this inv contains a block announcement, and this isn't coming from // our current sync peer or we're current, then update the last // announced block for this peer. We'll use this information later to // update the heights of peers based on blocks we've accepted that they // previously announced. if lastBlock != -1 && (peer != sm.syncPeer || sm.current()) { peer.UpdateLastAnnouncedBlock(&invVects[lastBlock].Hash) } // Ignore invs from peers that aren't the sync if we are not current. // Helps prevent fetching a mass of orphans. if peer != sm.syncPeer && !sm.current() { return } // If our chain is current and a peer announces a block we already // know of, then update their current block height. if lastBlock != -1 && sm.current() { blkHeight, err := sm.chain.BlockHeightByHash(&invVects[lastBlock].Hash) if err == nil { peer.UpdateLastBlockHeight(blkHeight) } } // Request the advertised inventory if we don't already have it. Also, // request parent blocks of orphans if we receive one we already have. // Finally, attempt to detect potential stalls due to long side chains // we already have and request more blocks to prevent them. for i, iv := range invVects { // Ignore unsupported inventory types. switch iv.Type { case wire.InvTypeBlock: case wire.InvTypeTx: case wire.InvTypeWitnessBlock: case wire.InvTypeWitnessTx: default: continue } // Add the inventory to the cache of known inventory // for the peer. peer.AddKnownInventory(iv) // Ignore inventory when we're in headers-first mode. if sm.headersFirstMode { continue } // Request the inventory if we don't already have it. haveInv, err := sm.haveInventory(iv) if err != nil { log.Warnf("Unexpected failure when checking for "+ "existing inventory during inv message "+ "processing: %v", err) continue } if !haveInv { if iv.Type == wire.InvTypeTx { // Skip the transaction if it has already been // rejected. if _, exists := sm.rejectedTxns[iv.Hash]; exists { continue } } // Ignore invs block invs from non-witness enabled // peers, as after segwit activation we only want to // download from peers that can provide us full witness // data for blocks. if !peer.IsWitnessEnabled() && iv.Type == wire.InvTypeBlock { continue } // Add it to the request queue. state.requestQueue = append(state.requestQueue, iv) continue } if iv.Type == wire.InvTypeBlock { // The block is an orphan block that we already have. // When the existing orphan was processed, it requested // the missing parent blocks. When this scenario // happens, it means there were more blocks missing // than are allowed into a single inventory message. As // a result, once this peer requested the final // advertised block, the remote peer noticed and is now // resending the orphan block as an available block // to signal there are more missing blocks that need to // be requested. if sm.chain.IsKnownOrphan(&iv.Hash) { // Request blocks starting at the latest known // up to the root of the orphan that just came // in. orphanRoot := sm.chain.GetOrphanRoot(&iv.Hash) locator, err := sm.chain.LatestBlockLocator() if err != nil { log.Errorf("PEER: Failed to get block "+ "locator for the latest block: "+ "%v", err) continue } peer.PushGetBlocksMsg(locator, orphanRoot) continue } // We already have the final block advertised by this // inventory message, so force a request for more. This // should only happen if we're on a really long side // chain. if i == lastBlock { // Request blocks after this one up to the // final one the remote peer knows about (zero // stop hash). locator := sm.chain.BlockLocatorFromHash(&iv.Hash) peer.PushGetBlocksMsg(locator, &zeroHash) } } } // Request as much as possible at once. Anything that won't fit into // the request will be requested on the next inv message. numRequested := 0 gdmsg := wire.NewMsgGetData() requestQueue := state.requestQueue for len(requestQueue) != 0 { iv := requestQueue[0] requestQueue[0] = nil requestQueue = requestQueue[1:] switch iv.Type { case wire.InvTypeWitnessBlock: fallthrough case wire.InvTypeBlock: // Request the block if there is not already a pending // request. if _, exists := sm.requestedBlocks[iv.Hash]; !exists { sm.requestedBlocks[iv.Hash] = struct{}{} sm.limitMap(sm.requestedBlocks, maxRequestedBlocks) state.requestedBlocks[iv.Hash] = struct{}{} if peer.IsWitnessEnabled() { iv.Type = wire.InvTypeWitnessBlock } gdmsg.AddInvVect(iv) numRequested++ } case wire.InvTypeWitnessTx: fallthrough case wire.InvTypeTx: // Request the transaction if there is not already a // pending request. if _, exists := sm.requestedTxns[iv.Hash]; !exists { sm.requestedTxns[iv.Hash] = struct{}{} sm.limitMap(sm.requestedTxns, maxRequestedTxns) state.requestedTxns[iv.Hash] = struct{}{} // If the peer is capable, request the txn // including all witness data. if peer.IsWitnessEnabled() { iv.Type = wire.InvTypeWitnessTx } gdmsg.AddInvVect(iv) numRequested++ } } if numRequested >= wire.MaxInvPerMsg { break } } state.requestQueue = requestQueue if len(gdmsg.InvList) > 0 { peer.QueueMessage(gdmsg, nil) } } // limitMap is a helper function for maps that require a maximum limit by // evicting a random transaction if adding a new value would cause it to // overflow the maximum allowed. func (sm *SyncManager) limitMap(m map[chainhash.Hash]struct{}, limit int) { if len(m)+1 > limit { // Remove a random entry from the map. For most compilers, Go's // range statement iterates starting at a random item although // that is not 100% guaranteed by the spec. The iteration order // is not important here because an adversary would have to be // able to pull off preimage attacks on the hashing function in // order to target eviction of specific entries anyways. for txHash := range m { delete(m, txHash) return } } } // blockHandler is the main handler for the sync manager. It must be run as a // goroutine. It processes block and inv messages in a separate goroutine // from the peer handlers so the block (MsgBlock) messages are handled by a // single thread without needing to lock memory data structures. This is // important because the sync manager controls which blocks are needed and how // the fetching should proceed. func (sm *SyncManager) blockHandler() { out: for { select { case m := <-sm.msgChan: switch msg := m.(type) { case *newPeerMsg: sm.handleNewPeerMsg(msg.peer) case *txMsg: sm.handleTxMsg(msg) msg.reply <- struct{}{} case *blockMsg: sm.handleBlockMsg(msg) msg.reply <- struct{}{} case *invMsg: sm.handleInvMsg(msg) case *headersMsg: sm.handleHeadersMsg(msg) case *donePeerMsg: sm.handleDonePeerMsg(msg.peer) case getSyncPeerMsg: var peerID int32 if sm.syncPeer != nil { peerID = sm.syncPeer.ID() } msg.reply <- peerID case processBlockMsg: _, isOrphan, err := sm.chain.ProcessBlock( msg.block, msg.flags) if err != nil { msg.reply <- processBlockResponse{ isOrphan: false, err: err, } } msg.reply <- processBlockResponse{ isOrphan: isOrphan, err: nil, } case isCurrentMsg: msg.reply <- sm.current() case pauseMsg: // Wait until the sender unpauses the manager. <-msg.unpause default: log.Warnf("Invalid message type in block "+ "handler: %T", msg) } case <-sm.quit: break out } } sm.wg.Done() log.Trace("Block handler done") } // handleBlockchainNotification handles notifications from blockchain. It does // things such as request orphan block parents and relay accepted blocks to // connected peers. func (sm *SyncManager) handleBlockchainNotification(notification *blockchain.Notification) { switch notification.Type { // A block has been accepted into the block chain. Relay it to other // peers. case blockchain.NTBlockAccepted: // Don't relay if we are not current. Other peers that are // current should already know about it. if !sm.current() { return } block, ok := notification.Data.(*btcutil.Block) if !ok { log.Warnf("Chain accepted notification is not a block.") break } // Generate the inventory vector and relay it. iv := wire.NewInvVect(wire.InvTypeBlock, block.Hash()) sm.peerNotifier.RelayInventory(iv, block.MsgBlock().Header) // A block has been connected to the main block chain. case blockchain.NTBlockConnected: block, ok := notification.Data.(*btcutil.Block) if !ok { log.Warnf("Chain connected notification is not a block.") break } // Remove all of the transactions (except the coinbase) in the // connected block from the transaction pool. Secondly, remove any // transactions which are now double spends as a result of these // new transactions. Finally, remove any transaction that is // no longer an orphan. Transactions which depend on a confirmed // transaction are NOT removed recursively because they are still // valid. for _, tx := range block.Transactions()[1:] { sm.txMemPool.RemoveTransaction(tx, false) sm.txMemPool.RemoveDoubleSpends(tx) sm.txMemPool.RemoveOrphan(tx) sm.peerNotifier.TransactionConfirmed(tx) acceptedTxs := sm.txMemPool.ProcessOrphans(tx) sm.peerNotifier.AnnounceNewTransactions(acceptedTxs) } // A block has been disconnected from the main block chain. case blockchain.NTBlockDisconnected: block, ok := notification.Data.(*btcutil.Block) if !ok { log.Warnf("Chain disconnected notification is not a block.") break } // Reinsert all of the transactions (except the coinbase) into // the transaction pool. for _, tx := range block.Transactions()[1:] { _, _, err := sm.txMemPool.MaybeAcceptTransaction(tx, false, false) if err != nil { // Remove the transaction and all transactions // that depend on it if it wasn't accepted into // the transaction pool. sm.txMemPool.RemoveTransaction(tx, true) } } } } // NewPeer informs the sync manager of a newly active peer. func (sm *SyncManager) NewPeer(peer *peerpkg.Peer) { // Ignore if we are shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &newPeerMsg{peer: peer} } // QueueTx adds the passed transaction message and peer to the block handling // queue. Responds to the done channel argument after the tx message is // processed. func (sm *SyncManager) QueueTx(tx *btcutil.Tx, peer *peerpkg.Peer, done chan struct{}) { // Don't accept more transactions if we're shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { done <- struct{}{} return } sm.msgChan <- &txMsg{tx: tx, peer: peer, reply: done} } // QueueBlock adds the passed block message and peer to the block handling // queue. Responds to the done channel argument after the block message is // processed. func (sm *SyncManager) QueueBlock(block *btcutil.Block, peer *peerpkg.Peer, done chan struct{}) { // Don't accept more blocks if we're shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { done <- struct{}{} return } sm.msgChan <- &blockMsg{block: block, peer: peer, reply: done} } // QueueInv adds the passed inv message and peer to the block handling queue. func (sm *SyncManager) QueueInv(inv *wire.MsgInv, peer *peerpkg.Peer) { // No channel handling here because peers do not need to block on inv // messages. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &invMsg{inv: inv, peer: peer} } // QueueHeaders adds the passed headers message and peer to the block handling // queue. func (sm *SyncManager) QueueHeaders(headers *wire.MsgHeaders, peer *peerpkg.Peer) { // No channel handling here because peers do not need to block on // headers messages. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &headersMsg{headers: headers, peer: peer} } // DonePeer informs the blockmanager that a peer has disconnected. func (sm *SyncManager) DonePeer(peer *peerpkg.Peer) { // Ignore if we are shutting down. if atomic.LoadInt32(&sm.shutdown) != 0 { return } sm.msgChan <- &donePeerMsg{peer: peer} } // Start begins the core block handler which processes block and inv messages. func (sm *SyncManager) Start() { // Already started? if atomic.AddInt32(&sm.started, 1) != 1 { return } log.Trace("Starting sync manager") sm.wg.Add(1) go sm.blockHandler() } // Stop gracefully shuts down the sync manager by stopping all asynchronous // handlers and waiting for them to finish. func (sm *SyncManager) Stop() error { if atomic.AddInt32(&sm.shutdown, 1) != 1 { log.Warnf("Sync manager is already in the process of " + "shutting down") return nil } log.Infof("Sync manager shutting down") close(sm.quit) sm.wg.Wait() return nil } // SyncPeerID returns the ID of the current sync peer, or 0 if there is none. func (sm *SyncManager) SyncPeerID() int32 { reply := make(chan int32) sm.msgChan <- getSyncPeerMsg{reply: reply} return <-reply } // ProcessBlock makes use of ProcessBlock on an internal instance of a block // chain. func (sm *SyncManager) ProcessBlock(block *btcutil.Block, flags blockchain.BehaviorFlags) (bool, error) { reply := make(chan processBlockResponse, 1) sm.msgChan <- processBlockMsg{block: block, flags: flags, reply: reply} response := <-reply return response.isOrphan, response.err } // IsCurrent returns whether or not the sync manager believes it is synced with // the connected peers. func (sm *SyncManager) IsCurrent() bool { reply := make(chan bool) sm.msgChan <- isCurrentMsg{reply: reply} return <-reply } // Pause pauses the sync manager until the returned channel is closed. // // Note that while paused, all peer and block processing is halted. The // message sender should avoid pausing the sync manager for long durations. func (sm *SyncManager) Pause() chan<- struct{} { c := make(chan struct{}) sm.msgChan <- pauseMsg{c} return c } // New constructs a new SyncManager. Use Start to begin processing asynchronous // block, tx, and inv updates. func New(config *Config) (*SyncManager, error) { sm := SyncManager{ peerNotifier: config.PeerNotifier, chain: config.Chain, txMemPool: config.TxMemPool, chainParams: config.ChainParams, rejectedTxns: make(map[chainhash.Hash]struct{}), requestedTxns: make(map[chainhash.Hash]struct{}), requestedBlocks: make(map[chainhash.Hash]struct{}), peerStates: make(map[*peerpkg.Peer]*peerSyncState), progressLogger: newBlockProgressLogger("Processed", log), msgChan: make(chan interface{}, config.MaxPeers*3), headerList: list.New(), quit: make(chan struct{}), } best := sm.chain.BestSnapshot() if !config.DisableCheckpoints { // Initialize the next checkpoint based on the current height. sm.nextCheckpoint = sm.findNextHeaderCheckpoint(best.Height) if sm.nextCheckpoint != nil { sm.resetHeaderState(&best.Hash, best.Height) } } else { log.Info("Checkpoints are disabled") } sm.chain.Subscribe(sm.handleBlockchainNotification) return &sm, nil }
adrianbrink/tendereum
vendor/github.com/cosmos/tendereum/vendor/github.com/btcsuite/btcd/netsync/manager.go
GO
agpl-3.0
46,884
<?php /** This file is part of KCFinder project * * @desc Autoload classes magic function * @package KCFinder * @version 2.21 * @author Pavel Tzonkov <pavelc@users.sourceforge.net> * @copyright 2010 KCFinder Project * @license http://www.opensource.org/licenses/gpl-2.0.php GPLv2 * @license http://www.opensource.org/licenses/lgpl-2.1.php LGPLv2 * @link http://kcfinder.sunhater.com */ require_once(dirname(__FILE__).'/../../../../config-defaults.php'); require_once(dirname(__FILE__).'/../../../../common.php'); require_once(dirname(__FILE__).'/../../../admin_functions.php'); $usquery = "SELECT stg_value FROM ".db_table_name("settings_global")." where stg_name='SessionName'"; $usresult = db_execute_assoc($usquery,'',true); if ($usresult) { $usrow = $usresult->FetchRow(); @session_name($usrow['stg_value']); } else { session_name("LimeSurveyAdmin"); } session_set_cookie_params(0,$relativeurl.'/'); if (session_id() == "") @session_start(); $_SESSION['KCFINDER'] = array(); $sAllowedExtensions = implode(' ',array_map('trim',explode(',',$allowedresourcesuploads))); $_SESSION['KCFINDER']['types']=array('files'=>$sAllowedExtensions, 'flash'=>$sAllowedExtensions, 'images'=>$sAllowedExtensions); if ($demoModeOnly === false && isset($_SESSION['loginID']) && isset($_SESSION['FileManagerContext'])) { // disable upload at survey creation time // because we don't know the sid yet if (preg_match('/^(create|edit):(question|group|answer)/',$_SESSION['FileManagerContext']) != 0 || preg_match('/^edit:survey/',$_SESSION['FileManagerContext']) !=0 || preg_match('/^edit:assessments/',$_SESSION['FileManagerContext']) !=0 || preg_match('/^edit:emailsettings/',$_SESSION['FileManagerContext']) != 0) { $contextarray=explode(':',$_SESSION['FileManagerContext'],3); $surveyid=$contextarray[2]; if(bHasSurveyPermission($surveyid,'surveycontent','update')) { $_SESSION['KCFINDER']['disabled'] = false ; $_SESSION['KCFINDER']['uploadURL'] = "{$relativeurl}/upload/surveys/{$surveyid}/" ; $_SESSION['KCFINDER']['uploadDir'] = $uploaddir.'/surveys/'.$surveyid; } } elseif (preg_match('/^edit:label/',$_SESSION['FileManagerContext']) != 0) { $contextarray=explode(':',$_SESSION['FileManagerContext'],3); $labelid=$contextarray[2]; // check if the user has label management right and labelid defined if ($_SESSION['USER_RIGHT_MANAGE_LABEL']==1 && isset($labelid) && $labelid != '') { $_SESSION['KCFINDER']['disabled'] = false ; $_SESSION['KCFINDER']['uploadURL'] = "{$relativeurl}/upload/labels/{$labelid}/" ; $_SESSION['KCFINDER']['uploadDir'] = "{$uploaddir}/labels/{$labelid}" ; } } } function __autoload($class) { if ($class == "uploader") require "core/uploader.php"; elseif ($class == "browser") require "core/browser.php"; elseif (file_exists("core/types/$class.php")) require "core/types/$class.php"; elseif (file_exists("lib/class_$class.php")) require "lib/class_$class.php"; elseif (file_exists("lib/helper_$class.php")) require "lib/helper_$class.php"; } ?>
yscdaxian/goweb
limesurvey/admin/scripts/kcfinder/core/autoload.php
PHP
agpl-3.0
3,384
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors // License: GNU General Public License v3. See license.txt erpnext.POS = Class.extend({ init: function(wrapper, frm) { this.wrapper = wrapper; this.frm = frm; this.wrapper.html('<div class="container">\ <div class="row" style="margin: -9px 0px 10px -30px; border-bottom: 1px solid #c7c7c7;">\ <div class="party-area col-sm-3 col-xs-6"></div>\ <div class="barcode-area col-sm-3 col-xs-6"></div>\ <div class="search-area col-sm-3 col-xs-6"></div>\ <div class="item-group-area col-sm-3 col-xs-6"></div>\ </div>\ <div class="row">\ <div class="col-sm-6">\ <div class="pos-bill">\ <div class="item-cart">\ <table class="table table-condensed table-hover" id="cart" style="table-layout: fixed;">\ <thead>\ <tr>\ <th style="width: 40%">Item</th>\ <th style="width: 9%"></th>\ <th style="width: 17%; text-align: right;">Qty</th>\ <th style="width: 9%"></th>\ <th style="width: 25%; text-align: right;">Rate</th>\ </tr>\ </thead>\ <tbody>\ </tbody>\ </table>\ </div>\ <br>\ <div class="totals-area" style="margin-left: 40%;">\ <table class="table table-condensed">\ <tr>\ <td><b>Net Total</b></td>\ <td style="text-align: right;" class="net-total"></td>\ </tr>\ </table>\ <div class="tax-table" style="display: none;">\ <table class="table table-condensed">\ <thead>\ <tr>\ <th style="width: 60%">Taxes</th>\ <th style="width: 40%; text-align: right;"></th>\ </tr>\ </thead>\ <tbody>\ </tbody>\ </table>\ </div>\ <div class="grand-total-area">\ <table class="table table-condensed">\ <tr>\ <td style="vertical-align: middle;"><b>Grand Total</b></td>\ <td style="text-align: right; font-size: 200%; \ font-size: bold;" class="grand-total"></td>\ </tr>\ </table>\ </div>\ </div>\ </div>\ <br><br>\ <div class="row">\ <div class="col-sm-9">\ <button class="btn btn-success btn-lg make-payment">\ <i class="icon-money"></i> Make Payment</button>\ </div>\ <div class="col-sm-3">\ <button class="btn btn-default btn-lg remove-items" style="display: none;">\ <i class="icon-trash"></i> Del</button>\ </div>\ </div>\ <br><br>\ </div>\ <div class="col-sm-6">\ <div class="item-list-area">\ <div class="col-sm-12">\ <div class="row item-list"></div></div>\ </div>\ </div>\ </div></div>'); this.check_transaction_type(); this.make(); var me = this; $(this.frm.wrapper).on("refresh-fields", function() { me.refresh(); }); this.call_function("remove-items", function() {me.remove_selected_items();}); this.call_function("make-payment", function() {me.make_payment();}); }, check_transaction_type: function() { var me = this; // Check whether the transaction is "Sales" or "Purchase" if (wn.meta.has_field(cur_frm.doc.doctype, "customer")) { this.set_transaction_defaults("Customer", "export"); } else if (wn.meta.has_field(cur_frm.doc.doctype, "supplier")) { this.set_transaction_defaults("Supplier", "import"); } }, set_transaction_defaults: function(party, export_or_import) { var me = this; this.party = party; this.price_list = (party == "Customer" ? this.frm.doc.selling_price_list : this.frm.doc.buying_price_list); this.sales_or_purchase = (party == "Customer" ? "Sales" : "Purchase"); this.net_total = "net_total_" + export_or_import; this.grand_total = "grand_total_" + export_or_import; this.amount = export_or_import + "_amount"; this.rate = export_or_import + "_rate"; }, call_function: function(class_name, fn, event_name) { this.wrapper.find("." + class_name).on(event_name || "click", fn); }, make: function() { this.make_party(); this.make_item_group(); this.make_search(); this.make_barcode(); this.make_item_list(); }, make_party: function() { var me = this; this.party_field = wn.ui.form.make_control({ df: { "fieldtype": "Link", "options": this.party, "label": this.party, "fieldname": "pos_party", "placeholder": this.party }, parent: this.wrapper.find(".party-area"), only_input: true, }); this.party_field.make_input(); this.party_field.$input.on("change", function() { if(!me.party_field.autocomplete_open) wn.model.set_value(me.frm.doctype, me.frm.docname, me.party.toLowerCase(), this.value); }); }, make_item_group: function() { var me = this; this.item_group = wn.ui.form.make_control({ df: { "fieldtype": "Link", "options": "Item Group", "label": "Item Group", "fieldname": "pos_item_group", "placeholder": "Item Group" }, parent: this.wrapper.find(".item-group-area"), only_input: true, }); this.item_group.make_input(); this.item_group.$input.on("change", function() { if(!me.item_group.autocomplete_open) me.make_item_list(); }); }, make_search: function() { var me = this; this.search = wn.ui.form.make_control({ df: { "fieldtype": "Data", "label": "Item", "fieldname": "pos_item", "placeholder": "Search Item" }, parent: this.wrapper.find(".search-area"), only_input: true, }); this.search.make_input(); this.search.$input.on("keypress", function() { if(!me.search.autocomplete_open) if(me.item_timeout) clearTimeout(me.item_timeout); me.item_timeout = setTimeout(function() { me.make_item_list(); }, 1000); }); }, make_barcode: function() { var me = this; this.barcode = wn.ui.form.make_control({ df: { "fieldtype": "Data", "label": "Barcode", "fieldname": "pos_barcode", "placeholder": "Barcode / Serial No" }, parent: this.wrapper.find(".barcode-area"), only_input: true, }); this.barcode.make_input(); this.barcode.$input.on("keypress", function() { if(me.barcode_timeout) clearTimeout(me.barcode_timeout); me.barcode_timeout = setTimeout(function() { me.add_item_thru_barcode(); }, 1000); }); }, make_item_list: function() { var me = this; me.item_timeout = null; wn.call({ method: 'accounts.doctype.sales_invoice.pos.get_items', args: { sales_or_purchase: this.sales_or_purchase, price_list: this.price_list, item_group: this.item_group.$input.val(), item: this.search.$input.val() }, callback: function(r) { var $wrap = me.wrapper.find(".item-list"); me.wrapper.find(".item-list").empty(); if (r.message) { $.each(r.message, function(index, obj) { if (obj.image) image = '<img src="' + obj.image + '" class="img-responsive" \ style="border:1px solid #eee; max-height: 140px;">'; else image = '<div class="missing-image"><i class="icon-camera"></i></div>'; $(repl('<div class="col-xs-3 pos-item" data-item_code="%(item_code)s">\ <div style="height: 140px; overflow: hidden;">%(item_image)s</div>\ <div class="small">%(item_code)s</div>\ <div class="small">%(item_name)s</div>\ <div class="small">%(item_price)s</div>\ </div>', { item_code: obj.name, item_price: format_currency(obj.ref_rate, obj.currency), item_name: obj.name===obj.item_name ? "" : obj.item_name, item_image: image })).appendTo($wrap); }); } // if form is local then allow this function $(me.wrapper).find("div.pos-item").on("click", function() { if(me.frm.doc.docstatus==0) { if(!me.frm.doc[me.party.toLowerCase()] && ((me.frm.doctype == "Quotation" && me.frm.doc.quotation_to == "Customer") || me.frm.doctype != "Quotation")) { msgprint("Please select " + me.party + " first."); return; } else me.add_to_cart($(this).attr("data-item_code")); } }); } }); }, add_to_cart: function(item_code, serial_no) { var me = this; var caught = false; // get no_of_items var no_of_items = me.wrapper.find("#cart tbody tr").length; // check whether the item is already added if (no_of_items != 0) { $.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype), function(i, d) { if (d.item_code == item_code) { caught = true; if (serial_no) { d.serial_no += '\n' + serial_no; me.frm.script_manager.trigger("serial_no", d.doctype, d.name); } else { d.qty += 1; me.frm.script_manager.trigger("qty", d.doctype, d.name); } } }); } // if item not found then add new item if (!caught) { this.add_new_item_to_grid(item_code, serial_no); } this.refresh(); this.refresh_search_box(); }, add_new_item_to_grid: function(item_code, serial_no) { var me = this; var child = wn.model.add_child(me.frm.doc, this.frm.doctype + " Item", this.frm.cscript.fname); child.item_code = item_code; if (serial_no) child.serial_no = serial_no; this.frm.script_manager.trigger("item_code", child.doctype, child.name); }, refresh_search_box: function() { var me = this; // Clear Item Box and remake item list if (this.search.$input.val()) { this.search.set_input(""); this.make_item_list(); } }, update_qty: function(item_code, qty) { var me = this; $.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype), function(i, d) { if (d.item_code == item_code) { if (qty == 0) { wn.model.clear_doc(d.doctype, d.name); me.refresh_grid(); } else { d.qty = qty; me.frm.script_manager.trigger("qty", d.doctype, d.name); } } }); me.refresh(); }, refresh: function() { var me = this; this.party_field.set_input(this.frm.doc[this.party.toLowerCase()]); this.barcode.set_input(""); this.show_items_in_item_cart(); this.show_taxes(); this.set_totals(); // if form is local then only run all these functions if (this.frm.doc.docstatus===0) { this.call_when_local(); } this.disable_text_box_and_button(); this.hide_payment_button(); // If quotation to is not Customer then remove party if (this.frm.doctype == "Quotation") { this.party_field.$wrapper.remove(); if (this.frm.doc.quotation_to == "Customer") this.make_party(); } }, show_items_in_item_cart: function() { var me = this; var $items = this.wrapper.find("#cart tbody").empty(); $.each(wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype), function(i, d) { $(repl('<tr id="%(item_code)s" data-selected="false">\ <td>%(item_code)s%(item_name)s</td>\ <td style="vertical-align:middle;" align="right">\ <div class="decrease-qty" style="cursor:pointer;">\ <i class="icon-minus-sign icon-large text-danger"></i>\ </div>\ </td>\ <td style="vertical-align:middle;"><input type="text" value="%(qty)s" \ class="form-control qty" style="text-align: right;"></td>\ <td style="vertical-align:middle;cursor:pointer;">\ <div class="increase-qty" style="cursor:pointer;">\ <i class="icon-plus-sign icon-large text-success"></i>\ </div>\ </td>\ <td style="text-align: right;"><b>%(amount)s</b><br>%(rate)s</td>\ </tr>', { item_code: d.item_code, item_name: d.item_name===d.item_code ? "" : ("<br>" + d.item_name), qty: d.qty, rate: format_currency(d[me.rate], me.frm.doc.currency), amount: format_currency(d[me.amount], me.frm.doc.currency) } )).appendTo($items); }); this.wrapper.find(".increase-qty, .decrease-qty").on("click", function() { var item_code = $(this).closest("tr").attr("id"); me.selected_item_qty_operation(item_code, $(this).attr("class")); }); }, show_taxes: function() { var me = this; var taxes = wn.model.get_children(this.sales_or_purchase + " Taxes and Charges", this.frm.doc.name, this.frm.cscript.other_fname, this.frm.doctype); $(this.wrapper).find(".tax-table") .toggle((taxes && taxes.length) ? true : false) .find("tbody").empty(); $.each(taxes, function(i, d) { if (d.tax_amount) { $(repl('<tr>\ <td>%(description)s %(rate)s</td>\ <td style="text-align: right;">%(tax_amount)s</td>\ <tr>', { description: d.description, rate: ((d.charge_type == "Actual") ? '' : ("(" + d.rate + "%)")), tax_amount: format_currency(flt(d.tax_amount)/flt(me.frm.doc.conversion_rate), me.frm.doc.currency) })).appendTo(".tax-table tbody"); } }); }, set_totals: function() { var me = this; this.wrapper.find(".net-total").text(format_currency(this.frm.doc[this.net_total], me.frm.doc.currency)); this.wrapper.find(".grand-total").text(format_currency(this.frm.doc[this.grand_total], me.frm.doc.currency)); }, call_when_local: function() { var me = this; // append quantity to the respective item after change from input box $(this.wrapper).find("input.qty").on("change", function() { var item_code = $(this).closest("tr")[0].id; me.update_qty(item_code, $(this).val()); }); // on td click toggle the highlighting of row $(this.wrapper).find("#cart tbody tr td").on("click", function() { var row = $(this).closest("tr"); if (row.attr("data-selected") == "false") { row.attr("class", "warning"); row.attr("data-selected", "true"); } else { row.prop("class", null); row.attr("data-selected", "false"); } me.refresh_delete_btn(); }); me.refresh_delete_btn(); this.barcode.$input.focus(); }, disable_text_box_and_button: function() { var me = this; // if form is submitted & cancelled then disable all input box & buttons if (this.frm.doc.docstatus>=1) { $(this.wrapper).find('input, button').each(function () { $(this).prop('disabled', true); }); $(this.wrapper).find(".remove-items").hide(); $(this.wrapper).find(".make-payment").hide(); } else { $(this.wrapper).find('input, button').each(function () { $(this).prop('disabled', false); }); $(this.wrapper).find(".make-payment").show(); } }, hide_payment_button: function() { var me = this; // Show Make Payment button only in Sales Invoice if (this.frm.doctype != "Sales Invoice") $(this.wrapper).find(".make-payment").hide(); }, refresh_delete_btn: function() { $(this.wrapper).find(".remove-items").toggle($(".item-cart .warning").length ? true : false); }, add_item_thru_barcode: function() { var me = this; me.barcode_timeout = null; wn.call({ method: 'accounts.doctype.sales_invoice.pos.get_item_code', args: {barcode_serial_no: this.barcode.$input.val()}, callback: function(r) { if (r.message) { if (r.message[1] == "serial_no") me.add_to_cart(r.message[0][0].item_code, r.message[0][0].name); else me.add_to_cart(r.message[0][0].name); } else msgprint(wn._("Invalid Barcode")); me.refresh(); } }); }, remove_selected_items: function() { var me = this; var selected_items = []; var no_of_items = $(this.wrapper).find("#cart tbody tr").length; for(var x=0; x<=no_of_items - 1; x++) { var row = $(this.wrapper).find("#cart tbody tr:eq(" + x + ")"); if(row.attr("data-selected") == "true") { selected_items.push(row.attr("id")); } } var child = wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype); $.each(child, function(i, d) { for (var i in selected_items) { if (d.item_code == selected_items[i]) { wn.model.clear_doc(d.doctype, d.name); } } }); this.refresh_grid(); }, refresh_grid: function() { this.frm.fields_dict[this.frm.cscript.fname].grid.refresh(); this.frm.script_manager.trigger("calculate_taxes_and_totals"); this.refresh(); }, selected_item_qty_operation: function(item_code, operation) { var me = this; var child = wn.model.get_children(this.frm.doctype + " Item", this.frm.doc.name, this.frm.cscript.fname, this.frm.doctype); $.each(child, function(i, d) { if (d.item_code == item_code) { if (operation == "increase-qty") d.qty += 1; else if (operation == "decrease-qty") d.qty != 1 ? d.qty -= 1 : d.qty = 1; me.refresh(); } }); }, make_payment: function() { var me = this; var no_of_items = $(this.wrapper).find("#cart tbody tr").length; var mode_of_payment = []; if (no_of_items == 0) msgprint(wn._("Payment cannot be made for empty cart")); else { wn.call({ method: 'accounts.doctype.sales_invoice.pos.get_mode_of_payment', callback: function(r) { for (x=0; x<=r.message.length - 1; x++) { mode_of_payment.push(r.message[x].name); } // show payment wizard var dialog = new wn.ui.Dialog({ width: 400, title: 'Payment', fields: [ {fieldtype:'Data', fieldname:'total_amount', label:'Total Amount', read_only:1}, {fieldtype:'Select', fieldname:'mode_of_payment', label:'Mode of Payment', options:mode_of_payment.join('\n'), reqd: 1}, {fieldtype:'Button', fieldname:'pay', label:'Pay'} ] }); dialog.set_values({ "total_amount": $(".grand-total").text() }); dialog.show(); dialog.get_input("total_amount").prop("disabled", true); dialog.fields_dict.pay.input.onclick = function() { me.frm.set_value("mode_of_payment", dialog.get_values().mode_of_payment); me.frm.set_value("paid_amount", dialog.get_values().total_amount); me.frm.cscript.mode_of_payment(me.frm.doc); me.frm.save(); dialog.hide(); me.refresh(); }; } }); } }, });
Tejal011089/Medsyn2_app
accounts/doctype/sales_invoice/pos.js
JavaScript
agpl-3.0
17,987
/* * eXist Open Source Native XML Database * Copyright (C) 2010 The eXist Project * http://exist-db.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * $Id$ */ package org.exist.versioning.svn.xquery; import org.exist.dom.QName; import org.exist.util.io.Resource; import org.exist.versioning.svn.internal.wc.DefaultSVNOptions; import org.exist.versioning.svn.wc.SVNClientManager; import org.exist.versioning.svn.wc.SVNWCUtil; import org.exist.xquery.Cardinality; import org.exist.xquery.FunctionSignature; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.value.FunctionReturnSequenceType; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.SequenceType; import org.exist.xquery.value.Type; import org.tmatesoft.svn.core.SVNException; /** * Recursively cleans up the working copy, removing locks and resuming unfinished operations. * * @author <a href="mailto:amir.akhmedov@gmail.com">Amir Akhmedov</a> * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> */ public class SVNCleanup extends AbstractSVNFunction { public final static FunctionSignature signature = new FunctionSignature( new QName("clean-up", SVNModule.NAMESPACE_URI, SVNModule.PREFIX), "Recursively cleans up the working copy, removing locks and resuming unfinished operations.", new SequenceType[] { DB_PATH }, new FunctionReturnSequenceType(Type.EMPTY, Cardinality.ZERO, "")); /** * * @param context */ public SVNCleanup(XQueryContext context) { super(context, signature); } /** * Process the function. All arguments are passed in the array args. The number of * arguments, their type and cardinality have already been checked to match * the function signature. * * @param args * @param contextSequence */ public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { String uri = args[0].getStringValue(); DefaultSVNOptions options = SVNWCUtil.createDefaultOptions(true); SVNClientManager manager = SVNClientManager.newInstance(options, "", ""); try { manager.getWCClient().doCleanup(new Resource(uri)); } catch (SVNException e) { throw new XPathException(this, e.getMessage(), e); } return Sequence.EMPTY_SEQUENCE; } }
shabanovd/exist
extensions/svn/src/org/exist/versioning/svn/xquery/SVNCleanup.java
Java
lgpl-2.1
3,112
// --------------------------------------------------------------------- // // Copyright (C) 2016 by the deal.II authors // // This file is part of the deal.II library. // // The deal.II library is free software; you can use it, redistribute // it, and/or modify it under the terms of the GNU Lesser General // Public License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // The full text of the license can be found in the file LICENSE at // the top level of the deal.II distribution. // // --------------------------------------------------------------------- // test Volume of a Ball #include "../tests.h" #include <deal.II/base/logstream.h> #include <deal.II/dofs/dof_tools.h> #include <deal.II/fe/fe_q.h> #include <deal.II/fe/fe_tools.h> #include <deal.II/fe/mapping_q.h> #include <deal.II/grid/grid_generator.h> #include <deal.II/numerics/vector_tools.h> #include <deal.II/numerics/data_out.h> #include <deal.II/grid/grid_out.h> #include <deal.II/grid/grid_in.h> #include <deal.II/grid/grid_tools.h> #include <deal.II/grid/manifold_lib.h> #include <deal.II/matrix_free/matrix_free.h> #include <deal.II/matrix_free/fe_evaluation.h> #include <iostream> #include <fstream> #include <sstream> using namespace dealii; void test (const double R) { const unsigned int dim = 3; const unsigned int global_mesh_refinement_steps = 4; const unsigned int fe_degree = 2; const unsigned int n_q_points_1d = 3; // derived Point<dim> center; for (unsigned int d=0; d < dim; d++) center[d] = d; Triangulation<dim> triangulation; DoFHandler<dim> dof_handler(triangulation); FE_Q<dim> fe(fe_degree); QGauss<dim> quadrature_formula(n_q_points_1d); GridGenerator::hyper_ball (triangulation, center, R); triangulation.set_all_manifold_ids_on_boundary(0); static SphericalManifold<dim> surface_description(center); triangulation.set_manifold (0, surface_description); triangulation.refine_global(global_mesh_refinement_steps); dof_handler.distribute_dofs (fe); MappingQ<dim> mapping(fe_degree); FEValues<dim> fe_values (mapping, fe, quadrature_formula, update_JxW_values); DoFHandler<dim>::active_cell_iterator cell = dof_handler.begin_active (), endc = dof_handler.end (); const unsigned int n_q_points = quadrature_formula.size(); double volume = 0.; for (; cell!=endc; ++cell) { fe_values.reinit (cell); for (unsigned int q=0; q<n_q_points; ++q) volume += fe_values.JxW (q); } deallog << "Volume: " << volume << std::endl << "Exact volume: " << 4.0*numbers::PI *std::pow(R,3.0)/3. << std::endl; dof_handler.clear (); } using namespace dealii; int main (int argc, char *argv[]) { initlog(); test(15); return 0; }
shakirbsm/dealii
tests/manifold/spherical_manifold_04.cc
C++
lgpl-2.1
2,888
package org.jaudiotagger.issues; import org.jaudiotagger.AbstractTestCase; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.tag.FieldKey; import java.io.File; /** * Test deletions of ID3v1 tag */ public class Issue383Test extends AbstractTestCase { /** * This song is incorrectly shown as 6:08 when should be 3:34 but all apps (Media Monkey, iTunes) * also report incorrect length, however think problem is audio does continue until 6:08 but is just quiet sound * * @throws Exception */ public void testIssueIncorrectTrackLength() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test106.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test106.mp3"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getAudioHeader().getTrackLength(),368); } catch(Exception e) { caught=e; } assertNull(caught); } /** * This song is incorrectly shown as 01:12:52, but correct length was 2:24. Other applications * such as Media Monkey show correct value. * * @throws Exception */ public void testIssue() throws Exception { Exception caught = null; try { File orig = new File("testdata", "test107.mp3"); if (!orig.isFile()) { System.err.println("Unable to test file - not available"); return; } File testFile = AbstractTestCase.copyAudioToTmp("test107.mp3"); AudioFile af = AudioFileIO.read(testFile); assertEquals(af.getTag().getFirst(FieldKey.TRACK),"01"); assertEquals(af.getAudioHeader().getTrackLength(),4372); } catch(Exception e) { caught=e; } assertNull(caught); } }
nhminus/jaudiotagger-androidpatch
srctest/org/jaudiotagger/issues/Issue383Test.java
Java
lgpl-2.1
2,217
/** * * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.functions.query; import lucee.runtime.PageContext; import lucee.runtime.exp.PageException; import lucee.runtime.functions.BIF; import lucee.runtime.op.Caster; import lucee.runtime.type.Query; public final class QueryDeleteRow extends BIF { private static final long serialVersionUID = 7610413135885802876L; public static boolean call(PageContext pc, Query query) throws PageException { return call(pc,query,query.getRowCount()); } public static boolean call(PageContext pc, Query query, double row) throws PageException { if(row==-9999) row=query.getRowCount();// used for named arguments query.removeRow((int)row); return true; } @Override public Object invoke(PageContext pc, Object[] args) throws PageException { if(args.length==1)return call(pc,Caster.toQuery(args[0])); return call(pc,Caster.toQuery(args[0]),Caster.toDoubleValue(args[1])); } }
paulklinkenberg/Lucee4
lucee-java/lucee-core/src/lucee/runtime/functions/query/QueryDeleteRow.java
Java
lgpl-2.1
1,691
/* * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.jboss.as.server.deployment; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.CONTENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.DEPLOYMENT; import static org.jboss.as.controller.descriptions.ModelDescriptionConstants.FULL_REPLACE_DEPLOYMENT; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_ARCHIVE; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_HASH; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_PATH; import static org.jboss.as.server.controller.resources.DeploymentAttributes.CONTENT_RELATIVE_TO; import static org.jboss.as.server.controller.resources.DeploymentAttributes.ENABLED; import static org.jboss.as.server.controller.resources.DeploymentAttributes.OWNER; import static org.jboss.as.server.controller.resources.DeploymentAttributes.PERSISTENT; import static org.jboss.as.server.controller.resources.DeploymentAttributes.RUNTIME_NAME; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.addFlushHandler; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.asString; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.createFailureException; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.getInputStream; import static org.jboss.as.server.deployment.DeploymentHandlerUtils.hasValidContentAdditionParameterDefined; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import org.jboss.as.controller.AttributeDefinition; import org.jboss.as.controller.OperationContext; import org.jboss.as.controller.OperationContext.ResultAction; import org.jboss.as.controller.OperationFailedException; import org.jboss.as.controller.OperationStepHandler; import org.jboss.as.controller.PathAddress; import org.jboss.as.controller.PathElement; import org.jboss.as.controller.registry.Resource; import org.jboss.as.protocol.StreamUtils; import org.jboss.as.repository.ContentReference; import org.jboss.as.repository.ContentRepository; import org.jboss.as.server.controller.resources.DeploymentAttributes; import org.jboss.as.server.logging.ServerLogger; import org.jboss.dmr.ModelNode; /** * Handles replacement in the runtime of one deployment by another. * * @author Brian Stansberry (c) 2011 Red Hat Inc. */ public class DeploymentFullReplaceHandler implements OperationStepHandler { public static final String OPERATION_NAME = FULL_REPLACE_DEPLOYMENT; protected final ContentRepository contentRepository; private final DeploymentTransformation deploymentTransformation; protected DeploymentFullReplaceHandler(final ContentRepository contentRepository) { assert contentRepository != null : "Null contentRepository"; this.contentRepository = contentRepository; this.deploymentTransformation = new DeploymentTransformation(); } public static DeploymentFullReplaceHandler create(final ContentRepository contentRepository) { return new DeploymentFullReplaceHandler(contentRepository); } public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { // Validate op. Store any corrected values back to the op before manipulating further ModelNode correctedOperation = operation.clone(); for (AttributeDefinition def : DeploymentAttributes.FULL_REPLACE_DEPLOYMENT_ATTRIBUTES.values()) { def.validateAndSet(operation, correctedOperation); } // Pull data from the op final String name = DeploymentAttributes.NAME.resolveModelAttribute(context, correctedOperation).asString(); final PathElement deploymentPath = PathElement.pathElement(DEPLOYMENT, name); final String runtimeName = correctedOperation.hasDefined(RUNTIME_NAME.getName()) ? correctedOperation.get(RUNTIME_NAME.getName()).asString() : name; // clone the content param, so we can modify it to our own content ModelNode content = correctedOperation.require(CONTENT).clone(); // Throw a specific exception if the replaced deployment doesn't already exist // BES 2013/10/30 -- this is pointless; the readResourceForUpdate call will throw // an exception with an equally informative message if the deployment doesn't exist // final Resource root = context.readResource(PathAddress.EMPTY_ADDRESS); // boolean exists = root.hasChild(deploymentPath); // if (!exists) { // throw ServerLogger.ROOT_LOGGER.noSuchDeployment(name); // } // verify that the resource existance before removing it context.readResourceForUpdate(PathAddress.pathAddress(deploymentPath)); // WFCORE-495 remove and call context.addResource() as below to add new resource with updated PERSISTENT value final ModelNode deploymentModel = context.removeResource(PathAddress.pathAddress(deploymentPath)).getModel(); final ModelNode originalDeployment = deploymentModel.clone(); // Keep track of runtime name of deployment we are replacing for use in Stage.RUNTIME final String replacedRuntimeName = RUNTIME_NAME.resolveModelAttribute(context, deploymentModel).asString(); final PathAddress address = PathAddress.pathAddress(deploymentPath); // Keep track of hash we are replacing so we can drop it from the content repo if all is well ModelNode replacedContent = deploymentModel.get(CONTENT).get(0); final byte[] replacedHash = replacedContent.hasDefined(CONTENT_HASH.getName()) ? CONTENT_HASH.resolveModelAttribute(context, replacedContent).asBytes() : null; // Set up the new content attribute final byte[] newHash; // TODO: JBAS-9020: for the moment overlays are not supported, so there is a single content item final DeploymentHandlerUtil.ContentItem contentItem; ModelNode contentItemNode = content.require(0); if (contentItemNode.hasDefined(CONTENT_HASH.getName())) { newHash = CONTENT_HASH.resolveModelAttribute(context, contentItemNode).asBytes(); ContentReference reference = ModelContentReference.fromModelAddress(address, newHash); contentItem = addFromHash(reference); } else if (hasValidContentAdditionParameterDefined(contentItemNode)) { contentItem = addFromContentAdditionParameter(context, contentItemNode, name); newHash = contentItem.getHash(); // Replace the content data contentItemNode = new ModelNode(); contentItemNode.get(CONTENT_HASH.getName()).set(newHash); content.clear(); content.add(contentItemNode); } else { contentItem = addUnmanaged(context, contentItemNode); newHash = null; } // deploymentModel.get(NAME).set(name); // already there deploymentModel.get(RUNTIME_NAME.getName()).set(runtimeName); deploymentModel.get(CONTENT).set(content); // The 'persistent' and 'owner' parameters are hidden internal API, so handle them specifically // Persistent is hidden from CLI users so let's set this to true here if it is not defined if (!operation.hasDefined(PERSISTENT.getName())) { operation.get(PERSISTENT.getName()).set(true); } PERSISTENT.validateAndSet(operation, deploymentModel); OWNER.validateAndSet(operation, deploymentModel); // ENABLED stays as is if not present in operation boolean wasDeployed = ENABLED.resolveModelAttribute(context, deploymentModel).asBoolean(); if (operation.hasDefined(ENABLED.getName())) { ENABLED.validateAndSet(operation, deploymentModel); } // Do the runtime part if the deployment is enabled if (ENABLED.resolveModelAttribute(context, deploymentModel).asBoolean()) { DeploymentUtils.enableAttribute(deploymentModel); } else if (wasDeployed) { DeploymentUtils.disableAttribute(deploymentModel); } boolean persistent = PERSISTENT.resolveModelAttribute(context, operation).asBoolean(); final Resource resource = Resource.Factory.create(!persistent); resource.writeModel(deploymentModel); context.addResource(PathAddress.pathAddress(deploymentPath), resource); if (ENABLED.resolveModelAttribute(context, deploymentModel).asBoolean()) { DeploymentHandlerUtil.replace(context, originalDeployment, runtimeName, name, replacedRuntimeName, contentItem); } else if (wasDeployed) { DeploymentHandlerUtil.undeploy(context, operation, name, runtimeName); } addFlushHandler(context, contentRepository, new OperationContext.ResultHandler() { @Override public void handleResult(ResultAction resultAction, OperationContext context, ModelNode operation) { if (resultAction == ResultAction.KEEP) { if (replacedHash != null && (newHash == null || !Arrays.equals(replacedHash, newHash))) { // The old content is no longer used; clean from repos contentRepository.removeContent(ModelContentReference.fromModelAddress(address, replacedHash)); } if (newHash != null) { contentRepository.addContentReference(ModelContentReference.fromModelAddress(address, newHash)); } } else if (newHash != null && (replacedHash == null || !Arrays.equals(replacedHash, newHash))) { // Due to rollback, the new content isn't used; clean from repos contentRepository.removeContent(ModelContentReference.fromModelAddress(address, newHash)); } } }); } DeploymentHandlerUtil.ContentItem addFromHash(ContentReference reference) throws OperationFailedException { if (!contentRepository.syncContent(reference)) { throw ServerLogger.ROOT_LOGGER.noSuchDeploymentContent(reference.getHexHash()); } return new DeploymentHandlerUtil.ContentItem(reference.getHash()); } DeploymentHandlerUtil.ContentItem addFromContentAdditionParameter(OperationContext context, ModelNode contentItemNode, String name) throws OperationFailedException { byte[] hash; InputStream in = getInputStream(context, contentItemNode); InputStream transformed = null; try { try { transformed = deploymentTransformation.doTransformation(context, contentItemNode, name, in); hash = contentRepository.addContent(transformed); } catch (IOException e) { throw createFailureException(e.toString()); } } finally { StreamUtils.safeClose(in); StreamUtils.safeClose(transformed); } contentItemNode.clear(); // AS7-1029 contentItemNode.get(CONTENT_HASH.getName()).set(hash); // TODO: remove the content addition stuff? return new DeploymentHandlerUtil.ContentItem(hash); } DeploymentHandlerUtil.ContentItem addUnmanaged(OperationContext context, ModelNode contentItemNode) throws OperationFailedException { final String path = CONTENT_PATH.resolveModelAttribute(context, contentItemNode).asString(); final String relativeTo = asString(contentItemNode, CONTENT_RELATIVE_TO.getName()); final boolean archive = CONTENT_ARCHIVE.resolveModelAttribute(context, contentItemNode).asBoolean(); return new DeploymentHandlerUtil.ContentItem(path, relativeTo, archive); } }
ivassile/wildfly-core
server/src/main/java/org/jboss/as/server/deployment/DeploymentFullReplaceHandler.java
Java
lgpl-2.1
12,747
/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** ** GNU Lesser General Public License Usage ** ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this file. ** Please review the following information to ensure the GNU Lesser General ** Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** Other Usage ** ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** **************************************************************************/ #include "currentprojectfind.h" #include "projectexplorer.h" #include "project.h" #include "session.h" #include <coreplugin/idocument.h> #include <utils/qtcassert.h> #include <QDebug> #include <QSettings> #include <QLabel> #include <QHBoxLayout> using namespace Find; using namespace ProjectExplorer; using namespace ProjectExplorer::Internal; using namespace TextEditor; CurrentProjectFind::CurrentProjectFind(ProjectExplorerPlugin *plugin) : AllProjectsFind(plugin), m_plugin(plugin) { connect(m_plugin, SIGNAL(currentProjectChanged(ProjectExplorer::Project*)), this, SLOT(handleProjectChanged())); } QString CurrentProjectFind::id() const { return QLatin1String("Current Project"); } QString CurrentProjectFind::displayName() const { return tr("Current Project"); } bool CurrentProjectFind::isEnabled() const { return ProjectExplorerPlugin::currentProject() != 0 && BaseFileFind::isEnabled(); } QVariant CurrentProjectFind::additionalParameters() const { Project *project = ProjectExplorerPlugin::currentProject(); if (project && project->document()) return qVariantFromValue(project->document()->fileName()); return QVariant(); } Utils::FileIterator *CurrentProjectFind::files(const QStringList &nameFilters, const QVariant &additionalParameters) const { QTC_ASSERT(additionalParameters.isValid(), return new Utils::FileIterator()); QList<Project *> allProjects = m_plugin->session()->projects(); QString projectFile = additionalParameters.toString(); foreach (Project *project, allProjects) { if (project->document() && projectFile == project->document()->fileName()) return filesForProjects(nameFilters, QList<Project *>() << project); } return new Utils::FileIterator(); } QString CurrentProjectFind::label() const { QTC_ASSERT(ProjectExplorerPlugin::currentProject(), return QString()); return tr("Project '%1':").arg(ProjectExplorerPlugin::currentProject()->displayName()); } void CurrentProjectFind::handleProjectChanged() { emit enabledChanged(isEnabled()); } void CurrentProjectFind::writeSettings(QSettings *settings) { settings->beginGroup(QLatin1String("CurrentProjectFind")); writeCommonSettings(settings); settings->endGroup(); } void CurrentProjectFind::readSettings(QSettings *settings) { settings->beginGroup(QLatin1String("CurrentProjectFind")); readCommonSettings(settings, QString(QLatin1Char('*'))); settings->endGroup(); }
ostash/qt-creator-i18n-uk
src/plugins/projectexplorer/currentprojectfind.cpp
C++
lgpl-2.1
3,806
package org.intermine.sql.writebatch; /* * Copyright (C) 2002-2015 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.DataOutputStream; import java.io.IOException; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.intermine.model.StringConstructor; import org.postgresql.PGConnection; import org.postgresql.copy.CopyManager; /** * An implementation of the BatchWriter interface that uses PostgreSQL-specific COPY commands. * * @author Matthew Wakeling */ public class BatchWriterPostgresCopyImpl extends BatchWriterPreparedStatementImpl { private static final Logger LOG = Logger.getLogger(BatchWriterPostgresCopyImpl.class); protected static final BigInteger TEN = new BigInteger("10"); protected static final BigInteger HUNDRED = new BigInteger("100"); protected static final BigInteger THOUSAND = new BigInteger("1000"); protected static final BigInteger TEN_THOUSAND = new BigInteger("10000"); /** * {@inheritDoc} */ @SuppressWarnings("unchecked") @Override protected int doInserts(String name, TableBatch table, List<FlushJob> batches) throws SQLException { String[] colNames = table.getColNames(); if ((colNames != null) && (!table.getIdsToInsert().isEmpty())) { try { CopyManager copyManager = null; if (con.isWrapperFor(PGConnection.class)) { copyManager = con.unwrap(PGConnection.class).getCopyAPI(); } if (copyManager == null) { LOG.warn("Database with Connection " + con.getClass().getName() + " is incompatible with the PostgreSQL COPY command - falling" + " back to prepared statements"); super.doInserts(name, table, batches); } else { PostgresByteArrayOutputStream baos = new PostgresByteArrayOutputStream(); PostgresDataOutputStream dos = new PostgresDataOutputStream(baos); dos.writeBytes("PGCOPY\n"); dos.writeByte(255); dos.writeBytes("\r\n"); dos.writeByte(0); // Signature done dos.writeInt(0); // Flags - we aren't supplying OIDS dos.writeInt(0); // Length of header extension for (Map.Entry<Object, Object> insertEntry : table.getIdsToInsert() .entrySet()) { Object inserts = insertEntry.getValue(); if (inserts instanceof Object[]) { Object[] values = (Object[]) inserts; dos.writeShort(colNames.length); for (int i = 0; i < colNames.length; i++) { writeObject(dos, values[i]); } } else { for (Object[] values : ((List<Object[]>) inserts)) { dos.writeShort(colNames.length); for (int i = 0; i < colNames.length; i++) { writeObject(dos, values[i]); } } } } StringBuffer sqlBuffer = new StringBuffer("COPY ").append(name).append(" ("); for (int i = 0; i < colNames.length; i++) { if (i > 0) { sqlBuffer.append(", "); } sqlBuffer.append(colNames[i]); } sqlBuffer.append(") FROM STDIN BINARY"); String sql = sqlBuffer.toString(); dos.writeShort(-1); dos.flush(); batches.add(new FlushJobPostgresCopyImpl(copyManager, sql, baos.getBuffer(), baos.size())); } } catch (IOException e) { throw new SQLException(e.toString()); } return table.getIdsToInsert().size(); } return 0; } // TODO: Add support for UUID. private static void writeObject(PostgresDataOutputStream dos, Object o) throws IOException { if (o == null) { dos.writeInt(-1); } else if (o instanceof Integer) { dos.writeInt(4); dos.writeInt(((Integer) o).intValue()); } else if (o instanceof Short) { dos.writeInt(2); dos.writeShort(((Short) o).intValue()); } else if (o instanceof Boolean) { dos.writeInt(1); dos.writeByte(((Boolean) o).booleanValue() ? 1 : 0); } else if (o instanceof Float) { dos.writeInt(4); dos.writeFloat(((Float) o).floatValue()); } else if (o instanceof Double) { dos.writeInt(8); dos.writeDouble(((Double) o).doubleValue()); } else if (o instanceof Long) { dos.writeInt(8); dos.writeLong(((Long) o).longValue()); } else if (o instanceof String) { dos.writeLargeUTF((String) o); } else if (o instanceof StringConstructor) { dos.writeLargeUTF((StringConstructor) o); } else if (o instanceof BigDecimal) { BigInteger unscaledValue = ((BigDecimal) o).unscaledValue(); int signum = ((BigDecimal) o).signum(); if (signum == -1) { unscaledValue = unscaledValue.negate(); } int scale = ((BigDecimal) o).scale(); int nBaseScale = (scale + 3) / 4; int nBaseScaleRemainder = scale % 4; List<Integer> digits = new ArrayList<Integer>(); if (nBaseScaleRemainder == 1) { BigInteger[] res = unscaledValue.divideAndRemainder(TEN); int digit = res[1].intValue() * 1000; digits.add(new Integer(digit)); unscaledValue = res[0]; } else if (nBaseScaleRemainder == 2) { BigInteger[] res = unscaledValue.divideAndRemainder(HUNDRED); int digit = res[1].intValue() * 100; digits.add(new Integer(digit)); unscaledValue = res[0]; } else if (nBaseScaleRemainder == 3) { BigInteger[] res = unscaledValue.divideAndRemainder(THOUSAND); int digit = res[1].intValue() * 10; digits.add(new Integer(digit)); unscaledValue = res[0]; } while (!unscaledValue.equals(BigInteger.ZERO)) { BigInteger[] res = unscaledValue.divideAndRemainder(TEN_THOUSAND); digits.add(new Integer(res[1].intValue())); unscaledValue = res[0]; } dos.writeInt(8 + (2 * digits.size())); dos.writeShort(digits.size()); dos.writeShort(digits.size() - nBaseScale - 1); dos.writeShort(signum == 1 ? 0x0000 : 0x4000); dos.writeShort(scale); //StringBuffer log = new StringBuffer("Writing BigDecimal ") // .append(o.toString()) // .append(" as (digitCount = ") // .append(Integer.toString(digits.size())) // .append(", weight = ") // .append(Integer.toString(digits.size() - nBaseScale - 1)) // .append(", sign = ") // .append(Integer.toString(signum == 1 ? 0x0000 : 0x4000)) // .append(", dscale = ") // .append(Integer.toString(scale)) // .append(")"); for (int i = digits.size() - 1; i >= 0; i--) { int digit = digits.get(i).intValue(); dos.writeShort(digit); // log.append(" " + digit); } //LOG.error(log.toString()); } else { throw new IllegalArgumentException("Cannot store values of type " + o.getClass()); } } /** * {@inheritDoc} */ @Override protected int doIndirectionInserts(String name, IndirectionTableBatch table, List<FlushJob> batches) throws SQLException { if (!table.getRowsToInsert().isEmpty()) { try { CopyManager copyManager = null; if (con.isWrapperFor(PGConnection.class)) { copyManager = con.unwrap(PGConnection.class).getCopyAPI(); } if (copyManager == null) { LOG.warn("Database is incompatible with the PostgreSQL COPY command - falling" + " back to prepared statements"); super.doIndirectionInserts(name, table, batches); } else { PostgresByteArrayOutputStream baos = new PostgresByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeBytes("PGCOPY\n"); dos.writeByte(255); dos.writeBytes("\r\n"); dos.writeByte(0); // Signature done dos.writeInt(0); // Flags - we aren't supplying OIDS dos.writeInt(0); // Length of header extension for (Row row : table.getRowsToInsert()) { dos.writeShort(2); dos.writeInt(4); dos.writeInt(row.getLeft()); dos.writeInt(4); dos.writeInt(row.getRight()); } String sql = "COPY " + name + " (" + table.getLeftColName() + ", " + table.getRightColName() + ") FROM STDIN BINARY"; dos.writeShort(-1); dos.flush(); batches.add(new FlushJobPostgresCopyImpl(copyManager, sql, baos.getBuffer(), baos.size())); } } catch (IOException e) { throw new SQLException(e.toString()); } } return table.getRowsToInsert().size(); } /** * {@inheritDoc} */ @Override protected int getTableSize(String name, Connection conn) throws SQLException { Statement s = conn.createStatement(); ResultSet r = s.executeQuery("SELECT reltuples FROM pg_class WHERE relname = '" + name.toLowerCase() + "'"); if (r.next()) { int returnValue = (int) r.getFloat(1); if (r.next()) { throw new SQLException("Too many results for table " + name.toLowerCase()); } return returnValue; } else { throw new SQLException("No results"); } } }
tomck/intermine
intermine/objectstore/main/src/org/intermine/sql/writebatch/BatchWriterPostgresCopyImpl.java
Java
lgpl-2.1
11,352
<?php /*************************************************************************************/ /* */ /* Thelia */ /* */ /* Copyright (c) OpenStudio */ /* email : info@thelia.net */ /* web : http://www.thelia.net */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 3 of the License */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /*************************************************************************************/ $bootstrapToggle = false; $bootstraped = false; // Autoload bootstrap foreach ($argv as $arg) { if ($arg === '-b') { $bootstrapToggle = true; continue; } if ($bootstrapToggle) { require __DIR__ . DIRECTORY_SEPARATOR . $arg; $bootstraped = true; } } if (!$bootstraped) { if (isset($bootstrapFile)) { require $bootstrapFile; } elseif (is_file($file = __DIR__ . '/../core/vendor/autoload.php')) { require $file; } elseif (is_file($file = __DIR__ . '/../../bootstrap.php')) { // Here we are on a thelia/thelia-project require $file; } else { cliOutput('No autoload file found. Please use the -b argument to include yours', 'error'); exit(1); } } if (php_sapi_name() != 'cli') { cliOutput('this script can only be launched with cli sapi', 'error'); exit(1); } use Symfony\Component\Filesystem\Filesystem; use Symfony\Component\Finder\Finder; use Thelia\Install\Exception\UpdateException; /*************************************************** * Load Update class ***************************************************/ try { $update = new \Thelia\Install\Update(false); } catch (UpdateException $ex) { cliOutput($ex->getMessage(), 'error'); exit(2); } /*************************************************** * Check if update is needed ***************************************************/ if ($update->isLatestVersion()) { cliOutput("You already have the latest version of Thelia : " . $update->getCurrentVersion(), 'success'); exit(3); } $current = $update->getCurrentVersion(); $files = $update->getLatestVersion(); $web = $update->getWebVersion(); while (1) { if ($web !== null && $files != $web) { cliOutput(sprintf( "Thelia server is reporting the current stable release version is %s ", $web ), 'warning'); } cliOutput(sprintf( "You are going to update Thelia from version %s to version %s.", $current, $files ), 'info'); if ($web !== null && $files < $web) { cliOutput(sprintf( "Your files belongs to version %s, which is not the latest stable release.", $web ), 'warning'); cliOutput(sprintf( "It is recommended to upgrade your files first then run this script again." . PHP_EOL . "The latest version is available at http://thelia.net/#download ." ), 'warning'); cliOutput("Continue update process anyway ? (Y/n)"); } else { cliOutput("Continue update process ? (Y/n)"); } $rep = readStdin(true); if ($rep == 'y') { break; } elseif ($rep == 'n') { cliOutput("Update aborted", 'warning'); exit(0); } } $backup = false; while (1) { cliOutput(sprintf("Would you like to backup the current database before proceeding ? (Y/n)")); $rep = readStdin(true); if ($rep == 'y') { $backup = true; break; } elseif ($rep == 'n') { $backup = false; break; } } /*************************************************** * Update ***************************************************/ $updateError = null; try { // backup db if (true === $backup) { try { $update->backupDb(); cliOutput(sprintf('Your database has been backed up. The sql file : %s', $update->getBackupFile()), 'info'); } catch (\Exception $e) { cliOutput('Sorry, your database can\'t be backed up. Reason : ' . $e->getMessage(), 'error'); exit(4); } } // update $update->process($backup); } catch (UpdateException $ex) { $updateError = $ex; } foreach ($update->getMessages() as $message) { cliOutput($message[0], $message[1]); } if (null === $updateError) { cliOutput(sprintf('Thelia as been successfully updated to version %s', $update->getCurrentVersion()), 'success'); if ($update->hasPostInstructions()) { cliOutput('==================================='); cliOutput($update->getPostInstructions()); cliOutput('==================================='); } } else { cliOutput(sprintf('Sorry, an unexpected error has occured : %s', $updateError->getMessage()), 'error'); print $updateError->getTraceAsString() . PHP_EOL; print "Trace: " . PHP_EOL; foreach ($update->getLogs() as $log) { cliOutput(sprintf('[%s] %s' . PHP_EOL, $log[0], $log[1]), 'error'); } if (true === $backup) { while (1) { cliOutput("Would you like to restore the backup database ? (Y/n)"); $rep = readStdin(true); if ($rep == 'y') { cliOutput("Database restore started. Wait, it could take a while..."); if (false === $update->restoreDb()) { cliOutput(sprintf( 'Sorry, your database can\'t be restore. Try to do it manually : %s', $update->getBackupFile() ), 'error'); exit(5); } else { cliOutput("Database successfully restore."); exit(5); } break; } elseif ($rep == 'n') { exit(0); } } } } /*************************************************** * Try to delete cache ***************************************************/ $finder = new Finder(); $fs = new Filesystem(); $hasDeleteError = false; $finder->files()->in(THELIA_CACHE_DIR); cliOutput(sprintf("Try to delete cache in : %s", THELIA_CACHE_DIR), 'info'); foreach ($finder as $file) { try { $fs->remove($file); } catch (\Symfony\Component\Filesystem\Exception\IOException $ex) { $hasDeleteError = true; } } if (true === $hasDeleteError) { cliOutput("The cache has not been cleared properly. Try to run the command manually : " . "(sudo) php Thelia cache:clear (--env=prod)."); } cliOutput("Update process finished.", 'info'); exit(0); /*************************************************** * Utils ***************************************************/ function readStdin($normalize = false) { $fr = fopen("php://stdin", "r"); $input = fgets($fr, 128); $input = rtrim($input); fclose($fr); if ($normalize) { $input = strtolower(trim($input)); } return $input; } function joinPaths() { $args = func_get_args(); $paths = []; foreach ($args as $arg) { $paths[] = trim($arg, '/\\'); } $path = join(DIRECTORY_SEPARATOR, $paths); if (substr($args[0], 0, 1) === '/') { $path = DIRECTORY_SEPARATOR . $path; } return $path; } function cliOutput($message, $type = null) { switch ($type) { case 'success': $color = "\033[0;32m"; break; case 'info': $color = "\033[0;34m"; break; case 'error': $color = "\033[0;31m"; break; case 'warning': $color = "\033[1;33m"; break; default: $color = "\033[0m"; } echo PHP_EOL . $color . $message . "\033[0m" . PHP_EOL; }
vigourouxjulien/thelia
setup/update.php
PHP
lgpl-3.0
9,119
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.filesys.repo.rules.operations; import org.alfresco.filesys.repo.OpenFileMode; import org.alfresco.filesys.repo.rules.Operation; import org.alfresco.service.cmr.repository.NodeRef; /** * Open File Operation. * <p> * Open a file with the given name. */ public class OpenFileOperation implements Operation { private String name; private OpenFileMode mode; private boolean truncate = false; private String path; private NodeRef rootNode; /** * * @param name the name of the file to open * @param mode if true open the file in read/write * @param truncate boolean * @param rootNode root node * @param path the full path/name to open */ public OpenFileOperation(String name, OpenFileMode mode, boolean truncate, NodeRef rootNode, String path) { this.name = name; this.rootNode = rootNode; this.truncate = truncate; this.path = path; this.mode = mode; } public String getName() { return name; } public String getPath() { return path; } public NodeRef getRootNodeRef() { return rootNode; } public OpenFileMode getMode() { return mode; } public boolean isTruncate() { return truncate; } public String toString() { return "OpenFileOperation: " + name; } public int hashCode() { return name.hashCode(); } public boolean equals(Object o) { if(o instanceof OpenFileOperation) { OpenFileOperation c = (OpenFileOperation)o; if(name.equals(c.getName())) { return true; } } return false; } }
Tybion/community-edition
projects/repository/source/java/org/alfresco/filesys/repo/rules/operations/OpenFileOperation.java
Java
lgpl-3.0
2,566
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetVMGetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = true }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetVMGetMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); string instanceId = (string)ParseParameter(invokeMethodInputParameters[2]); if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName) && !string.IsNullOrEmpty(instanceId)) { var result = VirtualMachineScaleSetVMsClient.Get(resourceGroupName, vmScaleSetName, instanceId); WriteObject(result); } else if (!string.IsNullOrEmpty(resourceGroupName) && !string.IsNullOrEmpty(vmScaleSetName)) { var result = VirtualMachineScaleSetVMsClient.List(resourceGroupName, vmScaleSetName); WriteObject(result); } } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetVMGetParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; string instanceId = string.Empty; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceId" }, new object[] { resourceGroupName, vmScaleSetName, instanceId }); } } [Cmdlet("Get", "AzureRmVmssVM", DefaultParameterSetName = "InvokeByDynamicParameters")] public partial class GetAzureRmVmssVM : InvokeAzureComputeMethodCmdlet { public override string MethodName { get; set; } protected override void ProcessRecord() { if (this.ParameterSetName == "InvokeByDynamicParameters") { this.MethodName = "VirtualMachineScaleSetVMGet"; } else { this.MethodName = "VirtualMachineScaleSetVMGetInstanceView"; } base.ProcessRecord(); } public override object GetDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = false, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 1, Mandatory = false, ValueFromPipeline = false }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = false, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 2, Mandatory = false, ValueFromPipeline = false }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceId = new RuntimeDefinedParameter(); pInstanceId.Name = "InstanceId"; pInstanceId.ParameterType = typeof(string); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 3, Mandatory = false, ValueFromPipeline = false }); pInstanceId.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceId); var pInstanceView = new RuntimeDefinedParameter(); pInstanceView.Name = "InstanceView"; pInstanceView.ParameterType = typeof(SwitchParameter); pInstanceView.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParametersForFriendMethod", Position = 4, Mandatory = true }); pInstanceView.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParametersForFriendMethod", Position = 5, Mandatory = true }); pInstanceView.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceView", pInstanceView); return dynamicParameters; } } }
nemanja88/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Generated/VirtualMachineScaleSetVM/VirtualMachineScaleSetVMGetMethod.cs
C#
apache-2.0
9,368
/* The contents of this file are subject to the license and copyright terms * detailed in the license directory at the root of the source tree (also * available online at http://fedora-commons.org/license/). */ package org.fcrepo.server.utilities.status; public class ServerState { public static final ServerState NEW_SERVER = new ServerState("New Server"); public static final ServerState NOT_STARTING = new ServerState("Not Starting"); public static final ServerState STARTING = new ServerState("Starting"); public static final ServerState STARTED = new ServerState("Started"); public static final ServerState STARTUP_FAILED = new ServerState("Startup Failed"); public static final ServerState STOPPING = new ServerState("Stopping"); public static final ServerState STOPPED = new ServerState("Stopped"); public static final ServerState STOPPED_WITH_ERR = new ServerState("Stopped with error"); public static final ServerState[] STATES = new ServerState[] {NEW_SERVER, NOT_STARTING, STARTING, STARTED, STARTUP_FAILED, STOPPING, STOPPED, STOPPED_WITH_ERR}; private final String _name; private ServerState(String name) { _name = name; } public String getName() { return _name; } @Override public String toString() { return _name; } public static ServerState fromString(String name) throws Exception { for (ServerState element : STATES) { if (element.getName().equals(name)) { return element; } } throw new Exception("Unrecognized Server State: " + name); } }
andreasnef/fcrepo
fcrepo-server/src/main/java/org/fcrepo/server/utilities/status/ServerState.java
Java
apache-2.0
1,711
#include "cbase.h" #include "asw_weapon_hornet_barrage.h" #ifdef CLIENT_DLL #include "c_asw_player.h" #include "c_asw_marine.h" #include "c_asw_alien.h" #include "asw_input.h" #include "prediction.h" #else #include "asw_marine.h" #include "asw_player.h" #include "asw_alien.h" #include "particle_parse.h" #include "te_effect_dispatch.h" #include "asw_rocket.h" #include "asw_gamerules.h" #endif #include "asw_marine_skills.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" IMPLEMENT_NETWORKCLASS_ALIASED( ASW_Weapon_Hornet_Barrage, DT_ASW_Weapon_Hornet_Barrage ) BEGIN_NETWORK_TABLE( CASW_Weapon_Hornet_Barrage, DT_ASW_Weapon_Hornet_Barrage ) #ifdef CLIENT_DLL RecvPropFloat( RECVINFO( m_flNextLaunchTime ) ), RecvPropFloat( RECVINFO( m_flFireInterval ) ), RecvPropInt( RECVINFO( m_iRocketsToFire ) ), #else SendPropFloat( SENDINFO( m_flNextLaunchTime ) ), SendPropFloat( SENDINFO( m_flFireInterval ) ), SendPropInt( SENDINFO( m_iRocketsToFire ), 8 ), #endif END_NETWORK_TABLE() #ifdef CLIENT_DLL BEGIN_PREDICTION_DATA( CASW_Weapon_Hornet_Barrage ) DEFINE_PRED_FIELD_TOL( m_flNextLaunchTime, FIELD_FLOAT, FTYPEDESC_INSENDTABLE, TD_MSECTOLERANCE ), DEFINE_PRED_FIELD( m_iRocketsToFire, FIELD_INTEGER, FTYPEDESC_INSENDTABLE ), END_PREDICTION_DATA() #endif LINK_ENTITY_TO_CLASS( asw_weapon_hornet_barrage, CASW_Weapon_Hornet_Barrage ); PRECACHE_WEAPON_REGISTER( asw_weapon_hornet_barrage ); #ifndef CLIENT_DLL //--------------------------------------------------------- // Save/Restore //--------------------------------------------------------- BEGIN_DATADESC( CASW_Weapon_Hornet_Barrage ) END_DATADESC() #endif /* not client */ CASW_Weapon_Hornet_Barrage::CASW_Weapon_Hornet_Barrage() { } void CASW_Weapon_Hornet_Barrage::Precache() { BaseClass::Precache(); PrecacheScriptSound( "ASW_Hornet_Barrage.Fire" ); } bool CASW_Weapon_Hornet_Barrage::OffhandActivate() { if (!GetMarine() || GetMarine()->GetFlags() & FL_FROZEN) // don't allow this if the marine is frozen return false; PrimaryAttack(); return true; } void CASW_Weapon_Hornet_Barrage::PrimaryAttack() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return; CASW_Player *pPlayer = GetCommander(); if ( !pPlayer ) return; if ( m_iRocketsToFire.Get() > 0 ) return; #ifndef CLIENT_DLL bool bThisActive = (pMarine && pMarine->GetActiveWeapon() == this); #endif // mine weapon is lost when all mines are gone if ( UsesClipsForAmmo1() && !m_iClip1 ) { //Reload(); #ifndef CLIENT_DLL if (pMarine) { pMarine->Weapon_Detach(this); if (bThisActive) pMarine->SwitchToNextBestWeapon(NULL); } Kill(); #endif return; } SetRocketsToFire(); m_flFireInterval = GetRocketFireInterval(); m_flNextLaunchTime = gpGlobals->curtime; const char *pszSound = "ASW_Hornet_Barrage.Fire"; CPASAttenuationFilter filter( this, pszSound ); if ( IsPredicted() && CBaseEntity::GetPredictionPlayer() ) { filter.UsePredictionRules(); } EmitSound( filter, entindex(), pszSound ); // decrement ammo m_iClip1 -= 1; m_flNextPrimaryAttack = gpGlobals->curtime + GetFireRate(); } void CASW_Weapon_Hornet_Barrage::ItemPostFrame( void ) { BaseClass::ItemPostFrame(); if ( GetRocketsToFire() > 0 && GetNextLaunchTime() <= gpGlobals->curtime ) { FireRocket(); #ifndef CLIENT_DLL if ( GetRocketsToFire() <= 0 ) { DestroyIfEmpty( true ); } #endif } } void CASW_Weapon_Hornet_Barrage::SetRocketsToFire() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return; m_iRocketsToFire = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_HORNET_COUNT ); } float CASW_Weapon_Hornet_Barrage::GetRocketFireInterval() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return 0.5f; return MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_HORNET_INTERVAL ); } void CASW_Weapon_Hornet_Barrage::FireRocket() { CASW_Player *pPlayer = GetCommander(); CASW_Marine *pMarine = GetMarine(); if ( !pPlayer || !pMarine || pMarine->GetHealth() <= 0 ) { m_iRocketsToFire = 0; return; } WeaponSound(SINGLE); // tell the marine to tell its weapon to draw the muzzle flash pMarine->DoMuzzleFlash(); pMarine->DoAnimationEvent( PLAYERANIMEVENT_FIRE_GUN_PRIMARY ); Vector vecSrc = GetRocketFiringPosition(); m_iRocketsToFire = m_iRocketsToFire.Get() - 1; m_flNextLaunchTime = gpGlobals->curtime + m_flFireInterval.Get(); #ifndef CLIENT_DLL float fGrenadeDamage = MarineSkills()->GetSkillBasedValueByMarine(pMarine, ASW_MARINE_SKILL_GRENADES, ASW_MARINE_SUBSKILL_GRENADE_HORNET_DMG ); CASW_Rocket::Create( fGrenadeDamage, vecSrc, GetRocketAngle(), pMarine, this ); if ( ASWGameRules() ) { ASWGameRules()->m_fLastFireTime = gpGlobals->curtime; } pMarine->OnWeaponFired( this, 1 ); #endif } const QAngle& CASW_Weapon_Hornet_Barrage::GetRocketAngle() { static QAngle angRocket = vec3_angle; CASW_Player *pPlayer = GetCommander(); CASW_Marine *pMarine = GetMarine(); if ( !pPlayer || !pMarine || pMarine->GetHealth() <= 0 ) { return angRocket; } Vector vecDir = pPlayer->GetAutoaimVectorForMarine(pMarine, GetAutoAimAmount(), GetVerticalAdjustOnlyAutoAimAmount()); // 45 degrees = 0.707106781187 VectorAngles( vecDir, angRocket ); angRocket[ YAW ] += random->RandomFloat( -35, 35 ); return angRocket; } const Vector& CASW_Weapon_Hornet_Barrage::GetRocketFiringPosition() { CASW_Marine *pMarine = GetMarine(); if ( !pMarine ) return vec3_origin; static Vector vecSrc; vecSrc = pMarine->Weapon_ShootPosition(); return vecSrc; }
ppittle/AlienSwarmDirectorMod
trunk/src/game/shared/swarm/asw_weapon_hornet_barrage.cpp
C++
apache-2.0
5,658