repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
facebook/jest | examples/jquery/__tests__/fetch_current_user.test.js | 1353 | // Copyright 2004-present Facebook. All Rights Reserved.
jest.mock('jquery');
beforeEach(() => jest.resetModules());
it('calls into $.ajax with the correct params', () => {
const $ = require('jquery');
const fetchCurrentUser = require('../fetchCurrentUser');
// Call into the function we want to test
const dummyCallback = () => {};
fetchCurrentUser(dummyCallback);
// Now make sure that $.ajax was properly called during the previous
// 2 lines
expect($.ajax).toBeCalledWith({
success: expect.any(Function),
type: 'GET',
url: 'http://example.com/currentUser',
});
});
it('calls the callback when $.ajax requests are finished', () => {
const $ = require('jquery');
const fetchCurrentUser = require('../fetchCurrentUser');
// Create a mock function for our callback
const callback = jest.fn();
fetchCurrentUser(callback);
// Now we emulate the process by which `$.ajax` would execute its own
// callback
$.ajax.mock.calls[0 /*first call*/][0 /*first argument*/].success({
firstName: 'Bobby',
lastName: 'Marley',
});
// And finally we assert that this emulated call by `$.ajax` incurred a
// call back into the mock function we provided as a callback
expect(callback.mock.calls[0 /*first call*/][0 /*first arg*/]).toEqual({
fullName: 'Bobby Marley',
loggedIn: true,
});
});
| mit |
Bitcoinlover123/siliconcoin | src/qt/paymentserver.cpp | 4505 | // Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <QApplication>
#include "paymentserver.h"
#include "guiconstants.h"
#include "ui_interface.h"
#include "util.h"
#include <QByteArray>
#include <QDataStream>
#include <QDebug>
#include <QFileOpenEvent>
#include <QHash>
#include <QLocalServer>
#include <QLocalSocket>
#include <QStringList>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
using namespace boost;
const int BITCOIN_IPC_CONNECT_TIMEOUT = 1000; // milliseconds
const QString BITCOIN_IPC_PREFIX("darkcoin:");
//
// Create a name that is unique for:
// testnet / non-testnet
// data directory
//
static QString ipcServerName()
{
QString name("BitcoinQt");
// Append a simple hash of the datadir
// Note that GetDataDir(true) returns a different path
// for -testnet versus main net
QString ddir(GetDataDir(true).string().c_str());
name.append(QString::number(qHash(ddir)));
return name;
}
//
// This stores payment requests received before
// the main GUI window is up and ready to ask the user
// to send payment.
//
static QStringList savedPaymentRequests;
//
// Sending to the server is done synchronously, at startup.
// If the server isn't already running, startup continues,
// and the items in savedPaymentRequest will be handled
// when uiReady() is called.
//
bool PaymentServer::ipcSendCommandLine()
{
bool fResult = false;
const QStringList& args = qApp->arguments();
for (int i = 1; i < args.size(); i++)
{
if (!args[i].startsWith(BITCOIN_IPC_PREFIX, Qt::CaseInsensitive))
continue;
savedPaymentRequests.append(args[i]);
}
foreach (const QString& arg, savedPaymentRequests)
{
QLocalSocket* socket = new QLocalSocket();
socket->connectToServer(ipcServerName(), QIODevice::WriteOnly);
if (!socket->waitForConnected(BITCOIN_IPC_CONNECT_TIMEOUT))
return false;
QByteArray block;
QDataStream out(&block, QIODevice::WriteOnly);
out.setVersion(QDataStream::Qt_4_0);
out << arg;
out.device()->seek(0);
socket->write(block);
socket->flush();
socket->waitForBytesWritten(BITCOIN_IPC_CONNECT_TIMEOUT);
socket->disconnectFromServer();
delete socket;
fResult = true;
}
return fResult;
}
PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(true)
{
// Install global event filter to catch QFileOpenEvents on the mac (sent when you click bitcoin: links)
parent->installEventFilter(this);
QString name = ipcServerName();
// Clean up old socket leftover from a crash:
QLocalServer::removeServer(name);
uriServer = new QLocalServer(this);
if (!uriServer->listen(name))
qDebug() << tr("Cannot start darkcoin: click-to-pay handler");
else
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
}
bool PaymentServer::eventFilter(QObject *object, QEvent *event)
{
// clicking on bitcoin: URLs creates FileOpen events on the Mac:
if (event->type() == QEvent::FileOpen)
{
QFileOpenEvent* fileEvent = static_cast<QFileOpenEvent*>(event);
if (!fileEvent->url().isEmpty())
{
if (saveURIs) // Before main window is ready:
savedPaymentRequests.append(fileEvent->url().toString());
else
emit receivedURI(fileEvent->url().toString());
return true;
}
}
return false;
}
void PaymentServer::uiReady()
{
saveURIs = false;
foreach (const QString& s, savedPaymentRequests)
emit receivedURI(s);
savedPaymentRequests.clear();
}
void PaymentServer::handleURIConnection()
{
QLocalSocket *clientConnection = uriServer->nextPendingConnection();
while (clientConnection->bytesAvailable() < (int)sizeof(quint32))
clientConnection->waitForReadyRead();
connect(clientConnection, SIGNAL(disconnected()),
clientConnection, SLOT(deleteLater()));
QDataStream in(clientConnection);
in.setVersion(QDataStream::Qt_4_0);
if (clientConnection->bytesAvailable() < (int)sizeof(quint16)) {
return;
}
QString message;
in >> message;
if (saveURIs)
savedPaymentRequests.append(message);
else
emit receivedURI(message);
}
| mit |
BraveSirAndrew/duality | Source/Plugins/EditorBase/PropertyEditors/Components/RigidBodyShapePropertyEditor.cs | 1089 | using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using AdamsLair.WinForms.PropertyEditing;
using Duality;
using Duality.Components.Physics;
using Duality.Editor;
using Duality.Editor.UndoRedoActions;
namespace Duality.Editor.Plugins.Base.PropertyEditors
{
[PropertyEditorAssignment(typeof(ShapeInfo))]
public class RigidBodyShapePropertyEditor : MemberwisePropertyEditor
{
public RigidBodyShapePropertyEditor()
{
this.Hints &= ~HintFlags.HasButton;
this.Hints &= ~HintFlags.ButtonEnabled;
}
protected override void OnPropertySet(PropertyInfo property, IEnumerable<object> targets)
{
base.OnPropertySet(property, targets);
var shapes = targets.OfType<ShapeInfo>().ToArray();
UndoRedoManager.Do(new EditPropertyAction(this.ParentGrid, property, shapes, null));
var parentBodies = shapes.Select(c => c.Parent).NotNull().ToArray();
foreach (var body in parentBodies) body.AwakeBody();
UndoRedoManager.Do(new EditPropertyAction(this.ParentGrid, ReflectionInfo.Property_RigidBody_Shapes, parentBodies, null));
}
}
}
| mit |
madhuracj/error-reporting-server | vendor/cakephp/bake/tests/TestCase/Shell/Task/TemplateTaskArticlesTable.php | 831 | <?php
/**
* CakePHP : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP Project
* @since 0.1.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Bake\Test\TestCase\Shell\Task;
use Cake\ORM\Table;
/**
* Test Template Task Article Model
*/
class TemplateTaskArticlesTable extends Table
{
public function intialize(array $config)
{
$this->table('articles');
}
}
| mit |
mono/referencesource | System.Data.Entity/System/Data/Common/ShippingAssemblyAttributes.cs | 5038 | //---------------------------------------------------------------------
// <copyright file="ShippingAssemblyAttributes.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//
// @owner srimand
// @backupowner adoshi
//---------------------------------------------------------------------
// comment this line out to see dead code:
[assembly: System.Runtime.CompilerServices.InternalsVisibleTo("System.Data.Entity.Design,PublicKey=" + AssemblyRef.EcmaPublicKeyFull)]
[assembly: System.Security.SecurityCritical]
// Code Analysis Global Supressions
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Edm", Scope = "namespace", Target = "System.Data.Metadata.Edm")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix", MessageId = "T", Scope = "member", Target = "System.Data.Objects.ObjectQuery`1.#System.Linq.IQueryProvider.CreateQuery`1(System.Linq.Expressions.Expression)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1715:IdentifiersShouldHaveCorrectPrefix", MessageId = "T", Scope = "member", Target = "System.Data.Objects.ObjectQuery`1.#System.Linq.IQueryProvider.Execute`1(System.Linq.Expressions.Expression)")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1701:ResourceStringCompoundWordsShouldBeCasedCorrectly", MessageId = "readonly", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Deref", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Edm", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Multiset", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "Niladic", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "URIs", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "csdl", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "dddddddd-dddd-dddd-dddd-dddddddddddd", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "edm", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "inout", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "msl", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "multiset", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "promotable", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "ssdl", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "subquery", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "supertype", Scope = "resource", Target = "System.Data.Entity.resources")]
[assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1703:ResourceStringsShouldBeSpelledCorrectly", MessageId = "untyped", Scope = "resource", Target = "System.Data.Entity.resources")]
| mit |
dkostenko/angular-strap-rails | vendor/assets/javascripts/scrollspy/test/scrollspy.spec.js | 1727 | 'use strict';
// https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/test/tooltip.spec.js
describe('affix', function () {
var $compile, scope, sandboxEl;
// var mouse = effroi.mouse;
beforeEach(module('ngSanitize'));
beforeEach(module('mgcrea.ngStrap.scrollspy'));
beforeEach(inject(function (_$rootScope_, _$compile_) {
scope = _$rootScope_.$new();
$compile = _$compile_;
sandboxEl = $('<div>').attr('id', 'sandbox').appendTo('body');
}));
afterEach(function() {
sandboxEl.remove();
scope.$destroy();
});
// Templates
var templates = {
'default': {
element: '<ul>' +
' <li data-target="#modals" bs-scrollspy>' +
' <a href="#modals">Modal</a>' +
' </li>' +
'</ul>'
}
};
function compileDirective(template, locals) {
template = templates[template];
angular.extend(scope, template.scope, locals);
var element = $(template.element).appendTo(sandboxEl);
element = $compile(element)(scope);
scope.$digest();
return jQuery(element[0]);
}
// Tests
describe('default', function () {
it('should support window.scrollTo', function() {
var elm = compileDirective('default');
// var windowEl = angular.element(window);
// windowEl.on('scroll', function() {
// dump('scroll');
// });
// windowEl[0].scrollTo(0, 200);
// setTimeout(function() {
// mouse.scroll(0, 100);
// expect(windowEl[0].pageYOffset).toEqual(100);
// done();
// }, 1000);
// @bug karma does not suppport scrollTo
// github.com/karma-runner/karma/issues/345
expect(1).toBe(1);
});
});
});
| mit |
devs4v/devs4v-information-retrieval15 | project/lucene/pylucene-4.9.0-0/jcc/helpers/__init__.py | 18 | # helpers package
| mit |
ocadni/citychrone | node_modules/bootstrap-select/dist/js/i18n/defaults-ja_JP.js | 1380 | /*!
* Bootstrap-select v1.13.3 (https://developer.snapappointments.com/bootstrap-select)
*
* Copyright 2012-2018 SnapAppointments, LLC
* Licensed under MIT (https://github.com/snapappointments/bootstrap-select/blob/master/LICENSE)
*/
(function (root, factory) {
if (root === undefined && window !== undefined) root = window;
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define(["jquery"], function (a0) {
return (factory(a0));
});
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory(require("jquery"));
} else {
factory(root["jQuery"]);
}
}(this, function (jQuery) {
(function ($) {
$.fn.selectpicker.defaults = {
noneSelectedText: '何もが選択した',
noneResultsText: '\'{0}\'が結果を返さない',
countSelectedText: '{0}/{1}が選択した',
maxOptionsText: ['限界は達した({n}{var}最大)', '限界をグループは達した({n}{var}最大)', ['アイテム', 'アイテム']],
selectAllText: '全部を選択する',
deselectAllText: '何も選択しない',
multipleSeparator: ', '
};
})(jQuery);
}));
| mit |
gucong3000/stylelint | lib/rules/value-list-comma-space-before/index.js | 1285 | "use strict";
const ruleMessages = require("../../utils/ruleMessages");
const validateOptions = require("../../utils/validateOptions");
const valueListCommaWhitespaceChecker = require("../valueListCommaWhitespaceChecker");
const whitespaceChecker = require("../../utils/whitespaceChecker");
const ruleName = "value-list-comma-space-before";
const messages = ruleMessages(ruleName, {
expectedBefore: () => 'Expected single space before ","',
rejectedBefore: () => 'Unexpected whitespace before ","',
expectedBeforeSingleLine: () =>
'Unexpected whitespace before "," in a single-line list',
rejectedBeforeSingleLine: () =>
'Unexpected whitespace before "," in a single-line list'
});
const rule = function(expectation) {
const checker = whitespaceChecker("space", expectation, messages);
return (root, result) => {
const validOptions = validateOptions(result, ruleName, {
actual: expectation,
possible: ["always", "never", "always-single-line", "never-single-line"]
});
if (!validOptions) {
return;
}
valueListCommaWhitespaceChecker({
root,
result,
locationChecker: checker.before,
checkedRuleName: ruleName
});
};
};
rule.ruleName = ruleName;
rule.messages = messages;
module.exports = rule;
| mit |
mmithril/XChange | xchange-vaultoro/src/main/java/org/knowm/xchange/vaultoro/Vaultoro.java | 792 | package org.knowm.xchange.vaultoro;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.knowm.xchange.vaultoro.dto.marketdata.VaultoroOrderBookResponse;
import org.knowm.xchange.vaultoro.dto.marketdata.VaultoroTrade;
@Path("/")
@Produces(MediaType.APPLICATION_JSON)
public interface Vaultoro {
@GET
@Path("latest")
BigDecimal getLatest() throws IOException, VaultoroException;
@GET
@Path("orderbook")
VaultoroOrderBookResponse getVaultoroOrderBook() throws IOException, VaultoroException;
@GET
@Path("transactions/month")
List<VaultoroTrade> getVaultoroTrades(String time) throws IOException, VaultoroException;
}
| mit |
reigg/JavaMine | Lesson-02/SOLUTIONS/Solution-DebugThisUnitConversionFtToIn/src/unitconversionfttoin/UnitConversionFtToIn.java | 923 | /*
* DEBUG THIS! Exercise
*
* Learning to read & debug existing code is an important skill.
* Fix the errors in this program.
* Try not to re-write the program, just correct what's wrong.
*
* This program will convert an input value in Inches to Feet and Inches.
* There are 12 inches in a foot.
* The remainder are the leftover inches
* Examples: 15 inches = 1 foot 3 inches.
* 29 inches = 2 feet 5 inches.
*/
package unitconversionfttoin;
import java.util.Scanner;
public class UnitConversionFtToIn {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a value in inches : ");
int inputInches = input.nextInt();
int ft, in;
ft = inputInches / 12;
in = inputInches % 12;
System.out.printf("%d inches == %d feet %d inches\n"
, inputInches, ft, in);
}
}
| mit |
danisein/Wox | Plugins/Wox.Plugin.WebSearch/Settings.cs | 7148 | using System;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using Wox.Plugin.WebSearch.SuggestionSources;
namespace Wox.Plugin.WebSearch
{
public class Settings : BaseModel
{
public Settings()
{
SelectedSuggestion = Suggestions[0];
if (SearchSources.Count > 0)
{
SelectedSearchSource = SearchSources[0];
}
}
public ObservableCollection<SearchSource> SearchSources { get; set; } = new ObservableCollection<SearchSource>
{
new SearchSource
{
Title = "Google",
ActionKeyword = "g",
Icon = "google.png",
Url = "https://www.google.com/search?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Google Scholar",
ActionKeyword = "sc",
Icon = "google.png",
Url = "https://scholar.google.com/scholar?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Wikipedia",
ActionKeyword = "wiki",
Icon = "wiki.png",
Url = "https://en.wikipedia.org/wiki/{q}",
Enabled = true
},
new SearchSource
{
Title = "FindIcon",
ActionKeyword = "findicon",
Icon = "pictures.png",
Url = "http://findicons.com/search/{q}",
Enabled = true
},
new SearchSource
{
Title = "Facebook",
ActionKeyword = "facebook",
Icon = "facebook.png",
Url = "https://www.facebook.com/search/?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Twitter",
ActionKeyword = "twitter",
Icon = "twitter.png",
Url = "https://twitter.com/search?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Google Maps",
ActionKeyword = "maps",
Icon = "google_maps.png",
Url = "https://maps.google.com/maps?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Google Translate",
ActionKeyword = "translate",
Icon = "google_translate.png",
Url = "https://translate.google.com/#auto|en|{q}",
Enabled = true
},
new SearchSource
{
Title = "Duckduckgo",
ActionKeyword = "duckduckgo",
Icon = "duckduckgo.png",
Url = "https://duckduckgo.com/?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Github",
ActionKeyword = "github",
Icon = "github.png",
Url = "https://github.com/search?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Github Gist",
ActionKeyword = "gist",
Icon = "gist.png",
Url = "https://gist.github.com/search?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Gmail",
ActionKeyword = "gmail",
Icon = "gmail.png",
Url = "https://mail.google.com/mail/ca/u/0/#apps/{q}",
Enabled = true
},
new SearchSource
{
Title = "Google Drive",
ActionKeyword = "drive",
Icon = "google_drive.png",
Url = "https://drive.google.com/?hl=en&tab=bo#search/{q}",
Enabled = true
},
new SearchSource
{
Title = "Wolframalpha",
ActionKeyword = "wolframalpha",
Icon = "wolframalpha.png",
Url = "https://www.wolframalpha.com/input/?i={q}",
Enabled = true
},
new SearchSource
{
Title = "Stackoverflow",
ActionKeyword = "stackoverflow",
Icon = "stackoverflow.png",
Url = "https://stackoverflow.com/search?q={q}",
Enabled = true
},
new SearchSource
{
Title = "I'm Feeling Lucky",
ActionKeyword = "lucky",
Icon = "google.png",
Url = "https://google.com/search?q={q}&btnI=I",
Enabled = true
},
new SearchSource
{
Title = "Google Image",
ActionKeyword = "image",
Icon = "google.png",
Url = "https://www.google.com/search?q={q}&tbm=isch",
Enabled = true
},
new SearchSource
{
Title = "Youtube",
ActionKeyword = "youtube",
Icon = "youtube.png",
Url = "https://www.youtube.com/results?search_query={q}",
Enabled = true
},
new SearchSource
{
Title = "Bing",
ActionKeyword = "bing",
Icon = "bing.png",
Url = "https://www.bing.com/search?q={q}",
Enabled = true
},
new SearchSource
{
Title = "Yahoo",
ActionKeyword = "yahoo",
Icon = "yahoo.png",
Url = "https://www.search.yahoo.com/search?p={q}",
Enabled = true
},
new SearchSource
{
Title = "Baidu",
ActionKeyword = "bd",
Icon = "baidu.png",
Url = "https://www.baidu.com/#ie=UTF-8&wd={q}",
Enabled = true
}
};
[JsonIgnore]
public SearchSource SelectedSearchSource { get; set; }
public bool EnableSuggestion { get; set; }
[JsonIgnore]
public SuggestionSource[] Suggestions { get; set; } = {
new Google(),
new Baidu()
};
[JsonIgnore]
public SuggestionSource SelectedSuggestion { get; set; }
/// <summary>
/// used to store Settings.json only
/// </summary>
public string Suggestion
{
get { return SelectedSuggestion.ToString(); }
set
{
foreach (var s in Suggestions)
{
if (string.Equals(s.ToString(), value, StringComparison.OrdinalIgnoreCase))
{
SelectedSuggestion = s;
}
}
}
}
}
} | mit |
GistIcon/travis-core | lib/travis/api/v1/http/hooks.rb | 824 | module Travis
module Api
module V1
module Http
class Hooks
attr_reader :repos, :options
def initialize(repos, options = {})
@repos = repos
@options = options
end
def data
repos.map { |repo| repo_data(repo) }
end
private
def repo_data(repo)
{
'uid' => [repo.owner_name, repo.name].join(':'),
'url' => "https://github.com/#{repo.owner_name}/#{repo.name}",
'name' => repo.name,
'owner_name' => repo.owner_name,
'description' => repo.description,
'active' => repo.active,
'private' => repo.private
}
end
end
end
end
end
end
| mit |
TeamNovatek/Sylius | src/Sylius/Bundle/AddressingBundle/spec/Form/Type/CountryChoiceTypeSpec.php | 1089 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\Sylius\Bundle\AddressingBundle\Form\Type;
use PhpSpec\ObjectBehavior;
use Sylius\Component\Resource\Repository\RepositoryInterface;
use Symfony\Component\Form\AbstractType;
/**
* @author Jan Góralski <jan.goralski@lakion.com>
*/
final class CountryChoiceTypeSpec extends ObjectBehavior
{
function let(RepositoryInterface $repository)
{
$this->beConstructedWith($repository);
}
function it_is_initializable()
{
$this->shouldHaveType('Sylius\Bundle\AddressingBundle\Form\Type\CountryChoiceType');
}
function it_extends_abstract_type()
{
$this->shouldHaveType(AbstractType::class);
}
function it_has_parent_type()
{
$this->getParent()->shouldReturn('choice');
}
function it_has_name()
{
$this->getName()->shouldReturn('sylius_country_choice');
}
}
| mit |
leeran88/ghost-blog | node_modules/newrelic/lib/util/sql/obfuscate.js | 1897 | 'use strict'
module.exports = obfuscate
var singleQuote = /'(?:[^']|'')*?(?:\\'.*|'(?!'))/
var doubleQuote = /"(?:[^"]|"")*?(?:\\".*|"(?!"))/
var dollarQuote = /(\$(?!\d)[^$]*?\$).*?(?:\1|$)/
var oracleQuote = /q'\[.*?(?:\]'|$)|q'\{.*?(?:\}'|$)|q'\<.*?(?:\>'|$)|q'\(.*?(?:\)'|$)/
var comment = /(?:#|--).*?(?=\r|\n|$)/
var multilineComment = /\/\*(?:[^/]|\/[^*])*?(?:\*\/|\/\*.*)/
var uuid = /\{?(?:[0-9a-f]\-*){32}\}?/
var hex = /0x[0-9a-f]+/
var boolean = /true|false|null/
var number = /\b-?(?:[0-9]+\.)?[0-9]+([eE][+-]?[0-9]+)?/
var dialects = {}
dialects.mysql = [
replacer(join(
[doubleQuote, singleQuote, comment, multilineComment, hex, boolean, number],
'gi'
)),
unmatchedPairs(/'|"|\/\*|\*\//)
]
dialects.postgres = [
replacer(join(
[dollarQuote, singleQuote, comment, multilineComment, uuid, boolean, number],
'gi'
)),
unmatchedPairs(/'|\/\*|\*\/|\$/)
]
dialects.cassandra = [
replacer(join(
[singleQuote, comment, multilineComment, uuid, hex, boolean, number],
'gi'
)),
unmatchedPairs(/'|\/\*|\*\//)
]
dialects.oracle = [
replacer(join(
[oracleQuote, singleQuote, comment, multilineComment, number],
'gi'
)),
unmatchedPairs(/'|\/\*|\*\//)
]
function obfuscate(raw, dialect) {
if (!dialects[dialect]) throw new Error('Unknown sql implementation')
var replacers = dialects[dialect]
var obfuscated = raw
for (var i = 0, l = replacers.length; i < l; ++i) {
obfuscated = replacers[i](obfuscated)
}
return obfuscated
}
function join(expressions, flags) {
return new RegExp(expressions.map(toPart).join('|'), flags)
}
function toPart(expressions) {
return expressions.toString().slice(1, -1)
}
function replacer(regex) {
return function replace(sql) {
return sql.replace(regex, '?')
}
}
function unmatchedPairs(regex) {
return function check(sql) {
return regex.test(sql) ? '?' : sql
}
}
| mit |
dorant/home-assistant | homeassistant/components/device_tracker/netgear.py | 3242 | """
homeassistant.components.device_tracker.netgear
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Device tracker platform that supports scanning a Netgear router for device
presence.
Configuration:
To use the Netgear tracker you will need to add something like the following
to your configuration.yaml file.
device_tracker:
platform: netgear
host: YOUR_ROUTER_IP
username: YOUR_ADMIN_USERNAME
password: YOUR_ADMIN_PASSWORD
Variables:
host
*Required
The IP address of your router, e.g. 192.168.1.1.
username
*Required
The username of an user with administrative privileges, usually 'admin'.
password
*Required
The password for your given admin account.
"""
import logging
from datetime import timedelta
import threading
from homeassistant.const import CONF_HOST, CONF_USERNAME, CONF_PASSWORD
from homeassistant.util import Throttle
from homeassistant.components.device_tracker import DOMAIN
# Return cached results if last scan was less then this time ago
MIN_TIME_BETWEEN_SCANS = timedelta(seconds=5)
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pynetgear==0.3']
def get_scanner(hass, config):
""" Validates config and returns a Netgear scanner. """
info = config[DOMAIN]
host = info.get(CONF_HOST)
username = info.get(CONF_USERNAME)
password = info.get(CONF_PASSWORD)
if password is not None and host is None:
_LOGGER.warning('Found username or password but no host')
return None
scanner = NetgearDeviceScanner(host, username, password)
return scanner if scanner.success_init else None
class NetgearDeviceScanner(object):
""" This class queries a Netgear wireless router using the SOAP-API. """
def __init__(self, host, username, password):
import pynetgear
self.last_results = []
self.lock = threading.Lock()
if host is None:
self._api = pynetgear.Netgear()
elif username is None:
self._api = pynetgear.Netgear(password, host)
else:
self._api = pynetgear.Netgear(password, host, username)
_LOGGER.info("Logging in")
results = self._api.get_attached_devices()
self.success_init = results is not None
if self.success_init:
self.last_results = results
else:
_LOGGER.error("Failed to Login")
def scan_devices(self):
"""
Scans for new devices and return a list containing found device ids.
"""
self._update_info()
return (device.mac for device in self.last_results)
def get_device_name(self, mac):
""" Returns the name of the given device or None if we don't know. """
try:
return next(device.name for device in self.last_results
if device.mac == mac)
except StopIteration:
return None
@Throttle(MIN_TIME_BETWEEN_SCANS)
def _update_info(self):
"""
Retrieves latest information from the Netgear router.
Returns boolean if scanning successful.
"""
if not self.success_init:
return
with self.lock:
_LOGGER.info("Scanning")
self.last_results = self._api.get_attached_devices() or []
| mit |
partheinstein/bc-java | core/src/main/jdk1.1/org/bouncycastle/crypto/signers/RSADigestSigner.java | 6661 | package org.bouncycastle.crypto.signers;
import java.io.IOException;
import java.util.Hashtable;
import org.bouncycastle.asn1.ASN1Encoding;
import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.DERNull;
import org.bouncycastle.asn1.nist.NISTObjectIdentifiers;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.asn1.teletrust.TeleTrusTObjectIdentifiers;
import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.asn1.x509.DigestInfo;
import org.bouncycastle.asn1.x509.X509ObjectIdentifiers;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.CryptoException;
import org.bouncycastle.crypto.DataLengthException;
import org.bouncycastle.crypto.Digest;
import org.bouncycastle.crypto.Signer;
import org.bouncycastle.crypto.encodings.PKCS1Encoding;
import org.bouncycastle.crypto.engines.RSABlindedEngine;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import org.bouncycastle.util.Arrays;
public class RSADigestSigner
implements Signer
{
private final AsymmetricBlockCipher rsaEngine = new PKCS1Encoding(new RSABlindedEngine());
private AlgorithmIdentifier algId;
private Digest digest;
private boolean forSigning;
private static final Hashtable oidMap = new Hashtable();
/*
* Load OID table.
*/
static
{
oidMap.put("RIPEMD128", TeleTrusTObjectIdentifiers.ripemd128);
oidMap.put("RIPEMD160", TeleTrusTObjectIdentifiers.ripemd160);
oidMap.put("RIPEMD256", TeleTrusTObjectIdentifiers.ripemd256);
oidMap.put("SHA-1", X509ObjectIdentifiers.id_SHA1);
oidMap.put("SHA-224", NISTObjectIdentifiers.id_sha224);
oidMap.put("SHA-256", NISTObjectIdentifiers.id_sha256);
oidMap.put("SHA-384", NISTObjectIdentifiers.id_sha384);
oidMap.put("SHA-512", NISTObjectIdentifiers.id_sha512);
oidMap.put("MD2", PKCSObjectIdentifiers.md2);
oidMap.put("MD4", PKCSObjectIdentifiers.md4);
oidMap.put("MD5", PKCSObjectIdentifiers.md5);
}
public RSADigestSigner(
Digest digest)
{
this(digest, (ASN1ObjectIdentifier)oidMap.get(digest.getAlgorithmName()));
}
public RSADigestSigner(
Digest digest,
ASN1ObjectIdentifier digestOid)
{
this.digest = digest;
this.algId = new AlgorithmIdentifier(digestOid, DERNull.INSTANCE);
}
/**
* @deprecated
*/
public String getAlgorithmName()
{
return digest.getAlgorithmName() + "withRSA";
}
/**
* initialise the signer for signing or verification.
*
* @param forSigning
* true if for signing, false otherwise
* @param parameters
* necessary parameters.
*/
public void init(
boolean forSigning,
CipherParameters parameters)
{
this.forSigning = forSigning;
AsymmetricKeyParameter k;
if (parameters instanceof ParametersWithRandom)
{
k = (AsymmetricKeyParameter)((ParametersWithRandom)parameters).getParameters();
}
else
{
k = (AsymmetricKeyParameter)parameters;
}
if (forSigning && !k.isPrivate())
{
throw new IllegalArgumentException("signing requires private key");
}
if (!forSigning && k.isPrivate())
{
throw new IllegalArgumentException("verification requires public key");
}
reset();
rsaEngine.init(forSigning, parameters);
}
/**
* update the internal digest with the byte b
*/
public void update(
byte input)
{
digest.update(input);
}
/**
* update the internal digest with the byte array in
*/
public void update(
byte[] input,
int inOff,
int length)
{
digest.update(input, inOff, length);
}
/**
* Generate a signature for the message we've been loaded with using the key
* we were initialised with.
*/
public byte[] generateSignature()
throws CryptoException, DataLengthException
{
if (!forSigning)
{
throw new IllegalStateException("RSADigestSigner not initialised for signature generation.");
}
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
try
{
byte[] data = derEncode(hash);
return rsaEngine.processBlock(data, 0, data.length);
}
catch (IOException e)
{
throw new CryptoException("unable to encode signature: " + e.getMessage(), e);
}
}
/**
* return true if the internal state represents the signature described in
* the passed in array.
*/
public boolean verifySignature(
byte[] signature)
{
if (forSigning)
{
throw new IllegalStateException("RSADigestSigner not initialised for verification");
}
byte[] hash = new byte[digest.getDigestSize()];
digest.doFinal(hash, 0);
byte[] sig;
byte[] expected;
try
{
sig = rsaEngine.processBlock(signature, 0, signature.length);
expected = derEncode(hash);
}
catch (Exception e)
{
return false;
}
if (sig.length == expected.length)
{
return Arrays.constantTimeAreEqual(sig, expected);
}
else if (sig.length == expected.length - 2) // NULL left out
{
int sigOffset = sig.length - hash.length - 2;
int expectedOffset = expected.length - hash.length - 2;
expected[1] -= 2; // adjust lengths
expected[3] -= 2;
int nonEqual = 0;
for (int i = 0; i < hash.length; i++)
{
nonEqual |= (sig[sigOffset + i] ^ expected[expectedOffset + i]);
}
for (int i = 0; i < sigOffset; i++)
{
nonEqual |= (sig[i] ^ expected[i]); // check header less NULL
}
return nonEqual == 0;
}
else
{
return false;
}
}
public void reset()
{
digest.reset();
}
private byte[] derEncode(
byte[] hash)
throws IOException
{
DigestInfo dInfo = new DigestInfo(algId, hash);
return dInfo.getEncoded(ASN1Encoding.DER);
}
}
| mit |
DJBuro/Telerik | JSOOP/JavaScript-OOP-master/09. ECMAScript 6/08. modules/otherApp.js | 70 | import { sum, pi } from "lib/math"
console.log("2? = " + sum(pi, pi)) | mit |
jackygrahamez/LineSocialPublic | node_modules/grunt-protractor-runner/test/failedTest.js | 147 |
describe('Failed test', function() {
ptor = protractor.getInstance();
it('should failed', function() {
expect(1).toEqual(0);
});
});
| mit |
jabley/rubyspec | core/float/divmod_spec.rb | 1531 | require File.expand_path('../../../spec_helper', __FILE__)
describe "Float#divmod" do
it "returns an [quotient, modulus] from dividing self by other" do
values = 3.14.divmod(2)
values[0].should == 1
values[1].should be_close(1.14, TOLERANCE)
values = 2.8284.divmod(3.1415)
values[0].should == 0
values[1].should be_close(2.8284, TOLERANCE)
values = -1.0.divmod(bignum_value)
values[0].should == -1
values[1].should be_close(9223372036854775808.000, TOLERANCE)
end
# Behaviour established as correct in r23953
it "raises a FloatDomainError if self is NaN" do
lambda { nan_value.divmod(1) }.should raise_error(FloatDomainError)
end
# Behaviour established as correct in r23953
it "raises a FloatDomainError if other is NaN" do
lambda { 1.divmod(nan_value) }.should raise_error(FloatDomainError)
end
# Behaviour established as correct in r23953
it "raises a FloatDomainError if self is Infinity" do
lambda { infinity_value.divmod(1) }.should raise_error(FloatDomainError)
end
ruby_version_is ""..."1.9" do
it "raises FloatDomainError if other is zero" do
lambda { 1.0.divmod(0) }.should raise_error(FloatDomainError)
lambda { 1.0.divmod(0.0) }.should raise_error(FloatDomainError)
end
end
ruby_version_is "1.9" do
it "raises a ZeroDivisionError if other is zero" do
lambda { 1.0.divmod(0) }.should raise_error(ZeroDivisionError)
lambda { 1.0.divmod(0.0) }.should raise_error(ZeroDivisionError)
end
end
end
| mit |
pilor/azure-sdk-for-net | src/SDKs/NotificationHubs/Management.NotificationHubs/Generated/INotificationHubsOperations.cs | 20972 | // <auto-generated>
// 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.
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
// </auto-generated>
namespace Microsoft.Azure.Management.NotificationHubs
{
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// NotificationHubsOperations operations.
/// </summary>
public partial interface INotificationHubsOperations
{
/// <summary>
/// Checks the availability of the given notificationHub in a
/// namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='parameters'>
/// The notificationHub name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<CheckAvailabilityResult>> CheckNotificationHubAvailabilityWithHttpMessagesAsync(string resourceGroupName, string namespaceName, CheckAvailabilityParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates/Update a NotificationHub in a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to the create/update a NotificationHub
/// Resource.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NotificationHubResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, NotificationHubCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a notification hub associated with a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<NotificationHubResource>> GetWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates/Updates an authorization rule for a NotificationHub
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
/// <param name='parameters'>
/// The shared access authorization rule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> CreateOrUpdateAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, SharedAccessAuthorizationRuleCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes a notificationHub authorization rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// Authorization Rule Name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets an authorization rule for a NotificationHub by name.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// authorization rule name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<SharedAccessAuthorizationRuleResource>> GetAuthorizationRuleWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NotificationHubResource>>> ListWithHttpMessagesAsync(string resourceGroupName, string namespaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the authorization rules for a NotificationHub.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the Primary and Secondary ConnectionStrings to the
/// NotificationHub
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the NotificationHub for the specified
/// authorizationRule.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ResourceListKeys>> ListKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Regenerates the Primary/Secondary Keys to the NotificationHub
/// Authorization Rule
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='authorizationRuleName'>
/// The connection string of the NotificationHub for the specified
/// authorizationRule.
/// </param>
/// <param name='parameters'>
/// Parameters supplied to regenerate the NotificationHub Authorization
/// Rule Key.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<ResourceListKeys>> RegenerateKeysWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, string authorizationRuleName, PolicykeyResource parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the PNS Credentials associated with a notification hub .
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='namespaceName'>
/// The namespace name.
/// </param>
/// <param name='notificationHubName'>
/// The notification hub name.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<PnsCredentialsResource>> GetPnsCredentialsWithHttpMessagesAsync(string resourceGroupName, string namespaceName, string notificationHubName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists the notification hubs associated with a namespace.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<NotificationHubResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the authorization rules for a NotificationHub.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="Microsoft.Rest.Azure.CloudException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<SharedAccessAuthorizationRuleResource>>> ListAuthorizationRulesNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| mit |
digitalplaywright/eak-simple-auth | config/environment.js | 285 | // Put general configuration here. This file is included
// in both production and development BEFORE Ember is
// loaded.
//
// For example to enable a feature on a canary build you
// might do:
//
// window.ENV = {FEATURES: {'with-controller': true}};
window.ENV = window.ENV || {};
| mit |
gscales/ews-managed-api | Autodiscover/ComparisonHelpers.cs | 2384 | /*
* Exchange Web Services Managed API
*
* Copyright (c) Microsoft Corporation
* All rights reserved.
*
* MIT License
*
* 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 Microsoft.Exchange.WebServices.Autodiscover
{
using System;
using System.Collections;
/// <summary>
/// Represents a set of helper methods for performing string comparisons.
/// </summary>
internal static class ComparisonHelpers
{
/// <summary>
/// Case insensitive check if the collection contains the string.
/// </summary>
/// <param name="collection">The collection of objects, only strings are checked</param>
/// <param name="match">String to match</param>
/// <returns>true, if match contained in the collection</returns>
internal static bool CaseInsensitiveContains(this ICollection collection, string match)
{
foreach (object obj in collection)
{
string str = obj as string;
if (str != null)
{
if (string.Compare(str, match, StringComparison.OrdinalIgnoreCase) == 0)
{
return true;
}
}
}
return false;
}
}
} | mit |
olegmack/oro-academic | src/Oro/Bundle/IssueBundle/OroIssueBundle.php | 131 | <?php
namespace Oro\Bundle\IssueBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class OroIssueBundle extends Bundle
{
}
| mit |
NateWardawg/godot | editor/editor_plugin_settings.cpp | 8838 | /*************************************************************************/
/* editor_plugin_settings.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "editor_plugin_settings.h"
#include "core/io/config_file.h"
#include "core/os/file_access.h"
#include "core/os/main_loop.h"
#include "core/project_settings.h"
#include "editor_node.h"
#include "scene/gui/margin_container.h"
void EditorPluginSettings::_notification(int p_what) {
if (p_what == MainLoop::NOTIFICATION_WM_FOCUS_IN) {
update_plugins();
} else if (p_what == Node::NOTIFICATION_READY) {
plugin_config_dialog->connect("plugin_ready", EditorNode::get_singleton(), "_on_plugin_ready");
plugin_list->connect("button_pressed", this, "_cell_button_pressed");
}
}
void EditorPluginSettings::update_plugins() {
plugin_list->clear();
DirAccess *da = DirAccess::create(DirAccess::ACCESS_RESOURCES);
Error err = da->change_dir("res://addons");
if (err != OK) {
memdelete(da);
return;
}
updating = true;
TreeItem *root = plugin_list->create_item();
da->list_dir_begin();
String d = da->get_next();
Vector<String> plugins;
while (d != String()) {
bool dir = da->current_is_dir();
String path = "res://addons/" + d + "/plugin.cfg";
if (dir && FileAccess::exists(path)) {
plugins.push_back(d);
}
d = da->get_next();
}
da->list_dir_end();
memdelete(da);
plugins.sort();
for (int i = 0; i < plugins.size(); i++) {
Ref<ConfigFile> cf;
cf.instance();
String path = "res://addons/" + plugins[i] + "/plugin.cfg";
Error err = cf->load(path);
if (err != OK) {
WARN_PRINTS("Can't load plugin config: " + path);
} else if (!cf->has_section_key("plugin", "name")) {
WARN_PRINTS("Plugin misses plugin/name: " + path);
} else if (!cf->has_section_key("plugin", "author")) {
WARN_PRINTS("Plugin misses plugin/author: " + path);
} else if (!cf->has_section_key("plugin", "version")) {
WARN_PRINTS("Plugin misses plugin/version: " + path);
} else if (!cf->has_section_key("plugin", "description")) {
WARN_PRINTS("Plugin misses plugin/description: " + path);
} else if (!cf->has_section_key("plugin", "script")) {
WARN_PRINTS("Plugin misses plugin/script: " + path);
} else {
String d = plugins[i];
String name = cf->get_value("plugin", "name");
String author = cf->get_value("plugin", "author");
String version = cf->get_value("plugin", "version");
String description = cf->get_value("plugin", "description");
String script = cf->get_value("plugin", "script");
TreeItem *item = plugin_list->create_item(root);
item->set_text(0, name);
item->set_tooltip(0, "Name: " + name + "\nPath: " + path + "\nMain Script: " + script + "\nDescription: " + description);
item->set_metadata(0, d);
item->set_text(1, version);
item->set_metadata(1, script);
item->set_text(2, author);
item->set_metadata(2, description);
item->set_cell_mode(3, TreeItem::CELL_MODE_RANGE);
item->set_range_config(3, 0, 1, 1);
item->set_text(3, "Inactive,Active");
item->set_editable(3, true);
item->add_button(4, get_icon("Edit", "EditorIcons"), BUTTON_PLUGIN_EDIT, false, TTR("Edit Plugin"));
if (EditorNode::get_singleton()->is_addon_plugin_enabled(d)) {
item->set_custom_color(3, get_color("success_color", "Editor"));
item->set_range(3, 1);
} else {
item->set_custom_color(3, get_color("disabled_font_color", "Editor"));
item->set_range(3, 0);
}
}
}
updating = false;
}
void EditorPluginSettings::_plugin_activity_changed() {
if (updating)
return;
TreeItem *ti = plugin_list->get_edited();
ERR_FAIL_COND(!ti);
bool active = ti->get_range(3);
String name = ti->get_metadata(0);
EditorNode::get_singleton()->set_addon_plugin_enabled(name, active);
bool is_active = EditorNode::get_singleton()->is_addon_plugin_enabled(name);
if (is_active != active) {
updating = true;
ti->set_range(3, is_active ? 1 : 0);
updating = false;
}
if (is_active)
ti->set_custom_color(3, get_color("success_color", "Editor"));
else
ti->set_custom_color(3, get_color("disabled_font_color", "Editor"));
}
void EditorPluginSettings::_create_clicked() {
plugin_config_dialog->config("");
plugin_config_dialog->popup_centered();
}
void EditorPluginSettings::_cell_button_pressed(Object *p_item, int p_column, int p_id) {
TreeItem *item = Object::cast_to<TreeItem>(p_item);
if (!item)
return;
if (p_id == BUTTON_PLUGIN_EDIT) {
if (p_column == 4) {
String dir = item->get_metadata(0);
plugin_config_dialog->config("res://addons/" + dir + "/plugin.cfg");
plugin_config_dialog->popup_centered();
}
}
}
void EditorPluginSettings::_bind_methods() {
ClassDB::bind_method("update_plugins", &EditorPluginSettings::update_plugins);
ClassDB::bind_method("_create_clicked", &EditorPluginSettings::_create_clicked);
ClassDB::bind_method("_plugin_activity_changed", &EditorPluginSettings::_plugin_activity_changed);
ClassDB::bind_method("_cell_button_pressed", &EditorPluginSettings::_cell_button_pressed);
}
EditorPluginSettings::EditorPluginSettings() {
plugin_config_dialog = memnew(PluginConfigDialog);
plugin_config_dialog->config("");
add_child(plugin_config_dialog);
HBoxContainer *title_hb = memnew(HBoxContainer);
title_hb->add_child(memnew(Label(TTR("Installed Plugins:"))));
title_hb->add_spacer();
create_plugin = memnew(Button(TTR("Create")));
create_plugin->connect("pressed", this, "_create_clicked");
title_hb->add_child(create_plugin);
update_list = memnew(Button(TTR("Update")));
update_list->connect("pressed", this, "update_plugins");
title_hb->add_child(update_list);
add_child(title_hb);
plugin_list = memnew(Tree);
plugin_list->set_v_size_flags(SIZE_EXPAND_FILL);
plugin_list->set_columns(5);
plugin_list->set_column_titles_visible(true);
plugin_list->set_column_title(0, TTR("Name:"));
plugin_list->set_column_title(1, TTR("Version:"));
plugin_list->set_column_title(2, TTR("Author:"));
plugin_list->set_column_title(3, TTR("Status:"));
plugin_list->set_column_title(4, TTR("Edit:"));
plugin_list->set_column_expand(0, true);
plugin_list->set_column_expand(1, false);
plugin_list->set_column_expand(2, false);
plugin_list->set_column_expand(3, false);
plugin_list->set_column_expand(4, false);
plugin_list->set_column_min_width(1, 100 * EDSCALE);
plugin_list->set_column_min_width(2, 250 * EDSCALE);
plugin_list->set_column_min_width(3, 80 * EDSCALE);
plugin_list->set_column_min_width(4, 40 * EDSCALE);
plugin_list->set_hide_root(true);
plugin_list->connect("item_edited", this, "_plugin_activity_changed");
VBoxContainer *mc = memnew(VBoxContainer);
mc->add_child(plugin_list);
mc->set_v_size_flags(SIZE_EXPAND_FILL);
mc->set_h_size_flags(SIZE_EXPAND_FILL);
add_child(mc);
updating = false;
}
| mit |
leonampd/DesignPatternsPHP | Behavioral/Visitor/Tests/VisitorTest.php | 768 | <?php
namespace DesignPatterns\Tests\Visitor\Tests;
use DesignPatterns\Behavioral\Visitor;
use PHPUnit\Framework\TestCase;
class VisitorTest extends TestCase
{
/**
* @var Visitor\RoleVisitor
*/
private $visitor;
protected function setUp()
{
$this->visitor = new Visitor\RoleVisitor();
}
public function provideRoles()
{
return [
[new Visitor\User('Dominik')],
[new Visitor\Group('Administrators')],
];
}
/**
* @dataProvider provideRoles
*
* @param Visitor\Role $role
*/
public function testVisitSomeRole(Visitor\Role $role)
{
$role->accept($this->visitor);
$this->assertSame($role, $this->visitor->getVisited()[0]);
}
}
| mit |
Myster/Umbraco-CMS | src/Umbraco.Web/umbraco.presentation/umbraco/developer/Packages/SubmitPackage.aspx.cs | 6355 | using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
namespace umbraco.presentation.developer.packages {
public partial class SubmitPackage : BasePages.UmbracoEnsuredPage {
public SubmitPackage()
{
CurrentApp = BusinessLogic.DefaultApps.developer.ToString();
}
private cms.businesslogic.packager.PackageInstance pack;
private cms.businesslogic.packager.CreatedPackage createdPackage;
protected void Page_Load(object sender, EventArgs e) {
if(!String.IsNullOrEmpty(helper.Request("id"))){
if (!IsPostBack) {
dd_repositories.Items.Clear();
dd_repositories.Items.Add(new ListItem("Choose a repository...", ""));
List<cms.businesslogic.packager.repositories.Repository> repos = cms.businesslogic.packager.repositories.Repository.getAll();
if (repos.Count == 1) {
ListItem li = new ListItem(repos[0].Name, repos[0].Guid);
li.Selected = true;
dd_repositories.Items.Add(li);
pl_repoChoose.Visible = false;
pl_repoLogin.Style.Clear();
privateRepoHelp.Visible = false;
publicRepoHelp.Style.Clear();
} else if (repos.Count == 0) {
Response.Redirect("editpackage.aspx?id=" + helper.Request("id"));
} else {
foreach (cms.businesslogic.packager.repositories.Repository repo in repos) {
dd_repositories.Items.Add(new ListItem(repo.Name, repo.Guid));
}
dd_repositories.Items[0].Selected = true;
dd_repositories.Attributes.Add("onChange", "onRepoChange()");
}
}
createdPackage = cms.businesslogic.packager.CreatedPackage.GetById(int.Parse(helper.Request("id")));
pack = createdPackage.Data;
if (pack.Url != "") {
Panel1.Text = "Submit '" + pack.Name + "' to a repository";
}
}
}
protected void submitPackage(object sender, EventArgs e) {
Page.Validate();
string feedback = "";
if (Page.IsValid) {
try {
cms.businesslogic.packager.repositories.Repository repo = cms.businesslogic.packager.repositories.Repository.getByGuid(dd_repositories.SelectedValue);
string memberKey = repo.Webservice.authenticate(tb_email.Text, library.md5(tb_password.Text));
byte[] doc = new byte[0];
if (fu_doc.HasFile)
doc = fu_doc.FileBytes;
if (memberKey != "") {
string result = repo.SubmitPackage(memberKey, pack, doc).ToString().ToLower();
switch (result) {
case "complete":
feedback = "Your package has been submitted successfully. It will be reviewed by the package repository administrator before it's publicly available";
fb_feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.success;
break;
case "error":
feedback = "There was a general error submitting your package to the repository. This can be due to general communitations error or too much traffic. Please try again later";
fb_feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error;
break;
case "exists":
feedback = "This package has already been submitted to the repository. You cannot submit it again. If you have updates for a package, you should contact the repositor administrator to submit an update";
fb_feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error;
break;
case "noaccess":
feedback = "Authentication failed, You do not have access to this repository. Contact your package repository administrator";
fb_feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error;
break;
default:
break;
}
if (result == "complete") {
Pane1.Visible = false;
Pane2.Visible = false;
submitControls.Visible = false;
feedbackControls.Visible = true;
} else {
Pane1.Visible = true;
Pane2.Visible = true;
submitControls.Visible = true;
feedbackControls.Visible = false;
}
} else {
feedback = "Authentication failed, You do not have access to this repository. Contact your package repository administrator";
fb_feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error;
}
} catch {
feedback = "Authentication failed, or the repository is currently off-line. Contact your package repository administrator";
fb_feedback.type = global::umbraco.uicontrols.Feedback.feedbacktype.error;
}
fb_feedback.Text = feedback;
}
}
}
}
| mit |
BlueDress/School | C# MVC Frameworks - ASP.NET Core/News System/NewsSystem.Web/wwwroot/lib/fontawesome/advanced-options/use-with-node-js/free-solid-svg-icons/faColumns.js | 789 | 'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var prefix = 'fas';
var iconName = 'columns';
var width = 512;
var height = 512;
var ligatures = [];
var unicode = 'f0db';
var svgPathData = 'M464 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h416c26.51 0 48-21.49 48-48V80c0-26.51-21.49-48-48-48zM224 416H64V160h160v256zm224 0H288V160h160v256z';
exports.definition = {
prefix: prefix,
iconName: iconName,
icon: [
width,
height,
ligatures,
unicode,
svgPathData
]};
exports.faColumns = exports.definition;
exports.prefix = prefix;
exports.iconName = iconName;
exports.width = width;
exports.height = height;
exports.ligatures = ligatures;
exports.unicode = unicode;
exports.svgPathData = svgPathData; | mit |
vaikan/kanboard | app/Controller/TaskFileController.php | 2830 | <?php
namespace Kanboard\Controller;
/**
* Task File Controller
*
* @package Kanboard\Controller
* @author Frederic Guillot
*/
class TaskFileController extends BaseController
{
/**
* Screenshot
*
* @access public
*/
public function screenshot()
{
$task = $this->getTask();
if ($this->request->isPost() && $this->taskFileModel->uploadScreenshot($task['id'], $this->request->getValue('screenshot')) !== false) {
$this->flash->success(t('Screenshot uploaded successfully.'));
return $this->response->redirect($this->helper->url->to('TaskViewController', 'show', array('task_id' => $task['id'], 'project_id' => $task['project_id'])), true);
}
return $this->response->html($this->template->render('task_file/screenshot', array(
'task' => $task,
)));
}
/**
* File upload form
*
* @access public
*/
public function create()
{
$task = $this->getTask();
$this->response->html($this->template->render('task_file/create', array(
'task' => $task,
'max_size' => $this->helper->text->phpToBytes(ini_get('upload_max_filesize')),
)));
}
/**
* File upload (save files)
*
* @access public
*/
public function save()
{
$task = $this->getTask();
if (! $this->taskFileModel->uploadFiles($task['id'], $this->request->getFileInfo('files'))) {
$this->flash->failure(t('Unable to upload the file.'));
}
$this->response->redirect($this->helper->url->to('TaskViewController', 'show', array('task_id' => $task['id'], 'project_id' => $task['project_id'])), true);
}
/**
* Remove a file
*
* @access public
*/
public function remove()
{
$this->checkCSRFParam();
$task = $this->getTask();
$file = $this->taskFileModel->getById($this->request->getIntegerParam('file_id'));
if ($file['task_id'] == $task['id'] && $this->taskFileModel->remove($file['id'])) {
$this->flash->success(t('File removed successfully.'));
} else {
$this->flash->failure(t('Unable to remove this file.'));
}
$this->response->redirect($this->helper->url->to('TaskViewController', 'show', array('task_id' => $task['id'], 'project_id' => $task['project_id'])));
}
/**
* Confirmation dialog before removing a file
*
* @access public
*/
public function confirm()
{
$task = $this->getTask();
$file = $this->taskFileModel->getById($this->request->getIntegerParam('file_id'));
$this->response->html($this->template->render('task_file/remove', array(
'task' => $task,
'file' => $file,
)));
}
}
| mit |
groenewold-pythian/gh-ost | vendor/github.com/siddontang/go-mysql/replication/parser_test.go | 7493 | package replication
import (
. "gopkg.in/check.v1"
)
func (t *testSyncerSuite) TestIndexOutOfRange(c *C) {
parser := NewBinlogParser()
parser.format = &FormatDescriptionEvent{
Version: 0x4,
ServerVersion: []uint8{0x35, 0x2e, 0x36, 0x2e, 0x32, 0x30, 0x2d, 0x6c, 0x6f, 0x67, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0},
CreateTimestamp: 0x0,
EventHeaderLength: 0x13,
EventTypeHeaderLengths: []uint8{0x38, 0xd, 0x0, 0x8, 0x0, 0x12, 0x0, 0x4, 0x4, 0x4, 0x4, 0x12, 0x0, 0x0, 0x5c, 0x0, 0x4, 0x1a, 0x8, 0x0, 0x0, 0x0, 0x8, 0x8, 0x8, 0x2, 0x0, 0x0, 0x0, 0xa, 0xa, 0xa, 0x19, 0x19, 0x0},
ChecksumAlgorithm: 0x1,
}
parser.tables = map[uint64]*TableMapEvent{
0x3043b: &TableMapEvent{tableIDSize: 6, TableID: 0x3043b, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x61, 0x70, 0x70, 0x5f, 0x63, 0x72, 0x6f, 0x6e}, ColumnCount: 0x15, ColumnType: []uint8{0x3, 0xf, 0xc, 0xc, 0xf, 0x3, 0xc, 0x3, 0xfc, 0xf, 0x1, 0xfe, 0x2, 0xc, 0xf, 0xf, 0xc, 0xf, 0xf, 0x3, 0xf}, ColumnMeta: []uint16{0x0, 0x180, 0x0, 0x0, 0x2fd, 0x0, 0x0, 0x0, 0x2, 0x180, 0x0, 0xfe78, 0x0, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x0, 0x2fd}, NullBitmap: []uint8{0xf8, 0xfb, 0x17}},
0x30453: &TableMapEvent{tableIDSize: 6, TableID: 0x30453, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x73, 0x74, 0x67, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x75, 0x70}, ColumnCount: 0x36, ColumnType: []uint8{0x3, 0x3, 0x3, 0x3, 0x3, 0xf, 0xf, 0x8, 0x3, 0x3, 0x3, 0xf, 0xf, 0x1, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xfe, 0x12, 0xf, 0xf, 0xf, 0xf6, 0x1, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xfe, 0xf6, 0x12, 0x3, 0xf, 0xf, 0x1, 0x1, 0x12, 0xf, 0xf, 0xf, 0xf, 0x3, 0xf, 0x3}, ColumnMeta: []uint16{0x0, 0x0, 0x0, 0x0, 0x0, 0x2fd, 0x12c, 0x0, 0x0, 0x0, 0x0, 0x180, 0x180, 0x0, 0x30, 0x180, 0x180, 0x180, 0x30, 0xc0, 0xfe03, 0x0, 0x180, 0x180, 0x180, 0xc02, 0x0, 0x5a, 0x5a, 0x5a, 0x5a, 0x2fd, 0x2fd, 0x2fd, 0xc0, 0x12c, 0x30, 0xc, 0xfe06, 0xb02, 0x0, 0x0, 0x180, 0x180, 0x0, 0x0, 0x0, 0x180, 0x180, 0x2d, 0x2fd, 0x0, 0x2fd, 0x0}, NullBitmap: []uint8{0xee, 0xdf, 0xff, 0xff, 0xff, 0xff, 0x17}},
0x30504: &TableMapEvent{tableIDSize: 6, TableID: 0x30504, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x6c, 0x6f, 0x67, 0x5f, 0x73, 0x74, 0x67, 0x5f, 0x73, 0x69, 0x67, 0x6e, 0x75, 0x70}, ColumnCount: 0x13, ColumnType: []uint8{0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0xf, 0xc, 0xc, 0xc, 0xf, 0xf, 0x3, 0xf}, ColumnMeta: []uint16{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x180, 0x0, 0x0, 0x0, 0x180, 0x180, 0x0, 0x2fd}, NullBitmap: []uint8{0x6, 0xfb, 0x5}},
0x30450: &TableMapEvent{tableIDSize: 6, TableID: 0x30450, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x73, 0x6e, 0x61, 0x70, 0x73, 0x68, 0x6f, 0x74}, ColumnCount: 0x16, ColumnType: []uint8{0x3, 0xfc, 0xc, 0x3, 0xc, 0xf, 0x3, 0xf, 0xc, 0xf, 0xf, 0xf, 0xf, 0x3, 0xc, 0xf, 0xf, 0xf, 0xf, 0x3, 0x3, 0xf}, ColumnMeta: []uint16{0x0, 0x2, 0x0, 0x0, 0x0, 0x2d, 0x0, 0x180, 0x0, 0x180, 0x180, 0x2fd, 0x2d, 0x0, 0x0, 0x180, 0x180, 0x2fd, 0x2d, 0x0, 0x0, 0x2fd}, NullBitmap: []uint8{0xfe, 0xff, 0x2f}},
0x305bb: &TableMapEvent{tableIDSize: 6, TableID: 0x305bb, Flags: 0x1, Schema: []uint8{0x79, 0x6d, 0x63, 0x61, 0x63, 0x68, 0x67, 0x6f}, Table: []uint8{0x72, 0x65, 0x64, 0x69, 0x72, 0x65, 0x63, 0x74, 0x5f, 0x6c, 0x6f, 0x67}, ColumnCount: 0x11, ColumnType: []uint8{0x3, 0x3, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xc, 0xf, 0xf, 0xc, 0xf, 0xf, 0x3, 0xf}, ColumnMeta: []uint16{0x0, 0x0, 0x2fd, 0x12c, 0x2fd, 0x2fd, 0x2d, 0x12c, 0x2fd, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x0, 0x2fd}, NullBitmap: []uint8{0xfe, 0x7f, 0x1}},
0x16c36b: &TableMapEvent{tableIDSize: 6, TableID: 0x16c36b, Flags: 0x1, Schema: []uint8{0x61, 0x63, 0x70}, Table: []uint8{0x73, 0x74, 0x67, 0x5f, 0x6d, 0x61, 0x69, 0x6c, 0x69, 0x6e, 0x67, 0x5f, 0x72, 0x65, 0x63, 0x69, 0x70, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x32}, ColumnCount: 0xe, ColumnType: []uint8{0x8, 0x8, 0x3, 0x3, 0x2, 0x2, 0xf, 0x12, 0xf, 0xf, 0x12, 0xf, 0xf, 0xf}, ColumnMeta: []uint16{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2d, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x2fd}, NullBitmap: []uint8{0xba, 0x3f}},
0x16c368: &TableMapEvent{tableIDSize: 6, TableID: 0x16c368, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x73, 0x74, 0x67, 0x5f, 0x6d, 0x61, 0x69, 0x6c, 0x69, 0x6e, 0x67, 0x5f, 0x72, 0x65, 0x63, 0x69, 0x70, 0x69, 0x65, 0x6e, 0x74, 0x5f, 0x63, 0x6c, 0x69, 0x63, 0x6b, 0x32}, ColumnCount: 0xe, ColumnType: []uint8{0x8, 0x8, 0x3, 0x3, 0x2, 0x2, 0xf, 0x12, 0xf, 0xf, 0x12, 0xf, 0xf, 0xf}, ColumnMeta: []uint16{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2d, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x2fd}, NullBitmap: []uint8{0xba, 0x3f}},
0x3045a: &TableMapEvent{tableIDSize: 6, TableID: 0x3045a, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x63, 0x6f, 0x6e, 0x73}, ColumnCount: 0x1e, ColumnType: []uint8{0x3, 0x3, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xfe, 0x12, 0xf, 0xf, 0xf, 0xf6, 0xf, 0xf, 0xf, 0xf, 0x1, 0x1, 0x1, 0x12, 0xf, 0xf, 0x12, 0xf, 0xf, 0x3, 0xf, 0x1}, ColumnMeta: []uint16{0x0, 0x0, 0x30, 0x180, 0x180, 0x180, 0x30, 0xc0, 0xfe03, 0x0, 0x180, 0x180, 0x180, 0xc02, 0x180, 0x180, 0x180, 0x180, 0x0, 0x0, 0x0, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x0, 0x2fd, 0x0}, NullBitmap: []uint8{0xfc, 0xff, 0xe3, 0x37}},
0x3045f: &TableMapEvent{tableIDSize: 6, TableID: 0x3045f, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x63, 0x6f, 0x6e, 0x73, 0x5f, 0x61, 0x64, 0x64, 0x72}, ColumnCount: 0x19, ColumnType: []uint8{0x3, 0x3, 0x3, 0x1, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xf, 0xfe, 0x3, 0xc, 0x1, 0xc, 0xf, 0xf, 0xc, 0xf, 0xf, 0x3, 0xf, 0x4, 0x4}, ColumnMeta: []uint16{0x0, 0x0, 0x0, 0x0, 0x2fd, 0x2fd, 0x2fd, 0xc0, 0x12c, 0x30, 0xc, 0xfe06, 0x0, 0x0, 0x0, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x0, 0x2fd, 0x4, 0x4}, NullBitmap: []uint8{0xf0, 0xef, 0x5f, 0x0}},
0x3065f: &TableMapEvent{tableIDSize: 6, TableID: 0x3065f, Flags: 0x1, Schema: []uint8{0x73, 0x65, 0x69, 0x75, 0x6d, 0x61, 0x73, 0x74, 0x65, 0x72}, Table: []uint8{0x63, 0x6f, 0x6e, 0x73, 0x5f, 0x61, 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x5f, 0x73, 0x70, 0x65, 0x61, 0x6b, 0x6f, 0x75, 0x74, 0x5f, 0x6c, 0x65, 0x74, 0x74, 0x65, 0x72}, ColumnCount: 0xd, ColumnType: []uint8{0x3, 0x3, 0x3, 0x3, 0x1, 0x12, 0xf, 0xf, 0x12, 0xf, 0xf, 0x3, 0xf}, ColumnMeta: []uint16{0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x180, 0x180, 0x0, 0x180, 0x180, 0x0, 0x2fd}, NullBitmap: []uint8{0xe0, 0x17}},
}
_, err := parser.parse([]byte{
/* 0x00, */ 0xc1, 0x86, 0x8e, 0x55, 0x1e, 0xa5, 0x14, 0x80, 0xa, 0x55, 0x0, 0x0, 0x0, 0x7, 0xc,
0xbf, 0xe, 0x0, 0x0, 0x5f, 0x6, 0x3, 0x0, 0x0, 0x0, 0x1, 0x0, 0x2, 0x0, 0xd, 0xff,
0x0, 0x0, 0x19, 0x63, 0x7, 0x0, 0xca, 0x61, 0x5, 0x0, 0x5e, 0xf7, 0xc, 0x0, 0xf5, 0x7,
0x0, 0x0, 0x1, 0x99, 0x96, 0x76, 0x74, 0xdd, 0x10, 0x0, 0x73, 0x69, 0x67, 0x6e, 0x75, 0x70,
0x5f, 0x64, 0x62, 0x5f, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x6, 0x0, 0x73, 0x79, 0x73, 0x74,
0x65, 0x6d, 0xb1, 0x3c, 0x38, 0xcb,
})
c.Assert(err, IsNil)
}
| mit |
tbanov/magento-test-env | homeforyou/lib/Zend/Service/DeveloperGarden/SmsValidation.php | 6553 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* 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@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @see Zend_Service_DeveloperGarden_Client_ClientAbstract
*/
#require_once 'Zend/Service/DeveloperGarden/Client/ClientAbstract.php';
/**
* @see Zend_Service_DeveloperGarden_Request_SmsValidation_GetValidatedNumbers
*/
#require_once 'Zend/Service/DeveloperGarden/Request/SmsValidation/GetValidatedNumbers.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SmsValidation_GetValidatedNumbersResponse
*/
#require_once 'Zend/Service/DeveloperGarden/Response/SmsValidation/GetValidatedNumbersResponse.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SmsValidation_ValidatedNumber
*/
#require_once 'Zend/Service/DeveloperGarden/Response/SmsValidation/ValidatedNumber.php';
/**
* @see Zend_Service_DeveloperGarden_Request_SmsValidation_SendValidationKeyword
*/
#require_once 'Zend/Service/DeveloperGarden/Request/SmsValidation/SendValidationKeyword.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SmsValidation_SendValidationKeywordResponse
*/
#require_once 'Zend/Service/DeveloperGarden/Response/SmsValidation/SendValidationKeywordResponse.php';
/**
* @see Zend_Service_DeveloperGarden_Request_SmsValidation_Validate
*/
#require_once 'Zend/Service/DeveloperGarden/Request/SmsValidation/Validate.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SmsValidation_ValidateResponse
*/
#require_once 'Zend/Service/DeveloperGarden/Response/SmsValidation/ValidateResponse.php';
/**
* @see Zend_Service_DeveloperGarden_Request_SmsValidation_Invalidate
*/
#require_once 'Zend/Service/DeveloperGarden/Request/SmsValidation/Invalidate.php';
/**
* @see Zend_Service_DeveloperGarden_Response_SmsValidation_InvalidateResponse
*/
#require_once 'Zend/Service/DeveloperGarden/Response/SmsValidation/InvalidateResponse.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @author Marco Kaiser
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Service_DeveloperGarden_SmsValidation extends Zend_Service_DeveloperGarden_Client_ClientAbstract
{
// @codeCoverageIgnoreStart
/**
* wsdl file
*
* @var string
*/
protected $_wsdlFile = 'https://gateway.developer.telekom.com/p3gw-mod-odg-sms-validation/services/SmsValidationUserService?wsdl';
/**
* wsdl file local
*
* @var string
*/
protected $_wsdlFileLocal = 'Wsdl/SmsValidationUserService.wsdl';
/**
* Response, Request Classmapping
*
* @var array
*
*/
protected $_classMap = array(
'getValidatedNumbersResponse' => 'Zend_Service_DeveloperGarden_Response_SmsValidation_GetValidatedNumbersResponse',
'ValidatedNumber' => 'Zend_Service_DeveloperGarden_Response_SmsValidation_ValidatedNumber',
'sendValidationKeywordResponse' => 'Zend_Service_DeveloperGarden_Response_SmsValidation_SendValidationKeywordResponse',
'validateResponse' => 'Zend_Service_DeveloperGarden_Response_SmsValidation_ValidateResponse',
'invalidateResponse' => 'Zend_Service_DeveloperGarden_Response_SmsValidation_InvalidateResponse',
);
/**
* validate the given number with the keyword
*
* @param string $keyword
* @param string $number
* @return Zend_Service_DeveloperGarden_Response_SmsValidation_ValidateResponse
*/
public function validate($keyword = null, $number = null)
{
$request = new Zend_Service_DeveloperGarden_Request_SmsValidation_Validate(
$this->getEnvironment(),
$keyword,
$number
);
return $this->getSoapClient()
->validate($request)
->parse();
}
/**
* invalidate the given number
*
* @param string $number
* @return Zend_Service_DeveloperGarden_Response_SmsValidation_InvalidateResponse
*/
public function inValidate($number = null)
{
$request = new Zend_Service_DeveloperGarden_Request_SmsValidation_Invalidate(
$this->getEnvironment(),
$number
);
return $this->getSoapClient()
->invalidate($request)
->parse();
}
/**
* this function sends the validation sms to the given number,
* if message is provided it should have to placeholder:
* #key# = the validation key
* #validUntil# = the valid until date
*
* @param string $number
* @param string $message
* @param string $originator
* @param integer $account
*
* @return Zend_Service_DeveloperGarden_Request_SmsValidation_SendValidationKeywordResponse
*/
public function sendValidationKeyword($number = null, $message = null, $originator = null, $account = null)
{
$request = new Zend_Service_DeveloperGarden_Request_SmsValidation_SendValidationKeyword(
$this->getEnvironment()
);
$request->setNumber($number)
->setMessage($message)
->setOriginator($originator)
->setAccount($account);
return $this->getSoapClient()
->sendValidationKeyword($request)
->parse();
}
/**
* returns a list of validated numbers
*
* @return Zend_Service_DeveloperGarden_Response_SmsValidation_GetValidatedNumbersResponse
*/
public function getValidatedNumbers()
{
$request = new Zend_Service_DeveloperGarden_Request_SmsValidation_GetValidatedNumbers(
$this->getEnvironment()
);
return $this->getSoapClient()
->getValidatedNumbers($request)
->parse();
}
// @codeCoverageIgnoreEnd
}
| mit |
chutterbox/chutter | vendor/angular-material/modules/closure/datepicker/datepicker.js | 66958 | /*!
* Angular Material Design
* https://github.com/angular/material
* @license MIT
* v0.11.1
*/
goog.provide('ng.material.components.datepicker');
goog.require('ng.material.components.icon');
goog.require('ng.material.components.virtualRepeat');
goog.require('ng.material.core');
(function() {
'use strict';
/**
* @ngdoc module
* @name material.components.datepicker
* @description Datepicker
*/
angular.module('material.components.datepicker', [
'material.core',
'material.components.icon',
'material.components.virtualRepeat'
]).directive('mdCalendar', calendarDirective);
// POST RELEASE
// TODO(jelbourn): Mac Cmd + left / right == Home / End
// TODO(jelbourn): Clicking on the month label opens the month-picker.
// TODO(jelbourn): Minimum and maximum date
// TODO(jelbourn): Refactor month element creation to use cloneNode (performance).
// TODO(jelbourn): Define virtual scrolling constants (compactness) users can override.
// TODO(jelbourn): Animated month transition on ng-model change (virtual-repeat)
// TODO(jelbourn): Scroll snapping (virtual repeat)
// TODO(jelbourn): Remove superfluous row from short months (virtual-repeat)
// TODO(jelbourn): Month headers stick to top when scrolling.
// TODO(jelbourn): Previous month opacity is lowered when partially scrolled out of view.
// TODO(jelbourn): Support md-calendar standalone on a page (as a tabstop w/ aria-live
// announcement and key handling).
// Read-only calendar (not just date-picker).
/**
* Height of one calendar month tbody. This must be made known to the virtual-repeat and is
* subsequently used for scrolling to specific months.
*/
var TBODY_HEIGHT = 265;
/**
* Height of a calendar month with a single row. This is needed to calculate the offset for
* rendering an extra month in virtual-repeat that only contains one row.
*/
var TBODY_SINGLE_ROW_HEIGHT = 45;
function calendarDirective() {
return {
template:
'<table aria-hidden="true" class="md-calendar-day-header"><thead></thead></table>' +
'<div class="md-calendar-scroll-mask">' +
'<md-virtual-repeat-container class="md-calendar-scroll-container" ' +
'md-offset-size="' + (TBODY_SINGLE_ROW_HEIGHT - TBODY_HEIGHT) + '">' +
'<table role="grid" tabindex="0" class="md-calendar" aria-readonly="true">' +
'<tbody role="rowgroup" md-virtual-repeat="i in ctrl.items" md-calendar-month ' +
'md-month-offset="$index" class="md-calendar-month" ' +
'md-start-index="ctrl.getSelectedMonthIndex()" ' +
'md-item-size="' + TBODY_HEIGHT + '"></tbody>' +
'</table>' +
'</md-virtual-repeat-container>' +
'</div>',
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
},
require: ['ngModel', 'mdCalendar'],
controller: CalendarCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var ngModelCtrl = controllers[0];
var mdCalendarCtrl = controllers[1];
mdCalendarCtrl.configureNgModel(ngModelCtrl);
}
};
}
/** Class applied to the selected date cell/. */
var SELECTED_DATE_CLASS = 'md-calendar-selected-date';
/** Class applied to the focused date cell/. */
var FOCUSED_DATE_CLASS = 'md-focus';
/** Next identifier for calendar instance. */
var nextUniqueId = 0;
/** The first renderable date in the virtual-scrolling calendar (for all instances). */
var firstRenderableDate = null;
/**
* Controller for the mdCalendar component.
* ngInject @constructor
*/
function CalendarCtrl($element, $attrs, $scope, $animate, $q, $mdConstant,
$mdTheming, $$mdDateUtil, $mdDateLocale, $mdInkRipple, $mdUtil) {
$mdTheming($element);
/**
* Dummy array-like object for virtual-repeat to iterate over. The length is the total
* number of months that can be viewed. This is shorter than ideal because of (potential)
* Firefox bug https://bugzilla.mozilla.org/show_bug.cgi?id=1181658.
*/
this.items = {length: 2000};
if (this.maxDate && this.minDate) {
// Limit the number of months if min and max dates are set.
var numMonths = $$mdDateUtil.getMonthDistance(this.minDate, this.maxDate) + 1;
numMonths = Math.max(numMonths, 1);
// Add an additional month as the final dummy month for rendering purposes.
numMonths += 1;
this.items.length = numMonths;
}
/** @final {!angular.$animate} */
this.$animate = $animate;
/** @final {!angular.$q} */
this.$q = $q;
/** @final */
this.$mdInkRipple = $mdInkRipple;
/** @final */
this.$mdUtil = $mdUtil;
/** @final */
this.keyCode = $mdConstant.KEY_CODE;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @final {HTMLElement} */
this.calendarElement = $element[0].querySelector('.md-calendar');
/** @final {HTMLElement} */
this.calendarScroller = $element[0].querySelector('.md-virtual-repeat-scroller');
/** @final {Date} */
this.today = this.dateUtil.createDateAtMidnight();
/** @type {Date} */
this.firstRenderableDate = this.dateUtil.incrementMonths(this.today, -this.items.length / 2);
if (this.minDate && this.minDate > this.firstRenderableDate) {
this.firstRenderableDate = this.minDate;
} else if (this.maxDate) {
// Calculate the difference between the start date and max date.
// Subtract 1 because it's an inclusive difference and 1 for the final dummy month.
//
var monthDifference = this.items.length - 2;
this.firstRenderableDate = this.dateUtil.incrementMonths(this.maxDate, -(this.items.length - 2));
}
/** @final {number} Unique ID for this calendar instance. */
this.id = nextUniqueId++;
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/**
* The selected date. Keep track of this separately from the ng-model value so that we
* can know, when the ng-model value changes, what the previous value was before its updated
* in the component's UI.
*
* @type {Date}
*/
this.selectedDate = null;
/**
* The date that is currently focused or showing in the calendar. This will initially be set
* to the ng-model value if set, otherwise to today. It will be updated as the user navigates
* to other months. The cell corresponding to the displayDate does not necesarily always have
* focus in the document (such as for cases when the user is scrolling the calendar).
* @type {Date}
*/
this.displayDate = null;
/**
* The date that has or should have focus.
* @type {Date}
*/
this.focusDate = null;
/** @type {boolean} */
this.isInitialized = false;
/** @type {boolean} */
this.isMonthTransitionInProgress = false;
// Unless the user specifies so, the calendar should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs['tabindex']) {
$element.attr('tabindex', '-1');
}
var self = this;
/**
* Handles a click event on a date cell.
* Created here so that every cell can use the same function instance.
* @this {HTMLTableCellElement} The cell that was clicked.
*/
this.cellClickHandler = function() {
var cellElement = this;
if (this.hasAttribute('data-timestamp')) {
$scope.$apply(function() {
var timestamp = Number(cellElement.getAttribute('data-timestamp'));
self.setNgModelValue(self.dateUtil.createDateAtMidnight(timestamp));
});
}
};
this.attachCalendarEventListeners();
}
CalendarCtrl.$inject = ["$element", "$attrs", "$scope", "$animate", "$q", "$mdConstant", "$mdTheming", "$$mdDateUtil", "$mdDateLocale", "$mdInkRipple", "$mdUtil"];
/*** Initialization ***/
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
CalendarCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
self.changeSelectedDate(self.ngModelCtrl.$viewValue);
};
};
/**
* Initialize the calendar by building the months that are initially visible.
* Initialization should occur after the ngModel value is known.
*/
CalendarCtrl.prototype.buildInitialCalendarDisplay = function() {
this.buildWeekHeader();
this.hideVerticalScrollbar();
this.displayDate = this.selectedDate || this.today;
this.isInitialized = true;
};
/**
* Hides the vertical scrollbar on the calendar scroller by setting the width on the
* calendar scroller and the `overflow: hidden` wrapper around the scroller, and then setting
* a padding-right on the scroller equal to the width of the browser's scrollbar.
*
* This will cause a reflow.
*/
CalendarCtrl.prototype.hideVerticalScrollbar = function() {
var element = this.$element[0];
var scrollMask = element.querySelector('.md-calendar-scroll-mask');
var scroller = this.calendarScroller;
var headerWidth = element.querySelector('.md-calendar-day-header').clientWidth;
var scrollbarWidth = scroller.offsetWidth - scroller.clientWidth;
scrollMask.style.width = headerWidth + 'px';
scroller.style.width = (headerWidth + scrollbarWidth) + 'px';
scroller.style.paddingRight = scrollbarWidth + 'px';
};
/** Attach event listeners for the calendar. */
CalendarCtrl.prototype.attachCalendarEventListeners = function() {
// Keyboard interaction.
this.$element.on('keydown', angular.bind(this, this.handleKeyEvent));
};
/*** User input handling ***/
/**
* Handles a key event in the calendar with the appropriate action. The action will either
* be to select the focused date or to navigate to focus a new date.
* @param {KeyboardEvent} event
*/
CalendarCtrl.prototype.handleKeyEvent = function(event) {
var self = this;
this.$scope.$apply(function() {
// Capture escape and emit back up so that a wrapping component
// (such as a date-picker) can decide to close.
if (event.which == self.keyCode.ESCAPE || event.which == self.keyCode.TAB) {
self.$scope.$emit('md-calendar-close');
if (event.which == self.keyCode.TAB) {
event.preventDefault();
}
return;
}
// Remaining key events fall into two categories: selection and navigation.
// Start by checking if this is a selection event.
if (event.which === self.keyCode.ENTER) {
self.setNgModelValue(self.displayDate);
event.preventDefault();
return;
}
// Selection isn't occuring, so the key event is either navigation or nothing.
var date = self.getFocusDateFromKeyEvent(event);
if (date) {
date = self.boundDateByMinAndMax(date);
event.preventDefault();
event.stopPropagation();
// Since this is a keyboard interaction, actually give the newly focused date keyboard
// focus after the been brought into view.
self.changeDisplayDate(date).then(function () {
self.focus(date);
});
}
});
};
/**
* Gets the date to focus as the result of a key event.
* @param {KeyboardEvent} event
* @returns {Date} Date to navigate to, or null if the key does not match a calendar shortcut.
*/
CalendarCtrl.prototype.getFocusDateFromKeyEvent = function(event) {
var dateUtil = this.dateUtil;
var keyCode = this.keyCode;
switch (event.which) {
case keyCode.RIGHT_ARROW: return dateUtil.incrementDays(this.displayDate, 1);
case keyCode.LEFT_ARROW: return dateUtil.incrementDays(this.displayDate, -1);
case keyCode.DOWN_ARROW:
return event.metaKey ?
dateUtil.incrementMonths(this.displayDate, 1) :
dateUtil.incrementDays(this.displayDate, 7);
case keyCode.UP_ARROW:
return event.metaKey ?
dateUtil.incrementMonths(this.displayDate, -1) :
dateUtil.incrementDays(this.displayDate, -7);
case keyCode.PAGE_DOWN: return dateUtil.incrementMonths(this.displayDate, 1);
case keyCode.PAGE_UP: return dateUtil.incrementMonths(this.displayDate, -1);
case keyCode.HOME: return dateUtil.getFirstDateOfMonth(this.displayDate);
case keyCode.END: return dateUtil.getLastDateOfMonth(this.displayDate);
default: return null;
}
};
/**
* Gets the "index" of the currently selected date as it would be in the virtual-repeat.
* @returns {number}
*/
CalendarCtrl.prototype.getSelectedMonthIndex = function() {
return this.dateUtil.getMonthDistance(this.firstRenderableDate,
this.selectedDate || this.today);
};
/**
* Scrolls to the month of the given date.
* @param {Date} date
*/
CalendarCtrl.prototype.scrollToMonth = function(date) {
if (!this.dateUtil.isValidDate(date)) {
return;
}
var monthDistance = this.dateUtil.getMonthDistance(this.firstRenderableDate, date);
this.calendarScroller.scrollTop = monthDistance * TBODY_HEIGHT;
};
/**
* Sets the ng-model value for the calendar and emits a change event.
* @param {Date} date
*/
CalendarCtrl.prototype.setNgModelValue = function(date) {
this.$scope.$emit('md-calendar-change', date);
this.ngModelCtrl.$setViewValue(date);
this.ngModelCtrl.$render();
};
/**
* Focus the cell corresponding to the given date.
* @param {Date=} opt_date
*/
CalendarCtrl.prototype.focus = function(opt_date) {
var date = opt_date || this.selectedDate || this.today;
var previousFocus = this.calendarElement.querySelector('.md-focus');
if (previousFocus) {
previousFocus.classList.remove(FOCUSED_DATE_CLASS);
}
var cellId = this.getDateId(date);
var cell = document.getElementById(cellId);
if (cell) {
cell.classList.add(FOCUSED_DATE_CLASS);
cell.focus();
} else {
this.focusDate = date;
}
};
/**
* If a date exceeds minDate or maxDate, returns date matching minDate or maxDate, respectively.
* Otherwise, returns the date.
* @param {Date} date
* @return {Date}
*/
CalendarCtrl.prototype.boundDateByMinAndMax = function(date) {
var boundDate = date;
if (this.minDate && date < this.minDate) {
boundDate = new Date(this.minDate.getTime());
}
if (this.maxDate && date > this.maxDate) {
boundDate = new Date(this.maxDate.getTime());
}
return boundDate;
};
/*** Updating the displayed / selected date ***/
/**
* Change the selected date in the calendar (ngModel value has already been changed).
* @param {Date} date
*/
CalendarCtrl.prototype.changeSelectedDate = function(date) {
var self = this;
var previousSelectedDate = this.selectedDate;
this.selectedDate = date;
this.changeDisplayDate(date).then(function() {
// Remove the selected class from the previously selected date, if any.
if (previousSelectedDate) {
var prevDateCell =
document.getElementById(self.getDateId(previousSelectedDate));
if (prevDateCell) {
prevDateCell.classList.remove(SELECTED_DATE_CLASS);
prevDateCell.setAttribute('aria-selected', 'false');
}
}
// Apply the select class to the new selected date if it is set.
if (date) {
var dateCell = document.getElementById(self.getDateId(date));
if (dateCell) {
dateCell.classList.add(SELECTED_DATE_CLASS);
dateCell.setAttribute('aria-selected', 'true');
}
}
});
};
/**
* Change the date that is being shown in the calendar. If the given date is in a different
* month, the displayed month will be transitioned.
* @param {Date} date
*/
CalendarCtrl.prototype.changeDisplayDate = function(date) {
// Initialization is deferred until this function is called because we want to reflect
// the starting value of ngModel.
if (!this.isInitialized) {
this.buildInitialCalendarDisplay();
return this.$q.when();
}
// If trying to show an invalid date or a transition is in progress, do nothing.
if (!this.dateUtil.isValidDate(date) || this.isMonthTransitionInProgress) {
return this.$q.when();
}
this.isMonthTransitionInProgress = true;
var animationPromise = this.animateDateChange(date);
this.displayDate = date;
var self = this;
animationPromise.then(function() {
self.isMonthTransitionInProgress = false;
});
return animationPromise;
};
/**
* Animates the transition from the calendar's current month to the given month.
* @param {Date} date
* @returns {angular.$q.Promise} The animation promise.
*/
CalendarCtrl.prototype.animateDateChange = function(date) {
this.scrollToMonth(date);
return this.$q.when();
};
/*** Constructing the calendar table ***/
/**
* Builds and appends a day-of-the-week header to the calendar.
* This should only need to be called once during initialization.
*/
CalendarCtrl.prototype.buildWeekHeader = function() {
var firstDayOfWeek = this.dateLocale.firstDayOfWeek;
var shortDays = this.dateLocale.shortDays;
var row = document.createElement('tr');
for (var i = 0; i < 7; i++) {
var th = document.createElement('th');
th.textContent = shortDays[(i + firstDayOfWeek) % 7];
row.appendChild(th);
}
this.$element.find('thead').append(row);
};
/**
* Gets an identifier for a date unique to the calendar instance for internal
* purposes. Not to be displayed.
* @param {Date} date
* @returns {string}
*/
CalendarCtrl.prototype.getDateId = function(date) {
return [
'md',
this.id,
date.getFullYear(),
date.getMonth(),
date.getDate()
].join('-');
};
})();
(function() {
'use strict';
angular.module('material.components.datepicker')
.directive('mdCalendarMonth', mdCalendarMonthDirective);
/**
* Private directive consumed by md-calendar. Having this directive lets the calender use
* md-virtual-repeat and also cleanly separates the month DOM construction functions from
* the rest of the calendar controller logic.
*/
function mdCalendarMonthDirective() {
return {
require: ['^^mdCalendar', 'mdCalendarMonth'],
scope: {offset: '=mdMonthOffset'},
controller: CalendarMonthCtrl,
controllerAs: 'mdMonthCtrl',
bindToController: true,
link: function(scope, element, attrs, controllers) {
var calendarCtrl = controllers[0];
var monthCtrl = controllers[1];
monthCtrl.calendarCtrl = calendarCtrl;
monthCtrl.generateContent();
// The virtual-repeat re-uses the same DOM elements, so there are only a limited number
// of repeated items that are linked, and then those elements have their bindings updataed.
// Since the months are not generated by bindings, we simply regenerate the entire thing
// when the binding (offset) changes.
scope.$watch(function() { return monthCtrl.offset; }, function(offset, oldOffset) {
if (offset != oldOffset) {
monthCtrl.generateContent();
}
});
}
};
}
/** Class applied to the cell for today. */
var TODAY_CLASS = 'md-calendar-date-today';
/** Class applied to the selected date cell/. */
var SELECTED_DATE_CLASS = 'md-calendar-selected-date';
/** Class applied to the focused date cell/. */
var FOCUSED_DATE_CLASS = 'md-focus';
/**
* Controller for a single calendar month.
* ngInject @constructor
*/
function CalendarMonthCtrl($element, $$mdDateUtil, $mdDateLocale) {
this.dateUtil = $$mdDateUtil;
this.dateLocale = $mdDateLocale;
this.$element = $element;
this.calendarCtrl = null;
/**
* Number of months from the start of the month "items" that the currently rendered month
* occurs. Set via angular data binding.
* @type {number}
*/
this.offset;
/**
* Date cell to focus after appending the month to the document.
* @type {HTMLElement}
*/
this.focusAfterAppend = null;
}
CalendarMonthCtrl.$inject = ["$element", "$$mdDateUtil", "$mdDateLocale"];
/** Generate and append the content for this month to the directive element. */
CalendarMonthCtrl.prototype.generateContent = function() {
var calendarCtrl = this.calendarCtrl;
var date = this.dateUtil.incrementMonths(calendarCtrl.firstRenderableDate, this.offset);
this.$element.empty();
this.$element.append(this.buildCalendarForMonth(date));
if (this.focusAfterAppend) {
this.focusAfterAppend.classList.add(FOCUSED_DATE_CLASS);
this.focusAfterAppend.focus();
this.focusAfterAppend = null;
}
};
/**
* Creates a single cell to contain a date in the calendar with all appropriate
* attributes and classes added. If a date is given, the cell content will be set
* based on the date.
* @param {Date=} opt_date
* @returns {HTMLElement}
*/
CalendarMonthCtrl.prototype.buildDateCell = function(opt_date) {
var calendarCtrl = this.calendarCtrl;
// TODO(jelbourn): cloneNode is likely a faster way of doing this.
var cell = document.createElement('td');
cell.tabIndex = -1;
cell.classList.add('md-calendar-date');
cell.setAttribute('role', 'gridcell');
if (opt_date) {
cell.setAttribute('tabindex', '-1');
cell.setAttribute('aria-label', this.dateLocale.longDateFormatter(opt_date));
cell.id = calendarCtrl.getDateId(opt_date);
// Use `data-timestamp` attribute because IE10 does not support the `dataset` property.
cell.setAttribute('data-timestamp', opt_date.getTime());
// TODO(jelourn): Doing these comparisons for class addition during generation might be slow.
// It may be better to finish the construction and then query the node and add the class.
if (this.dateUtil.isSameDay(opt_date, calendarCtrl.today)) {
cell.classList.add(TODAY_CLASS);
}
if (this.dateUtil.isValidDate(calendarCtrl.selectedDate) &&
this.dateUtil.isSameDay(opt_date, calendarCtrl.selectedDate)) {
cell.classList.add(SELECTED_DATE_CLASS);
cell.setAttribute('aria-selected', 'true');
}
var cellText = this.dateLocale.dates[opt_date.getDate()];
if (this.dateUtil.isDateWithinRange(opt_date,
this.calendarCtrl.minDate, this.calendarCtrl.maxDate)) {
// Add a indicator for select, hover, and focus states.
var selectionIndicator = document.createElement('span');
cell.appendChild(selectionIndicator);
selectionIndicator.classList.add('md-calendar-date-selection-indicator');
selectionIndicator.textContent = cellText;
cell.addEventListener('click', calendarCtrl.cellClickHandler);
if (calendarCtrl.focusDate && this.dateUtil.isSameDay(opt_date, calendarCtrl.focusDate)) {
this.focusAfterAppend = cell;
}
} else {
cell.classList.add('md-calendar-date-disabled');
cell.textContent = cellText;
}
}
return cell;
};
/**
* Builds a `tr` element for the calendar grid.
* @param rowNumber The week number within the month.
* @returns {HTMLElement}
*/
CalendarMonthCtrl.prototype.buildDateRow = function(rowNumber) {
var row = document.createElement('tr');
row.setAttribute('role', 'row');
// Because of an NVDA bug (with Firefox), the row needs an aria-label in order
// to prevent the entire row being read aloud when the user moves between rows.
// See http://community.nvda-project.org/ticket/4643.
row.setAttribute('aria-label', this.dateLocale.weekNumberFormatter(rowNumber));
return row;
};
/**
* Builds the <tbody> content for the given date's month.
* @param {Date=} opt_dateInMonth
* @returns {DocumentFragment} A document fragment containing the <tr> elements.
*/
CalendarMonthCtrl.prototype.buildCalendarForMonth = function(opt_dateInMonth) {
var date = this.dateUtil.isValidDate(opt_dateInMonth) ? opt_dateInMonth : new Date();
var firstDayOfMonth = this.dateUtil.getFirstDateOfMonth(date);
var firstDayOfTheWeek = this.getLocaleDay_(firstDayOfMonth);
var numberOfDaysInMonth = this.dateUtil.getNumberOfDaysInMonth(date);
// Store rows for the month in a document fragment so that we can append them all at once.
var monthBody = document.createDocumentFragment();
var rowNumber = 1;
var row = this.buildDateRow(rowNumber);
monthBody.appendChild(row);
// If this is the final month in the list of items, only the first week should render,
// so we should return immediately after the first row is complete and has been
// attached to the body.
var isFinalMonth = this.offset === this.calendarCtrl.items.length - 1;
// Add a label for the month. If the month starts on a Sun/Mon/Tues, the month label
// goes on a row above the first of the month. Otherwise, the month label takes up the first
// two cells of the first row.
var blankCellOffset = 0;
var monthLabelCell = document.createElement('td');
monthLabelCell.classList.add('md-calendar-month-label');
// If the entire month is after the max date, render the label as a disabled state.
if (this.calendarCtrl.maxDate && firstDayOfMonth > this.calendarCtrl.maxDate) {
monthLabelCell.classList.add('md-calendar-month-label-disabled');
}
monthLabelCell.textContent = this.dateLocale.monthHeaderFormatter(date);
if (firstDayOfTheWeek <= 2) {
monthLabelCell.setAttribute('colspan', '7');
var monthLabelRow = this.buildDateRow();
monthLabelRow.appendChild(monthLabelCell);
monthBody.insertBefore(monthLabelRow, row);
if (isFinalMonth) {
return monthBody;
}
} else {
blankCellOffset = 2;
monthLabelCell.setAttribute('colspan', '2');
row.appendChild(monthLabelCell);
}
// Add a blank cell for each day of the week that occurs before the first of the month.
// For example, if the first day of the month is a Tuesday, add blank cells for Sun and Mon.
// The blankCellOffset is needed in cases where the first N cells are used by the month label.
for (var i = blankCellOffset; i < firstDayOfTheWeek; i++) {
row.appendChild(this.buildDateCell());
}
// Add a cell for each day of the month, keeping track of the day of the week so that
// we know when to start a new row.
var dayOfWeek = firstDayOfTheWeek;
var iterationDate = firstDayOfMonth;
for (var d = 1; d <= numberOfDaysInMonth; d++) {
// If we've reached the end of the week, start a new row.
if (dayOfWeek === 7) {
// We've finished the first row, so we're done if this is the final month.
if (isFinalMonth) {
return monthBody;
}
dayOfWeek = 0;
rowNumber++;
row = this.buildDateRow(rowNumber);
monthBody.appendChild(row);
}
iterationDate.setDate(d);
var cell = this.buildDateCell(iterationDate);
row.appendChild(cell);
dayOfWeek++;
}
// Ensure that the last row of the month has 7 cells.
while (row.childNodes.length < 7) {
row.appendChild(this.buildDateCell());
}
// Ensure that all months have 6 rows. This is necessary for now because the virtual-repeat
// requires that all items have exactly the same height.
while (monthBody.childNodes.length < 6) {
var whitespaceRow = this.buildDateRow();
for (var i = 0; i < 7; i++) {
whitespaceRow.appendChild(this.buildDateCell());
}
monthBody.appendChild(whitespaceRow);
}
return monthBody;
};
/**
* Gets the day-of-the-week index for a date for the current locale.
* @private
* @param {Date} date
* @returns {number} The column index of the date in the calendar.
*/
CalendarMonthCtrl.prototype.getLocaleDay_ = function(date) {
return (date.getDay() + (7 - this.dateLocale.firstDayOfWeek)) % 7
};
})();
(function() {
'use strict';
/**
* @ngdoc service
* @name $mdDateLocaleProvider
* @module material.components.datepicker
*
* @description
* The `$mdDateLocaleProvider` is the provider that creates the `$mdDateLocale` service.
* This provider that allows the user to specify messages, formatters, and parsers for date
* internationalization. The `$mdDateLocale` service itself is consumed by Angular Material
* components that that deal with dates.
*
* @property {(Array<string>)=} months Array of month names (in order).
* @property {(Array<string>)=} shortMonths Array of abbreviated month names.
* @property {(Array<string>)=} days Array of the days of the week (in order).
* @property {(Array<string>)=} shortDays Array of abbreviated dayes of the week.
* @property {(Array<string>)=} dates Array of dates of the month. Only necessary for locales
* using a numeral system other than [1, 2, 3...].
* @property {(Array<string>)=} firstDayOfWeek The first day of the week. Sunday = 0, Monday = 1,
* etc.
* @property {(function(string): Date)=} parseDate Function to parse a date object from a string.
* @property {(function(Date): string)=} formatDate Function to format a date object to a string.
* @property {(function(Date): string)=} monthHeaderFormatter Function that returns the label for
* a month given a date.
* @property {(function(number): string)=} weekNumberFormatter Function that returns a label for
* a week given the week number.
* @property {(string)=} msgCalendar Translation of the label "Calendar" for the current locale.
* @property {(string)=} msgOpenCalendar Translation of the button label "Open calendar" for the
* current locale.
*
* @usage
* <hljs lang="js">
* myAppModule.config(function($mdDateLocaleProvider) {
*
* // Example of a French localization.
* $mdDateLocaleProvider.months = ['janvier', 'février', 'mars', ...];
* $mdDateLocaleProvider.shortMonths = ['janv', 'févr', 'mars', ...];
* $mdDateLocaleProvider.days = ['dimanche', 'lundi', 'mardi', ...];
* $mdDateLocaleProvider.shortDays = ['Di', 'Lu', 'Ma', ...];
*
* // Can change week display to start on Monday.
* $mdDateLocaleProvider.firstDayOfWeek = 1;
*
* // Optional.
* $mdDateLocaleProvider.dates = [1, 2, 3, 4, 5, 6, ...];
*
* // Example uses moment.js to parse and format dates.
* $mdDateLocaleProvider.parseDate = function(dateString) {
* var m = moment(dateString, 'L', true);
* return m.isValid() ? m.toDate() : new Date(NaN);
* };
*
* $mdDateLocaleProvider.formatDate = function(date) {
* return moment(date).format('L');
* };
*
* $mdDateLocaleProvider.monthHeaderFormatter = function(date) {
* return myShortMonths[date.getMonth()] + ' ' + date.getFullYear();
* };
*
* // In addition to date display, date components also need localized messages
* // for aria-labels for screen-reader users.
*
* $mdDateLocaleProvider.weekNumberFormatter = function(weekNumber) {
* return 'Semaine ' + weekNumber;
* };
*
* $mdDateLocaleProvider.msgCalendar = 'Calendrier';
* $mdDateLocaleProvider.msgOpenCalendar = 'Ouvrir le calendrier';
*
* });
* </hljs>
*
*/
angular.module('material.components.datepicker').config(["$provide", function($provide) {
// TODO(jelbourn): Assert provided values are correctly formatted. Need assertions.
/** @constructor */
function DateLocaleProvider() {
/** Array of full month names. E.g., ['January', 'Febuary', ...] */
this.months = null;
/** Array of abbreviated month names. E.g., ['Jan', 'Feb', ...] */
this.shortMonths = null;
/** Array of full day of the week names. E.g., ['Monday', 'Tuesday', ...] */
this.days = null;
/** Array of abbreviated dat of the week names. E.g., ['M', 'T', ...] */
this.shortDays = null;
/** Array of dates of a month (1 - 31). Characters might be different in some locales. */
this.dates = null;
/** Index of the first day of the week. 0 = Sunday, 1 = Monday, etc. */
this.firstDayOfWeek = 0;
/**
* Function that converts the date portion of a Date to a string.
* @type {(function(Date): string)}
*/
this.formatDate = null;
/**
* Function that converts a date string to a Date object (the date portion)
* @type {function(string): Date}
*/
this.parseDate = null;
/**
* Function that formats a Date into a month header string.
* @type {function(Date): string}
*/
this.monthHeaderFormatter = null;
/**
* Function that formats a week number into a label for the week.
* @type {function(number): string}
*/
this.weekNumberFormatter = null;
/**
* Function that formats a date into a long aria-label that is read
* when the focused date changes.
* @type {function(Date): string}
*/
this.longDateFormatter = null;
/**
* ARIA label for the calendar "dialog" used in the datepicker.
* @type {string}
*/
this.msgCalendar = '';
/**
* ARIA label for the datepicker's "Open calendar" buttons.
* @type {string}
*/
this.msgOpenCalendar = '';
}
/**
* Factory function that returns an instance of the dateLocale service.
* ngInject
* @param $locale
* @returns {DateLocale}
*/
DateLocaleProvider.prototype.$get = function($locale) {
/**
* Default date-to-string formatting function.
* @param {!Date} date
* @returns {string}
*/
function defaultFormatDate(date) {
if (!date) {
return '';
}
// All of the dates created through ng-material *should* be set to midnight.
// If we encounter a date where the localeTime shows at 11pm instead of midnight,
// we have run into an issue with DST where we need to increment the hour by one:
// var d = new Date(1992, 9, 8, 0, 0, 0);
// d.toLocaleString(); // == "10/7/1992, 11:00:00 PM"
var localeTime = date.toLocaleTimeString();
var formatDate = date;
if (date.getHours() == 0 &&
(localeTime.indexOf('11:') !== -1 || localeTime.indexOf('23:') !== -1)) {
formatDate = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 1, 0, 0);
}
return formatDate.toLocaleDateString();
}
/**
* Default string-to-date parsing function.
* @param {string} dateString
* @returns {!Date}
*/
function defaultParseDate(dateString) {
return new Date(dateString);
}
/**
* Default function to determine whether a string makes sense to be
* parsed to a Date object.
*
* This is very permissive and is just a basic sanity check to ensure that
* things like single integers aren't able to be parsed into dates.
* @param {string} dateString
* @returns {boolean}
*/
function defaultIsDateComplete(dateString) {
dateString = dateString.trim();
// Looks for three chunks of content (either numbers or text) separated
// by delimiters.
var re = /^(([a-zA-Z]{3,}|[0-9]{1,4})([ \.,]+|[\/\-])){2}([a-zA-Z]{3,}|[0-9]{1,4})$/;
return re.test(dateString);
}
/**
* Default date-to-string formatter to get a month header.
* @param {!Date} date
* @returns {string}
*/
function defaultMonthHeaderFormatter(date) {
return service.shortMonths[date.getMonth()] + ' ' + date.getFullYear();
}
/**
* Default week number formatter.
* @param number
* @returns {string}
*/
function defaultWeekNumberFormatter(number) {
return 'Week ' + number;
}
/**
* Default formatter for date cell aria-labels.
* @param {!Date} date
* @returns {string}
*/
function defaultLongDateFormatter(date) {
// Example: 'Thursday June 18 2015'
return [
service.days[date.getDay()],
service.months[date.getMonth()],
service.dates[date.getDate()],
date.getFullYear()
].join(' ');
}
// The default "short" day strings are the first character of each day,
// e.g., "Monday" => "M".
var defaultShortDays = $locale.DATETIME_FORMATS.DAY.map(function(day) {
return day[0];
});
// The default dates are simply the numbers 1 through 31.
var defaultDates = Array(32);
for (var i = 1; i <= 31; i++) {
defaultDates[i] = i;
}
// Default ARIA messages are in English (US).
var defaultMsgCalendar = 'Calendar';
var defaultMsgOpenCalendar = 'Open calendar';
var service = {
months: this.months || $locale.DATETIME_FORMATS.MONTH,
shortMonths: this.shortMonths || $locale.DATETIME_FORMATS.SHORTMONTH,
days: this.days || $locale.DATETIME_FORMATS.DAY,
shortDays: this.shortDays || defaultShortDays,
dates: this.dates || defaultDates,
firstDayOfWeek: this.firstDayOfWeek || 0,
formatDate: this.formatDate || defaultFormatDate,
parseDate: this.parseDate || defaultParseDate,
isDateComplete: this.isDateComplete || defaultIsDateComplete,
monthHeaderFormatter: this.monthHeaderFormatter || defaultMonthHeaderFormatter,
weekNumberFormatter: this.weekNumberFormatter || defaultWeekNumberFormatter,
longDateFormatter: this.longDateFormatter || defaultLongDateFormatter,
msgCalendar: this.msgCalendar || defaultMsgCalendar,
msgOpenCalendar: this.msgOpenCalendar || defaultMsgOpenCalendar
};
return service;
};
DateLocaleProvider.prototype.$get.$inject = ["$locale"];
$provide.provider('$mdDateLocale', new DateLocaleProvider());
}]);
})();
(function() {
'use strict';
// POST RELEASE
// TODO(jelbourn): Demo that uses moment.js
// TODO(jelbourn): make sure this plays well with validation and ngMessages.
// TODO(jelbourn): calendar pane doesn't open up outside of visible viewport.
// TODO(jelbourn): forward more attributes to the internal input (required, autofocus, etc.)
// TODO(jelbourn): something better for mobile (calendar panel takes up entire screen?)
// TODO(jelbourn): input behavior (masking? auto-complete?)
// TODO(jelbourn): UTC mode
// TODO(jelbourn): RTL
angular.module('material.components.datepicker')
.directive('mdDatepicker', datePickerDirective);
/**
* @ngdoc directive
* @name mdDatepicker
* @module material.components.datepicker
*
* @param {Date} ng-model The component's model. Expects a JavaScript Date object.
* @param {expression=} ng-change Expression evaluated when the model value changes.
* @param {Date=} md-min-date Expression representing a min date (inclusive).
* @param {Date=} md-max-date Expression representing a max date (inclusive).
* @param {boolean=} disabled Whether the datepicker is disabled.
* @param {boolean=} required Whether a value is required for the datepicker.
*
* @description
* `<md-datepicker>` is a component used to select a single date.
* For information on how to configure internationalization for the date picker,
* see `$mdDateLocaleProvider`.
*
* This component supports [ngMessages](https://docs.angularjs.org/api/ngMessages/directive/ngMessages).
* Supported attributes are:
* * `required`: whether a required date is not set.
* * `mindate`: whether the selected date is before the minimum allowed date.
* * `maxdate`: whether the selected date is after the maximum allowed date.
*
* @usage
* <hljs lang="html">
* <md-datepicker ng-model="birthday"></md-datepicker>
* </hljs>
*
*/
function datePickerDirective() {
return {
template:
// Buttons are not in the tab order because users can open the calendar via keyboard
// interaction on the text input, and multiple tab stops for one component (picker)
// may be confusing.
'<md-button class="md-datepicker-button md-icon-button" type="button" ' +
'tabindex="-1" aria-hidden="true" ' +
'ng-click="ctrl.openCalendarPane($event)">' +
'<md-icon class="md-datepicker-calendar-icon" md-svg-icon="md-calendar"></md-icon>' +
'</md-button>' +
'<div class="md-datepicker-input-container" ' +
'ng-class="{\'md-datepicker-focused\': ctrl.isFocused}">' +
'<input class="md-datepicker-input" aria-haspopup="true" ' +
'ng-focus="ctrl.setFocused(true)" ng-blur="ctrl.setFocused(false)">' +
'<md-button type="button" md-no-ink ' +
'class="md-datepicker-triangle-button md-icon-button" ' +
'ng-click="ctrl.openCalendarPane($event)" ' +
'aria-label="{{::ctrl.dateLocale.msgOpenCalendar}}">' +
'<div class="md-datepicker-expand-triangle"></div>' +
'</md-button>' +
'</div>' +
// This pane will be detached from here and re-attached to the document body.
'<div class="md-datepicker-calendar-pane md-whiteframe-z1">' +
'<div class="md-datepicker-input-mask">' +
'<div class="md-datepicker-input-mask-opaque"></div>' +
'</div>' +
'<div class="md-datepicker-calendar">' +
'<md-calendar role="dialog" aria-label="{{::ctrl.dateLocale.msgCalendar}}" ' +
'md-min-date="ctrl.minDate" md-max-date="ctrl.maxDate"' +
'ng-model="ctrl.date" ng-if="ctrl.isCalendarOpen">' +
'</md-calendar>' +
'</div>' +
'</div>',
require: ['ngModel', 'mdDatepicker'],
scope: {
minDate: '=mdMinDate',
maxDate: '=mdMaxDate',
placeholder: '@mdPlaceholder'
},
controller: DatePickerCtrl,
controllerAs: 'ctrl',
bindToController: true,
link: function(scope, element, attr, controllers) {
var ngModelCtrl = controllers[0];
var mdDatePickerCtrl = controllers[1];
mdDatePickerCtrl.configureNgModel(ngModelCtrl);
}
};
}
/** Additional offset for the input's `size` attribute, which is updated based on its content. */
var EXTRA_INPUT_SIZE = 3;
/** Class applied to the container if the date is invalid. */
var INVALID_CLASS = 'md-datepicker-invalid';
/** Default time in ms to debounce input event by. */
var DEFAULT_DEBOUNCE_INTERVAL = 500;
/**
* Height of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-height is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_HEIGHT = 368;
/**
* Width of the calendar pane used to check if the pane is going outside the boundary of
* the viewport. See calendar.scss for how $md-calendar-width is computed; an extra 20px is
* also added to space the pane away from the exact edge of the screen.
*
* This is computed statically now, but can be changed to be measured if the circumstances
* of calendar sizing are changed.
*/
var CALENDAR_PANE_WIDTH = 360;
/**
* Controller for md-datepicker.
*
* ngInject @constructor
*/
function DatePickerCtrl($scope, $element, $attrs, $compile, $timeout, $mdConstant, $mdTheming,
$mdUtil, $mdDateLocale, $$mdDateUtil, $$rAF) {
/** @final */
this.$compile = $compile;
/** @final */
this.$timeout = $timeout;
/** @final */
this.dateLocale = $mdDateLocale;
/** @final */
this.dateUtil = $$mdDateUtil;
/** @final */
this.$mdConstant = $mdConstant;
/* @final */
this.$mdUtil = $mdUtil;
/** @final */
this.$$rAF = $$rAF;
/** @type {!angular.NgModelController} */
this.ngModelCtrl = null;
/** @type {HTMLInputElement} */
this.inputElement = $element[0].querySelector('input');
/** @final {!angular.JQLite} */
this.ngInputElement = angular.element(this.inputElement);
/** @type {HTMLElement} */
this.inputContainer = $element[0].querySelector('.md-datepicker-input-container');
/** @type {HTMLElement} Floating calendar pane. */
this.calendarPane = $element[0].querySelector('.md-datepicker-calendar-pane');
/** @type {HTMLElement} Calendar icon button. */
this.calendarButton = $element[0].querySelector('.md-datepicker-button');
/**
* Element covering everything but the input in the top of the floating calendar pane.
* @type {HTMLElement}
*/
this.inputMask = $element[0].querySelector('.md-datepicker-input-mask-opaque');
/** @final {!angular.JQLite} */
this.$element = $element;
/** @final {!angular.Attributes} */
this.$attrs = $attrs;
/** @final {!angular.Scope} */
this.$scope = $scope;
/** @type {Date} */
this.date = null;
/** @type {boolean} */
this.isFocused = false;
/** @type {boolean} */
this.isDisabled;
this.setDisabled($element[0].disabled || angular.isString($attrs['disabled']));
/** @type {boolean} Whether the date-picker's calendar pane is open. */
this.isCalendarOpen = false;
/**
* Element from which the calendar pane was opened. Keep track of this so that we can return
* focus to it when the pane is closed.
* @type {HTMLElement}
*/
this.calendarPaneOpenedFrom = null;
this.calendarPane.id = 'md-date-pane' + $mdUtil.nextUid();
$mdTheming($element);
/** Pre-bound click handler is saved so that the event listener can be removed. */
this.bodyClickHandler = angular.bind(this, this.handleBodyClick);
/** Pre-bound resize handler so that the event listener can be removed. */
this.windowResizeHandler = $mdUtil.debounce(angular.bind(this, this.closeCalendarPane), 100);
// Unless the user specifies so, the datepicker should not be a tab stop.
// This is necessary because ngAria might add a tabindex to anything with an ng-model
// (based on whether or not the user has turned that particular feature on/off).
if (!$attrs['tabindex']) {
$element.attr('tabindex', '-1');
}
this.installPropertyInterceptors();
this.attachChangeListeners();
this.attachInteractionListeners();
var self = this;
$scope.$on('$destroy', function() {
self.detachCalendarPane();
});
}
DatePickerCtrl.$inject = ["$scope", "$element", "$attrs", "$compile", "$timeout", "$mdConstant", "$mdTheming", "$mdUtil", "$mdDateLocale", "$$mdDateUtil", "$$rAF"];
/**
* Sets up the controller's reference to ngModelController.
* @param {!angular.NgModelController} ngModelCtrl
*/
DatePickerCtrl.prototype.configureNgModel = function(ngModelCtrl) {
this.ngModelCtrl = ngModelCtrl;
var self = this;
ngModelCtrl.$render = function() {
self.date = self.ngModelCtrl.$viewValue;
self.inputElement.value = self.dateLocale.formatDate(self.date);
self.resizeInputElement();
self.setErrorFlags();
};
};
/**
* Attach event listeners for both the text input and the md-calendar.
* Events are used instead of ng-model so that updates don't infinitely update the other
* on a change. This should also be more performant than using a $watch.
*/
DatePickerCtrl.prototype.attachChangeListeners = function() {
var self = this;
self.$scope.$on('md-calendar-change', function(event, date) {
self.ngModelCtrl.$setViewValue(date);
self.date = date;
self.inputElement.value = self.dateLocale.formatDate(date);
self.closeCalendarPane();
self.resizeInputElement();
self.inputContainer.classList.remove(INVALID_CLASS);
});
self.ngInputElement.on('input', angular.bind(self, self.resizeInputElement));
// TODO(chenmike): Add ability for users to specify this interval.
self.ngInputElement.on('input', self.$mdUtil.debounce(self.handleInputEvent,
DEFAULT_DEBOUNCE_INTERVAL, self));
};
/** Attach event listeners for user interaction. */
DatePickerCtrl.prototype.attachInteractionListeners = function() {
var self = this;
var $scope = this.$scope;
var keyCodes = this.$mdConstant.KEY_CODE;
// Add event listener through angular so that we can triggerHandler in unit tests.
self.ngInputElement.on('keydown', function(event) {
if (event.altKey && event.keyCode == keyCodes.DOWN_ARROW) {
self.openCalendarPane(event);
$scope.$digest();
}
});
$scope.$on('md-calendar-close', function() {
self.closeCalendarPane();
});
};
/**
* Capture properties set to the date-picker and imperitively handle internal changes.
* This is done to avoid setting up additional $watches.
*/
DatePickerCtrl.prototype.installPropertyInterceptors = function() {
var self = this;
if (this.$attrs['ngDisabled']) {
// The expression is to be evaluated against the directive element's scope and not
// the directive's isolate scope.
var scope = this.$mdUtil.validateScope(this.$element) ? this.$element.scope() : null;
if ( scope ) {
scope.$watch(this.$attrs['ngDisabled'], function(isDisabled) {
self.setDisabled(isDisabled);
});
}
}
Object.defineProperty(this, 'placeholder', {
get: function() { return self.inputElement.placeholder; },
set: function(value) { self.inputElement.placeholder = value || ''; }
});
};
/**
* Sets whether the date-picker is disabled.
* @param {boolean} isDisabled
*/
DatePickerCtrl.prototype.setDisabled = function(isDisabled) {
this.isDisabled = isDisabled;
this.inputElement.disabled = isDisabled;
this.calendarButton.disabled = isDisabled;
};
/**
* Sets the custom ngModel.$error flags to be consumed by ngMessages. Flags are:
* - mindate: whether the selected date is before the minimum date.
* - maxdate: whether the selected flag is after the maximum date.
*/
DatePickerCtrl.prototype.setErrorFlags = function() {
if (this.dateUtil.isValidDate(this.date)) {
if (this.dateUtil.isValidDate(this.minDate)) {
this.ngModelCtrl.$error['mindate'] = this.date < this.minDate;
}
if (this.dateUtil.isValidDate(this.maxDate)) {
this.ngModelCtrl.$error['maxdate'] = this.date > this.maxDate;
}
}
};
/** Resizes the input element based on the size of its content. */
DatePickerCtrl.prototype.resizeInputElement = function() {
this.inputElement.size = this.inputElement.value.length + EXTRA_INPUT_SIZE;
};
/**
* Sets the model value if the user input is a valid date.
* Adds an invalid class to the input element if not.
*/
DatePickerCtrl.prototype.handleInputEvent = function() {
var inputString = this.inputElement.value;
var parsedDate = this.dateLocale.parseDate(inputString);
this.dateUtil.setDateTimeToMidnight(parsedDate);
if (inputString === '') {
this.ngModelCtrl.$setViewValue(null);
this.date = null;
this.inputContainer.classList.remove(INVALID_CLASS);
} else if (this.dateUtil.isValidDate(parsedDate) &&
this.dateLocale.isDateComplete(inputString) &&
this.dateUtil.isDateWithinRange(parsedDate, this.minDate, this.maxDate)) {
this.ngModelCtrl.$setViewValue(parsedDate);
this.date = parsedDate;
this.inputContainer.classList.remove(INVALID_CLASS);
} else {
// If there's an input string, it's an invalid date.
this.inputContainer.classList.toggle(INVALID_CLASS, inputString);
}
};
/** Position and attach the floating calendar to the document. */
DatePickerCtrl.prototype.attachCalendarPane = function() {
var calendarPane = this.calendarPane;
calendarPane.style.transform = '';
this.$element.addClass('md-datepicker-open');
var elementRect = this.inputContainer.getBoundingClientRect();
var bodyRect = document.body.getBoundingClientRect();
// Check to see if the calendar pane would go off the screen. If so, adjust position
// accordingly to keep it within the viewport.
var paneTop = elementRect.top - bodyRect.top;
var paneLeft = elementRect.left - bodyRect.left;
// If the right edge of the pane would be off the screen and shifting it left by the
// difference would not go past the left edge of the screen. If the calendar pane is too
// big to fit on the screen at all, move it to the left of the screen and scale the entire
// element down to fit.
if (paneLeft + CALENDAR_PANE_WIDTH > bodyRect.right) {
if (bodyRect.right - CALENDAR_PANE_WIDTH > 0) {
paneLeft = bodyRect.right - CALENDAR_PANE_WIDTH;
} else {
paneLeft = 0;
var scale = bodyRect.width / CALENDAR_PANE_WIDTH;
calendarPane.style.transform = 'scale(' + scale + ')';
}
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
if (paneLeft + CALENDAR_PANE_WIDTH > bodyRect.right &&
bodyRect.right - CALENDAR_PANE_WIDTH > 0) {
paneLeft = bodyRect.right - CALENDAR_PANE_WIDTH;
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
// If the bottom edge of the pane would be off the screen and shifting it up by the
// difference would not go past the top edge of the screen.
if (paneTop + CALENDAR_PANE_HEIGHT > bodyRect.bottom &&
bodyRect.bottom - CALENDAR_PANE_HEIGHT > 0) {
paneTop = bodyRect.bottom - CALENDAR_PANE_HEIGHT;
calendarPane.classList.add('md-datepicker-pos-adjusted');
}
calendarPane.style.left = paneLeft + 'px';
calendarPane.style.top = paneTop + 'px';
document.body.appendChild(calendarPane);
// The top of the calendar pane is a transparent box that shows the text input underneath.
// Since the pane is floating, though, the page underneath the pane *adjacent* to the input is
// also shown unless we cover it up. The inputMask does this by filling up the remaining space
// based on the width of the input.
this.inputMask.style.left = elementRect.width + 'px';
// Add CSS class after one frame to trigger open animation.
this.$$rAF(function() {
calendarPane.classList.add('md-pane-open');
});
};
/** Detach the floating calendar pane from the document. */
DatePickerCtrl.prototype.detachCalendarPane = function() {
this.$element.removeClass('md-datepicker-open');
this.calendarPane.classList.remove('md-pane-open');
this.calendarPane.classList.remove('md-datepicker-pos-adjusted');
if (this.calendarPane.parentNode) {
// Use native DOM removal because we do not want any of the angular state of this element
// to be disposed.
this.calendarPane.parentNode.removeChild(this.calendarPane);
}
};
/**
* Open the floating calendar pane.
* @param {Event} event
*/
DatePickerCtrl.prototype.openCalendarPane = function(event) {
if (!this.isCalendarOpen && !this.isDisabled) {
this.isCalendarOpen = true;
this.calendarPaneOpenedFrom = event.target;
this.attachCalendarPane();
this.focusCalendar();
// Because the calendar pane is attached directly to the body, it is possible that the
// rest of the component (input, etc) is in a different scrolling container, such as
// an md-content. This means that, if the container is scrolled, the pane would remain
// stationary. To remedy this, we disable scrolling while the calendar pane is open, which
// also matches the native behavior for things like `<select>` on Mac and Windows.
this.$mdUtil.disableScrollAround(this.calendarPane);
// Attach click listener inside of a timeout because, if this open call was triggered by a
// click, we don't want it to be immediately propogated up to the body and handled.
var self = this;
this.$mdUtil.nextTick(function() {
document.body.addEventListener('click', self.bodyClickHandler);
}, false);
window.addEventListener('resize', this.windowResizeHandler);
}
};
/** Close the floating calendar pane. */
DatePickerCtrl.prototype.closeCalendarPane = function() {
this.isCalendarOpen = false;
this.detachCalendarPane();
this.calendarPaneOpenedFrom.focus();
this.calendarPaneOpenedFrom = null;
this.$mdUtil.enableScrolling();
document.body.removeEventListener('click', this.bodyClickHandler);
window.removeEventListener('resize', this.windowResizeHandler);
};
/** Gets the controller instance for the calendar in the floating pane. */
DatePickerCtrl.prototype.getCalendarCtrl = function() {
return angular.element(this.calendarPane.querySelector('md-calendar')).controller('mdCalendar');
};
/** Focus the calendar in the floating pane. */
DatePickerCtrl.prototype.focusCalendar = function() {
// Use a timeout in order to allow the calendar to be rendered, as it is gated behind an ng-if.
var self = this;
this.$mdUtil.nextTick(function() {
self.getCalendarCtrl().focus();
}, false);
};
/**
* Sets whether the input is currently focused.
* @param {boolean} isFocused
*/
DatePickerCtrl.prototype.setFocused = function(isFocused) {
this.isFocused = isFocused;
};
/**
* Handles a click on the document body when the floating calendar pane is open.
* Closes the floating calendar pane if the click is not inside of it.
* @param {MouseEvent} event
*/
DatePickerCtrl.prototype.handleBodyClick = function(event) {
if (this.isCalendarOpen) {
// TODO(jelbourn): way want to also include the md-datepicker itself in this check.
var isInCalendar = this.$mdUtil.getClosest(event.target, 'md-calendar');
if (!isInCalendar) {
this.closeCalendarPane();
}
this.$scope.$digest();
}
};
})();
(function() {
'use strict';
/**
* Utility for performing date calculations to facilitate operation of the calendar and
* datepicker.
*/
angular.module('material.components.datepicker').factory('$$mdDateUtil', function() {
return {
getFirstDateOfMonth: getFirstDateOfMonth,
getNumberOfDaysInMonth: getNumberOfDaysInMonth,
getDateInNextMonth: getDateInNextMonth,
getDateInPreviousMonth: getDateInPreviousMonth,
isInNextMonth: isInNextMonth,
isInPreviousMonth: isInPreviousMonth,
getDateMidpoint: getDateMidpoint,
isSameMonthAndYear: isSameMonthAndYear,
getWeekOfMonth: getWeekOfMonth,
incrementDays: incrementDays,
incrementMonths: incrementMonths,
getLastDateOfMonth: getLastDateOfMonth,
isSameDay: isSameDay,
getMonthDistance: getMonthDistance,
isValidDate: isValidDate,
setDateTimeToMidnight: setDateTimeToMidnight,
createDateAtMidnight: createDateAtMidnight,
isDateWithinRange: isDateWithinRange
};
/**
* Gets the first day of the month for the given date's month.
* @param {Date} date
* @returns {Date}
*/
function getFirstDateOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), 1);
}
/**
* Gets the number of days in the month for the given date's month.
* @param date
* @returns {number}
*/
function getNumberOfDaysInMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}
/**
* Get an arbitrary date in the month after the given date's month.
* @param date
* @returns {Date}
*/
function getDateInNextMonth(date) {
return new Date(date.getFullYear(), date.getMonth() + 1, 1);
}
/**
* Get an arbitrary date in the month before the given date's month.
* @param date
* @returns {Date}
*/
function getDateInPreviousMonth(date) {
return new Date(date.getFullYear(), date.getMonth() - 1, 1);
}
/**
* Gets whether two dates have the same month and year.
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
function isSameMonthAndYear(d1, d2) {
return d1.getFullYear() === d2.getFullYear() && d1.getMonth() === d2.getMonth();
}
/**
* Gets whether two dates are the same day (not not necesarily the same time).
* @param {Date} d1
* @param {Date} d2
* @returns {boolean}
*/
function isSameDay(d1, d2) {
return d1.getDate() == d2.getDate() && isSameMonthAndYear(d1, d2);
}
/**
* Gets whether a date is in the month immediately after some date.
* @param {Date} startDate The date from which to compare.
* @param {Date} endDate The date to check.
* @returns {boolean}
*/
function isInNextMonth(startDate, endDate) {
var nextMonth = getDateInNextMonth(startDate);
return isSameMonthAndYear(nextMonth, endDate);
}
/**
* Gets whether a date is in the month immediately before some date.
* @param {Date} startDate The date from which to compare.
* @param {Date} endDate The date to check.
* @returns {boolean}
*/
function isInPreviousMonth(startDate, endDate) {
var previousMonth = getDateInPreviousMonth(startDate);
return isSameMonthAndYear(endDate, previousMonth);
}
/**
* Gets the midpoint between two dates.
* @param {Date} d1
* @param {Date} d2
* @returns {Date}
*/
function getDateMidpoint(d1, d2) {
return createDateAtMidnight((d1.getTime() + d2.getTime()) / 2);
}
/**
* Gets the week of the month that a given date occurs in.
* @param {Date} date
* @returns {number} Index of the week of the month (zero-based).
*/
function getWeekOfMonth(date) {
var firstDayOfMonth = getFirstDateOfMonth(date);
return Math.floor((firstDayOfMonth.getDay() + date.getDate() - 1) / 7);
}
/**
* Gets a new date incremented by the given number of days. Number of days can be negative.
* @param {Date} date
* @param {number} numberOfDays
* @returns {Date}
*/
function incrementDays(date, numberOfDays) {
return new Date(date.getFullYear(), date.getMonth(), date.getDate() + numberOfDays);
}
/**
* Gets a new date incremented by the given number of months. Number of months can be negative.
* If the date of the given month does not match the target month, the date will be set to the
* last day of the month.
* @param {Date} date
* @param {number} numberOfMonths
* @returns {Date}
*/
function incrementMonths(date, numberOfMonths) {
// If the same date in the target month does not actually exist, the Date object will
// automatically advance *another* month by the number of missing days.
// For example, if you try to go from Jan. 30 to Feb. 30, you'll end up on March 2.
// So, we check if the month overflowed and go to the last day of the target month instead.
var dateInTargetMonth = new Date(date.getFullYear(), date.getMonth() + numberOfMonths, 1);
var numberOfDaysInMonth = getNumberOfDaysInMonth(dateInTargetMonth);
if (numberOfDaysInMonth < date.getDate()) {
dateInTargetMonth.setDate(numberOfDaysInMonth);
} else {
dateInTargetMonth.setDate(date.getDate());
}
return dateInTargetMonth;
}
/**
* Get the integer distance between two months. This *only* considers the month and year
* portion of the Date instances.
*
* @param {Date} start
* @param {Date} end
* @returns {number} Number of months between `start` and `end`. If `end` is before `start`
* chronologically, this number will be negative.
*/
function getMonthDistance(start, end) {
return (12 * (end.getFullYear() - start.getFullYear())) + (end.getMonth() - start.getMonth());
}
/**
* Gets the last day of the month for the given date.
* @param {Date} date
* @returns {Date}
*/
function getLastDateOfMonth(date) {
return new Date(date.getFullYear(), date.getMonth(), getNumberOfDaysInMonth(date));
}
/**
* Checks whether a date is valid.
* @param {Date} date
* @return {boolean} Whether the date is a valid Date.
*/
function isValidDate(date) {
return date != null && date.getTime && !isNaN(date.getTime());
}
/**
* Sets a date's time to midnight.
* @param {Date} date
*/
function setDateTimeToMidnight(date) {
if (isValidDate(date)) {
date.setHours(0, 0, 0, 0);
}
}
/**
* Creates a date with the time set to midnight.
* Drop-in replacement for two forms of the Date constructor:
* 1. No argument for Date representing now.
* 2. Single-argument value representing number of seconds since Unix Epoch.
* @param {number=} opt_value
* @return {Date} New date with time set to midnight.
*/
function createDateAtMidnight(opt_value) {
var date;
if (angular.isUndefined(opt_value)) {
date = new Date();
} else {
date = new Date(opt_value);
}
setDateTimeToMidnight(date);
return date;
}
/**
* Checks if a date is within a min and max range.
* If minDate or maxDate are not dates, they are ignored.
* @param {Date} date
* @param {Date} minDate
* @param {Date} maxDate
*/
function isDateWithinRange(date, minDate, maxDate) {
return (!angular.isDate(minDate) || minDate <= date) &&
(!angular.isDate(maxDate) || maxDate >= date);
}
});
})();
ng.material.components.datepicker = angular.module("material.components.datepicker"); | mit |
wendywill25/node-api-server | src/App/shared/PokemonTable/index.js | 840 | /*** @jsx React.DOM */
import React from 'react';
var PokemonTable = React.createClass({
render: function() {
var rows = this.props.pokemon.map(function(pokemon) {
return (
<tr key={pokemon.id}>
<td>{pokemon.id}</td>
<td>{pokemon.name}</td>
<td>{pokemon.level}</td>
</tr>
);
});
return (
<table className="pokemon-table">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Level</th>
</tr>
</thead>
<tbody>
{rows}
</tbody>
</table>
);
}
});
export default PokemonTable;
| mit |
sfrenza/test-for-bot | venv/Lib/site-packages/nltk/stem/util.py | 354 | # Natural Language Toolkit: Stemmer Utilities
#
# Copyright (C) 2001-2017 NLTK Project
# Author: Helder <he7d3r@gmail.com>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
def suffix_replace(original, old, new):
"""
Replaces the old suffix of the original string by a new suffix
"""
return original[:-len(old)] + new
| mit |
google-code-export/gwtquery | gwtquery-core/src/main/java/com/google/gwt/query/rebind/JsniBundleGenerator.java | 10501 | /*
* Copyright 2013, The gwtquery team.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.query.rebind;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.JMethod;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.query.client.builders.JsniBundle.LibrarySource;
import com.google.gwt.query.client.builders.JsniBundle.MethodSource;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;
import org.apache.commons.io.output.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
/**
* Generates an implementation of a user-defined interface <code>T</code> that
* extends {@link JsniBundle}.
*
* The generated implementation includes hand-written external js-files into
* jsni methods so as those files can take advantage of gwt compiler optimizations.
*
*/
public class JsniBundleGenerator extends Generator {
public String generate(TreeLogger logger, GeneratorContext context, String requestedClass)
throws UnableToCompleteException {
TypeOracle oracle = context.getTypeOracle();
JClassType clazz = oracle.findType(requestedClass);
String packageName = clazz.getPackage().getName();
String className = clazz.getName().replace('.', '_') + "_Impl";
String fullName = packageName + "." + className;
PrintWriter pw = context.tryCreate(logger, packageName, className);
if (pw != null) {
ClassSourceFileComposerFactory fact =
new ClassSourceFileComposerFactory(packageName, className);
if (clazz.isInterface() != null) {
fact.addImplementedInterface(requestedClass);
} else {
fact.setSuperclass(requestedClass);
}
SourceWriter sw = fact.createSourceWriter(context, pw);
if (sw != null) {
for (JMethod method : clazz.getMethods()) {
LibrarySource librarySource = method.getAnnotation(LibrarySource.class);
String value, prepend, postpend;
String replace[];
if (librarySource != null) {
value = librarySource.value();
prepend = librarySource.prepend();
postpend = librarySource.postpend();
replace = librarySource.replace();
} else {
MethodSource methodSource = method.getAnnotation(MethodSource.class);
if (methodSource != null) {
value = methodSource.value();
prepend = methodSource.prepend();
postpend = methodSource.postpend();
replace = methodSource.replace();
} else {
continue;
}
}
try {
// Read the javascript content
String content = getContent(logger, packageName.replace(".", "/"), value);
// Adjust javascript so as we can introduce it in a JSNI comment block without
// breaking java syntax.
String jsni = parseJavascriptSource(content);
for (int i = 0; i < replace.length - 1; i += 2) {
jsni = jsni.replaceAll(replace[i], replace[i + 1]);
}
pw.println(method.toString().replace("abstract", "native") + "/*-{");
pw.println(prepend);
pw.println(jsni);
pw.println(postpend);
pw.println("}-*/;");
} catch (Exception e) {
logger.log(TreeLogger.ERROR, "Error parsing javascript source: " + value + " "
+ e.getMessage());
throw new UnableToCompleteException();
}
}
}
sw.commit(logger);
}
return fullName;
}
/**
* Get the content of a javascript source. It supports remote sources hosted in CDN's.
*/
private String getContent(TreeLogger logger, String path, String src)
throws UnableToCompleteException {
HttpURLConnection connection = null;
InputStream in = null;
try {
if (!src.matches("(?i)https?://.*")) {
String file = path + "/" + src;
logger.log(TreeLogger.INFO, getClass().getSimpleName()
+ " - importing external javascript: " + file);
in = this.getClass().getClassLoader().getResourceAsStream(file);
if (in == null) {
logger.log(TreeLogger.ERROR, "Unable to read javascript file: " + file);
}
} else {
logger.log(TreeLogger.INFO, getClass().getSimpleName()
+ " - downloading external javascript: " + src);
URL url = new URL(src);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Encoding", "gzip, deflate");
connection.setRequestProperty("Host", url.getHost());
connection.setConnectTimeout(3000);
connection.setReadTimeout(3000);
int status = connection.getResponseCode();
if (status != HttpURLConnection.HTTP_OK) {
logger.log(TreeLogger.ERROR, "Server Error: " + status + " "
+ connection.getResponseMessage());
throw new UnableToCompleteException();
}
String encoding = connection.getContentEncoding();
in = connection.getInputStream();
if ("gzip".equalsIgnoreCase(encoding)) {
in = new GZIPInputStream(in);
} else if ("deflate".equalsIgnoreCase(encoding)) {
in = new InflaterInputStream(in);
}
}
return inputStreamToString(in);
} catch (IOException e) {
logger.log(TreeLogger.ERROR, "Error: " + e.getMessage());
throw new UnableToCompleteException();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
/**
* Adapt a java-script block which could produce a syntax error when
* embedding it in a JSNI block.
*
* The objective is to replace any 'c' comment-ending occurrence to avoid closing
* JSNI comment blocks prematurely.
*
* A Regexp based parser is not reliable, this approach is better and faster.
*/
// Note: this comment is intentionally using c++ style to allow writing the '*/' sequence.
//
// - Remove C comments: /* ... */
// - Remove C++ comments: // ...
// - Escape certain strings: '...*/...' to '...*' + '/...'
// - Rewrite inline regex: /...*/igm to new RegExp('...*' + 'igm');
private String parseJavascriptSource(String js) throws Exception {
boolean isJS = true;
boolean isSingQuot = false;
boolean isDblQuot = false;
boolean isSlash = false;
boolean isCComment = false;
boolean isCPPComment = false;
boolean isRegex = false;
boolean isOper = false;
StringBuilder ret = new StringBuilder();
String tmp = "";
Character last = 0;
Character prev = 0;
for (int i = 0, l = js.length(); i < l; i++) {
Character c = js.charAt(i);
String out = c.toString();
if (isJS) {
isDblQuot = c == '"';
isSingQuot = c == '\'';
isSlash = c == '/';
isJS = !isDblQuot && !isSingQuot && !isSlash;
if (!isJS) {
out = tmp = "";
isCPPComment = isCComment = isRegex = false;
}
} else if (isSingQuot) {
isJS = !(isSingQuot = last == '\\' || c != '\'');
if (isJS)
out = escapeQuotedString(tmp, c);
else
tmp += c;
} else if (isDblQuot) {
isJS = !(isDblQuot = last == '\\' || c != '"');
if (isJS)
out = escapeQuotedString(tmp, c);
else
tmp += c;
} else if (isSlash) {
if (!isCPPComment && !isCComment && !isRegex && !isOper) {
isCPPComment = c == '/';
isCComment = c == '*';
isOper = !isCPPComment && !isCComment && !"=(&|?:;},".contains("" + prev);
isRegex = !isCPPComment && !isCComment && !isOper;
}
if (isOper) {
isJS = !(isSlash = isOper = false);
out = "" + last + c;
} else if (isCPPComment) {
isJS = !(isSlash = isCPPComment = c != '\n');
if (isJS)
out = "\n";
} else if (isCComment) {
isSlash = isCComment = !(isJS = (last == '*' && c == '/'));
if (isJS)
out = "";
} else if (isRegex) {
isJS = !(isSlash = isRegex = (last == '\\' || c != '/'));
if (isJS) {
String mod = "";
while (++i < l) {
c = js.charAt(i);
if ("igm".contains("" + c))
mod += c;
else
break;
}
out = escapeInlineRegex(tmp, mod) + c;
} else {
tmp += c;
}
} else {
isJS = true;
}
}
if (isJS) {
ret.append(out);
}
if (last != ' ') {
prev = last;
}
last = prev == '\\' && c == '\\' ? 0 : c;
}
return ret.toString();
}
private String escapeQuotedString(String s, Character quote) {
return quote + s.replace("*/", "*" + quote + " + " + quote + "/") + quote;
}
private String escapeInlineRegex(String s, String mod) {
if (s.endsWith("*")) {
return "new RegExp('" + s.replace("\\", "\\\\") + "','" + mod + "')";
} else {
return '/' + s + '/' + mod;
}
}
private String inputStreamToString(InputStream in) throws IOException {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int read = in.read(buffer);
while (read != -1) {
bytes.write(buffer, 0, read);
read = in.read(buffer);
}
in.close();
return bytes.toString();
}
}
| mit |
akervern/che | infrastructures/kubernetes/src/test/java/org/eclipse/che/workspace/infrastructure/kubernetes/wsplugins/SidecarServicesProvisionerTest.java | 5700 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.workspace.infrastructure.kubernetes.wsplugins;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static java.util.Collections.singletonMap;
import static java.util.stream.Collectors.toMap;
import static org.eclipse.che.workspace.infrastructure.kubernetes.Constants.CHE_ORIGINAL_NAME_LABEL;
import static org.testng.Assert.assertEquals;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.fabric8.kubernetes.api.model.Service;
import io.fabric8.kubernetes.api.model.ServiceBuilder;
import io.fabric8.kubernetes.api.model.ServicePort;
import io.fabric8.kubernetes.api.model.ServicePortBuilder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.eclipse.che.api.workspace.server.spi.InfrastructureException;
import org.eclipse.che.api.workspace.server.wsplugins.model.ChePluginEndpoint;
import org.eclipse.che.workspace.infrastructure.kubernetes.environment.KubernetesEnvironment;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
/** @author Oleksandr Garagatyi */
public class SidecarServicesProvisionerTest {
private static final String POD_NAME = "testPod";
private static final String CONFLICTING_SERVICE_NAME = "testService";
private SidecarServicesProvisioner provisioner;
private List<ChePluginEndpoint> endpoints;
@BeforeMethod
public void setUp() {
endpoints = new ArrayList<>();
provisioner = new SidecarServicesProvisioner(endpoints, POD_NAME);
}
@Test
public void shouldAddServiceForEachEndpoint() throws Exception {
List<ChePluginEndpoint> actualEndpoints =
asList(
new ChePluginEndpoint().name("testE1").targetPort(8080),
new ChePluginEndpoint().name("testE2").targetPort(10000));
endpoints.addAll(actualEndpoints);
KubernetesEnvironment kubernetesEnvironment = KubernetesEnvironment.builder().build();
provisioner.provision(kubernetesEnvironment);
assertEquals(kubernetesEnvironment.getServices(), toK8sServices(actualEndpoints));
}
@Test
public void shouldNotAddServiceForNotdDiscoverableEndpoint() throws Exception {
List<ChePluginEndpoint> actualEndpoints =
asList(
new ChePluginEndpoint().name("testE1").targetPort(8080),
new ChePluginEndpoint()
.name("testE2")
.targetPort(10000)
.attributes(ImmutableMap.of("discoverable", "false")));
endpoints.addAll(actualEndpoints);
KubernetesEnvironment kubernetesEnvironment = KubernetesEnvironment.builder().build();
provisioner.provision(kubernetesEnvironment);
assertEquals(
kubernetesEnvironment.getServices(),
toK8sServices(ImmutableList.of(new ChePluginEndpoint().name("testE1").targetPort(8080))));
}
@Test(
expectedExceptions = InfrastructureException.class,
expectedExceptionsMessageRegExp =
"Applying of sidecar tooling failed. Kubernetes service with name '"
+ CONFLICTING_SERVICE_NAME
+ "' already exists in the workspace environment.")
public void shouldNotDuplicateServicesWhenThereAreConflictingEndpoints() throws Exception {
List<ChePluginEndpoint> actualEndpoints =
asList(
new ChePluginEndpoint().name(CONFLICTING_SERVICE_NAME).targetPort(8080),
new ChePluginEndpoint().name(CONFLICTING_SERVICE_NAME).targetPort(10000));
endpoints.addAll(actualEndpoints);
KubernetesEnvironment kubernetesEnvironment = KubernetesEnvironment.builder().build();
provisioner.provision(kubernetesEnvironment);
}
@Test(
expectedExceptions = InfrastructureException.class,
expectedExceptionsMessageRegExp =
"Applying of sidecar tooling failed. Kubernetes service with name '"
+ CONFLICTING_SERVICE_NAME
+ "' already exists in the workspace environment.")
public void shouldNotDuplicateServicesWhenThereIsConflictingServiceInK8sEnv() throws Exception {
List<ChePluginEndpoint> actualEndpoints =
singletonList(new ChePluginEndpoint().name(CONFLICTING_SERVICE_NAME).targetPort(8080));
endpoints.addAll(actualEndpoints);
KubernetesEnvironment kubernetesEnvironment =
KubernetesEnvironment.builder()
.setServices(singletonMap(CONFLICTING_SERVICE_NAME, new Service()))
.build();
provisioner.provision(kubernetesEnvironment);
}
private Map<String, Service> toK8sServices(List<ChePluginEndpoint> endpoints) {
return endpoints
.stream()
.map(this::createService)
.collect(toMap(s -> s.getMetadata().getName(), Function.identity()));
}
private Service createService(ChePluginEndpoint endpoint) {
ServicePort servicePort =
new ServicePortBuilder()
.withPort(endpoint.getTargetPort())
.withProtocol("TCP")
.withNewTargetPort(endpoint.getTargetPort())
.build();
return new ServiceBuilder()
.withNewMetadata()
.withName(endpoint.getName())
.endMetadata()
.withNewSpec()
.withSelector(singletonMap(CHE_ORIGINAL_NAME_LABEL, POD_NAME))
.withPorts(singletonList(servicePort))
.endSpec()
.build();
}
}
| epl-1.0 |
cemalkilic/che | plugins/plugin-docker/che-plugin-docker-client/src/test/java/org/eclipse/che/plugin/docker/client/params/RemoveContainerParamsTest.java | 3019 | /*******************************************************************************
* Copyright (c) 2012-2017 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.plugin.docker.client.params;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
/**
* @author Mykola Morhun
*/
public class RemoveContainerParamsTest {
private static final String CONTAINER = "container";
private static final Boolean FORCE = Boolean.FALSE;
private static final Boolean REMOVE_VOLUMES = Boolean.TRUE;
private RemoveContainerParams removeContainerParams;
@Test
public void shouldCreateParamsObjectWithRequiredParameters() {
removeContainerParams = RemoveContainerParams.create(CONTAINER);
assertEquals(removeContainerParams.getContainer(), CONTAINER);
assertNull(removeContainerParams.isForce());
assertNull(removeContainerParams.isRemoveVolumes());
}
@Test
public void shouldCreateParamsObjectWithAllPossibleParameters() {
removeContainerParams = RemoveContainerParams.create(CONTAINER)
.withForce(FORCE)
.withRemoveVolumes(REMOVE_VOLUMES);
assertEquals(removeContainerParams.getContainer(), CONTAINER);
assertEquals(removeContainerParams.isForce(), FORCE);
assertEquals(removeContainerParams.isRemoveVolumes(), REMOVE_VOLUMES);
}
@Test(expectedExceptions = NullPointerException.class)
public void shouldThrowNullPointerExceptionIfContainerRequiredParameterIsNull() {
removeContainerParams = RemoveContainerParams.create(null);
}
@Test(expectedExceptions = NullPointerException.class)
public void shouldThrowNullPointerExceptionIfContainerRequiredParameterResetWithNull() {
removeContainerParams = RemoveContainerParams.create(CONTAINER)
.withContainer(null);
}
@Test
public void forceParameterShouldEqualsNullIfItNotSet() {
removeContainerParams = RemoveContainerParams.create(CONTAINER)
.withRemoveVolumes(REMOVE_VOLUMES);
assertNull(removeContainerParams.isForce());
}
@Test
public void removeVolumesParameterShouldEqualsNullIfItNotSet() {
removeContainerParams = RemoveContainerParams.create(CONTAINER)
.withForce(FORCE);
assertNull(removeContainerParams.isRemoveVolumes());
}
}
| epl-1.0 |
zero-24/joomla-cms | administrator/components/com_installer/views/update/tmpl/default.php | 5124 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_installer
*
* @copyright (C) 2008 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
JHtml::_('behavior.multiselect');
JHtml::_('formbehavior.chosen', 'select');
JHtml::_('bootstrap.tooltip');
$listOrder = $this->escape($this->state->get('list.ordering'));
$listDirn = $this->escape($this->state->get('list.direction'));
?>
<div id="installer-update" class="clearfix">
<form action="<?php echo JRoute::_('index.php?option=com_installer&view=update'); ?>" method="post" name="adminForm" id="adminForm">
<?php if (!empty( $this->sidebar)) : ?>
<div id="j-sidebar-container" class="span2">
<?php echo $this->sidebar; ?>
</div>
<div id="j-main-container" class="span10">
<?php else : ?>
<div id="j-main-container">
<?php endif; ?>
<?php if ($this->showMessage) : ?>
<?php echo $this->loadTemplate('message'); ?>
<?php endif; ?>
<?php if ($this->ftp) : ?>
<?php echo $this->loadTemplate('ftp'); ?>
<?php endif; ?>
<?php echo JLayoutHelper::render('joomla.searchtools.default', array('view' => $this)); ?>
<div class="clearfix"></div>
<?php if (empty($this->items)) : ?>
<div class="alert alert-no-items alert-info">
<?php echo JText::_('COM_INSTALLER_MSG_UPDATE_NOUPDATES'); ?>
</div>
<?php else : ?>
<table class="table table-striped">
<thead>
<tr>
<th width="1%" class="nowrap">
<?php echo JHtml::_('grid.checkall'); ?>
</th>
<th class="nowrap">
<?php echo JHtml::_('searchtools.sort', 'COM_INSTALLER_HEADING_NAME', 'u.name', $listDirn, $listOrder); ?>
</th>
<th class="nowrap center">
<?php echo JHtml::_('searchtools.sort', 'COM_INSTALLER_HEADING_LOCATION', 'client_translated', $listDirn, $listOrder); ?>
</th>
<th class="nowrap center">
<?php echo JHtml::_('searchtools.sort', 'COM_INSTALLER_HEADING_TYPE', 'type_translated', $listDirn, $listOrder); ?>
</th>
<th class="nowrap hidden-phone center">
<?php echo JText::_('COM_INSTALLER_CURRENT_VERSION'); ?>
</th>
<th class="nowrap center">
<?php echo JText::_('COM_INSTALLER_NEW_VERSION'); ?>
</th>
<th class="nowrap hidden-phone center">
<?php echo JHtml::_('searchtools.sort', 'COM_INSTALLER_HEADING_FOLDER', 'folder_translated', $listDirn, $listOrder); ?>
</th>
<th class="nowrap hidden-phone center">
<?php echo JText::_('COM_INSTALLER_HEADING_INSTALLTYPE'); ?>
</th>
<th width="40%" class="nowrap hidden-phone hidden-tablet">
<?php echo JText::_('COM_INSTALLER_HEADING_DETAILSURL'); ?>
</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="9">
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
</tfoot>
<tbody>
<?php foreach ($this->items as $i => $item) : ?>
<?php
$client = $item->client_id ? JText::_('JADMINISTRATOR') : JText::_('JSITE');
$manifest = json_decode($item->manifest_cache);
$current_version = isset($manifest->version) ? $manifest->version : JText::_('JLIB_UNKNOWN');
?>
<tr class="row<?php echo $i % 2; ?>">
<td>
<?php echo JHtml::_('grid.id', $i, $item->update_id); ?>
</td>
<td>
<label for="cb<?php echo $i; ?>">
<span class="editlinktip hasTooltip" title="<?php echo JHtml::_('tooltipText', JText::_('JGLOBAL_DESCRIPTION'), $item->description ?: JText::_('COM_INSTALLER_MSG_UPDATE_NODESC'), 0); ?>">
<?php echo $this->escape($item->name); ?>
</span>
</label>
</td>
<td class="center">
<?php echo $item->client_translated; ?>
</td>
<td class="center">
<?php echo $item->type_translated; ?>
</td>
<td class="hidden-phone center">
<span class="label label-warning"><?php echo $item->current_version; ?></span>
</td>
<td class="center">
<span class="label label-success"><?php echo $item->version; ?></span>
</td>
<td class="hidden-phone center">
<?php echo $item->folder_translated; ?>
</td>
<td class="hidden-phone center">
<?php echo $item->install_type; ?>
</td>
<td class="hidden-phone hidden-tablet">
<span class="break-word">
<?php echo $item->detailsurl; ?>
<?php if (isset($item->infourl)) : ?>
<br />
<a href="<?php echo $item->infourl; ?>" target="_blank" rel="noopener noreferrer"><?php echo $this->escape($item->infourl); ?></a>
<?php endif; ?>
</span>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<?php echo JHtml::_('form.token'); ?>
</div>
</form>
</div>
| gpl-2.0 |
cuongnd/test_pro | administrator/components/com_easyblog/views/settings/tmpl/default_social_twitter_bootstrap.php | 9753 | <?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');
?>
<div class="row-fluid">
<div class="span12">
<div class="span6">
<fieldset class="adminform">
<legend><?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_TWITTER_TITLE' ); ?></legend>
<table class="admintable" cellspacing="1">
<tbody>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_USE_TWITTER_BUTTON' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_USE_TWITTER_BUTTON_DESC' ); ?></div>
<?php echo $this->renderCheckbox( 'main_twitter_button' , $this->config->get( 'main_twitter_button' ) );?>
</div>
</td>
</tr>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_SHOW_ON_FRONTPAGE' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_SHOW_ON_FRONTPAGE_DESC' ); ?></div>
<?php echo $this->renderCheckbox( 'main_twitter_button_frontpage' , $this->config->get( 'main_twitter_button_frontpage' ) );?>
</div>
</td>
</tr>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_VIA_SCREEN_NAME' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_VIA_SCREEN_NAME_DESC' ); ?></div>
<textarea name="main_twitter_button_via_screen_name" class="inputbox half-width" style="margin-bottom: 10px;height: 75px;"><?php echo $this->config->get( 'main_twitter_button_via_screen_name' );?></textarea>
<div>
<?php echo JText::_('COM_EASYBLOG_SETTINGS_SOCIALSHARE_VIA_SCREEN_NAME_EXAMPLE'); ?>
</div>
</div>
</td>
</tr>
<tr>
<td width="300" class="key" style="vertical-align: top !important;">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_TWITTER_BUTTON_STYLE' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_( 'COM_EASYBLOG_SETTINGS_SOCIALSHARE_TWITTER_BUTTON_STYLE_DESC' ); ?></div>
<table width="70%" class="social-buttons-preview">
<tr>
<td valign="top">
<div>
<input type="radio" name="main_twitter_button_style" id="tweet_vertical" value="vertical"<?php echo $this->config->get('main_twitter_button_style') == 'vertical' ? ' checked="checked"' : '';?> />
<label for="tweet_vertical"><?php echo JText::_('COM_EASYBLOG_SETTINGS_SOCIALSHARE_BUTTON_LARGE');?></label>
</div>
<div style="text-align: center;margin-top: 5px;"><img src="<?php echo JURI::root() . 'administrator/components/com_easyblog/assets/images/tweet/button_vertical.png';?>" /></div>
</td>
<td valign="top">
<div>
<input type="radio" name="main_twitter_button_style" id="tweet_horizontal" value="horizontal"<?php echo $this->config->get('main_twitter_button_style') == 'horizontal' ? ' checked="checked"' : '';?> />
<label for="tweet_horizontal"><?php echo JText::_('COM_EASYBLOG_SETTINGS_SOCIALSHARE_BUTTON_SMALL');?></label>
</div>
<div style="text-align: center;margin-top: 5px;"><img src="<?php echo JURI::root() . 'administrator/components/com_easyblog/assets/images/tweet/button_horizontal.png';?>" /></div>
</td>
<td valign="top">
<div>
<input type="radio" name="main_twitter_button_style" id="tweet_button" value="none"<?php echo $this->config->get('main_twitter_button_style') == 'none' ? ' checked="checked"' : '';?> />
<label for="tweet_button"><?php echo JText::_('COM_EASYBLOG_SETTINGS_SOCIALSHARE_BUTTON_PLAIN');?></label>
</div>
<div style="text-align: center;margin-top: 5px;"><img src="<?php echo JURI::root() . 'administrator/components/com_easyblog/assets/images/tweet/button.png';?>" /></div>
</td>
</tr>
</table>
</div>
</td>
</tr>
</tbody>
</table>
</fieldset>
<fieldset class="adminform">
<legend><?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_CARDS_TITLE' ); ?></legend>
<p><?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_CARDS_DESC' ); ?></p>
<table class="admintable" cellspacing="1">
<tbody>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_CARDS_ENABLE' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_('COM_EASYBLOG_INTEGRATIONS_TWITTER_CARDS_ENABLE_DESC'); ?></div>
<?php echo $this->renderCheckbox( 'main_twitter_cards' , $this->config->get( 'main_twitter_cards' ) );?>
</div>
</td>
</tr>
</table>
</fieldset>
</div>
<div class="span6">
<fieldset class="adminform">
<legend><?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_TITLE' ); ?></legend>
<p><?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_INFO' ); ?></p>
<table class="admintable" cellspacing="1">
<tbody>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::sprintf( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_ENABLE', 'Twitter' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::sprintf('COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_ENABLE_DESC', 'Twitter'); ?></div>
<?php echo $this->renderCheckbox( 'integrations_twitter_microblog' , $this->config->get( 'integrations_twitter_microblog', false ) );?>
</div>
</td>
</tr>
<tr>
<td width="300" class="key" style="vertical-align: top !important;">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_SEARCH_HASHTAGS' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_('COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_SEARCH_HASHTAGS_DESC' ); ?></div>
<textarea name="integrations_twitter_microblog_hashes" class="inputbox half-width" style="margin-bottom: 10px;height: 75px;"><?php echo $this->config->get( 'integrations_twitter_microblog_hashes' );?></textarea>
<div><?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_SEARCH_HASHTAGS_INSTRUCTIONS' ); ?></div>
</div>
</td>
</tr>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_CATEGORY' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_('COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_CATEGORY_DESC' ); ?></div>
<?php echo EasyBlogHelper::populateCategories('', '', 'select', 'integrations_twitter_microblog_category', $this->config->get( 'integrations_twitter_microblog_category') , true); ?>
</div>
</td>
</tr>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_PUBLISH_STATE' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_('COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_PUBLISH_STATE_DESC' ); ?></div>
<?php
$publishFormat = array();
$publishFormat[] = JHTML::_('select.option', '0', JText::_( 'COM_EASYBLOG_UNPUBLISHED_OPTION' ) );
$publishFormat[] = JHTML::_('select.option', '1', JText::_( 'COM_EASYBLOG_PUBLISHED_OPTION' ) );
$publishFormat[] = JHTML::_('select.option', '2', JText::_( 'COM_EASYBLOG_SCHEDULED_OPTION' ) );
$publishFormat[] = JHTML::_('select.option', '3', JText::_( 'COM_EASYBLOG_DRAFT_OPTION' ) );
$showdet = JHTML::_('select.genericlist', $publishFormat, 'integrations_twitter_microblog_publish', 'size="1" class="inputbox"', 'value', 'text', $this->config->get('integrations_twitter_microblog_publish' , '1' ) );
echo $showdet;
?>
</div>
</td>
</tr>
<tr>
<td width="300" class="key">
<span class="editlinktip">
<?php echo JText::_( 'COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_FRONTPAGE' ); ?>
</span>
</td>
<td valign="top">
<div class="has-tip">
<div class="tip"><i></i><?php echo JText::_('COM_EASYBLOG_INTEGRATIONS_TWITTER_MICROBLOGGING_FRONTPAGE_DESC' ); ?></div>
<?php echo $this->renderCheckbox( 'integrations_twitter_microblog_frontpage' , $this->config->get( 'integrations_twitter_microblog_frontpage' ) );?>
</div>
</td>
</tr>
</table>
</fieldset>
</div>
</div>
</div> | gpl-2.0 |
RJRetro/mame | src/mame/video/gcpinbal.cpp | 4634 | // license:BSD-3-Clause
// copyright-holders:David Graves, R. Belmont
#include "emu.h"
#include "includes/gcpinbal.h"
/*******************************************************************/
TILE_GET_INFO_MEMBER(gcpinbal_state::get_bg0_tile_info)
{
UINT16 tilenum = m_tilemapram[0 + tile_index * 2];
UINT16 attr = m_tilemapram[1 + tile_index * 2];
SET_TILE_INFO_MEMBER(1,
(tilenum & 0xfff) + m_bg0_gfxset,
(attr & 0x1f),
TILE_FLIPYX( (attr & 0x300) >> 8));
}
TILE_GET_INFO_MEMBER(gcpinbal_state::get_bg1_tile_info)
{
UINT16 tilenum = m_tilemapram[0x800 + tile_index * 2];
UINT16 attr = m_tilemapram[0x801 + tile_index * 2];
SET_TILE_INFO_MEMBER(1,
(tilenum & 0xfff) + 0x2000 + m_bg1_gfxset,
(attr & 0x1f) + 0x30,
TILE_FLIPYX( (attr & 0x300) >> 8));
}
TILE_GET_INFO_MEMBER(gcpinbal_state::get_fg_tile_info)
{
UINT16 tilenum = m_tilemapram[0x1000 + tile_index];
SET_TILE_INFO_MEMBER(2,
(tilenum & 0xfff),
(tilenum >> 12) | 0x70,
0);
}
void gcpinbal_state::gcpinbal_core_vh_start( )
{
int xoffs = 0;
int yoffs = 0;
m_tilemap[0] = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(gcpinbal_state::get_bg0_tile_info),this),TILEMAP_SCAN_ROWS,16,16,32,32);
m_tilemap[1] = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(gcpinbal_state::get_bg1_tile_info),this),TILEMAP_SCAN_ROWS,16,16,32,32);
m_tilemap[2] = &machine().tilemap().create(m_gfxdecode, tilemap_get_info_delegate(FUNC(gcpinbal_state::get_fg_tile_info),this), TILEMAP_SCAN_ROWS,8,8,64,64);
m_tilemap[0]->set_transparent_pen(0);
m_tilemap[1]->set_transparent_pen(0);
m_tilemap[2]->set_transparent_pen(0);
/* flipscreen n/a */
m_tilemap[0]->set_scrolldx(-xoffs, 0);
m_tilemap[1]->set_scrolldx(-xoffs, 0);
m_tilemap[2]->set_scrolldx(-xoffs, 0);
m_tilemap[0]->set_scrolldy(-yoffs, 0);
m_tilemap[1]->set_scrolldy(-yoffs, 0);
m_tilemap[2]->set_scrolldy(-yoffs, 0);
}
void gcpinbal_state::video_start()
{
gcpinbal_core_vh_start();
}
/******************************************************************
TILEMAP READ AND WRITE HANDLERS
*******************************************************************/
READ16_MEMBER(gcpinbal_state::gcpinbal_tilemaps_word_r)
{
return m_tilemapram[offset];
}
WRITE16_MEMBER(gcpinbal_state::gcpinbal_tilemaps_word_w)
{
COMBINE_DATA(&m_tilemapram[offset]);
if (offset < 0x800) /* BG0 */
m_tilemap[0]->mark_tile_dirty(offset / 2);
else if ((offset < 0x1000)) /* BG1 */
m_tilemap[1]->mark_tile_dirty((offset % 0x800) / 2);
else if ((offset < 0x1800)) /* FG */
m_tilemap[2]->mark_tile_dirty((offset % 0x800));
}
/**************************************************************
SCREEN REFRESH
**************************************************************/
UINT32 gcpinbal_state::screen_update_gcpinbal(screen_device &screen, bitmap_ind16 &bitmap, const rectangle &cliprect)
{
int i;
UINT16 tile_sets = 0;
UINT8 layer[3];
#ifdef MAME_DEBUG
if (machine().input().code_pressed_once(KEYCODE_V))
{
m_dislayer[0] ^= 1;
popmessage("bg0: %01x", m_dislayer[0]);
}
if (machine().input().code_pressed_once(KEYCODE_B))
{
m_dislayer[1] ^= 1;
popmessage("bg1: %01x", m_dislayer[1]);
}
if (machine().input().code_pressed_once(KEYCODE_N))
{
m_dislayer[2] ^= 1;
popmessage("fg: %01x", m_dislayer[2]);
}
#endif
m_scrollx[0] = m_ioc_ram[0x14 / 2];
m_scrolly[0] = m_ioc_ram[0x16 / 2];
m_scrollx[1] = m_ioc_ram[0x18 / 2];
m_scrolly[1] = m_ioc_ram[0x1a / 2];
m_scrollx[2] = m_ioc_ram[0x1c / 2];
m_scrolly[2] = m_ioc_ram[0x1e / 2];
tile_sets = m_ioc_ram[0x88 / 2];
m_bg0_gfxset = (tile_sets & 0x400) ? 0x1000 : 0;
m_bg1_gfxset = (tile_sets & 0x800) ? 0x1000 : 0;
for (i = 0; i < 3; i++)
{
m_tilemap[i]->set_scrollx(0, m_scrollx[i]);
m_tilemap[i]->set_scrolly(0, m_scrolly[i]);
}
screen.priority().fill(0, cliprect);
bitmap.fill(0, cliprect);
layer[0] = 0;
layer[1] = 1;
layer[2] = 2;
#ifdef MAME_DEBUG
if (m_dislayer[layer[0]] == 0)
#endif
m_tilemap[layer[0]]->draw(screen, bitmap, cliprect, TILEMAP_DRAW_OPAQUE, 1);
#ifdef MAME_DEBUG
if (m_dislayer[layer[1]] == 0)
#endif
m_tilemap[layer[1]]->draw(screen, bitmap, cliprect, 0, 2);
#ifdef MAME_DEBUG
if (m_dislayer[layer[2]] == 0)
#endif
m_tilemap[layer[2]]->draw(screen, bitmap, cliprect, 0, 4);
int sprpri = (m_ioc_ram[0x68 / 2] & 0x8800) ? 0 : 1;
m_sprgen->gcpinbal_draw_sprites(screen, bitmap, cliprect, m_gfxdecode, 16, sprpri);
#if 0
{
// char buf[80];
sprintf(buf,"bg0_gfx: %04x bg1_gfx: %04x ", m_bg0_gfxset, m_bg1_gfxset);
popmessage(buf);
}
#endif
return 0;
}
| gpl-2.0 |
joomla/joomla-cms | administrator/components/com_scheduler/src/Helper/ExecRuleHelper.php | 3328 | <?php
/**
* @package Joomla.Administrator
* @subpackage com_scheduler
*
* @copyright (C) 2021 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\Component\Scheduler\Administrator\Helper;
// Restrict direct access
\defined('_JEXEC') or die;
use Cron\CronExpression;
use Joomla\CMS\Date\Date;
use Joomla\CMS\Factory;
use Joomla\Component\Scheduler\Administrator\Task\Task;
use Joomla\Database\DatabaseDriver;
use Joomla\Utilities\ArrayHelper;
/**
* Helper class for supporting task execution rules.
*
* @since 4.1.0
* @todo This helper should probably be merged into the {@see Task} class.
*/
class ExecRuleHelper
{
/**
* The execution rule type
*
* @var string
* @since 4.1.0
*/
private $type;
/**
* @var array
* @since 4.1.0
*/
private $task;
/**
* @var object
* @since 4.1.0
*/
private $rule;
/**
* @param array|object $task A task entry
*
* @since 4.1.0
*/
public function __construct($task)
{
$this->task = \is_array($task) ? $task : ArrayHelper::fromObject($task);
$rule = $this->getFromTask('cron_rules');
$this->rule = \is_string($rule)
? (object) json_decode($rule)
: (\is_array($rule) ? (object) $rule : $rule);
$this->type = $this->rule->type;
}
/**
* Get a property from the task array
*
* @param string $property The property to get
* @param mixed $default The default value returned if property does not exist
*
* @return mixed
*
* @since 4.1.0
*/
private function getFromTask(string $property, $default = null)
{
$property = ArrayHelper::getValue($this->task, $property);
return $property ?? $default;
}
/**
* @param boolean $string If true, an SQL formatted string is returned.
* @param boolean $basisNow If true, the current date-time is used as the basis for projecting the next
* execution.
*
* @return ?Date|string
*
* @since 4.1.0
* @throws \Exception
*/
public function nextExec(bool $string = true, bool $basisNow = false)
{
// Exception handling here
switch ($this->type)
{
case 'interval':
$lastExec = Factory::getDate($basisNow ? 'now' : $this->getFromTask('last_execution'), 'UTC');
$interval = new \DateInterval($this->rule->exp);
$nextExec = $lastExec->add($interval);
$nextExec = $string ? $nextExec->toSql() : $nextExec;
break;
case 'cron-expression':
// @todo: testing
$cExp = new CronExpression((string) $this->rule->exp);
$nextExec = $cExp->getNextRunDate('now', 0, false, 'UTC');
$nextExec = $string ? $this->dateTimeToSql($nextExec) : $nextExec;
break;
default:
// 'manual' execution is handled here.
$nextExec = null;
}
return $nextExec;
}
/**
* Returns a sql-formatted string for a DateTime object.
* Only needed for DateTime objects returned by CronExpression, JDate supports this as class method.
*
* @param \DateTime $dateTime A DateTime object to format
*
* @return string
*
* @since 4.1.0
*/
private function dateTimeToSql(\DateTime $dateTime): string
{
static $db;
$db = $db ?? Factory::getContainer()->get(DatabaseDriver::class);
return $dateTime->format($db->getDateFormat());
}
}
| gpl-2.0 |
overdrive3000/cyclos | src/nl/strohalm/cyclos/dao/ads/AdDAO.java | 3929 | /*
This file is part of Cyclos (www.cyclos.org).
A project of the Social Trade Organisation (www.socialtrade.org).
Cyclos 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.
Cyclos 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 Cyclos; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package nl.strohalm.cyclos.dao.ads;
import java.util.Calendar;
import java.util.Collection;
import java.util.List;
import nl.strohalm.cyclos.dao.BaseDAO;
import nl.strohalm.cyclos.dao.DeletableDAO;
import nl.strohalm.cyclos.dao.IndexedDAO;
import nl.strohalm.cyclos.dao.InsertableDAO;
import nl.strohalm.cyclos.dao.UpdatableDAO;
import nl.strohalm.cyclos.entities.ads.Ad;
import nl.strohalm.cyclos.entities.ads.AdCategory;
import nl.strohalm.cyclos.entities.ads.AdCategoryWithCounterQuery;
import nl.strohalm.cyclos.entities.ads.AdCategoryWithCounterVO;
import nl.strohalm.cyclos.entities.ads.AdQuery;
import nl.strohalm.cyclos.entities.ads.FullTextAdQuery;
import nl.strohalm.cyclos.entities.exceptions.DaoException;
import nl.strohalm.cyclos.entities.groups.Group;
import nl.strohalm.cyclos.utils.Period;
/**
* Interface for ad DAO
* @author rafael
*/
public interface AdDAO extends BaseDAO<Ad>, InsertableDAO<Ad>, UpdatableDAO<Ad>, DeletableDAO<Ad>, IndexedDAO<Ad> {
/**
* Searches for Ads using a full text search, sorting results by relevance. The searched fields using keywords are:
* <ul>
* <li>title</li>
* <li>description</li>
* <li>custom fields</li>
* <li>owner name</li>
* <li>owner username</li>
* <li>owner email</li>
* <li>owner custom fields</li>
* </ul>
*/
public List<Ad> fullTextSearch(FullTextAdQuery query) throws DaoException;
/**
* Returns the counters for each of the given ad category, given the ad query
*/
public List<AdCategoryWithCounterVO> getCategoriesWithCounters(final List<AdCategory> categories, final AdCategoryWithCounterQuery query);
/**
* Get the number of ads of the given status and at the given date, and with the member belonging to the given group.
*
* @param date usually the enddate of a period
* @param groups a Collection containing the group of which the number of ads is requested. If this is an empty collection, the param is ignored.
* @param status the ad status requested
* @return an Integer with the number of ads.
*/
public Integer getNumberOfAds(Calendar date, final Collection<? extends Group> groups, Ad.Status status) throws DaoException;
/**
* Get the number of ads created in the given period
*/
public Integer getNumberOfCreatedAds(Period period, final Collection<? extends Group> groups) throws DaoException;
/**
* Get the number of active members with ads at the given date, and with the member belonging to the given groups.
*/
public Integer getNumberOfMembersWithAds(Calendar date, final Collection<? extends Group> groups) throws DaoException;
/**
* Searches for Ads. The results are expected to be ordered by publication start descending, or randomly if randomOrder is true on the query
* parameters. If no entity can be found, returns an empty list. If any exception is thrown by the underlying implementation, it should be wrapped
* by a DaoException.
*/
public List<Ad> search(AdQuery queryParameters) throws DaoException;
}
| gpl-2.0 |
pulibrary/recap | core/tests/Drupal/KernelTests/Core/Config/Storage/CachedStorageTest.php | 1920 | <?php
namespace Drupal\KernelTests\Core\Config\Storage;
use Drupal\Core\Config\FileStorage;
use Drupal\Core\Config\CachedStorage;
use Drupal\Core\StreamWrapper\PublicStream;
/**
* Tests CachedStorage operations.
*
* @group config
*/
class CachedStorageTest extends ConfigStorageTestBase {
/**
* The cache backend the cached storage is using.
*
* @var \Drupal\Core\Cache\CacheBackendInterface
*/
protected $cache;
/**
* The file storage the cached storage is using.
*
* @var \Drupal\Core\Config\FileStorage
*/
protected $fileStorage;
protected function setUp(): void {
parent::setUp();
// Create a directory.
$dir = PublicStream::basePath() . '/config';
$this->fileStorage = new FileStorage($dir);
$this->storage = new CachedStorage($this->fileStorage, \Drupal::service('cache.config'));
$this->cache = \Drupal::service('cache_factory')->get('config');
// ::listAll() verifications require other configuration data to exist.
$this->storage->write('system.performance', []);
}
/**
* {@inheritdoc}
*/
public function testInvalidStorage() {
$this->markTestSkipped('No-op as this test does not make sense');
}
/**
* {@inheritdoc}
*/
protected function read($name) {
$data = $this->cache->get($name);
// Cache misses fall through to the underlying storage.
return $data ? $data->data : $this->fileStorage->read($name);
}
/**
* {@inheritdoc}
*/
protected function insert($name, $data) {
$this->fileStorage->write($name, $data);
$this->cache->set($name, $data);
}
/**
* {@inheritdoc}
*/
protected function update($name, $data) {
$this->fileStorage->write($name, $data);
$this->cache->set($name, $data);
}
/**
* {@inheritdoc}
*/
protected function delete($name) {
$this->cache->delete($name);
unlink($this->fileStorage->getFilePath($name));
}
}
| gpl-2.0 |
amirkoklan/hollywood | kernel/classes/ezpreferences.php | 8863 | <?php
/**
* File containing the eZPreferences class.
*
* @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved.
* @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2
* @version 2012.6
* @package kernel
*/
/*!
\class eZPreferences ezpreferences.php
\brief Handles user/session preferences
Preferences can be either pr user or pr session. eZPreferences will automatically
set a session preference if the user is not logged in, if not a user preference will be set.
*/
class eZPreferences
{
const SESSION_NAME = "eZPreferences";
/*!
\static
Sets a preference value for a given user. If
the user is anonymous the value is only stored in session.
\param $name The name of the preference to store
\param $value The value of the preference to store
\param $storeUserID The user which should get the preference,
if \c false it will use the current user
\return \c true if the preference was stored correctly or \c false if something went wrong
\note Transaction unsafe. If you call several transaction unsafe methods you must enclose
the calls within a db transaction; thus within db->begin and db->commit.
*/
static function setValue( $name, $value, $storeUserID = false )
{
$db = eZDB::instance();
$name = $db->escapeString( $name );
$rawValue = $value;
$value = $db->escapeString( $value );
$isCurrentUser = true;
if ( $storeUserID === false )
{
$user = eZUser::currentUser();
}
else
{
$currentID = eZUser::currentUserID();
if ( $currentID != $storeUserID )
$isCurrentUser = false;
$user = eZUser::fetch( $storeUserID );
if ( !is_object( $user ) )
{
eZDebug::writeError( "Cannot set preference for user $storeUserID, the user does not exist" );
return false;
}
}
// We must store the database changes if:
// a - The current user is logged in (ie. not anonymous)
// b - We have specified a specific user (not the current).
// in which case isLoggedIn() will fail.
if ( $storeUserID !== false or $user->isLoggedIn() )
{
// Only store in DB if user is logged in or we have
// a specific user ID defined
$userID = $user->attribute( 'contentobject_id' );
$existingRes = $db->arrayQuery( "SELECT * FROM ezpreferences WHERE user_id = $userID AND name='$name'" );
if ( count( $existingRes ) > 0 )
{
$prefID = $existingRes[0]['id'];
$query = "UPDATE ezpreferences SET value='$value' WHERE id = $prefID AND name='$name'";
$db->query( $query );
}
else
{
$query = "INSERT INTO ezpreferences ( user_id, name, value ) VALUES ( $userID, '$name', '$value' )";
$db->query( $query );
}
}
// We also store in session if this is the current user (anonymous or normal user)
// use $rawValue as value will be escaped by session code (see #014520)
if ( $isCurrentUser )
{
eZPreferences::storeInSession( $name, $rawValue );
}
return true;
}
/*!
\static
\param $user The user object to read preferences for, if \c false it will read using the current user.
\return The preference value for the specified user.
If no variable is found \c false is returned.
\note The preferences variable will be stored in session after fetching
if the specified user is the current user.
*/
static function value( $name, $user = false )
{
if ( !( $user instanceof eZUser ) )
$user = eZUser::currentUser();
$value = false;
// If the user object is not the currently logged in user we cannot use the session values
$http = eZHTTPTool::instance();
$useCache = ( $user->ContentObjectID == $http->sessionVariable( 'eZUserLoggedInID', false ) );
if ( $useCache and eZPreferences::isStoredInSession( $name ) )
return eZPreferences::storedSessionValue( $name );
// If this the anonymous user we should return false, no need to check database.
if ( $user->isAnonymous() )
return false;
$db = eZDB::instance();
$name = $db->escapeString( $name );
$userID = $user->attribute( 'contentobject_id' );
$existingRes = $db->arrayQuery( "SELECT value FROM ezpreferences WHERE user_id = $userID AND name = '$name'" );
if ( count( $existingRes ) == 1 )
{
$value = $existingRes[0]['value'];
if ( $useCache )
eZPreferences::storeInSession( $name, $value );
}
else
{
if ( $useCache )
eZPreferences::storeInSession( $name, false );
}
return $value;
}
/*!
\static
\param $user The user object to read preferences for, if \c false it will read using the current user.
\return An array with all the preferences for the specified user.
If the user is not logged in the empty array will be returned.
*/
static function values( $user = false )
{
if ( !( $user instanceof eZUser ) )
$user = eZUser::currentUser();
if ( !$user->isAnonymous() )
{
// If the user object is not the currently logged in user we cannot use the session values
$http = eZHTTPTool::instance();
$useCache = ( $user->ContentObjectID == $http->sessionVariable( 'eZUserLoggedInID', false ) );
$returnArray = array();
$userID = $user->attribute( 'contentobject_id' );
$db = eZDB::instance();
$values = $db->arrayQuery( "SELECT name,value FROM ezpreferences WHERE user_id=$userID ORDER BY id" );
foreach ( $values as $item )
{
if ( $useCache )
eZPreferences::storeInSession( $item['name'], $item['value'] );
$returnArray[$item['name']] = $item['value'];
}
return $returnArray;
}
else
{
// For the anonymous user we just return all values, or empty array if session is un-started / value undefined
$http = eZHTTPTool::instance();
return $http->sessionVariable( eZPreferences::SESSION_NAME, array() );
}
}
/*!
\static
Makes sure the stored session values are cleaned up.
*/
static function sessionCleanup()
{
$http = eZHTTPTool::instance();
$http->removeSessionVariable( eZPreferences::SESSION_NAME );
}
/*!
\static
Makes sure the preferences named \a $name is stored in the session with the value \a $value.
*/
static function storeInSession( $name, $value )
{
$http = eZHTTPTool::instance();
$preferencesInSession = array();
if ( $http->hasSessionVariable( eZPreferences::SESSION_NAME ) )
$preferencesInSession = $http->sessionVariable( eZPreferences::SESSION_NAME );
$preferencesInSession[$name] = $value;
$http->setSessionVariable( eZPreferences::SESSION_NAME, $preferencesInSession );
}
/*!
\static
\return \c true if the preference named \a $name is stored in session.
*/
static function isStoredInSession( $name )
{
$http = eZHTTPTool::instance();
if ( !$http->hasSessionVariable( eZPreferences::SESSION_NAME, false ) )
return false;
$preferencesInSession = $http->sessionVariable( eZPreferences::SESSION_NAME );
return array_key_exists( $name, $preferencesInSession );
}
/*!
\static
\return the stored preferenced value found in the session or \c null if none were found.
*/
static function storedSessionValue( $name )
{
$http = eZHTTPTool::instance();
if ( !$http->hasSessionVariable( eZPreferences::SESSION_NAME ) )
return null;
$preferencesInSession = $http->sessionVariable( eZPreferences::SESSION_NAME );
if ( !array_key_exists( $name, $preferencesInSession ) )
return null;
return $preferencesInSession[$name];
}
/*!
\static
Removes all preferences for all users.
\note Transaction unsafe. If you call several transaction unsafe methods you must enclose
the calls within a db transaction; thus within db->begin and db->commit.
*/
static function cleanup()
{
$db = eZDB::instance();
$db->query( "DELETE FROM ezpreferences" );
}
}
?>
| gpl-2.0 |
nextgis/NextGIS_QGIS_open | python/plugins/processing/algs/qgis/Difference.py | 4490 | # -*- coding: utf-8 -*-
"""
***************************************************************************
Difference.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************************************************
* *
* 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. *
* *
***************************************************************************
"""
__author__ = 'Victor Olaya'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive
__revision__ = '$Format:%H$'
from qgis.core import QgsFeatureRequest, QgsFeature, QgsGeometry
from processing.core.ProcessingLog import ProcessingLog
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.parameters import ParameterVector
from processing.core.outputs import OutputVector
from processing.tools import dataobjects, vector
class Difference(GeoAlgorithm):
INPUT = 'INPUT'
OVERLAY = 'OVERLAY'
OUTPUT = 'OUTPUT'
#==========================================================================
#def getIcon(self):
# return QtGui.QIcon(os.path.dirname(__file__) + "/icons/difference.png")
#==========================================================================
def defineCharacteristics(self):
self.name = 'Difference'
self.group = 'Vector overlay tools'
self.addParameter(ParameterVector(Difference.INPUT,
self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_ANY]))
self.addParameter(ParameterVector(Difference.OVERLAY,
self.tr('Difference layer'), [ParameterVector.VECTOR_TYPE_ANY]))
self.addOutput(OutputVector(Difference.OUTPUT, self.tr('Difference')))
def processAlgorithm(self, progress):
layerA = dataobjects.getObjectFromUri(
self.getParameterValue(Difference.INPUT))
layerB = dataobjects.getObjectFromUri(
self.getParameterValue(Difference.OVERLAY))
GEOS_EXCEPT = True
FEATURE_EXCEPT = True
writer = self.getOutputFromName(
Difference.OUTPUT).getVectorWriter(layerA.pendingFields(),
layerA.dataProvider().geometryType(),
layerA.dataProvider().crs())
inFeatA = QgsFeature()
inFeatB = QgsFeature()
outFeat = QgsFeature()
index = vector.spatialindex(layerB)
selectionA = vector.features(layerA)
current = 0
total = 100.0 / float(len(selectionA))
for inFeatA in selectionA:
add = True
geom = QgsGeometry(inFeatA.geometry())
diff_geom = QgsGeometry(geom)
attrs = inFeatA.attributes()
intersections = index.intersects(geom.boundingBox())
for i in intersections:
request = QgsFeatureRequest().setFilterFid(i)
inFeatB = layerB.getFeatures(request).next()
tmpGeom = QgsGeometry(inFeatB.geometry())
try:
if diff_geom.intersects(tmpGeom):
diff_geom = QgsGeometry(diff_geom.difference(tmpGeom))
except:
GEOS_EXCEPT = False
add = False
break
if add:
try:
outFeat.setGeometry(diff_geom)
outFeat.setAttributes(attrs)
writer.addFeature(outFeat)
except:
FEATURE_EXCEPT = False
continue
current += 1
progress.setPercentage(int(current * total))
del writer
if not GEOS_EXCEPT:
ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
self.tr('Geometry exception while computing difference'))
if not FEATURE_EXCEPT:
ProcessingLog.addToLog(ProcessingLog.LOG_WARNING,
self.tr('Feature exception while computing difference'))
| gpl-2.0 |
Achilles-96/phpmyadmin | test/libraries/common/PMA_getDbLink_test.php | 2787 | <?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Test for PMA_getDbLink_test from Util.php
*
* @package PhpMyAdmin-test
* @group common.lib-tests
*/
/**
* Test for PMA_getDbLink_test from Util.php
*
* @package PhpMyAdmin-test
* @group common.lib-tests
*/
class PMA_GetDbLink_Test extends PHPUnit_Framework_TestCase
{
/**
* Set up
*
* @return void
*/
function setUp()
{
global $cfg;
include 'libraries/config.default.php';
$GLOBALS['server'] = 99;
}
/**
* Test for getDbLink
*
* @return void
*
* @group medium
*/
function testGetDbLinkEmpty()
{
$GLOBALS['db'] = null;
$this->assertEmpty(PMA\libraries\Util::getDbLink());
}
/**
* Test for getDbLink
*
* @return void
*
* @group medium
*/
function testGetDbLinkNull()
{
global $cfg;
$GLOBALS['db'] = 'test_db';
$database = $GLOBALS['db'];
$this->assertEquals(
'<a href="'
. PMA\libraries\Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
)
. '?db=' . $database
. '&server=99&lang=en" '
. 'title="Jump to database “'
. htmlspecialchars($database) . '”.">'
. htmlspecialchars($database) . '</a>',
PMA\libraries\Util::getDbLink()
);
}
/**
* Test for getDbLink
*
* @return void
*/
function testGetDbLink()
{
global $cfg;
$database = 'test_database';
$this->assertEquals(
'<a href="' . PMA\libraries\Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
)
. '?db=' . $database
. '&server=99&lang=en" title="Jump to database “'
. htmlspecialchars($database) . '”.">'
. htmlspecialchars($database) . '</a>',
PMA\libraries\Util::getDbLink($database)
);
}
/**
* Test for getDbLink
*
* @return void
*/
function testGetDbLinkWithSpecialChars()
{
global $cfg;
$database = 'test&data\'base';
$this->assertEquals(
'<a href="'
. PMA\libraries\Util::getScriptNameForOption(
$GLOBALS['cfg']['DefaultTabDatabase'], 'database'
)
. '?db='
. htmlspecialchars(urlencode($database))
. '&server=99&lang=en" title="Jump to database “'
. htmlspecialchars($database) . '”.">'
. htmlspecialchars($database) . '</a>',
PMA\libraries\Util::getDbLink($database)
);
}
}
| gpl-2.0 |
ohio813/pyflag | utilities/load_dictionary.py | 2620 | #!/usr/bin/env python
""" A small script to load all 4 letter words or more from the english
dictionary into the dictionary table within pyflag """
import pyflag.DB as DB
import getopt,sys,os
#
# Usage
#
def usage():
print """This script loads a list of words into the pyflag
dictionary. These words will then be indexed during scanning.
Usage: %s [options] dictionary.txt
The dictionary is expected to have one word per line, for example
andy
andies
andrews
Options:
-c|--class Specify a class for the words. The default class is 'English'.
-d|--drop Drop old table before loading
-r|--regex Add entries as regular expressions rather than strings.
-l|--literal Add entries as string literals.
-h|--help Print help (this message)
-v|--verbose Be verbose
""" % os.path.basename(sys.argv[0])
sys.exit(2)
#
# Main routine
#
try:
opts, args = getopt.getopt(sys.argv[1:], "lrhdvc:", ["literal","regex","help", "drop","verbose","class"])
except getopt.GetoptError:
# print help information and exit:
usage()
sys.exit(2)
if not args:
usage()
sys.exit(1)
# option defaults
drop = False
verbose = False
wordclass = "English"
type="word"
# parse options
for o, a in opts:
if o in ("-c", "--class"):
wordclass = a
if o in ("-v", "--verbose"):
verbose = True
if o in ("-h", "--help"):
usage()
sys.exit()
if o in ("-d", "--drop"):
drop = True
if o in ("-l", "--literal"):
type="literal"
if o in ("-r", "--regex"):
type="regex"
print "wordclass is /%s/" % wordclass
dbh=DB.DBO(None)
if drop:
print "Dropping old dictionary"
dbh.execute("DROP TABLE dictionary")
dbh.execute(
""" CREATE TABLE if not exists `dictionary` (
`id` int auto_increment,
`word` VARCHAR( 250 ) binary NOT NULL ,
`class` VARCHAR( 50 ) NOT NULL ,
`encoding` SET( 'all', 'asci', 'ucs16' ) DEFAULT 'all' NOT NULL,
`type` set ( 'word','literal','regex' ) DEFAULT 'literal' NOT NULL,
PRIMARY KEY (`id`)
)""")
count=0
for file in args[0:]:
fd=open(file)
print "Reading File %s" % file
for line in fd:
if len(line)>3:
try:
dbh.execute("insert into dictionary set word=\"%s\",class=\"%s\",type=%r" %
(DB.escape(line.strip()),wordclass,type))
count+=1
except DB.DBError:
pass
if (count % 1000) == 0:
sys.stdout.write("Added %s words\r" % count)
sys.stdout.flush()
fd.close()
| gpl-2.0 |
abergmeier/jedi_academy | code/renderer/tr_terrain.cpp | 26695 | #include "../server/exe_headers.h"
// this include must remain at the top of every CPP file
#include "tr_local.h"
#if !defined(GENERICPARSER2_H_INC)
#include "../game/genericparser2.h"
#endif
// To do:
// Alter variance dependent on global distance from player (colour code this for cg_terrainCollisionDebug)
// Improve texture blending on edge conditions
// Link to neightbouring terrains or architecture (edge conditions)
// Post process generated light data to make sure there are no bands within a patch
#include "../qcommon/cm_landscape.h"
#include "tr_landscape.h"
#define VectorSet5(v,x,y,z,a,b) ((v)[0]=(x), (v)[1]=(y), (v)[2]=(z), (v)[3]=(a), (v)[4]=(b))
#define VectorScaleVectorAdd(c,a,b,o) ((o)[0]=(c)[0]+((a)[0]*(b)[0]),(o)[1]=(c)[1]+((a)[1]*(b)[1]),(o)[2]=(c)[2]+((a)[2]*(b)[2]))
cvar_t *r_drawTerrain;
cvar_t *r_terrainTessellate;
cvar_t *r_terrainWaterOffset;
cvar_t *r_count;
static int TerrainFog = 0;
static float TerrainDistanceCull;
//
// Render the tree.
//
void CTRPatch::RenderCorner(ivec5_t corner)
{
if((corner[3] < 0) || (tess.registration != corner[4]))
{
CTerVert *vert;
vert = mRenderMap + (corner[1] * owner->GetRealWidth()) + corner[0];
VectorCopy(vert->coords, tess.xyz[tess.numVertexes]);
VectorCopy(vert->normal, tess.normal[tess.numVertexes]);
*(ulong *)tess.vertexColors[tess.numVertexes] = *(ulong *)vert->tint;
*(ulong *)tess.vertexAlphas[tess.numVertexes] = corner[2];
tess.texCoords[tess.numVertexes][0][0] = vert->tex[0];
tess.texCoords[tess.numVertexes][0][1] = vert->tex[1];
tess.indexes[tess.numIndexes++] = tess.numVertexes;
corner[3] = tess.numVertexes++;
corner[4] = tess.registration;
}
else
{
tess.indexes[tess.numIndexes++] = corner[3];
}
}
void CTRPatch::RecurseRender(int depth, ivec5_t left, ivec5_t right, ivec5_t apex)
{
// All non-leaf nodes have both children, so just check for one
if (depth >= 0)
{
ivec5_t center;
byte *centerAlphas;
byte *leftAlphas;
byte *rightAlphas;
// Work out the centre of the hypoteneuse
center[0] = (left[0] + right[0]) >> 1;
center[1] = (left[1] + right[1]) >> 1;
// Work out the relevant texture coefficients at that point
leftAlphas = (byte *)&left[2];
rightAlphas = (byte *)&right[2];
centerAlphas = (byte *)¢er[2];
centerAlphas[0] = (leftAlphas[0] + rightAlphas[0]) >> 1;
centerAlphas[1] = (leftAlphas[1] + rightAlphas[1]) >> 1;
centerAlphas[2] = (leftAlphas[2] + rightAlphas[2]) >> 1;
centerAlphas[3] = (leftAlphas[3] + rightAlphas[3]) >> 1;
// Make sure the vert index and tesselation registration are not set
center[3] = -1;
center[4] = 0;
if (apex[0] == left[0] && apex[0] == center[0])
{
depth = 0;
}
RecurseRender(depth-1, apex, left, center);
RecurseRender(depth-1, right, apex, center);
}
else
{
if (left[0] == right[0] && left[0] == apex[0])
{
return;
}
if (left[1] == right[1] && left[1] == apex[1])
{
return;
}
// A leaf node! Output a triangle to be rendered.
RB_CheckOverflow(4, 4);
// assert(left[0] != right[0] || left[1] != right[1]);
// assert(left[0] != apex[0] || left[1] != apex[1]);
RenderCorner(left);
RenderCorner(right);
RenderCorner(apex);
}
}
//
// Render the mesh.
//
// The order of triangles is critical to the subdivision working
void CTRPatch::Render(int Part)
{
ivec5_t lTL, lTR, lBL, lBR;
int patchTerxels = owner->GetTerxels();
// VectorSet5(TL, 0, 0, TEXTURE_ALPHA_TL, -1, 0);
lTL[0] = 0;
lTL[1] = 0;
lTL[2] = TEXTURE_ALPHA_TL;
lTL[3] = -1;
lTL[4] = 0;
// VectorSet5(TR, owner->GetTerxels(), 0, TEXTURE_ALPHA_TR, -1, 0);
lTR[0] = patchTerxels;
lTR[1] = 0;
lTR[2] = TEXTURE_ALPHA_TR;
lTR[3] = -1;
lTR[4] = 0;
// VectorSet5(BL, 0, owner->GetTerxels(), TEXTURE_ALPHA_BL, -1, 0);
lBL[0] = 0;
lBL[1] = patchTerxels;
lBL[2] = TEXTURE_ALPHA_BL;
lBL[3] = -1;
lBL[4] = 0;
// VectorSet5(BR, owner->GetTerxels(), owner->GetTerxels(), TEXTURE_ALPHA_BR, -1, 0);
lBR[0] = patchTerxels;
lBR[1] = patchTerxels;
lBR[2] = TEXTURE_ALPHA_BR;
lBR[3] = -1;
lBR[4] = 0;
if ((Part & PI_TOP) && mTLShader)
{
/* float d;
d = DotProduct (backEnd.refdef.vieworg, mNormal[0]) - mDistance[0];
if (d <= 0.0)*/
{
RecurseRender(r_terrainTessellate->integer, lBL, lTR, lTL);
}
}
if ((Part & PI_BOTTOM) && mBRShader)
{
/* float d;
d = DotProduct (backEnd.refdef.vieworg, mNormal[1]) - mDistance[1];
if (d >= 0.0)*/
{
RecurseRender(r_terrainTessellate->integer, lTR, lBL, lBR);
}
}
}
//
// At this point the patch is visible and at least part of it is below water level
//
int CTRPatch::RenderWaterVert(int x, int y)
{
CTerVert *vert;
vert = mRenderMap + x + (y * owner->GetRealWidth());
if(vert->tessRegistration == tess.registration)
{
return(vert->tessIndex);
}
tess.xyz[tess.numVertexes][0] = vert->coords[0];
tess.xyz[tess.numVertexes][1] = vert->coords[1];
tess.xyz[tess.numVertexes][2] = owner->GetWaterHeight();
*(ulong *)tess.vertexColors[tess.numVertexes] = 0xffffffff;
tess.texCoords[tess.numVertexes][0][0] = vert->tex[0];
tess.texCoords[tess.numVertexes][0][1] = vert->tex[1];
vert->tessIndex = tess.numVertexes;
vert->tessRegistration = tess.registration;
tess.numVertexes++;
return(vert->tessIndex);
}
void CTRPatch::RenderWater(void)
{
RB_CheckOverflow(4, 6);
// Get the neighbouring patches
int TL = RenderWaterVert(0, 0);
int TR = RenderWaterVert(owner->GetTerxels(), 0);
int BL = RenderWaterVert(0, owner->GetTerxels());
int BR = RenderWaterVert(owner->GetTerxels(), owner->GetTerxels());
// TL
tess.indexes[tess.numIndexes++] = BL;
tess.indexes[tess.numIndexes++] = TR;
tess.indexes[tess.numIndexes++] = TL;
// BR
tess.indexes[tess.numIndexes++] = TR;
tess.indexes[tess.numIndexes++] = BL;
tess.indexes[tess.numIndexes++] = BR;
}
const bool CTRPatch::HasWater(void) const
{
owner->SetRealWaterHeight( owner->GetBaseWaterHeight() + r_terrainWaterOffset->integer );
return(common->GetMins()[2] < owner->GetWaterHeight());
}
bool CM_CullWorldBox (const cplane_t *frustum, const vec3pair_t bounds);
void CTRPatch::SetVisibility(bool visCheck)
{
if(visCheck)
{
if(DistanceSquared(mCenter, backEnd.refdef.vieworg) > TerrainDistanceCull)
{
misVisible = false;
}
else
{
// Set the visibility of the patch
misVisible = CM_CullWorldBox(backEnd.viewParms.frustum, GetBounds());
}
}
else
{
misVisible = true;
}
}
/*
void CTRPatch::CalcNormal(void)
{
CTerVert *vert1, *vert2, *vert3;
ivec5_t TL, TR, BL, BR;
vec3_t v1, v2;
VectorSet5(TL, 0, 0, TEXTURE_ALPHA_TL, -1, 0);
VectorSet5(TR, owner->GetTerxels(), 0, TEXTURE_ALPHA_TR, -1, 0);
VectorSet5(BL, 0, owner->GetTerxels(), TEXTURE_ALPHA_BL, -1, 0);
VectorSet5(BR, owner->GetTerxels(), owner->GetTerxels(), TEXTURE_ALPHA_BR, -1, 0);
vert1 = mRenderMap + (BL[1] * owner->GetRealWidth()) + BL[0];
vert2 = mRenderMap + (TR[1] * owner->GetRealWidth()) + TR[0];
vert3 = mRenderMap + (TL[1] * owner->GetRealWidth()) + TL[0];
VectorSubtract(vert2->coords, vert1->coords, v1);
VectorSubtract(vert3->coords, vert1->coords, v2);
CrossProduct(v1, v2, mNormal[0]);
VectorNormalize(mNormal[0]);
mDistance[0] = DotProduct (vert1->coords, mNormal[0]);
vert1 = mRenderMap + (BL[1] * owner->GetRealWidth()) + BL[0];
vert2 = mRenderMap + (TR[1] * owner->GetRealWidth()) + TR[0];
vert3 = mRenderMap + (BR[1] * owner->GetRealWidth()) + BR[0];
VectorSubtract(vert2->coords, vert1->coords, v1);
VectorSubtract(vert3->coords, vert1->coords, v2);
CrossProduct(v1, v2, mNormal[1]);
VectorNormalize(mNormal[1]);
mDistance[1] = DotProduct (vert1->coords, mNormal[1]);
}
*/
//
// Reset all patches, recompute variance if needed
//
void CTRLandScape::Reset(bool visCheck)
{
int x, y;
CTRPatch *patch;
TerrainDistanceCull = tr.distanceCull + mPatchSize;
TerrainDistanceCull *= TerrainDistanceCull;
// Go through the patches performing resets, compute variances, and linking.
for(y = mPatchMiny; y < mPatchMaxy; y++)
{
for(x = mPatchMinx; x < mPatchMaxx; x++, patch++)
{
patch = GetPatch(x, y);
patch->SetVisibility(visCheck);
}
}
}
//
// Render each patch of the landscape & adjust the frame variance.
//
void CTRLandScape::Render(void)
{
int x, y;
CTRPatch *patch;
TPatchInfo *current;
int i;
// Render all the visible patches
current = mSortedPatches;
for(i=0;i<mSortedCount;i++)
{
if (current->mPatch->isVisible())
{
if (tess.shader != current->mShader)
{
RB_EndSurface();
RB_BeginSurface(current->mShader, TerrainFog);
}
current->mPatch->Render(current->mPart);
}
current++;
}
RB_EndSurface();
// Render all the water for visible patches
// Done as a separate iteration to reduce the number of tesses created
if(mWaterShader && (mWaterShader != tr.defaultShader))
{
RB_BeginSurface( mWaterShader, tr.world->globalFog );
for(y = mPatchMiny; y < mPatchMaxy; y++ )
{
for(x = mPatchMinx; x < mPatchMaxx; x++ )
{
patch = GetPatch(x, y);
if(patch->isVisible() && patch->HasWater())
{
patch->RenderWater();
}
}
}
RB_EndSurface();
}
}
void CTRLandScape::CalculateRegion(void)
{
vec3_t mins, maxs, size, offset;
#if _DEBUG
mCycleCount++;
#endif
VectorCopy(GetPatchSize(), size);
VectorCopy(GetMins(), offset);
mins[0] = backEnd.refdef.vieworg[0] - tr.distanceCull - (size[0] * 2.0f) - offset[0];
mins[1] = backEnd.refdef.vieworg[1] - tr.distanceCull - (size[1] * 2.0f) - offset[1];
maxs[0] = backEnd.refdef.vieworg[0] + tr.distanceCull + (size[0] * 2.0f) - offset[0];
maxs[1] = backEnd.refdef.vieworg[1] + tr.distanceCull + (size[1] * 2.0f) - offset[1];
mPatchMinx = Com_Clamp(0, GetBlockWidth(), floorf(mins[0] / size[0]));
mPatchMaxx = Com_Clamp(0, GetBlockWidth(), ceilf(maxs[0] / size[0]));
mPatchMiny = Com_Clamp(0, GetBlockHeight(), floorf(mins[1] / size[1]));
mPatchMaxy = Com_Clamp(0, GetBlockHeight(), ceilf(maxs[1] / size[1]));
}
void CTRLandScape::CalculateRealCoords(void)
{
int x, y;
// Work out the real world coordinates of each heightmap entry
for(y = 0; y < GetRealHeight(); y++)
{
for(x = 0; x < GetRealWidth(); x++)
{
ivec3_t icoords;
int offset;
offset = (y * GetRealWidth()) + x;
VectorSet(icoords, x, y, mRenderMap[offset].height);
VectorScaleVectorAdd(GetMins(), icoords, GetTerxelSize(), mRenderMap[offset].coords);
}
}
}
void CTRLandScape::CalculateNormals(void)
{
int x, y, offset = 0;
// Work out the normals for every face
for(y = 0; y < GetHeight(); y++)
{
for(x = 0; x < GetWidth(); x++)
{
vec3_t vcenter, vleft;
offset = (y * GetRealWidth()) + x;
VectorSubtract(mRenderMap[offset].coords, mRenderMap[offset + 1].coords, vcenter);
VectorSubtract(mRenderMap[offset].coords, mRenderMap[offset + GetRealWidth()].coords, vleft);
CrossProduct(vcenter, vleft, mRenderMap[offset].normal);
VectorNormalize(mRenderMap[offset].normal);
}
// Duplicate right edge condition
VectorCopy(mRenderMap[offset].normal, mRenderMap[offset + 1].normal);
}
// Duplicate bottom line
offset = GetHeight() * GetRealWidth();
for(x = 0; x < GetRealWidth(); x++)
{
VectorCopy(mRenderMap[offset - GetRealWidth() + x].normal, mRenderMap[offset + x].normal);
}
}
int R_LightForPoint( vec3_t point, vec3_t ambientLight, vec3_t directedLight, vec3_t lightDir );
void CTRLandScape::CalculateLighting(void)
{
int x, y, offset = 0;
// Work out the vertex normal (average of every attached face normal) and apply to the direction of the light
for(y = 0; y < GetHeight(); y++)
{
for(x = 0; x < GetWidth(); x++)
{
vec3_t ambient;
vec3_t directed, direction;
vec3_t total, tint;
vec_t dp;
offset = (y * GetRealWidth()) + x;
// Work out average normal
VectorCopy(GetRenderMap(x, y)->normal, total);
VectorAdd(total, GetRenderMap(x + 1, y)->normal, total);
VectorAdd(total, GetRenderMap(x + 1, y + 1)->normal, total);
VectorAdd(total, GetRenderMap(x, y + 1)->normal, total);
VectorNormalize(total);
if (!R_LightForPoint(mRenderMap[offset].coords, ambient, directed, direction))
{
mRenderMap[offset].tint[0] =
mRenderMap[offset].tint[1] =
mRenderMap[offset].tint[2] = 255 >> tr.overbrightBits;
mRenderMap[offset].tint[3] = 255;
continue;
}
if(mRenderMap[offset].coords[2] < common->GetBaseWaterHeight())
{
VectorScale(ambient, 0.75f, ambient);
}
// Both normalised, so -1.0 < dp < 1.0
dp = Com_Clamp(0.0f, 1.0f, DotProduct(direction, total));
dp = powf(dp, 3);
VectorScale(ambient, (1.0 - dp) * 0.5, ambient);
VectorMA(ambient, dp, directed, tint);
// rjr - in R_SetupEntityLighting, ambient light is automatically increased by 32, so do it here to match
// rjr - decided to disable both the lighting boost automatically in there as well as here.
mRenderMap[offset].tint[0] = (byte)Com_Clamp(0.0f, 255.0f, tint[0] ) >> tr.overbrightBits;
mRenderMap[offset].tint[1] = (byte)Com_Clamp(0.0f, 255.0f, tint[1] ) >> tr.overbrightBits;
mRenderMap[offset].tint[2] = (byte)Com_Clamp(0.0f, 255.0f, tint[2] ) >> tr.overbrightBits;
mRenderMap[offset].tint[3] = 0xff;
}
mRenderMap[offset + 1].tint[0] = mRenderMap[offset].tint[0];
mRenderMap[offset + 1].tint[1] = mRenderMap[offset].tint[1];
mRenderMap[offset + 1].tint[2] = mRenderMap[offset].tint[2];
mRenderMap[offset + 1].tint[3] = 0xff;
}
// Duplicate bottom line
offset = GetHeight() * GetRealWidth();
for(x = 0; x < GetRealWidth(); x++)
{
mRenderMap[offset + x].tint[0] = mRenderMap[offset - GetRealWidth() + x].tint[0];
mRenderMap[offset + x].tint[1] = mRenderMap[offset - GetRealWidth() + x].tint[1];
mRenderMap[offset + x].tint[2] = mRenderMap[offset - GetRealWidth() + x].tint[2];
mRenderMap[offset + x].tint[3] = 0xff;
}
}
void CTRLandScape::CalculateTextureCoords(void)
{
int x, y;
for(y = 0; y < GetRealHeight(); y++)
{
for(x = 0; x < GetRealWidth(); x++)
{
int offset = (y * GetRealWidth()) + x;
mRenderMap[offset].tex[0] = x * mTextureScale * GetTerxelSize()[0];
mRenderMap[offset].tex[1] = y * mTextureScale * GetTerxelSize()[1];
}
}
}
void CTRLandScape::SetShaders(const int height, const qhandle_t shader)
{
int i;
for(i = height; shader && (i < HEIGHT_RESOLUTION); i++)
{
if(!mHeightDetails[i].GetShader())
{
mHeightDetails[i].SetShader(shader);
}
}
}
void CTRLandScape::LoadTerrainDef(const char *td)
{
#ifndef PRE_RELEASE_DEMO
char terrainDef[MAX_QPATH];
CGenericParser2 parse;
CGPGroup *basegroup, *classes, *items;
Com_sprintf(terrainDef, MAX_QPATH, "ext_data/RMG/%s.terrain", td);
Com_Printf("R_Terrain: Loading and parsing terrainDef %s.....\n", td);
mWaterShader = NULL;
mFlatShader = NULL;
if(!Com_ParseTextFile(terrainDef, parse))
{
Com_sprintf(terrainDef, MAX_QPATH, "ext_data/arioche/%s.terrain", td);
if(!Com_ParseTextFile(terrainDef, parse))
{
Com_Printf("Could not open %s\n", terrainDef);
return;
}
}
// The whole file....
basegroup = parse.GetBaseParseGroup();
// The root { } struct
classes = basegroup->GetSubGroups();
while(classes)
{
items = classes->GetSubGroups();
while(items)
{
const char* type = items->GetName ( );
if(!stricmp( type, "altitudetexture"))
{
int height;
const char *shaderName;
qhandle_t shader;
// Height must exist - the rest are optional
height = atol(items->FindPairValue("height", "0"));
// Shader for this height
shaderName = items->FindPairValue("shader", "");
if(shaderName[0])
{
shader = RE_RegisterShader(shaderName);
if(shader)
{
SetShaders(height, shader);
}
}
}
else if(!stricmp(type, "water"))
{
mWaterShader = R_GetShaderByHandle(RE_RegisterShader(items->FindPairValue("shader", "")));
}
else if(!stricmp(type, "flattexture"))
{
mFlatShader = RE_RegisterShader ( items->FindPairValue("shader", "") );
}
items = (CGPGroup *)items->GetNext();
}
classes = (CGPGroup *)classes->GetNext();
}
Com_ParseTextFileDestroy(parse);
#endif // PRE_RELEASE_DEMO
}
qhandle_t R_CreateBlendedShader(qhandle_t a, qhandle_t b, qhandle_t c, bool surfaceSprites );
qhandle_t CTRLandScape::GetBlendedShader(qhandle_t a, qhandle_t b, qhandle_t c, bool surfaceSprites)
{
qhandle_t blended;
// Special case single pass shader
if((a == b) && (a == c))
{
return(a);
}
blended = R_CreateBlendedShader(a, b, c, surfaceSprites );
return(blended);
}
static int ComparePatchInfo(const TPatchInfo *arg1, const TPatchInfo *arg2)
{
shader_t *s1, *s2;
if ((arg1->mPart & PI_TOP))
{
s1 = arg1->mPatch->GetTLShader();
}
else
{
s1 = arg1->mPatch->GetBRShader();
}
if ((arg2->mPart & PI_TOP))
{
s2 = arg2->mPatch->GetTLShader();
}
else
{
s2 = arg2->mPatch->GetBRShader();
}
if (s1 < s2)
{
return -1;
}
else if (s1 > s2)
{
return 1;
}
return 0;
}
void CTRLandScape::CalculateShaders(void)
{
#ifndef PRE_RELEASE_DEMO
int x, y;
int width, height;
int offset;
// int offsets[4];
qhandle_t handles[4];
CTRPatch *patch;
qhandle_t *shaders;
TPatchInfo *current = mSortedPatches;
width = GetWidth ( ) / common->GetTerxels ( );
height = GetHeight ( ) / common->GetTerxels ( );
shaders = new qhandle_t [ (width+1) * (height+1) ];
// On the first pass determine all of the shaders for the entire
// terrain assuming no flat ground
offset = 0;
for ( y = 0; y < height + 1; y ++ )
{
if ( y <= height )
{
offset = common->GetTerxels ( ) * y * GetRealWidth ( );
}
else
{
offset = common->GetTerxels ( ) * (y-1) * GetRealWidth ( );
offset += GetRealWidth ( );
}
for ( x = 0; x < width + 1; x ++, offset += common->GetTerxels ( ) )
{
// Save the shader
shaders[y * width + x] = GetHeightDetail(mRenderMap[offset].height)->GetShader ( );
}
}
// On the second pass determine flat ground and replace the shader
// at that point with the flat ground shader
byte* flattenMap = common->GetFlattenMap ( );
if ( mFlatShader && flattenMap )
{
for ( y = 1; y < height; y ++ )
{
for ( x = 1; x < width; x ++ )
{
int offset;
int xx;
int yy;
bool flat = false;
offset = (x) * common->GetTerxels ( );
offset += (y) * common->GetTerxels ( ) * GetRealWidth();
offset -= GetRealWidth();
offset -= 1;
for ( yy = 0; yy < 3 && !flat; yy++ )
{
for ( xx = 0; xx < 3 && !flat; xx++ )
{
if ( flattenMap [ offset + xx] & 0x80)
{
flat = true;
break;
}
}
offset += GetRealWidth();
}
// This shader is now a flat shader
if ( flat )
{
shaders[y * width + x] = mFlatShader;
}
#ifdef _DEBUG
OutputDebugString ( va("Flat Area: %f %f\n",
GetMins()[0] + (GetMaxs()[0]-GetMins()[0])/width * x,
GetMins()[1] + (GetMaxs()[1]-GetMins()[1])/height * y) );
#endif
}
}
}
// Now that the shaders have been determined, set them for each patch
patch = mTRPatches;
mSortedCount = 0;
for ( y = 0; y < height; y ++ )
{
for ( x = 0; x < width; x ++, patch++ )
{
bool surfaceSprites = true;
/*
handles[INDEX_TL] = shaders[ (x + y) * width ];
handles[INDEX_TR] = shaders[ ((x + 1) + y) * width ];
handles[INDEX_BL] = shaders[ (x + (y + 1)) * width ];
handles[INDEX_BR] = shaders[ ((x + 1) + (y + 1)) * width ];
*/
handles[INDEX_TL] = shaders[ x + y * width ];
handles[INDEX_TR] = shaders[ x + 1 + y * width ];
handles[INDEX_BL] = shaders[ x + (y + 1) * width ];
handles[INDEX_BR] = shaders[ x + 1 + (y + 1) * width ];
if ( handles[INDEX_TL] == mFlatShader ||
handles[INDEX_TR] == mFlatShader ||
handles[INDEX_BL] == mFlatShader ||
handles[INDEX_BR] == mFlatShader )
{
surfaceSprites = false;
}
patch->SetTLShader(GetBlendedShader(handles[INDEX_TR], handles[INDEX_BL], handles[INDEX_TL], surfaceSprites));
current->mPatch = patch;
current->mShader = patch->GetTLShader();
current->mPart = PI_TOP;
patch->SetBRShader(GetBlendedShader(handles[INDEX_TR], handles[INDEX_BL], handles[INDEX_BR], surfaceSprites));
if (patch->GetBRShader() == current->mShader)
{
current->mPart |= PI_BOTTOM;
}
else
{
mSortedCount++;
current++;
current->mPatch = patch;
current->mShader = patch->GetBRShader();
current->mPart = PI_BOTTOM;
}
mSortedCount++;
current++;
}
}
// Cleanup our temporary array
delete[] shaders;
qsort(mSortedPatches, mSortedCount, sizeof(*mSortedPatches), (int (__cdecl *)(const void *,const void *))ComparePatchInfo);
#endif // PRE_RELEASE_DEMO
}
void CTRPatch::SetRenderMap(const int x, const int y)
{
mRenderMap = localowner->GetRenderMap(x, y);
}
void InitRendererPatches( CCMPatch *patch, void *userdata )
{
int tx, ty, bx, by;
CTRPatch *localpatch;
CCMLandScape *owner;
CTRLandScape *localowner;
// Set owning landscape
localowner = (CTRLandScape *)userdata;
owner = (CCMLandScape *)localowner->GetCommon();
// Get TRPatch pointer
tx = patch->GetHeightMapX();
ty = patch->GetHeightMapY();
bx = tx / owner->GetTerxels();
by = ty / owner->GetTerxels();
localpatch = localowner->GetPatch(bx, by);
localpatch->Clear();
localpatch->SetCommon(patch);
localpatch->SetOwner(owner);
localpatch->SetLocalOwner(localowner);
localpatch->SetRenderMap(tx, ty);
localpatch->SetCenter();
// localpatch->CalcNormal();
}
void CTRLandScape::CopyHeightMap(void)
{
const CCMLandScape *common = GetCommon();
const byte *heightMap = common->GetHeightMap();
CTerVert *renderMap = mRenderMap;
int i;
for(i = 0; i < common->GetRealArea(); i++)
{
renderMap->height = *heightMap;
renderMap++;
heightMap++;
}
}
CTRLandScape::~CTRLandScape(void)
{
if(mTRPatches)
{
Z_Free(mTRPatches);
mTRPatches = NULL;
}
if (mSortedPatches)
{
Z_Free(mSortedPatches);
mSortedPatches = 0;
}
if(mRenderMap)
{
Z_Free(mRenderMap);
mRenderMap = NULL;
}
}
CCMLandScape *CM_RegisterTerrain(const char *config, bool server);
qhandle_t R_GetShaderByNum(int shaderNum, world_t &worldData);
CTRLandScape::CTRLandScape(const char *configstring)
{
#ifndef PRE_RELEASE_DEMO
int shaderNum;
const CCMLandScape *common;
memset(this, 0, sizeof(*this));
// Sets up the common aspects of the terrain
common = CM_RegisterTerrain(configstring, false);
SetCommon(common);
tr.landScape.landscape = this;
mTextureScale = (float)atof(Info_ValueForKey(configstring, "texturescale")) / common->GetTerxels();
LoadTerrainDef(Info_ValueForKey(configstring, "terrainDef"));
// To normalise the variance value to a reasonable number
mScalarSize = VectorLengthSquared(common->GetSize());
// Calculate and set variance depth
mMaxNode = (Q_log2(common->GetTerxels()) << 1) - 1;
// Allocate space for the renderer specific data
mRenderMap = (CTerVert *)Z_Malloc(sizeof(CTerVert) * common->GetRealArea(), TAG_R_TERRAIN, qfalse);
// Copy byte heightmap to rendermap to speed up calcs
CopyHeightMap();
// Calculate the real world location for each heightmap entry
CalculateRealCoords();
// Calculate the normal of each terxel
CalculateNormals();
// Calculate modulation values for the heightmap
CalculateLighting();
// Calculate texture coords (not projected - real)
CalculateTextureCoords();
Com_Printf ("R_Terrain: Creating renderer patches.....\n");
// Initialise all terrain patches
mTRPatches = (CTRPatch *)Z_Malloc(sizeof(CTRPatch) * common->GetBlockCount(), TAG_R_TERRAIN, qfalse);
mSortedCount = 2 * common->GetBlockCount();
mSortedPatches = (TPatchInfo *)Z_Malloc(sizeof(TPatchInfo) * mSortedCount, TAG_R_TERRAIN, qfalse);
CM_TerrainPatchIterate(common, InitRendererPatches, this);
// Calculate shaders dependent on the .terrain file
CalculateShaders();
// Get the contents shader
shaderNum = atol(Info_ValueForKey(configstring, "shader"));
mShader = R_GetShaderByHandle(R_GetShaderByNum(shaderNum, *tr.world));
mPatchSize = VectorLength(common->GetPatchSize());
#if _DEBUG
mCycleCount = 0;
#endif
#endif // PRE_RELEASE_DEMO
}
// ---------------------------------------------------------------------
void RB_SurfaceTerrain( surfaceInfo_t *surf )
{
srfTerrain_t *ls = (srfTerrain_t *)surf;
CTRLandScape *landscape = ls->landscape;
TerrainFog = tr.world->globalFog;
landscape->CalculateRegion();
landscape->Reset();
// landscape->Tessellate();
landscape->Render();
}
void R_CalcTerrainVisBounds(CTRLandScape *landscape)
{
const CCMLandScape *common = landscape->GetCommon();
// Set up the visbounds using terrain data
if ( common->GetMins()[0] < tr.viewParms.visBounds[0][0] )
{
tr.viewParms.visBounds[0][0] = common->GetMins()[0];
}
if ( common->GetMins()[1] < tr.viewParms.visBounds[0][1] )
{
tr.viewParms.visBounds[0][1] = common->GetMins()[1];
}
if ( common->GetMins()[2] < tr.viewParms.visBounds[0][2] )
{
tr.viewParms.visBounds[0][2] = common->GetMins()[2];
}
if ( common->GetMaxs()[0] > tr.viewParms.visBounds[1][0] )
{
tr.viewParms.visBounds[1][0] = common->GetMaxs()[0];
}
if ( common->GetMaxs()[1] > tr.viewParms.visBounds[1][1] )
{
tr.viewParms.visBounds[1][1] = common->GetMaxs()[1];
}
if ( common->GetMaxs()[2] > tr.viewParms.visBounds[1][2] )
{
tr.viewParms.visBounds[1][2] = common->GetMaxs()[2];
}
}
void R_AddTerrainSurfaces(void)
{
CTRLandScape *landscape;
if (!r_drawTerrain->integer || (tr.refdef.rdflags & RDF_NOWORLDMODEL))
{
return;
}
landscape = tr.landScape.landscape;
if(landscape)
{
R_AddDrawSurf( (surfaceType_t *)(&tr.landScape), landscape->GetShader(), 0, qfalse );
R_CalcTerrainVisBounds(landscape);
}
}
void RE_InitRendererTerrain( const char *info )
{
CTRLandScape *ls;
if ( !info || !info[0] )
{
Com_Printf( "RE_RegisterTerrain: NULL name\n" );
return;
}
Com_Printf("R_Terrain: Creating RENDERER data.....\n");
// Create and register a new landscape structure
ls = new CTRLandScape(info);
}
void R_TerrainInit(void)
{
int i;
for(i = 0; i < MAX_TERRAINS; i++)
{
tr.landScape.surfaceType = SF_TERRAIN;
tr.landScape.landscape = NULL;
}
r_terrainTessellate = Cvar_Get("r_terrainTessellate", "3", CVAR_CHEAT);
r_drawTerrain = Cvar_Get("r_drawTerrain", "1", CVAR_CHEAT);
r_terrainWaterOffset = Cvar_Get("r_terrainWaterOffset", "0", 0);
r_count = Cvar_Get("r_count", "2", 0);
}
void CM_ShutdownTerrain( thandle_t terrainId);
void R_TerrainShutdown(void)
{
CTRLandScape *ls;
//Com_Printf("R_Terrain: Shutting down RENDERER terrain.....\n");
ls = tr.landScape.landscape;
if(ls)
{
CM_ShutdownTerrain(0);
delete ls;
tr.landScape.landscape = NULL;
}
}
// end
| gpl-2.0 |
zjhuntin/katello | test/controllers/api/v2/environments_controller_test.rb | 4776 | # encoding: utf-8
require "katello_test_helper"
module Katello
class Api::V2::EnvironmentsControllerTest < ActionController::TestCase
include Support::ForemanTasks::Task
def models
@organization = get_organization
@library = katello_environments(:library)
@staging = katello_environments(:staging)
end
def permissions
@resource_type = "Katello::KTEnvironment"
@view_permission = :view_lifecycle_environments
@create_permission = :create_lifecycle_environments
@update_permission = :edit_lifecycle_environments
@destroy_permission = :destroy_lifecycle_environments
end
def setup
setup_controller_defaults_api
login_user(User.find(users(:admin).id))
Katello::PuppetModule.stubs(:module_count).returns(0)
models
permissions
end
def test_create
Organization.any_instance.stubs(:save!).returns(@organization)
post :create,
:organization_id => @organization.id,
:environment => {
:name => 'dev env',
:label => 'dev_env',
:description => 'This environment is for development.',
:prior => @library.id
}
assert_response :success
end
def test_create_fail
Organization.any_instance.stubs(:save!).returns(@organization)
post :create,
:organization_id => @organization.id,
:environment => {
:description => 'This environment is for development.'
}
assert_response :bad_request
end
def test_create_protected
Organization.any_instance.stubs(:save!).returns(@organization)
KTEnvironment.expects(:readable).returns(KTEnvironment)
allowed_perms = [@create_permission]
denied_perms = [@view_permission, @update_permission, @destroy_permission]
assert_protected_action(:create, allowed_perms, denied_perms) do
post :create,
:organization_id => @organization.id,
:environment => {
:name => 'dev env',
:label => 'dev_env',
:description => 'This environment is for development.',
:prior => @library.id
}
end
end
def test_update
original_label = @staging.label
put :update,
:organization_id => @organization.id,
:id => @staging.id,
:environment => {
:new_name => 'New Name',
:label => 'New Label'
}
assert_response :success
assert_template 'api/v2/common/update'
assert_equal 'New Name', @staging.reload.name
# note: label is not editable; therefore, confirm that it is unchanged
assert_equal original_label, @staging.label
end
def test_update_protected
allowed_perms = [@update_permission]
denied_perms = [@view_permission, @create_permission, @destroy_permission]
assert_protected_action(:destroy, allowed_perms, denied_perms) do
put :update,
:organization_id => @organization.id,
:id => @staging.id,
:environment => {
:new_name => 'New Name'
}
end
end
def test_index
get :index, :organization_id => @organization.id
assert_response :success
end
def test_index_with_name
get :index, :organization_id => @organization.id, :name => @organization.library.name
assert_response :success
end
def test_destroy
destroyable_env = KTEnvironment.create!(:name => "DestroyAble",
:organization => @staging.organization,
:prior => @staging)
assert_sync_task(::Actions::Katello::Environment::Destroy, destroyable_env)
delete :destroy, :organization_id => @organization.id,
:id => destroyable_env.id
assert_response :success
end
def test_destroy_protected
allowed_perms = [@destroy_permission]
denied_perms = [@view_permission, @update_permission, @create_permission]
assert_protected_action(:destroy, allowed_perms, denied_perms) do
delete :destroy, :organization_id => @organization.id,
:id => @staging.id
end
end
def test_paths
get :paths, :organization_id => @organization.id
assert_response :success
assert_template layout: 'katello/api/v2/layouts/collection'
assert_template 'api/v2/environments/paths'
end
def test_paths_protected
allowed_perms = [@view_permission]
denied_perms = [@destroy_permission, @update_permission, @create_permission]
assert_protected_action(:paths, allowed_perms, denied_perms) do
get :paths, :organization_id => @organization.id
end
end
end
end
| gpl-2.0 |
andyhebear/DOLSharp | GameServer/events/keep/KeepEvent.cs | 2076 | /*
* DAWN OF LIGHT - The first free open source DAoC server emulator
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
*/
using System;
using DOL.Events;
using DOL.GS;
using DOL.GS.Keeps;
namespace DOL.Events
{
/// <summary>
/// This class holds all possible keep events.
/// Only constants defined here!
/// </summary>
public class KeepEvent : DOLEvent
{
public KeepEvent(string name) : base(name)
{
}
/// <summary>
/// Tests if this event is valid for the specified object
/// </summary>
/// <param name="o">The object for which the event wants to be registered</param>
/// <returns>true if valid, false if not</returns>
public override bool IsValidFor(object o)
{
return o is AbstractGameKeep;
}
/// <summary>
/// The KeepClaimed event is fired whenever the keep is claimed by a guild
/// </summary>
public static readonly KeepEvent KeepClaimed = new KeepEvent("KeepEvent.KeepClaimed");
/// <summary>
/// The KeepTaken event is fired whenever the keep is taken by another realm (lord killed)
/// </summary>
public static readonly KeepEvent KeepTaken = new KeepEvent("KeepEvent.KeepTaken");
/// <summary>
/// The TowerRaized event is fired when a tower is raized
/// </summary>
public static readonly KeepEvent TowerRaized = new KeepEvent("KeepEvent.TowerRaized");
}
}
| gpl-2.0 |
asaadani/testwordpress | wp-admin/includes/plugin.php | 67613 | <?php
/**
* WordPress Plugin Administration API
*
* @package WordPress
* @subpackage Administration
*/
/**
* Parses the plugin contents to retrieve plugin's metadata.
*
* The metadata of the plugin's data searches for the following in the plugin's
* header. All plugin data must be on its own line. For plugin description, it
* must not have any newlines or only parts of the description will be displayed
* and the same goes for the plugin data. The below is formatted for printing.
*
* /*
* Plugin Name: Name of Plugin
* Plugin URI: Link to plugin information
* Description: Plugin Description
* Author: Plugin author's name
* Author URI: Link to the author's web site
* Version: Must be set in the plugin for WordPress 2.3+
* Text Domain: Optional. Unique identifier, should be same as the one used in
* load_plugin_textdomain()
* Domain Path: Optional. Only useful if the translations are located in a
* folder above the plugin's base path. For example, if .mo files are
* located in the locale folder then Domain Path will be "/locale/" and
* must have the first slash. Defaults to the base folder the plugin is
* located in.
* Network: Optional. Specify "Network: true" to require that a plugin is activated
* across all sites in an installation. This will prevent a plugin from being
* activated on a single site when Multisite is enabled.
* * / # Remove the space to close comment
*
* Some users have issues with opening large files and manipulating the contents
* for want is usually the first 1kiB or 2kiB. This function stops pulling in
* the plugin contents when it has all of the required plugin data.
*
* The first 8kiB of the file will be pulled in and if the plugin data is not
* within that first 8kiB, then the plugin author should correct their plugin
* and move the plugin data headers to the top.
*
* The plugin file is assumed to have permissions to allow for scripts to read
* the file. This is not checked however and the file is only opened for
* reading.
*
* @since 1.5.0
*
* @param string $plugin_file Path to the plugin file
* @param bool $markup Optional. If the returned data should have HTML markup applied.
* Default true.
* @param bool $translate Optional. If the returned data should be translated. Default true.
* @return array {
* Plugin data. Values will be empty if not supplied by the plugin.
*
* @type string $Name Name of the plugin. Should be unique.
* @type string $Title Title of the plugin and link to the plugin's site (if set).
* @type string $Description Plugin description.
* @type string $Author Author's name.
* @type string $AuthorURI Author's website address (if set).
* @type string $Version Plugin version.
* @type string $TextDomain Plugin textdomain.
* @type string $DomainPath Plugins relative directory path to .mo files.
* @type bool $Network Whether the plugin can only be activated network-wide.
* }
*/
function get_plugin_data( $plugin_file, $markup = true, $translate = true ) {
$default_headers = array(
'Name' => 'Plugin Name',
'PluginURI' => 'Plugin URI',
'Version' => 'Version',
'Description' => 'Description',
'Author' => 'Author',
'AuthorURI' => 'Author URI',
'TextDomain' => 'Text Domain',
'DomainPath' => 'Domain Path',
'Network' => 'Network',
// Site Wide Only is deprecated in favor of Network.
'_sitewide' => 'Site Wide Only',
);
$plugin_data = get_file_data( $plugin_file, $default_headers, 'plugin' );
// Site Wide Only is the old header for Network
if ( ! $plugin_data['Network'] && $plugin_data['_sitewide'] ) {
/* translators: 1: Site Wide Only: true, 2: Network: true */
_deprecated_argument( __FUNCTION__, '3.0', sprintf( __( 'The %1$s plugin header is deprecated. Use %2$s instead.' ), '<code>Site Wide Only: true</code>', '<code>Network: true</code>' ) );
$plugin_data['Network'] = $plugin_data['_sitewide'];
}
$plugin_data['Network'] = ( 'true' == strtolower( $plugin_data['Network'] ) );
unset( $plugin_data['_sitewide'] );
if ( $markup || $translate ) {
$plugin_data = _get_plugin_data_markup_translate( $plugin_file, $plugin_data, $markup, $translate );
} else {
$plugin_data['Title'] = $plugin_data['Name'];
$plugin_data['AuthorName'] = $plugin_data['Author'];
}
return $plugin_data;
}
/**
* Sanitizes plugin data, optionally adds markup, optionally translates.
*
* @since 2.7.0
* @access private
* @see get_plugin_data()
*/
function _get_plugin_data_markup_translate( $plugin_file, $plugin_data, $markup = true, $translate = true ) {
// Sanitize the plugin filename to a WP_PLUGIN_DIR relative path
$plugin_file = plugin_basename( $plugin_file );
// Translate fields
if ( $translate ) {
if ( $textdomain = $plugin_data['TextDomain'] ) {
if ( ! is_textdomain_loaded( $textdomain ) ) {
if ( $plugin_data['DomainPath'] ) {
load_plugin_textdomain( $textdomain, false, dirname( $plugin_file ) . $plugin_data['DomainPath'] );
} else {
load_plugin_textdomain( $textdomain, false, dirname( $plugin_file ) );
}
}
} elseif ( 'hello.php' == basename( $plugin_file ) ) {
$textdomain = 'default';
}
if ( $textdomain ) {
foreach ( array( 'Name', 'PluginURI', 'Description', 'Author', 'AuthorURI', 'Version' ) as $field )
$plugin_data[ $field ] = translate( $plugin_data[ $field ], $textdomain );
}
}
// Sanitize fields
$allowed_tags = $allowed_tags_in_links = array(
'abbr' => array( 'title' => true ),
'acronym' => array( 'title' => true ),
'code' => true,
'em' => true,
'strong' => true,
);
$allowed_tags['a'] = array( 'href' => true, 'title' => true );
// Name is marked up inside <a> tags. Don't allow these.
// Author is too, but some plugins have used <a> here (omitting Author URI).
$plugin_data['Name'] = wp_kses( $plugin_data['Name'], $allowed_tags_in_links );
$plugin_data['Author'] = wp_kses( $plugin_data['Author'], $allowed_tags );
$plugin_data['Description'] = wp_kses( $plugin_data['Description'], $allowed_tags );
$plugin_data['Version'] = wp_kses( $plugin_data['Version'], $allowed_tags );
$plugin_data['PluginURI'] = esc_url( $plugin_data['PluginURI'] );
$plugin_data['AuthorURI'] = esc_url( $plugin_data['AuthorURI'] );
$plugin_data['Title'] = $plugin_data['Name'];
$plugin_data['AuthorName'] = $plugin_data['Author'];
// Apply markup
if ( $markup ) {
if ( $plugin_data['PluginURI'] && $plugin_data['Name'] )
$plugin_data['Title'] = '<a href="' . $plugin_data['PluginURI'] . '">' . $plugin_data['Name'] . '</a>';
if ( $plugin_data['AuthorURI'] && $plugin_data['Author'] )
$plugin_data['Author'] = '<a href="' . $plugin_data['AuthorURI'] . '">' . $plugin_data['Author'] . '</a>';
$plugin_data['Description'] = wptexturize( $plugin_data['Description'] );
if ( $plugin_data['Author'] )
$plugin_data['Description'] .= ' <cite>' . sprintf( __('By %s.'), $plugin_data['Author'] ) . '</cite>';
}
return $plugin_data;
}
/**
* Get a list of a plugin's files.
*
* @since 2.8.0
*
* @param string $plugin Plugin ID
* @return array List of files relative to the plugin root.
*/
function get_plugin_files($plugin) {
$plugin_file = WP_PLUGIN_DIR . '/' . $plugin;
$dir = dirname($plugin_file);
$plugin_files = array($plugin);
if ( is_dir($dir) && $dir != WP_PLUGIN_DIR ) {
$plugins_dir = @ opendir( $dir );
if ( $plugins_dir ) {
while (($file = readdir( $plugins_dir ) ) !== false ) {
if ( substr($file, 0, 1) == '.' )
continue;
if ( is_dir( $dir . '/' . $file ) ) {
$plugins_subdir = @ opendir( $dir . '/' . $file );
if ( $plugins_subdir ) {
while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( substr($subfile, 0, 1) == '.' )
continue;
$plugin_files[] = plugin_basename("$dir/$file/$subfile");
}
@closedir( $plugins_subdir );
}
} else {
if ( plugin_basename("$dir/$file") != $plugin )
$plugin_files[] = plugin_basename("$dir/$file");
}
}
@closedir( $plugins_dir );
}
}
return $plugin_files;
}
/**
* Check the plugins directory and retrieve all plugin files with plugin data.
*
* WordPress only supports plugin files in the base plugins directory
* (wp-content/plugins) and in one directory above the plugins directory
* (wp-content/plugins/my-plugin). The file it looks for has the plugin data
* and must be found in those two locations. It is recommended to keep your
* plugin files in their own directories.
*
* The file with the plugin data is the file that will be included and therefore
* needs to have the main execution for the plugin. This does not mean
* everything must be contained in the file and it is recommended that the file
* be split for maintainability. Keep everything in one file for extreme
* optimization purposes.
*
* @since 1.5.0
*
* @param string $plugin_folder Optional. Relative path to single plugin folder.
* @return array Key is the plugin file path and the value is an array of the plugin data.
*/
function get_plugins($plugin_folder = '') {
if ( ! $cache_plugins = wp_cache_get('plugins', 'plugins') )
$cache_plugins = array();
if ( isset($cache_plugins[ $plugin_folder ]) )
return $cache_plugins[ $plugin_folder ];
$wp_plugins = array ();
$plugin_root = WP_PLUGIN_DIR;
if ( !empty($plugin_folder) )
$plugin_root .= $plugin_folder;
// Files in wp-content/plugins directory
$plugins_dir = @ opendir( $plugin_root);
$plugin_files = array();
if ( $plugins_dir ) {
while (($file = readdir( $plugins_dir ) ) !== false ) {
if ( substr($file, 0, 1) == '.' )
continue;
if ( is_dir( $plugin_root.'/'.$file ) ) {
$plugins_subdir = @ opendir( $plugin_root.'/'.$file );
if ( $plugins_subdir ) {
while (($subfile = readdir( $plugins_subdir ) ) !== false ) {
if ( substr($subfile, 0, 1) == '.' )
continue;
if ( substr($subfile, -4) == '.php' )
$plugin_files[] = "$file/$subfile";
}
closedir( $plugins_subdir );
}
} else {
if ( substr($file, -4) == '.php' )
$plugin_files[] = $file;
}
}
closedir( $plugins_dir );
}
if ( empty($plugin_files) )
return $wp_plugins;
foreach ( $plugin_files as $plugin_file ) {
if ( !is_readable( "$plugin_root/$plugin_file" ) )
continue;
$plugin_data = get_plugin_data( "$plugin_root/$plugin_file", false, false ); //Do not apply markup/translate as it'll be cached.
if ( empty ( $plugin_data['Name'] ) )
continue;
$wp_plugins[plugin_basename( $plugin_file )] = $plugin_data;
}
uasort( $wp_plugins, '_sort_uname_callback' );
$cache_plugins[ $plugin_folder ] = $wp_plugins;
wp_cache_set('plugins', $cache_plugins, 'plugins');
return $wp_plugins;
}
/**
* Check the mu-plugins directory and retrieve all mu-plugin files with any plugin data.
*
* WordPress only includes mu-plugin files in the base mu-plugins directory (wp-content/mu-plugins).
*
* @since 3.0.0
* @return array Key is the mu-plugin file path and the value is an array of the mu-plugin data.
*/
function get_mu_plugins() {
$wp_plugins = array();
// Files in wp-content/mu-plugins directory
$plugin_files = array();
if ( ! is_dir( WPMU_PLUGIN_DIR ) )
return $wp_plugins;
if ( $plugins_dir = @ opendir( WPMU_PLUGIN_DIR ) ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( substr( $file, -4 ) == '.php' )
$plugin_files[] = $file;
}
} else {
return $wp_plugins;
}
@closedir( $plugins_dir );
if ( empty($plugin_files) )
return $wp_plugins;
foreach ( $plugin_files as $plugin_file ) {
if ( !is_readable( WPMU_PLUGIN_DIR . "/$plugin_file" ) )
continue;
$plugin_data = get_plugin_data( WPMU_PLUGIN_DIR . "/$plugin_file", false, false ); //Do not apply markup/translate as it'll be cached.
if ( empty ( $plugin_data['Name'] ) )
$plugin_data['Name'] = $plugin_file;
$wp_plugins[ $plugin_file ] = $plugin_data;
}
if ( isset( $wp_plugins['index.php'] ) && filesize( WPMU_PLUGIN_DIR . '/index.php') <= 30 ) // silence is golden
unset( $wp_plugins['index.php'] );
uasort( $wp_plugins, '_sort_uname_callback' );
return $wp_plugins;
}
/**
* Callback to sort array by a 'Name' key.
*
* @since 3.1.0
* @access private
*/
function _sort_uname_callback( $a, $b ) {
return strnatcasecmp( $a['Name'], $b['Name'] );
}
/**
* Check the wp-content directory and retrieve all drop-ins with any plugin data.
*
* @since 3.0.0
* @return array Key is the file path and the value is an array of the plugin data.
*/
function get_dropins() {
$dropins = array();
$plugin_files = array();
$_dropins = _get_dropins();
// These exist in the wp-content directory
if ( $plugins_dir = @ opendir( WP_CONTENT_DIR ) ) {
while ( ( $file = readdir( $plugins_dir ) ) !== false ) {
if ( isset( $_dropins[ $file ] ) )
$plugin_files[] = $file;
}
} else {
return $dropins;
}
@closedir( $plugins_dir );
if ( empty($plugin_files) )
return $dropins;
foreach ( $plugin_files as $plugin_file ) {
if ( !is_readable( WP_CONTENT_DIR . "/$plugin_file" ) )
continue;
$plugin_data = get_plugin_data( WP_CONTENT_DIR . "/$plugin_file", false, false ); //Do not apply markup/translate as it'll be cached.
if ( empty( $plugin_data['Name'] ) )
$plugin_data['Name'] = $plugin_file;
$dropins[ $plugin_file ] = $plugin_data;
}
uksort( $dropins, 'strnatcasecmp' );
return $dropins;
}
/**
* Returns drop-ins that WordPress uses.
*
* Includes Multisite drop-ins only when is_multisite()
*
* @since 3.0.0
* @return array Key is file name. The value is an array, with the first value the
* purpose of the drop-in and the second value the name of the constant that must be
* true for the drop-in to be used, or true if no constant is required.
*/
function _get_dropins() {
$dropins = array(
'advanced-cache.php' => array( __( 'Advanced caching plugin.' ), 'WP_CACHE' ), // WP_CACHE
'db.php' => array( __( 'Custom database class.' ), true ), // auto on load
'db-error.php' => array( __( 'Custom database error message.' ), true ), // auto on error
'install.php' => array( __( 'Custom install script.' ), true ), // auto on install
'maintenance.php' => array( __( 'Custom maintenance message.' ), true ), // auto on maintenance
'object-cache.php' => array( __( 'External object cache.' ), true ), // auto on load
);
if ( is_multisite() ) {
$dropins['sunrise.php' ] = array( __( 'Executed before Multisite is loaded.' ), 'SUNRISE' ); // SUNRISE
$dropins['blog-deleted.php' ] = array( __( 'Custom site deleted message.' ), true ); // auto on deleted blog
$dropins['blog-inactive.php' ] = array( __( 'Custom site inactive message.' ), true ); // auto on inactive blog
$dropins['blog-suspended.php'] = array( __( 'Custom site suspended message.' ), true ); // auto on archived or spammed blog
}
return $dropins;
}
/**
* Check whether a plugin is active.
*
* Only plugins installed in the plugins/ folder can be active.
*
* Plugins in the mu-plugins/ folder can't be "activated," so this function will
* return false for those plugins.
*
* @since 2.5.0
*
* @param string $plugin Base plugin path from plugins directory.
* @return bool True, if in the active plugins list. False, not in the list.
*/
function is_plugin_active( $plugin ) {
return in_array( $plugin, (array) get_option( 'active_plugins', array() ) ) || is_plugin_active_for_network( $plugin );
}
/**
* Check whether the plugin is inactive.
*
* Reverse of is_plugin_active(). Used as a callback.
*
* @since 3.1.0
* @see is_plugin_active()
*
* @param string $plugin Base plugin path from plugins directory.
* @return bool True if inactive. False if active.
*/
function is_plugin_inactive( $plugin ) {
return ! is_plugin_active( $plugin );
}
/**
* Check whether the plugin is active for the entire network.
*
* Only plugins installed in the plugins/ folder can be active.
*
* Plugins in the mu-plugins/ folder can't be "activated," so this function will
* return false for those plugins.
*
* @since 3.0.0
*
* @param string $plugin Base plugin path from plugins directory.
* @return bool True, if active for the network, otherwise false.
*/
function is_plugin_active_for_network( $plugin ) {
if ( !is_multisite() )
return false;
$plugins = get_site_option( 'active_sitewide_plugins');
if ( isset($plugins[$plugin]) )
return true;
return false;
}
/**
* Checks for "Network: true" in the plugin header to see if this should
* be activated only as a network wide plugin. The plugin would also work
* when Multisite is not enabled.
*
* Checks for "Site Wide Only: true" for backwards compatibility.
*
* @since 3.0.0
*
* @param string $plugin Plugin to check
* @return bool True if plugin is network only, false otherwise.
*/
function is_network_only_plugin( $plugin ) {
$plugin_data = get_plugin_data( WP_PLUGIN_DIR . '/' . $plugin );
if ( $plugin_data )
return $plugin_data['Network'];
return false;
}
/**
* Attempts activation of plugin in a "sandbox" and redirects on success.
*
* A plugin that is already activated will not attempt to be activated again.
*
* The way it works is by setting the redirection to the error before trying to
* include the plugin file. If the plugin fails, then the redirection will not
* be overwritten with the success message. Also, the options will not be
* updated and the activation hook will not be called on plugin error.
*
* It should be noted that in no way the below code will actually prevent errors
* within the file. The code should not be used elsewhere to replicate the
* "sandbox", which uses redirection to work.
* {@source 13 1}
*
* If any errors are found or text is outputted, then it will be captured to
* ensure that the success redirection will update the error redirection.
*
* @since 2.5.0
*
* @param string $plugin Plugin path to main plugin file with plugin data.
* @param string $redirect Optional. URL to redirect to.
* @param bool $network_wide Optional. Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default false.
* @param bool $silent Optional. Whether to prevent calling activation hooks. Default false.
* @return WP_Error|null WP_Error on invalid file or null on success.
*/
function activate_plugin( $plugin, $redirect = '', $network_wide = false, $silent = false ) {
$plugin = plugin_basename( trim( $plugin ) );
if ( is_multisite() && ( $network_wide || is_network_only_plugin($plugin) ) ) {
$network_wide = true;
$current = get_site_option( 'active_sitewide_plugins', array() );
$_GET['networkwide'] = 1; // Back compat for plugins looking for this value.
} else {
$current = get_option( 'active_plugins', array() );
}
$valid = validate_plugin($plugin);
if ( is_wp_error($valid) )
return $valid;
if ( ( $network_wide && ! isset( $current[ $plugin ] ) ) || ( ! $network_wide && ! in_array( $plugin, $current ) ) ) {
if ( !empty($redirect) )
wp_redirect(add_query_arg('_error_nonce', wp_create_nonce('plugin-activation-error_' . $plugin), $redirect)); // we'll override this later if the plugin can be included without fatal error
ob_start();
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $plugin );
$_wp_plugin_file = $plugin;
include_once( WP_PLUGIN_DIR . '/' . $plugin );
$plugin = $_wp_plugin_file; // Avoid stomping of the $plugin variable in a plugin.
if ( ! $silent ) {
/**
* Fires before a plugin is activated.
*
* If a plugin is silently activated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Plugin path to main plugin file with plugin data.
* @param bool $network_wide Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default is false.
*/
do_action( 'activate_plugin', $plugin, $network_wide );
/**
* Fires as a specific plugin is being activated.
*
* This hook is the "activation" hook used internally by
* {@see register_activation_hook()}. The dynamic portion of the
* hook name, `$plugin`, refers to the plugin basename.
*
* If a plugin is silently activated (such as during an update),
* this hook does not fire.
*
* @since 2.0.0
*
* @param bool $network_wide Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default is false.
*/
do_action( 'activate_' . $plugin, $network_wide );
}
if ( $network_wide ) {
$current = get_site_option( 'active_sitewide_plugins', array() );
$current[$plugin] = time();
update_site_option( 'active_sitewide_plugins', $current );
} else {
$current = get_option( 'active_plugins', array() );
$current[] = $plugin;
sort($current);
update_option('active_plugins', $current);
}
if ( ! $silent ) {
/**
* Fires after a plugin has been activated.
*
* If a plugin is silently activated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Plugin path to main plugin file with plugin data.
* @param bool $network_wide Whether to enable the plugin for all sites in the network
* or just the current site. Multisite only. Default is false.
*/
do_action( 'activated_plugin', $plugin, $network_wide );
}
if ( ob_get_length() > 0 ) {
$output = ob_get_clean();
return new WP_Error('unexpected_output', __('The plugin generated unexpected output.'), $output);
}
ob_end_clean();
}
return null;
}
/**
* Deactivate a single plugin or multiple plugins.
*
* The deactivation hook is disabled by the plugin upgrader by using the $silent
* parameter.
*
* @since 2.5.0
*
* @param string|array $plugins Single plugin or list of plugins to deactivate.
* @param bool $silent Prevent calling deactivation hooks. Default is false.
* @param mixed $network_wide Whether to deactivate the plugin for all sites in the network.
* A value of null (the default) will deactivate plugins for both the site and the network.
*/
function deactivate_plugins( $plugins, $silent = false, $network_wide = null ) {
if ( is_multisite() )
$network_current = get_site_option( 'active_sitewide_plugins', array() );
$current = get_option( 'active_plugins', array() );
$do_blog = $do_network = false;
foreach ( (array) $plugins as $plugin ) {
$plugin = plugin_basename( trim( $plugin ) );
if ( ! is_plugin_active($plugin) )
continue;
$network_deactivating = false !== $network_wide && is_plugin_active_for_network( $plugin );
if ( ! $silent ) {
/**
* Fires before a plugin is deactivated.
*
* If a plugin is silently deactivated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Plugin path to main plugin file with plugin data.
* @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
* or just the current site. Multisite only. Default is false.
*/
do_action( 'deactivate_plugin', $plugin, $network_deactivating );
}
if ( false !== $network_wide ) {
if ( is_plugin_active_for_network( $plugin ) ) {
$do_network = true;
unset( $network_current[ $plugin ] );
} elseif ( $network_wide ) {
continue;
}
}
if ( true !== $network_wide ) {
$key = array_search( $plugin, $current );
if ( false !== $key ) {
$do_blog = true;
unset( $current[ $key ] );
}
}
if ( ! $silent ) {
/**
* Fires as a specific plugin is being deactivated.
*
* This hook is the "deactivation" hook used internally by
* {@see register_deactivation_hook()}. The dynamic portion of the
* hook name, `$plugin`, refers to the plugin basename.
*
* If a plugin is silently deactivated (such as during an update),
* this hook does not fire.
*
* @since 2.0.0
*
* @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
* or just the current site. Multisite only. Default is false.
*/
do_action( 'deactivate_' . $plugin, $network_deactivating );
/**
* Fires after a plugin is deactivated.
*
* If a plugin is silently deactivated (such as during an update),
* this hook does not fire.
*
* @since 2.9.0
*
* @param string $plugin Plugin basename.
* @param bool $network_deactivating Whether the plugin is deactivated for all sites in the network
* or just the current site. Multisite only. Default false.
*/
do_action( 'deactivated_plugin', $plugin, $network_deactivating );
}
}
if ( $do_blog )
update_option('active_plugins', $current);
if ( $do_network )
update_site_option( 'active_sitewide_plugins', $network_current );
}
/**
* Activate multiple plugins.
*
* When WP_Error is returned, it does not mean that one of the plugins had
* errors. It means that one or more of the plugins file path was invalid.
*
* The execution will be halted as soon as one of the plugins has an error.
*
* @since 2.6.0
*
* @param string|array $plugins Single plugin or list of plugins to activate.
* @param string $redirect Redirect to page after successful activation.
* @param bool $network_wide Whether to enable the plugin for all sites in the network.
* @param bool $silent Prevent calling activation hooks. Default is false.
* @return bool|WP_Error True when finished or WP_Error if there were errors during a plugin activation.
*/
function activate_plugins( $plugins, $redirect = '', $network_wide = false, $silent = false ) {
if ( !is_array($plugins) )
$plugins = array($plugins);
$errors = array();
foreach ( $plugins as $plugin ) {
if ( !empty($redirect) )
$redirect = add_query_arg('plugin', $plugin, $redirect);
$result = activate_plugin($plugin, $redirect, $network_wide, $silent);
if ( is_wp_error($result) )
$errors[$plugin] = $result;
}
if ( !empty($errors) )
return new WP_Error('plugins_invalid', __('One of the plugins is invalid.'), $errors);
return true;
}
/**
* Remove directory and files of a plugin for a list of plugins.
*
* @since 2.6.0
*
* @global WP_Filesystem_Base $wp_filesystem
*
* @param array $plugins List of plugins to delete.
* @param string $deprecated Deprecated.
* @return bool|null|WP_Error True on success, false is $plugins is empty, WP_Error on failure.
* Null if filesystem credentials are required to proceed.
*/
function delete_plugins( $plugins, $deprecated = '' ) {
global $wp_filesystem;
if ( empty($plugins) )
return false;
$checked = array();
foreach ( $plugins as $plugin )
$checked[] = 'checked[]=' . $plugin;
ob_start();
$url = wp_nonce_url('plugins.php?action=delete-selected&verify-delete=1&' . implode('&', $checked), 'bulk-plugins');
if ( false === ($credentials = request_filesystem_credentials($url)) ) {
$data = ob_get_clean();
if ( ! empty($data) ){
include_once( ABSPATH . 'wp-admin/admin-header.php');
echo $data;
include( ABSPATH . 'wp-admin/admin-footer.php');
exit;
}
return;
}
if ( ! WP_Filesystem($credentials) ) {
request_filesystem_credentials($url, '', true); //Failed to connect, Error and request again
$data = ob_get_clean();
if ( ! empty($data) ){
include_once( ABSPATH . 'wp-admin/admin-header.php');
echo $data;
include( ABSPATH . 'wp-admin/admin-footer.php');
exit;
}
return;
}
if ( ! is_object($wp_filesystem) )
return new WP_Error('fs_unavailable', __('Could not access filesystem.'));
if ( is_wp_error($wp_filesystem->errors) && $wp_filesystem->errors->get_error_code() )
return new WP_Error('fs_error', __('Filesystem error.'), $wp_filesystem->errors);
// Get the base plugin folder.
$plugins_dir = $wp_filesystem->wp_plugins_dir();
if ( empty( $plugins_dir ) ) {
return new WP_Error( 'fs_no_plugins_dir', __( 'Unable to locate WordPress Plugin directory.' ) );
}
$plugins_dir = trailingslashit( $plugins_dir );
$plugin_translations = wp_get_installed_translations( 'plugins' );
$errors = array();
foreach ( $plugins as $plugin_file ) {
// Run Uninstall hook.
if ( is_uninstallable_plugin( $plugin_file ) ) {
uninstall_plugin($plugin_file);
}
/**
* Fires immediately before a plugin deletion attempt.
*
* @since 4.4.0
*
* @param string $plugin_file Plugin file name.
*/
do_action( 'delete_plugin', $plugin_file );
$this_plugin_dir = trailingslashit( dirname( $plugins_dir . $plugin_file ) );
// If plugin is in its own directory, recursively delete the directory.
if ( strpos( $plugin_file, '/' ) && $this_plugin_dir != $plugins_dir ) { //base check on if plugin includes directory separator AND that it's not the root plugin folder
$deleted = $wp_filesystem->delete( $this_plugin_dir, true );
} else {
$deleted = $wp_filesystem->delete( $plugins_dir . $plugin_file );
}
/**
* Fires immediately after a plugin deletion attempt.
*
* @since 4.4.0
*
* @param string $plugin_file Plugin file name.
* @param bool $deleted Whether the plugin deletion was successful.
*/
do_action( 'deleted_plugin', $plugin_file, $deleted );
if ( ! $deleted ) {
$errors[] = $plugin_file;
continue;
}
// Remove language files, silently.
$plugin_slug = dirname( $plugin_file );
if ( '.' !== $plugin_slug && ! empty( $plugin_translations[ $plugin_slug ] ) ) {
$translations = $plugin_translations[ $plugin_slug ];
foreach ( $translations as $translation => $data ) {
$wp_filesystem->delete( WP_LANG_DIR . '/plugins/' . $plugin_slug . '-' . $translation . '.po' );
$wp_filesystem->delete( WP_LANG_DIR . '/plugins/' . $plugin_slug . '-' . $translation . '.mo' );
}
}
}
// Remove deleted plugins from the plugin updates list.
if ( $current = get_site_transient('update_plugins') ) {
// Don't remove the plugins that weren't deleted.
$deleted = array_diff( $plugins, $errors );
foreach ( $deleted as $plugin_file ) {
unset( $current->response[ $plugin_file ] );
}
set_site_transient( 'update_plugins', $current );
}
if ( ! empty($errors) )
return new WP_Error('could_not_remove_plugin', sprintf(__('Could not fully remove the plugin(s) %s.'), implode(', ', $errors)) );
return true;
}
/**
* Validate active plugins
*
* Validate all active plugins, deactivates invalid and
* returns an array of deactivated ones.
*
* @since 2.5.0
* @return array invalid plugins, plugin as key, error as value
*/
function validate_active_plugins() {
$plugins = get_option( 'active_plugins', array() );
// Validate vartype: array.
if ( ! is_array( $plugins ) ) {
update_option( 'active_plugins', array() );
$plugins = array();
}
if ( is_multisite() && current_user_can( 'manage_network_plugins' ) ) {
$network_plugins = (array) get_site_option( 'active_sitewide_plugins', array() );
$plugins = array_merge( $plugins, array_keys( $network_plugins ) );
}
if ( empty( $plugins ) )
return array();
$invalid = array();
// Invalid plugins get deactivated.
foreach ( $plugins as $plugin ) {
$result = validate_plugin( $plugin );
if ( is_wp_error( $result ) ) {
$invalid[$plugin] = $result;
deactivate_plugins( $plugin, true );
}
}
return $invalid;
}
/**
* Validate the plugin path.
*
* Checks that the file exists and {@link validate_file() is valid file}.
*
* @since 2.5.0
*
* @param string $plugin Plugin Path
* @return WP_Error|int 0 on success, WP_Error on failure.
*/
function validate_plugin($plugin) {
if ( validate_file($plugin) )
return new WP_Error('plugin_invalid', __('Invalid plugin path.'));
if ( ! file_exists(WP_PLUGIN_DIR . '/' . $plugin) )
return new WP_Error('plugin_not_found', __('Plugin file does not exist.'));
$installed_plugins = get_plugins();
if ( ! isset($installed_plugins[$plugin]) )
return new WP_Error('no_plugin_header', __('The plugin does not have a valid header.'));
return 0;
}
/**
* Whether the plugin can be uninstalled.
*
* @since 2.7.0
*
* @param string $plugin Plugin path to check.
* @return bool Whether plugin can be uninstalled.
*/
function is_uninstallable_plugin($plugin) {
$file = plugin_basename($plugin);
$uninstallable_plugins = (array) get_option('uninstall_plugins');
if ( isset( $uninstallable_plugins[$file] ) || file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) )
return true;
return false;
}
/**
* Uninstall a single plugin.
*
* Calls the uninstall hook, if it is available.
*
* @since 2.7.0
*
* @param string $plugin Relative plugin path from Plugin Directory.
* @return true True if a plugin's uninstall.php file has been found and included.
*/
function uninstall_plugin($plugin) {
$file = plugin_basename($plugin);
$uninstallable_plugins = (array) get_option('uninstall_plugins');
/**
* Fires in uninstall_plugin() before the plugin is uninstalled.
*
* @since 4.5.0
*
* @param string $plugin Relative plugin path from plugin directory.
* @param array $uninstallable_plugins Uninstallable plugins.
*/
do_action( 'pre_uninstall_plugin', $plugin, $uninstallable_plugins );
if ( file_exists( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' ) ) {
if ( isset( $uninstallable_plugins[$file] ) ) {
unset($uninstallable_plugins[$file]);
update_option('uninstall_plugins', $uninstallable_plugins);
}
unset($uninstallable_plugins);
define('WP_UNINSTALL_PLUGIN', $file);
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . dirname( $file ) );
include( WP_PLUGIN_DIR . '/' . dirname($file) . '/uninstall.php' );
return true;
}
if ( isset( $uninstallable_plugins[$file] ) ) {
$callable = $uninstallable_plugins[$file];
unset($uninstallable_plugins[$file]);
update_option('uninstall_plugins', $uninstallable_plugins);
unset($uninstallable_plugins);
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $file );
include( WP_PLUGIN_DIR . '/' . $file );
add_action( 'uninstall_' . $file, $callable );
/**
* Fires in uninstall_plugin() once the plugin has been uninstalled.
*
* The action concatenates the 'uninstall_' prefix with the basename of the
* plugin passed to {@see uninstall_plugin()} to create a dynamically-named action.
*
* @since 2.7.0
*/
do_action( 'uninstall_' . $file );
}
}
//
// Menu
//
/**
* Add a top-level menu page.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @global array $menu
* @global array $admin_page_hooks
* @global array $_registered_pages
* @global array $_parent_pages
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @param string $icon_url The URL to the icon to be used for this menu.
* * Pass a base64-encoded SVG using a data URI, which will be colored to match
* the color scheme. This should begin with 'data:image/svg+xml;base64,'.
* * Pass the name of a Dashicons helper class to use a font icon,
* e.g. 'dashicons-chart-pie'.
* * Pass 'none' to leave div.wp-menu-image empty so an icon can be added via CSS.
* @param int $position The position in the menu order this one should appear.
* @return string The resulting page's hook_suffix.
*/
function add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function = '', $icon_url = '', $position = null ) {
global $menu, $admin_page_hooks, $_registered_pages, $_parent_pages;
$menu_slug = plugin_basename( $menu_slug );
$admin_page_hooks[$menu_slug] = sanitize_title( $menu_title );
$hookname = get_plugin_page_hookname( $menu_slug, '' );
if ( !empty( $function ) && !empty( $hookname ) && current_user_can( $capability ) )
add_action( $hookname, $function );
if ( empty($icon_url) ) {
$icon_url = 'dashicons-admin-generic';
$icon_class = 'menu-icon-generic ';
} else {
$icon_url = set_url_scheme( $icon_url );
$icon_class = '';
}
$new_menu = array( $menu_title, $capability, $menu_slug, $page_title, 'menu-top ' . $icon_class . $hookname, $hookname, $icon_url );
if ( null === $position ) {
$menu[] = $new_menu;
} elseif ( isset( $menu[ "$position" ] ) ) {
$position = $position + substr( base_convert( md5( $menu_slug . $menu_title ), 16, 10 ) , -5 ) * 0.00001;
$menu[ "$position" ] = $new_menu;
} else {
$menu[ $position ] = $new_menu;
}
$_registered_pages[$hookname] = true;
// No parent as top level
$_parent_pages[$menu_slug] = false;
return $hookname;
}
/**
* Add a submenu page.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @global array $submenu
* @global array $menu
* @global array $_wp_real_parent_file
* @global bool $_wp_submenu_nopriv
* @global array $_registered_pages
* @global array $_parent_pages
*
* @param string $parent_slug The slug name for the parent menu (or the file name of a standard WordPress admin page).
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_submenu_page( $parent_slug, $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
global $submenu, $menu, $_wp_real_parent_file, $_wp_submenu_nopriv,
$_registered_pages, $_parent_pages;
$menu_slug = plugin_basename( $menu_slug );
$parent_slug = plugin_basename( $parent_slug);
if ( isset( $_wp_real_parent_file[$parent_slug] ) )
$parent_slug = $_wp_real_parent_file[$parent_slug];
if ( !current_user_can( $capability ) ) {
$_wp_submenu_nopriv[$parent_slug][$menu_slug] = true;
return false;
}
/*
* If the parent doesn't already have a submenu, add a link to the parent
* as the first item in the submenu. If the submenu file is the same as the
* parent file someone is trying to link back to the parent manually. In
* this case, don't automatically add a link back to avoid duplication.
*/
if (!isset( $submenu[$parent_slug] ) && $menu_slug != $parent_slug ) {
foreach ( (array)$menu as $parent_menu ) {
if ( $parent_menu[2] == $parent_slug && current_user_can( $parent_menu[1] ) )
$submenu[$parent_slug][] = array_slice( $parent_menu, 0, 4 );
}
}
$submenu[$parent_slug][] = array ( $menu_title, $capability, $menu_slug, $page_title );
$hookname = get_plugin_page_hookname( $menu_slug, $parent_slug);
if (!empty ( $function ) && !empty ( $hookname ))
add_action( $hookname, $function );
$_registered_pages[$hookname] = true;
/*
* Backward-compatibility for plugins using add_management page.
* See wp-admin/admin.php for redirect from edit.php to tools.php
*/
if ( 'tools.php' == $parent_slug )
$_registered_pages[get_plugin_page_hookname( $menu_slug, 'edit.php')] = true;
// No parent as top level.
$_parent_pages[$menu_slug] = $parent_slug;
return $hookname;
}
/**
* Add submenu page to the Tools main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_management_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'tools.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Settings main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_options_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'options-general.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Appearance main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_theme_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'themes.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Plugins main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_plugins_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'plugins.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Users/Profile main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_users_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
if ( current_user_can('edit_users') )
$parent = 'users.php';
else
$parent = 'profile.php';
return add_submenu_page( $parent, $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Dashboard main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_dashboard_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'index.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Posts main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_posts_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'edit.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Media main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_media_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'upload.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Links main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_links_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'link-manager.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Pages main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_pages_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'edit.php?post_type=page', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Add submenu page to the Comments main menu.
*
* This function takes a capability which will be used to determine whether
* or not a page is included in the menu.
*
* The function which is hooked in to handle the output of the page must check
* that the user has the required capability as well.
*
* @param string $page_title The text to be displayed in the title tags of the page when the menu is selected.
* @param string $menu_title The text to be used for the menu.
* @param string $capability The capability required for this menu to be displayed to the user.
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu).
* @param callable $function The function to be called to output the content for this page.
* @return false|string The resulting page's hook_suffix, or false if the user does not have the capability required.
*/
function add_comments_page( $page_title, $menu_title, $capability, $menu_slug, $function = '' ) {
return add_submenu_page( 'edit-comments.php', $page_title, $menu_title, $capability, $menu_slug, $function );
}
/**
* Remove a top-level admin menu.
*
* @since 3.1.0
*
* @global array $menu
*
* @param string $menu_slug The slug of the menu.
* @return array|bool The removed menu on success, false if not found.
*/
function remove_menu_page( $menu_slug ) {
global $menu;
foreach ( $menu as $i => $item ) {
if ( $menu_slug == $item[2] ) {
unset( $menu[$i] );
return $item;
}
}
return false;
}
/**
* Remove an admin submenu.
*
* @since 3.1.0
*
* @global array $submenu
*
* @param string $menu_slug The slug for the parent menu.
* @param string $submenu_slug The slug of the submenu.
* @return array|bool The removed submenu on success, false if not found.
*/
function remove_submenu_page( $menu_slug, $submenu_slug ) {
global $submenu;
if ( !isset( $submenu[$menu_slug] ) )
return false;
foreach ( $submenu[$menu_slug] as $i => $item ) {
if ( $submenu_slug == $item[2] ) {
unset( $submenu[$menu_slug][$i] );
return $item;
}
}
return false;
}
/**
* Get the url to access a particular menu page based on the slug it was registered with.
*
* If the slug hasn't been registered properly no url will be returned
*
* @since 3.0.0
*
* @global array $_parent_pages
*
* @param string $menu_slug The slug name to refer to this menu by (should be unique for this menu)
* @param bool $echo Whether or not to echo the url - default is true
* @return string the url
*/
function menu_page_url($menu_slug, $echo = true) {
global $_parent_pages;
if ( isset( $_parent_pages[$menu_slug] ) ) {
$parent_slug = $_parent_pages[$menu_slug];
if ( $parent_slug && ! isset( $_parent_pages[$parent_slug] ) ) {
$url = admin_url( add_query_arg( 'page', $menu_slug, $parent_slug ) );
} else {
$url = admin_url( 'admin.php?page=' . $menu_slug );
}
} else {
$url = '';
}
$url = esc_url($url);
if ( $echo )
echo $url;
return $url;
}
//
// Pluggable Menu Support -- Private
//
/**
*
* @global string $parent_file
* @global array $menu
* @global array $submenu
* @global string $pagenow
* @global string $typenow
* @global string $plugin_page
* @global array $_wp_real_parent_file
* @global array $_wp_menu_nopriv
* @global array $_wp_submenu_nopriv
*/
function get_admin_page_parent( $parent = '' ) {
global $parent_file, $menu, $submenu, $pagenow, $typenow,
$plugin_page, $_wp_real_parent_file, $_wp_menu_nopriv, $_wp_submenu_nopriv;
if ( !empty ( $parent ) && 'admin.php' != $parent ) {
if ( isset( $_wp_real_parent_file[$parent] ) )
$parent = $_wp_real_parent_file[$parent];
return $parent;
}
if ( $pagenow == 'admin.php' && isset( $plugin_page ) ) {
foreach ( (array)$menu as $parent_menu ) {
if ( $parent_menu[2] == $plugin_page ) {
$parent_file = $plugin_page;
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
}
if ( isset( $_wp_menu_nopriv[$plugin_page] ) ) {
$parent_file = $plugin_page;
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
}
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) ) {
$parent_file = $pagenow;
if ( isset( $_wp_real_parent_file[$parent_file] ) )
$parent_file = $_wp_real_parent_file[$parent_file];
return $parent_file;
}
foreach (array_keys( (array)$submenu ) as $parent) {
foreach ( $submenu[$parent] as $submenu_array ) {
if ( isset( $_wp_real_parent_file[$parent] ) )
$parent = $_wp_real_parent_file[$parent];
if ( !empty($typenow) && ($submenu_array[2] == "$pagenow?post_type=$typenow") ) {
$parent_file = $parent;
return $parent;
} elseif ( $submenu_array[2] == $pagenow && empty($typenow) && ( empty($parent_file) || false === strpos($parent_file, '?') ) ) {
$parent_file = $parent;
return $parent;
} elseif ( isset( $plugin_page ) && ($plugin_page == $submenu_array[2] ) ) {
$parent_file = $parent;
return $parent;
}
}
}
if ( empty($parent_file) )
$parent_file = '';
return '';
}
/**
*
* @global string $title
* @global array $menu
* @global array $submenu
* @global string $pagenow
* @global string $plugin_page
* @global string $typenow
*/
function get_admin_page_title() {
global $title, $menu, $submenu, $pagenow, $plugin_page, $typenow;
if ( ! empty ( $title ) )
return $title;
$hook = get_plugin_page_hook( $plugin_page, $pagenow );
$parent = $parent1 = get_admin_page_parent();
if ( empty ( $parent) ) {
foreach ( (array)$menu as $menu_array ) {
if ( isset( $menu_array[3] ) ) {
if ( $menu_array[2] == $pagenow ) {
$title = $menu_array[3];
return $menu_array[3];
} elseif ( isset( $plugin_page ) && ($plugin_page == $menu_array[2] ) && ($hook == $menu_array[3] ) ) {
$title = $menu_array[3];
return $menu_array[3];
}
} else {
$title = $menu_array[0];
return $title;
}
}
} else {
foreach ( array_keys( $submenu ) as $parent ) {
foreach ( $submenu[$parent] as $submenu_array ) {
if ( isset( $plugin_page ) &&
( $plugin_page == $submenu_array[2] ) &&
(
( $parent == $pagenow ) ||
( $parent == $plugin_page ) ||
( $plugin_page == $hook ) ||
( $pagenow == 'admin.php' && $parent1 != $submenu_array[2] ) ||
( !empty($typenow) && $parent == $pagenow . '?post_type=' . $typenow)
)
) {
$title = $submenu_array[3];
return $submenu_array[3];
}
if ( $submenu_array[2] != $pagenow || isset( $_GET['page'] ) ) // not the current page
continue;
if ( isset( $submenu_array[3] ) ) {
$title = $submenu_array[3];
return $submenu_array[3];
} else {
$title = $submenu_array[0];
return $title;
}
}
}
if ( empty ( $title ) ) {
foreach ( $menu as $menu_array ) {
if ( isset( $plugin_page ) &&
( $plugin_page == $menu_array[2] ) &&
( $pagenow == 'admin.php' ) &&
( $parent1 == $menu_array[2] ) )
{
$title = $menu_array[3];
return $menu_array[3];
}
}
}
}
return $title;
}
/**
* @since 2.3.0
*
* @param string $plugin_page
* @param string $parent_page
* @return string|null
*/
function get_plugin_page_hook( $plugin_page, $parent_page ) {
$hook = get_plugin_page_hookname( $plugin_page, $parent_page );
if ( has_action($hook) )
return $hook;
else
return null;
}
/**
*
* @global array $admin_page_hooks
* @param string $plugin_page
* @param string $parent_page
*/
function get_plugin_page_hookname( $plugin_page, $parent_page ) {
global $admin_page_hooks;
$parent = get_admin_page_parent( $parent_page );
$page_type = 'admin';
if ( empty ( $parent_page ) || 'admin.php' == $parent_page || isset( $admin_page_hooks[$plugin_page] ) ) {
if ( isset( $admin_page_hooks[$plugin_page] ) ) {
$page_type = 'toplevel';
} elseif ( isset( $admin_page_hooks[$parent] )) {
$page_type = $admin_page_hooks[$parent];
}
} elseif ( isset( $admin_page_hooks[$parent] ) ) {
$page_type = $admin_page_hooks[$parent];
}
$plugin_name = preg_replace( '!\.php!', '', $plugin_page );
return $page_type . '_page_' . $plugin_name;
}
/**
*
* @global string $pagenow
* @global array $menu
* @global array $submenu
* @global array $_wp_menu_nopriv
* @global array $_wp_submenu_nopriv
* @global string $plugin_page
* @global array $_registered_pages
*/
function user_can_access_admin_page() {
global $pagenow, $menu, $submenu, $_wp_menu_nopriv, $_wp_submenu_nopriv,
$plugin_page, $_registered_pages;
$parent = get_admin_page_parent();
if ( !isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$parent][$pagenow] ) )
return false;
if ( isset( $plugin_page ) ) {
if ( isset( $_wp_submenu_nopriv[$parent][$plugin_page] ) )
return false;
$hookname = get_plugin_page_hookname($plugin_page, $parent);
if ( !isset($_registered_pages[$hookname]) )
return false;
}
if ( empty( $parent) ) {
if ( isset( $_wp_menu_nopriv[$pagenow] ) )
return false;
if ( isset( $_wp_submenu_nopriv[$pagenow][$pagenow] ) )
return false;
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$pagenow][$plugin_page] ) )
return false;
if ( isset( $plugin_page ) && isset( $_wp_menu_nopriv[$plugin_page] ) )
return false;
foreach (array_keys( $_wp_submenu_nopriv ) as $key ) {
if ( isset( $_wp_submenu_nopriv[$key][$pagenow] ) )
return false;
if ( isset( $plugin_page ) && isset( $_wp_submenu_nopriv[$key][$plugin_page] ) )
return false;
}
return true;
}
if ( isset( $plugin_page ) && ( $plugin_page == $parent ) && isset( $_wp_menu_nopriv[$plugin_page] ) )
return false;
if ( isset( $submenu[$parent] ) ) {
foreach ( $submenu[$parent] as $submenu_array ) {
if ( isset( $plugin_page ) && ( $submenu_array[2] == $plugin_page ) ) {
if ( current_user_can( $submenu_array[1] ))
return true;
else
return false;
} elseif ( $submenu_array[2] == $pagenow ) {
if ( current_user_can( $submenu_array[1] ))
return true;
else
return false;
}
}
}
foreach ( $menu as $menu_array ) {
if ( $menu_array[2] == $parent) {
if ( current_user_can( $menu_array[1] ))
return true;
else
return false;
}
}
return true;
}
/* Whitelist functions */
/**
* Register a setting and its sanitization callback
*
* @since 2.7.0
*
* @global array $new_whitelist_options
*
* @param string $option_group A settings group name. Should correspond to a whitelisted option key name.
* Default whitelisted option key names include "general," "discussion," and "reading," among others.
* @param string $option_name The name of an option to sanitize and save.
* @param callable $sanitize_callback A callback function that sanitizes the option's value.
*/
function register_setting( $option_group, $option_name, $sanitize_callback = '' ) {
global $new_whitelist_options;
if ( 'misc' == $option_group ) {
_deprecated_argument( __FUNCTION__, '3.0', sprintf( __( 'The "%s" options group has been removed. Use another settings group.' ), 'misc' ) );
$option_group = 'general';
}
if ( 'privacy' == $option_group ) {
_deprecated_argument( __FUNCTION__, '3.5', sprintf( __( 'The "%s" options group has been removed. Use another settings group.' ), 'privacy' ) );
$option_group = 'reading';
}
$new_whitelist_options[ $option_group ][] = $option_name;
if ( $sanitize_callback != '' )
add_filter( "sanitize_option_{$option_name}", $sanitize_callback );
}
/**
* Unregister a setting
*
* @since 2.7.0
*
* @global array $new_whitelist_options
*
* @param string $option_group
* @param string $option_name
* @param callable $sanitize_callback
*/
function unregister_setting( $option_group, $option_name, $sanitize_callback = '' ) {
global $new_whitelist_options;
if ( 'misc' == $option_group ) {
_deprecated_argument( __FUNCTION__, '3.0', sprintf( __( 'The "%s" options group has been removed. Use another settings group.' ), 'misc' ) );
$option_group = 'general';
}
if ( 'privacy' == $option_group ) {
_deprecated_argument( __FUNCTION__, '3.5', sprintf( __( 'The "%s" options group has been removed. Use another settings group.' ), 'privacy' ) );
$option_group = 'reading';
}
$pos = array_search( $option_name, (array) $new_whitelist_options[ $option_group ] );
if ( $pos !== false )
unset( $new_whitelist_options[ $option_group ][ $pos ] );
if ( $sanitize_callback != '' )
remove_filter( "sanitize_option_{$option_name}", $sanitize_callback );
}
/**
* Refreshes the value of the options whitelist available via the 'whitelist_options' filter.
*
* @since 2.7.0
*
* @global array $new_whitelist_options
*
* @param array $options
* @return array
*/
function option_update_filter( $options ) {
global $new_whitelist_options;
if ( is_array( $new_whitelist_options ) )
$options = add_option_whitelist( $new_whitelist_options, $options );
return $options;
}
/**
* Adds an array of options to the options whitelist.
*
* @since 2.7.0
*
* @global array $whitelist_options
*
* @param array $new_options
* @param string|array $options
* @return array
*/
function add_option_whitelist( $new_options, $options = '' ) {
if ( $options == '' )
global $whitelist_options;
else
$whitelist_options = $options;
foreach ( $new_options as $page => $keys ) {
foreach ( $keys as $key ) {
if ( !isset($whitelist_options[ $page ]) || !is_array($whitelist_options[ $page ]) ) {
$whitelist_options[ $page ] = array();
$whitelist_options[ $page ][] = $key;
} else {
$pos = array_search( $key, $whitelist_options[ $page ] );
if ( $pos === false )
$whitelist_options[ $page ][] = $key;
}
}
}
return $whitelist_options;
}
/**
* Removes a list of options from the options whitelist.
*
* @since 2.7.0
*
* @global array $whitelist_options
*
* @param array $del_options
* @param string|array $options
* @return array
*/
function remove_option_whitelist( $del_options, $options = '' ) {
if ( $options == '' )
global $whitelist_options;
else
$whitelist_options = $options;
foreach ( $del_options as $page => $keys ) {
foreach ( $keys as $key ) {
if ( isset($whitelist_options[ $page ]) && is_array($whitelist_options[ $page ]) ) {
$pos = array_search( $key, $whitelist_options[ $page ] );
if ( $pos !== false )
unset( $whitelist_options[ $page ][ $pos ] );
}
}
}
return $whitelist_options;
}
/**
* Output nonce, action, and option_page fields for a settings page.
*
* @since 2.7.0
*
* @param string $option_group A settings group name. This should match the group name used in register_setting().
*/
function settings_fields($option_group) {
echo "<input type='hidden' name='option_page' value='" . esc_attr($option_group) . "' />";
echo '<input type="hidden" name="action" value="update" />';
wp_nonce_field("$option_group-options");
}
/**
* Clears the Plugins cache used by get_plugins() and by default, the Plugin Update cache.
*
* @since 3.7.0
*
* @param bool $clear_update_cache Whether to clear the Plugin updates cache
*/
function wp_clean_plugins_cache( $clear_update_cache = true ) {
if ( $clear_update_cache )
delete_site_transient( 'update_plugins' );
wp_cache_delete( 'plugins', 'plugins' );
}
/**
* @param string $plugin
*/
function plugin_sandbox_scrape( $plugin ) {
wp_register_plugin_realpath( WP_PLUGIN_DIR . '/' . $plugin );
include( WP_PLUGIN_DIR . '/' . $plugin );
}
| gpl-2.0 |
BigBoss424/a-zplumbing | Magento-CE-2/dev/tests/integration/testsuite/Magento/Paypal/_files/ipn.php | 337 | <?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
return [
'mc_gross' => '100.00',
'invoice' => '100000001',
'payment_status' => 'Completed',
'auth_status' => 'Completed',
'mc_currency' => 'USD',
'receiver_email' => 'merchant_2012050718_biz@example.com'
];
| gpl-3.0 |
vincent-tr/rpi-js-os | ext/libcxx-5.0/libcxx/test/libcxx/depr/exception.unexpected/set_unexpected.pass.cpp | 976 | //===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// test set_unexpected
// MODULES_DEFINES: _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS
#define _LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS
#include <exception>
#include <cassert>
#include <cstdlib>
void f1() {}
void f2() {}
void f3()
{
std::exit(0);
}
int main()
{
std::unexpected_handler old = std::set_unexpected(f1);
// verify there is a previous unexpected handler
assert(old);
// verify f1 was replace with f2
assert(std::set_unexpected(f2) == f1);
// verify calling original unexpected handler calls terminate
std::set_terminate(f3);
(*old)();
assert(0);
}
| gpl-3.0 |
mcseemka/frostwire-desktop | lib/jars-src/h2-1.4.186/src/main/org/h2/compress/Compressor.java | 1625 | /*
* Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0,
* and the EPL 1.0 (http://h2database.com/html/license.html).
* Initial Developer: H2 Group
*/
package org.h2.compress;
/**
* Each data compression algorithm must implement this interface.
*/
public interface Compressor {
/**
* No compression is used.
*/
int NO = 0;
/**
* The LZF compression algorithm is used
*/
int LZF = 1;
/**
* The DEFLATE compression algorithm is used.
*/
int DEFLATE = 2;
/**
* Get the compression algorithm type.
*
* @return the type
*/
int getAlgorithm();
/**
* Compress a number of bytes.
*
* @param in the input data
* @param inLen the number of bytes to compress
* @param out the output area
* @param outPos the offset at the output array
* @return the end position
*/
int compress(byte[] in, int inLen, byte[] out, int outPos);
/**
* Expand a number of compressed bytes.
*
* @param in the compressed data
* @param inPos the offset at the input array
* @param inLen the number of bytes to read
* @param out the output area
* @param outPos the offset at the output array
* @param outLen the size of the uncompressed data
*/
void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos,
int outLen);
/**
* Set the compression options. This may include settings for
* higher performance but less compression.
*
* @param options the options
*/
void setOptions(String options);
}
| gpl-3.0 |
pro-memoria/providence | themes/default3/views/find/Browse/widget_ca_occurrences_browse_tools.php | 1524 | <?php
/* ----------------------------------------------------------------------
* themes/default/views/find/widget_ca_occurrences_browse_tools.php
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2009-2014 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
$vo_result_context = $this->getVar('result_context');
$vo_result = $this->getVar('result');
?>
<h3 class='occurrences'>
<?php print _t("Browse %1", $this->getVar('mode_type_plural'))."<br/>\n"; ?>
</h3>
<?php
if ($vo_result) {
print $this->render('Search/search_sets_html.php');
}
?> | gpl-3.0 |
hpp3/shattered-pixel-dungeon | java/com/hpp3/shatteredpixeldungeon/Dungeon.java | 20504 | /*
* Pixel Dungeon
* Copyright (C) 2012-2014 Oleg Dolya
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.shatteredpixel.shatteredpixeldungeon;
import com.shatteredpixel.shatteredpixeldungeon.actors.Actor;
import com.shatteredpixel.shatteredpixeldungeon.actors.Char;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Amok;
import com.shatteredpixel.shatteredpixeldungeon.actors.buffs.Light;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.Hero;
import com.shatteredpixel.shatteredpixeldungeon.actors.hero.HeroClass;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Blacksmith;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Ghost;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Imp;
import com.shatteredpixel.shatteredpixeldungeon.actors.mobs.npcs.Wandmaker;
import com.shatteredpixel.shatteredpixeldungeon.items.Ankh;
import com.shatteredpixel.shatteredpixeldungeon.items.Generator;
import com.shatteredpixel.shatteredpixeldungeon.items.Item;
import com.shatteredpixel.shatteredpixeldungeon.items.potions.Potion;
import com.shatteredpixel.shatteredpixeldungeon.items.rings.Ring;
import com.shatteredpixel.shatteredpixeldungeon.items.scrolls.Scroll;
import com.shatteredpixel.shatteredpixeldungeon.items.wands.Wand;
import com.shatteredpixel.shatteredpixeldungeon.levels.CavesBossLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.CavesLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.CityBossLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.CityLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.DeadEndLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.HallsBossLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.HallsLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.LastLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.LastShopLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.Level;
import com.shatteredpixel.shatteredpixeldungeon.levels.PrisonBossLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.PrisonLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.Room;
import com.shatteredpixel.shatteredpixeldungeon.levels.SewerBossLevel;
import com.shatteredpixel.shatteredpixeldungeon.levels.SewerLevel;
import com.shatteredpixel.shatteredpixeldungeon.scenes.GameScene;
import com.shatteredpixel.shatteredpixeldungeon.scenes.StartScene;
import com.shatteredpixel.shatteredpixeldungeon.ui.QuickSlotButton;
import com.shatteredpixel.shatteredpixeldungeon.utils.BArray;
import com.shatteredpixel.shatteredpixeldungeon.utils.Utils;
import com.shatteredpixel.shatteredpixeldungeon.windows.WndResurrect;
import com.watabou.noosa.Game;
import com.watabou.utils.Bundlable;
import com.watabou.utils.Bundle;
import com.watabou.utils.PathFinder;
import com.watabou.utils.Random;
import com.watabou.utils.SparseArray;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
public class Dungeon {
public static int transmutation; // depth number for a well of transmutation
//enum of items which have limited spawns, records how many have spawned
//could all be their own separate numbers, but this allows iterating, much nicer for bundling/initializing.
public static enum limitedDrops{
//limited world drops
strengthPotions,
upgradeScrolls,
arcaneStyli,
//all unlimited health potion sources
swarmHP,
batHP,
warlockHP,
scorpioHP,
cookingHP,
//blandfruit, which can technically be an unlimited health potion source
blandfruitSeed,
//doesn't use Generator, so we have to enforce one armband drop here
armband,
//containers
dewVial,
seedBag,
scrollBag,
potionBag,
wandBag;
public int count = 0;
//for items which can only be dropped once, should directly access count otherwise.
public boolean dropped(){
return count != 0;
}
public void drop(){
count = 1;
}
}
public static int challenges;
public static Hero hero;
public static Level level;
public static QuickSlot quickslot = new QuickSlot();
public static int depth;
public static int gold;
// Reason of death
public static String resultDescription;
public static HashSet<Integer> chapters;
// Hero's field of view
public static boolean[] visible = new boolean[Level.LENGTH];
public static SparseArray<ArrayList<Item>> droppedItems;
public static int version;
public static void init() {
challenges = ShatteredPixelDungeon.challenges();
Generator.initArtifacts();
Actor.clear();
Actor.resetNextID();
PathFinder.setMapSize( Level.WIDTH, Level.HEIGHT );
Scroll.initLabels();
Potion.initColors();
Wand.initWoods();
Ring.initGems();
Statistics.reset();
Journal.reset();
quickslot.reset();
QuickSlotButton.reset();
depth = 0;
gold = 0;
droppedItems = new SparseArray<ArrayList<Item>>();
for (limitedDrops a : limitedDrops.values())
a.count = 0;
transmutation = Random.IntRange( 6, 14 );
chapters = new HashSet<Integer>();
Ghost.Quest.reset();
Wandmaker.Quest.reset();
Blacksmith.Quest.reset();
Imp.Quest.reset();
Room.shuffleTypes();
hero = new Hero();
hero.live();
Badges.reset();
StartScene.curClass.initHero( hero );
}
public static boolean isChallenged( int mask ) {
return (challenges & mask) != 0;
}
public static Level newLevel() {
Dungeon.level = null;
Actor.clear();
depth++;
if (depth > Statistics.deepestFloor) {
Statistics.deepestFloor = depth;
if (Statistics.qualifiedForNoKilling) {
Statistics.completedWithNoKilling = true;
} else {
Statistics.completedWithNoKilling = false;
}
}
Arrays.fill( visible, false );
Level level;
switch (depth) {
case 1:
case 2:
case 3:
case 4:
level = new SewerLevel();
break;
case 5:
level = new SewerBossLevel();
break;
case 6:
case 7:
case 8:
case 9:
level = new PrisonLevel();
break;
case 10:
level = new PrisonBossLevel();
break;
case 11:
case 12:
case 13:
case 14:
level = new CavesLevel();
break;
case 15:
level = new CavesBossLevel();
break;
case 16:
case 17:
case 18:
case 19:
level = new CityLevel();
break;
case 20:
level = new CityBossLevel();
break;
case 21:
level = new LastShopLevel();
break;
case 22:
case 23:
case 24:
level = new HallsLevel();
break;
case 25:
level = new HallsBossLevel();
break;
case 26:
level = new LastLevel();
break;
default:
level = new DeadEndLevel();
Statistics.deepestFloor--;
}
level.create();
Statistics.qualifiedForNoKilling = !bossLevel();
return level;
}
public static void resetLevel() {
Actor.clear();
Arrays.fill( visible, false );
level.reset();
switchLevel( level, level.entrance );
}
public static boolean shopOnLevel() {
return depth == 6 || depth == 11 || depth == 16;
}
public static boolean bossLevel() {
return bossLevel( depth );
}
public static boolean bossLevel( int depth ) {
return depth == 5 || depth == 10 || depth == 15 || depth == 20 || depth == 25;
}
@SuppressWarnings("deprecation")
public static void switchLevel( final Level level, int pos ) {
Dungeon.level = level;
Actor.init();
Actor respawner = level.respawner();
if (respawner != null) {
Actor.add( level.respawner() );
}
hero.pos = pos != -1 ? pos : level.exit;
Light light = hero.buff( Light.class );
hero.viewDistance = light == null ? level.viewDistance : Math.max( Light.DISTANCE, level.viewDistance );
observe();
try {
saveAll();
} catch (IOException e) {
/*This only catches IO errors. Yes, this means things can go wrong, and they can go wrong catastrophically.
But when they do the user will get a nice 'report this issue' dialogue, and I can fix the bug.*/
}
}
public static void dropToChasm( Item item ) {
int depth = Dungeon.depth + 1;
ArrayList<Item> dropped = (ArrayList<Item>)Dungeon.droppedItems.get( depth );
if (dropped == null) {
Dungeon.droppedItems.put( depth, dropped = new ArrayList<Item>() );
}
dropped.add( item );
}
public static boolean posNeeded() {
int[] quota = {4, 2, 9, 4, 14, 6, 19, 8, 24, 9};
return chance( quota, limitedDrops.strengthPotions.count );
}
public static boolean souNeeded() {
int[] quota = {5, 3, 10, 6, 15, 9, 20, 12, 25, 13};
return chance( quota, limitedDrops.upgradeScrolls.count );
}
private static boolean chance( int[] quota, int number ) {
for (int i=0; i < quota.length; i += 2) {
int qDepth = quota[i];
if (depth <= qDepth) {
int qNumber = quota[i + 1];
return Random.Float() < (float)(qNumber - number) / (qDepth - depth + 1);
}
}
return false;
}
public static boolean asNeeded() {
return Random.Int( 12 * (1 + limitedDrops.arcaneStyli.count) ) < depth;
}
private static final String RG_GAME_FILE = "game.dat";
private static final String RG_DEPTH_FILE = "depth%d.dat";
private static final String WR_GAME_FILE = "warrior.dat";
private static final String WR_DEPTH_FILE = "warrior%d.dat";
private static final String MG_GAME_FILE = "mage.dat";
private static final String MG_DEPTH_FILE = "mage%d.dat";
private static final String RN_GAME_FILE = "ranger.dat";
private static final String RN_DEPTH_FILE = "ranger%d.dat";
private static final String VERSION = "version";
private static final String CHALLENGES = "challenges";
private static final String HERO = "hero";
private static final String GOLD = "gold";
private static final String DEPTH = "depth";
private static final String DROPPED = "dropped%d";
private static final String LEVEL = "level";
private static final String LIMDROPS = "limiteddrops";
private static final String DV = "dewVial";
private static final String WT = "transmutation";
private static final String CHAPTERS = "chapters";
private static final String QUESTS = "quests";
private static final String BADGES = "badges";
//TODO: to support pre-0.2.3 saves, remove when needed
private static final String POS = "potionsOfStrength";
private static final String SOU = "scrollsOfEnhancement";
private static final String AS = "arcaneStyli";
public static String gameFile( HeroClass cl ) {
switch (cl) {
case WARRIOR:
return WR_GAME_FILE;
case MAGE:
return MG_GAME_FILE;
case HUNTRESS:
return RN_GAME_FILE;
default:
return RG_GAME_FILE;
}
}
private static String depthFile( HeroClass cl ) {
switch (cl) {
case WARRIOR:
return WR_DEPTH_FILE;
case MAGE:
return MG_DEPTH_FILE;
case HUNTRESS:
return RN_DEPTH_FILE;
default:
return RG_DEPTH_FILE;
}
}
public static void saveGame( String fileName ) throws IOException {
try {
Bundle bundle = new Bundle();
bundle.put( VERSION, Game.versionCode );
bundle.put( CHALLENGES, challenges );
bundle.put( HERO, hero );
bundle.put( GOLD, gold );
bundle.put( DEPTH, depth );
for (int d : droppedItems.keyArray()) {
bundle.put(String.format(DROPPED, d), droppedItems.get(d));
}
quickslot.storePlaceholders( bundle );
bundle.put( WT, transmutation );
int[] dropValues = new int[limitedDrops.values().length];
for (limitedDrops value : limitedDrops.values())
dropValues[value.ordinal()] = value.count;
bundle.put ( LIMDROPS, dropValues );
int count = 0;
int ids[] = new int[chapters.size()];
for (Integer id : chapters) {
ids[count++] = id;
}
bundle.put( CHAPTERS, ids );
Bundle quests = new Bundle();
Ghost .Quest.storeInBundle( quests );
Wandmaker .Quest.storeInBundle( quests );
Blacksmith .Quest.storeInBundle( quests );
Imp .Quest.storeInBundle( quests );
bundle.put( QUESTS, quests );
Room.storeRoomsInBundle( bundle );
Statistics.storeInBundle( bundle );
Journal.storeInBundle( bundle );
Generator.storeInBundle( bundle );
Scroll.save( bundle );
Potion.save( bundle );
Wand.save( bundle );
Ring.save( bundle );
Actor.storeNextID( bundle );
Bundle badges = new Bundle();
Badges.saveLocal( badges );
bundle.put( BADGES, badges );
OutputStream output = Game.instance.openFileOutput( fileName, Game.MODE_PRIVATE );
Bundle.write( bundle, output );
output.close();
} catch (IOException e) {
GamesInProgress.setUnknown( hero.heroClass );
}
}
public static void saveLevel() throws IOException {
Bundle bundle = new Bundle();
bundle.put( LEVEL, level );
OutputStream output = Game.instance.openFileOutput(
Utils.format( depthFile( hero.heroClass ), depth ), Game.MODE_PRIVATE );
Bundle.write( bundle, output );
output.close();
}
public static void saveAll() throws IOException {
if (hero.isAlive()) {
Actor.fixTime();
saveGame( gameFile( hero.heroClass ) );
saveLevel();
GamesInProgress.set( hero.heroClass, depth, hero.lvl, challenges != 0 );
} else if (WndResurrect.instance != null) {
WndResurrect.instance.hide();
Hero.reallyDie( WndResurrect.causeOfDeath );
}
}
public static void loadGame( HeroClass cl ) throws IOException {
loadGame( gameFile( cl ), true );
}
public static void loadGame( String fileName ) throws IOException {
loadGame( fileName, false );
}
public static void loadGame( String fileName, boolean fullLoad ) throws IOException {
Bundle bundle = gameBundle( fileName );
version = bundle.getInt( VERSION );
Generator.reset();
Actor.restoreNextID( bundle );
quickslot.reset();
QuickSlotButton.reset();
Dungeon.challenges = bundle.getInt( CHALLENGES );
Dungeon.level = null;
Dungeon.depth = -1;
if (fullLoad) {
PathFinder.setMapSize( Level.WIDTH, Level.HEIGHT );
}
Scroll.restore( bundle );
Potion.restore( bundle );
Wand.restore( bundle );
Ring.restore( bundle );
quickslot.restorePlaceholders( bundle );
if (fullLoad) {
transmutation = bundle.getInt( WT );
//TODO: adjust this when dropping support for pre-0.2.3 saves
if (bundle.contains( LIMDROPS )) {
int[] dropValues = bundle.getIntArray(LIMDROPS);
for (limitedDrops value : limitedDrops.values())
value.count = value.ordinal() < dropValues.length ?
dropValues[value.ordinal()] : 0;
} else {
for (limitedDrops value : limitedDrops.values())
value.count = 0;
limitedDrops.strengthPotions.count = bundle.getInt(POS);
limitedDrops.upgradeScrolls.count = bundle.getInt(SOU);
limitedDrops.arcaneStyli.count = bundle.getInt(AS);
}
//for pre-0.2.4 saves
if (bundle.getBoolean(DV)) limitedDrops.dewVial.drop();
chapters = new HashSet<Integer>();
int ids[] = bundle.getIntArray( CHAPTERS );
if (ids != null) {
for (int id : ids) {
chapters.add( id );
}
}
Bundle quests = bundle.getBundle( QUESTS );
if (!quests.isNull()) {
Ghost.Quest.restoreFromBundle( quests );
Wandmaker.Quest.restoreFromBundle( quests );
Blacksmith.Quest.restoreFromBundle( quests );
Imp.Quest.restoreFromBundle( quests );
} else {
Ghost.Quest.reset();
Wandmaker.Quest.reset();
Blacksmith.Quest.reset();
Imp.Quest.reset();
}
Room.restoreRoomsFromBundle(bundle);
}
Bundle badges = bundle.getBundle(BADGES);
if (!badges.isNull()) {
Badges.loadLocal( badges );
} else {
Badges.reset();
}
hero = null;
hero = (Hero)bundle.get( HERO );
gold = bundle.getInt( GOLD );
depth = bundle.getInt( DEPTH );
Statistics.restoreFromBundle( bundle );
Journal.restoreFromBundle( bundle );
Generator.restoreFromBundle( bundle );
droppedItems = new SparseArray<ArrayList<Item>>();
for (int i=2; i <= Statistics.deepestFloor + 1; i++) {
ArrayList<Item> dropped = new ArrayList<Item>();
for (Bundlable b : bundle.getCollection( String.format( DROPPED, i ) ) ) {
dropped.add( (Item)b );
}
if (!dropped.isEmpty()) {
droppedItems.put( i, dropped );
}
}
//logic for pre 0.2.4 bags, remove when no longer supporting those saves.
if (version <= 32){
int deepest = Statistics.deepestFloor;
if (deepest > 15) limitedDrops.wandBag.count = 1;
if (deepest > 10) limitedDrops.scrollBag.count = 1;
if (deepest > 5) limitedDrops.seedBag.count = 1;
}
}
public static Level loadLevel( HeroClass cl ) throws IOException {
Dungeon.level = null;
Actor.clear();
InputStream input = Game.instance.openFileInput( Utils.format( depthFile( cl ), depth ) ) ;
Bundle bundle = Bundle.read( input );
input.close();
return (Level)bundle.get( "level" );
}
public static void deleteGame( HeroClass cl, boolean deleteLevels ) {
Game.instance.deleteFile( gameFile( cl ) );
if (deleteLevels) {
int depth = 1;
while (Game.instance.deleteFile( Utils.format( depthFile( cl ), depth ) )) {
depth++;
}
}
GamesInProgress.delete( cl );
}
public static Bundle gameBundle( String fileName ) throws IOException {
InputStream input = Game.instance.openFileInput( fileName );
Bundle bundle = Bundle.read( input );
input.close();
return bundle;
}
public static void preview( GamesInProgress.Info info, Bundle bundle ) {
info.depth = bundle.getInt( DEPTH );
info.challenges = (bundle.getInt( CHALLENGES ) != 0);
if (info.depth == -1) {
info.depth = bundle.getInt( "maxDepth" ); // FIXME
}
Hero.preview( info, bundle.getBundle( HERO ) );
}
public static void fail( String desc ) {
resultDescription = desc;
if (hero.belongings.getItem( Ankh.class ) == null) {
Rankings.INSTANCE.submit( false );
}
}
public static void win( String desc ) {
hero.belongings.identify();
if (challenges != 0) {
Badges.validateChampion();
}
resultDescription = desc;
Rankings.INSTANCE.submit( true );
}
public static void observe() {
if (level == null) {
return;
}
level.updateFieldOfView( hero );
System.arraycopy( Level.fieldOfView, 0, visible, 0, visible.length );
BArray.or( level.visited, visible, level.visited );
GameScene.afterObserve();
}
private static boolean[] passable = new boolean[Level.LENGTH];
public static int findPath( Char ch, int from, int to, boolean pass[], boolean[] visible ) {
if (Level.adjacent( from, to )) {
return Actor.findChar( to ) == null && (pass[to] || Level.avoid[to]) ? to : -1;
}
if (ch.flying || ch.buff( Amok.class ) != null) {
BArray.or( pass, Level.avoid, passable );
} else {
System.arraycopy( pass, 0, passable, 0, Level.LENGTH );
}
for (Actor actor : Actor.all()) {
if (actor instanceof Char) {
int pos = ((Char)actor).pos;
if (visible[pos]) {
passable[pos] = false;
}
}
}
return PathFinder.getStep( from, to, passable );
}
public static int flee( Char ch, int cur, int from, boolean pass[], boolean[] visible ) {
if (ch.flying) {
BArray.or( pass, Level.avoid, passable );
} else {
System.arraycopy( pass, 0, passable, 0, Level.LENGTH );
}
for (Actor actor : Actor.all()) {
if (actor instanceof Char) {
int pos = ((Char)actor).pos;
if (visible[pos]) {
passable[pos] = false;
}
}
}
passable[cur] = true;
return PathFinder.getStepBack( cur, from, passable );
}
}
| gpl-3.0 |
Cloudef/darkstar | scripts/globals/items/fuscina.lua | 1060 | -----------------------------------------
-- ID: 18104
-- Item: Fuscina
-- Additional Effect: Lightning Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(3,10);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHTNING, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHTNING,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHTNING);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHTNING,dmg);
local message = msgBasic.ADD_EFFECT_DMG;
if (dmg < 0) then
message = msgBasic.ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHTNING_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
JamesWeirFluidsLab/OpenFOAM-MultiScale | src/postProcessing/functionObjects/systemCall/systemCall.H | 3846 | /*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright (C) 2011 OpenFOAM Foundation
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM. If not, see <http://www.gnu.org/licenses/>.
Class
Foam::systemCall
Description
Executes system calls, entered in the form of a string list
SourceFiles
systemCall.C
IOsystemCall.H
\*---------------------------------------------------------------------------*/
#ifndef systemCall_H
#define systemCall_H
#include "stringList.H"
#include "pointFieldFwd.H"
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
namespace Foam
{
// Forward declaration of classes
class objectRegistry;
class dictionary;
class mapPolyMesh;
/*---------------------------------------------------------------------------*\
Class systemCall Declaration
\*---------------------------------------------------------------------------*/
class systemCall
{
protected:
// Private data
//- Name of this set of system calls
word name_;
//- List of calls to execute - every step
stringList executeCalls_;
//- List of calls to execute when exiting the time-loop
stringList endCalls_;
//- List of calls to execute - write steps
stringList writeCalls_;
// Private Member Functions
//- Disallow default bitwise copy construct
systemCall(const systemCall&);
//- Disallow default bitwise assignment
void operator=(const systemCall&);
public:
//- Runtime type information
TypeName("systemCall");
// Constructors
//- Construct for given objectRegistry and dictionary.
// Allow the possibility to load fields from files
systemCall
(
const word& name,
const objectRegistry& unused,
const dictionary&,
const bool loadFromFilesUnused = false
);
//- Destructor
virtual ~systemCall();
// Member Functions
//- Return name of the system call set
virtual const word& name() const
{
return name_;
}
//- Read the system calls
virtual void read(const dictionary&);
//- Execute the "executeCalls" at each time-step
virtual void execute();
//- Execute the "endCalls" at the final time-loop
virtual void end();
//- Write, execute the "writeCalls"
virtual void write();
//- Update for changes of mesh
virtual void updateMesh(const mapPolyMesh&)
{}
//- Update for changes of mesh
virtual void movePoints(const pointField&)
{}
};
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
} // End namespace Foam
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
#endif
// ************************************************************************* //
| gpl-3.0 |
tomkluas/SmartStoreNET | src/Presentation/SmartStore.Web.Framework/ViewEngines/Razor/WebViewPage.cs | 10319 | using System;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Web.Mvc;
using System.Web.WebPages;
using SmartStore.Core;
using SmartStore.Core.Data;
using SmartStore.Core.Infrastructure;
using SmartStore.Core.Localization;
using SmartStore.Core.Logging;
using SmartStore.Core.Themes;
using SmartStore.Web.Framework.Controllers;
using SmartStore.Web.Framework.Localization;
using SmartStore.Web.Framework.Themes;
namespace SmartStore.Web.Framework.ViewEngines.Razor
{
public abstract class WebViewPage<TModel> : System.Web.Mvc.WebViewPage<TModel>
{
private IText _text;
private IWorkContext _workContext;
private IList<NotifyEntry> _internalNotifications;
private IThemeRegistry _themeRegistry;
private IThemeContext _themeContext;
private ExpandoObject _themeVars;
private bool? _isHomePage;
private int? _currentCategoryId;
private int? _currentManufacturerId;
private int? _currentProductId;
protected int CurrentCategoryId
{
get
{
if (!_currentCategoryId.HasValue)
{
int id = 0;
var routeValues = Url.RequestContext.RouteData.Values;
if (routeValues["controller"].ToString().IsCaseInsensitiveEqual("catalog") && routeValues["action"].ToString().IsCaseInsensitiveEqual("category"))
{
id = Convert.ToInt32(routeValues["categoryId"].ToString());
}
_currentCategoryId = id;
}
return _currentCategoryId.Value;
}
}
protected int CurrentManufacturerId
{
get
{
if (!_currentManufacturerId.HasValue)
{
var routeValues = Url.RequestContext.RouteData.Values;
int id = 0;
if (routeValues["controller"].ToString().IsCaseInsensitiveEqual("catalog") && routeValues["action"].ToString().IsCaseInsensitiveEqual("manufacturer"))
{
id = Convert.ToInt32(routeValues["manufacturerId"].ToString());
}
_currentManufacturerId = id;
}
return _currentManufacturerId.Value;
}
}
protected int CurrentProductId
{
get
{
if (!_currentProductId.HasValue)
{
var routeValues = Url.RequestContext.RouteData.Values;
int id = 0;
if (routeValues["controller"].ToString().IsCaseInsensitiveEqual("product") && routeValues["action"].ToString().IsCaseInsensitiveEqual("productdetails"))
{
id = Convert.ToInt32(routeValues["productId"].ToString());
}
_currentProductId = id;
}
return _currentProductId.Value;
}
}
protected bool IsHomePage
{
get
{
if (!_isHomePage.HasValue)
{
var routeData = Url.RequestContext.RouteData;
_isHomePage = routeData.GetRequiredString("controller").IsCaseInsensitiveEqual("Home") &&
routeData.GetRequiredString("action").IsCaseInsensitiveEqual("Index");
}
return _isHomePage.Value;
}
}
protected bool HasMessages
{
get
{
return ResolveNotifications(null).Any();
}
}
protected ICollection<LocalizedString> GetMessages(NotifyType type)
{
return ResolveNotifications(type).AsReadOnly();
}
private IEnumerable<LocalizedString> ResolveNotifications(NotifyType? type)
{
IEnumerable<NotifyEntry> result = Enumerable.Empty<NotifyEntry>();
if (_internalNotifications == null)
{
string key = NotifyAttribute.NotificationsKey;
IList<NotifyEntry> entries;
if (TempData.ContainsKey(key))
{
entries = TempData[key] as IList<NotifyEntry>;
if (entries != null)
{
result = result.Concat(entries);
}
}
if (ViewData.ContainsKey(key))
{
entries = ViewData[key] as IList<NotifyEntry>;
if (entries != null)
{
result = result.Concat(entries);
}
}
_internalNotifications = new List<NotifyEntry>(result);
}
if (type == null)
{
return _internalNotifications.Select(x => x.Message);
}
return _internalNotifications.Where(x => x.Type == type.Value).Select(x => x.Message);
}
/// <summary>
/// Get a localized resource
/// </summary>
public Localizer T
{
get
{
return _text.Get;
}
}
public IWorkContext WorkContext
{
get
{
return _workContext;
}
}
public override void InitHelpers()
{
base.InitHelpers();
if (DataSettings.DatabaseIsInstalled())
{
_text = EngineContext.Current.Resolve<IText>();
_workContext = EngineContext.Current.Resolve<IWorkContext>();
}
}
public HelperResult RenderWrappedSection(string name, object wrapperHtmlAttributes)
{
Action<TextWriter> action = delegate(TextWriter tw)
{
var htmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(wrapperHtmlAttributes);
var tagBuilder = new TagBuilder("div");
tagBuilder.MergeAttributes(htmlAttributes);
var section = RenderSection(name, false);
if (section != null)
{
tw.Write(tagBuilder.ToString(TagRenderMode.StartTag));
section.WriteTo(tw);
tw.Write(tagBuilder.ToString(TagRenderMode.EndTag));
}
};
return new HelperResult(action);
}
public HelperResult RenderSection(string sectionName, Func<object, HelperResult> defaultContent)
{
return IsSectionDefined(sectionName) ? RenderSection(sectionName) : defaultContent(new object());
}
public override string Layout
{
get
{
var layout = base.Layout;
if (!string.IsNullOrEmpty(layout))
{
var filename = System.IO.Path.GetFileNameWithoutExtension(layout);
ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindView(ViewContext.Controller.ControllerContext, filename, "");
if (viewResult.View != null && viewResult.View is RazorView)
{
layout = (viewResult.View as RazorView).ViewPath;
}
}
return layout;
}
set
{
base.Layout = value;
}
}
/// <summary>
/// Return a value indicating whether the working language and theme support RTL (right-to-left)
/// </summary>
/// <returns></returns>
public bool ShouldUseRtlTheme()
{
var supportRtl = _workContext.WorkingLanguage.Rtl;
if (supportRtl)
{
//ensure that the active theme also supports it
supportRtl = this.ThemeManifest.SupportRtl;
}
return supportRtl;
}
/// <summary>
/// Gets the manifest of the current active theme
/// </summary>
protected ThemeManifest ThemeManifest
{
get
{
EnsureThemeContextInitialized();
return _themeContext.CurrentTheme;
}
}
/// <summary>
/// Gets the current theme name. Override this in configuration views.
/// </summary>
[Obsolete("The theme name gets resolved automatically now. No need to override anymore.")]
protected virtual string ThemeName
{
get
{
EnsureThemeContextInitialized();
return _themeContext.WorkingDesktopTheme;
}
}
/// <summary>
/// Gets the runtime theme variables as specified in the theme's config file
/// alongside the merged user-defined variables
/// </summary>
public dynamic ThemeVariables
{
get
{
if (_themeVars == null)
{
var storeContext = EngineContext.Current.Resolve<IStoreContext>();
var repo = new ThemeVarsRepository();
_themeVars = repo.GetRawVariables(this.ThemeManifest.ThemeName, storeContext.CurrentStore.Id);
}
return _themeVars;
}
}
public string GetThemeVariable(string varname, string defaultValue = "")
{
return GetThemeVariable<string>(varname, defaultValue);
}
/// <summary>
/// Gets a runtime theme variable value
/// </summary>
/// <param name="varName">The name of the variable</param>
/// <param name="defaultValue">The default value to return if the variable does not exist</param>
/// <returns>The theme variable value</returns>
public T GetThemeVariable<T>(string varName, T defaultValue = default(T))
{
Guard.ArgumentNotEmpty(varName, "varName");
var vars = this.ThemeVariables as IDictionary<string, object>;
if (vars != null && vars.ContainsKey(varName))
{
string value = vars[varName] as string;
if (!value.HasValue())
{
return defaultValue;
}
return (T)value.Convert(typeof(T));
}
return defaultValue;
}
private void EnsureThemeContextInitialized()
{
if (_themeRegistry == null)
_themeRegistry = EngineContext.Current.Resolve<IThemeRegistry>();
if (_themeContext == null)
_themeContext = EngineContext.Current.Resolve<IThemeContext>();
}
}
public abstract class WebViewPage : WebViewPage<dynamic>
{
}
} | gpl-3.0 |
jeremiahyan/odoo | addons/membership/wizard/membership_invoice.py | 1519 | # -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models
class MembershipInvoice(models.TransientModel):
_name = "membership.invoice"
_description = "Membership Invoice"
product_id = fields.Many2one('product.product', string='Membership', required=True)
member_price = fields.Float(string='Member Price', digits='Product Price', required=True)
@api.onchange('product_id')
def onchange_product(self):
"""This function returns value of product's member price based on product id.
"""
price_dict = self.product_id.price_compute('list_price')
self.member_price = price_dict.get(self.product_id.id) or False
def membership_invoice(self):
invoice_list = self.env['res.partner'].browse(self._context.get('active_ids')).create_membership_invoice(self.product_id, self.member_price)
search_view_ref = self.env.ref('account.view_account_invoice_filter', False)
form_view_ref = self.env.ref('account.view_move_form', False)
tree_view_ref = self.env.ref('account.view_move_tree', False)
return {
'domain': [('id', 'in', invoice_list.ids)],
'name': 'Membership Invoices',
'res_model': 'account.move',
'type': 'ir.actions.act_window',
'views': [(tree_view_ref.id, 'tree'), (form_view_ref.id, 'form')],
'search_view_id': search_view_ref and [search_view_ref.id],
}
| gpl-3.0 |
xaocbozzz/genbo | plugins/box/users/views/frontend/edit.view.php | 1793 | <h3><?php echo __('Edit profile', 'users') ?></h3>
<hr>
<?php if (Notification::get('success')) Alert::success(Notification::get('success')); ?>
<?php if (Notification::get('error')) Alert::success(Notification::get('error')); ?>
<form method="post">
<?php
echo (
Form::hidden('csrf', Security::token()).
Form::hidden('user_id', $user['id'])
);
?>
<?php if (isset($_SESSION['user_role']) && in_array($_SESSION['user_role'], array('admin'))) { ?>
<label><?php echo __('Username', 'users'); ?></label><input class="input-xlarge" type="text" value="<?php echo $user['login']; ?>" name="login">
<?php } else { echo Form::hidden('login', $user['login']); } ?>
<label><?php echo __('Firstname', 'users'); ?></label><input class="input-xlarge" type="text" value="<?php echo $user['firstname']; ?>" name="firstname">
<label><?php echo __('Lastname', 'users'); ?></label><input class="input-xlarge" type="text" value="<?php echo $user['lastname']; ?>" name="lastname">
<label><?php echo __('Email', 'users'); ?></label><input class="input-xlarge" type="text" value="<?php echo $user['email']; ?>" name="email">
<label><?php echo __('Twitter', 'users'); ?></label><input class="input-xlarge" type="text" value="<?php echo $user['twitter']; ?>" name="twitter">
<label><?php echo __('Skype', 'users'); ?></label><input class="input-xlarge" type="text" value="<?php echo $user['skype']; ?>" name="skype">
<label><?php echo __('About Me', 'users'); ?></label><textarea class="input-xlarge" name="about_me"><?php echo $user['about_me']; ?></textarea>
<label><?php echo __('New Password', 'users'); ?></label><input class="input-xlarge" type="text" name="new_password">
<br/><input type="submit" class="btn" value="<?php echo __('Save', 'users'); ?>" name="edit_profile">
</form>
| gpl-3.0 |
sarwan-nxb/open-source-billing | db/migrate/20150211114857_create_payments.rb | 799 | class CreatePayments < ActiveRecord::Migration
def change
create_table :payments do |t|
t.integer "invoice_id"
t.decimal "payment_amount", precision: 8, scale: 2
t.string "payment_type"
t.string "payment_method"
t.date "payment_date"
t.text "notes"
t.boolean "send_payment_notification"
t.boolean "paid_full"
t.string "archive_number"
t.datetime "archived_at"
t.datetime "deleted_at"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.decimal "credit_applied", precision: 10, scale: 2
t.integer "client_id"
t.integer "company_id"
end
end
end
| gpl-3.0 |
paulmey/packer | vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/ecs/struct_value_item.go | 1151 | package ecs
//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.
//
// Code generated by Alibaba Cloud SDK Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
// ValueItem is a nested struct in ecs response
type ValueItem struct {
Value string `json:"Value" xml:"Value"`
ExpiredTime string `json:"ExpiredTime" xml:"ExpiredTime"`
ZoneId string `json:"ZoneId" xml:"ZoneId"`
InstanceChargeType string `json:"InstanceChargeType" xml:"InstanceChargeType"`
InstanceType string `json:"InstanceType" xml:"InstanceType"`
Count int `json:"Count" xml:"Count"`
}
| mpl-2.0 |
ddrmanxbxfr/servo | components/script/dom/customevent.rs | 3449 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
use dom::bindings::codegen::Bindings::CustomEventBinding;
use dom::bindings::codegen::Bindings::CustomEventBinding::CustomEventMethods;
use dom::bindings::codegen::Bindings::EventBinding::EventMethods;
use dom::bindings::error::Fallible;
use dom::bindings::inheritance::Castable;
use dom::bindings::js::{MutHeapJSVal, Root};
use dom::bindings::reflector::reflect_dom_object;
use dom::bindings::str::DOMString;
use dom::bindings::trace::RootedTraceableBox;
use dom::event::Event;
use dom::globalscope::GlobalScope;
use js::jsapi::{HandleValue, JSContext};
use js::jsval::JSVal;
use servo_atoms::Atom;
// https://dom.spec.whatwg.org/#interface-customevent
#[dom_struct]
pub struct CustomEvent {
event: Event,
#[ignore_heap_size_of = "Defined in rust-mozjs"]
detail: MutHeapJSVal,
}
impl CustomEvent {
fn new_inherited() -> CustomEvent {
CustomEvent {
event: Event::new_inherited(),
detail: MutHeapJSVal::new(),
}
}
pub fn new_uninitialized(global: &GlobalScope) -> Root<CustomEvent> {
reflect_dom_object(box CustomEvent::new_inherited(),
global,
CustomEventBinding::Wrap)
}
pub fn new(global: &GlobalScope,
type_: Atom,
bubbles: bool,
cancelable: bool,
detail: HandleValue)
-> Root<CustomEvent> {
let ev = CustomEvent::new_uninitialized(global);
ev.init_custom_event(type_, bubbles, cancelable, detail);
ev
}
#[allow(unsafe_code)]
pub fn Constructor(global: &GlobalScope,
type_: DOMString,
init: RootedTraceableBox<CustomEventBinding::CustomEventInit>)
-> Fallible<Root<CustomEvent>> {
Ok(CustomEvent::new(global,
Atom::from(type_),
init.parent.bubbles,
init.parent.cancelable,
init.detail.handle()))
}
fn init_custom_event(&self,
type_: Atom,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
let event = self.upcast::<Event>();
if event.dispatching() {
return;
}
self.detail.set(detail.get());
event.init_event(type_, can_bubble, cancelable);
}
}
impl CustomEventMethods for CustomEvent {
#[allow(unsafe_code)]
// https://dom.spec.whatwg.org/#dom-customevent-detail
unsafe fn Detail(&self, _cx: *mut JSContext) -> JSVal {
self.detail.get()
}
#[allow(unsafe_code)]
// https://dom.spec.whatwg.org/#dom-customevent-initcustomevent
unsafe fn InitCustomEvent(&self,
_cx: *mut JSContext,
type_: DOMString,
can_bubble: bool,
cancelable: bool,
detail: HandleValue) {
self.init_custom_event(Atom::from(type_), can_bubble, cancelable, detail)
}
// https://dom.spec.whatwg.org/#dom-event-istrusted
fn IsTrusted(&self) -> bool {
self.event.IsTrusted()
}
}
| mpl-2.0 |
BehavioralInsightsTeam/edx-platform | common/lib/xmodule/xmodule/tests/test_import_static.py | 2304 | """
Tests that check that we ignore the appropriate files when importing courses.
"""
import unittest
from mock import Mock
from xmodule.modulestore.xml_importer import StaticContentImporter
from opaque_keys.edx.locator import CourseLocator
from xmodule.tests import DATA_DIR
class IgnoredFilesTestCase(unittest.TestCase):
"Tests for ignored files"
shard = 1
def test_ignore_tilde_static_files(self):
course_dir = DATA_DIR / "tilde"
course_id = CourseLocator("edX", "tilde", "Fall_2012")
content_store = Mock()
content_store.generate_thumbnail.return_value = ("content", "location")
static_content_importer = StaticContentImporter(
static_content_store=content_store,
course_data_path=course_dir,
target_id=course_id
)
static_content_importer.import_static_content_directory()
saved_static_content = [call[0][0] for call in content_store.save.call_args_list]
name_val = {sc.name: sc.data for sc in saved_static_content}
self.assertIn("example.txt", name_val)
self.assertNotIn("example.txt~", name_val)
self.assertIn("GREEN", name_val["example.txt"])
def test_ignore_dot_underscore_static_files(self):
"""
Test for ignored Mac OS metadata files (filename starts with "._")
"""
course_dir = DATA_DIR / "dot-underscore"
course_id = CourseLocator("edX", "dot-underscore", "2014_Fall")
content_store = Mock()
content_store.generate_thumbnail.return_value = ("content", "location")
static_content_importer = StaticContentImporter(
static_content_store=content_store,
course_data_path=course_dir,
target_id=course_id
)
static_content_importer.import_static_content_directory()
saved_static_content = [call[0][0] for call in content_store.save.call_args_list]
name_val = {sc.name: sc.data for sc in saved_static_content}
self.assertIn("example.txt", name_val)
self.assertIn(".example.txt", name_val)
self.assertNotIn("._example.txt", name_val)
self.assertNotIn(".DS_Store", name_val)
self.assertIn("GREEN", name_val["example.txt"])
self.assertIn("BLUE", name_val[".example.txt"])
| agpl-3.0 |
MihailProg/Rotux | server/wServer/logic/db/BehaviorDb.EntAncient.cs | 13076 | #region
using wServer.logic.behaviors;
using wServer.logic.loot;
using wServer.logic.transitions;
#endregion
namespace wServer.logic
{
partial class BehaviorDb
{
private _ EntAncient = () => Behav()
.Init("Ent Ancient",
new State(
new State("Idle",
new StayCloseToSpawn(0.1, 6),
new Wander(0.1),
new HpLessTransition(0.99999, "EvaluationStart1")
),
new State("EvaluationStart1",
new Taunt("Uhh. So... sleepy..."),
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new Prioritize(
new StayCloseToSpawn(0.2, 3),
new Wander(0.2)
),
new TimedTransition(2500, "EvaluationStart2")
),
new State("EvaluationStart2",
new Flash(0x0000ff, 0.1, 60),
new Shoot(10, 2, 180, coolDown: 800),
new Prioritize(
new StayCloseToSpawn(0.3, range: 5),
new Wander(0.3)
),
new HpLessTransition(0.87, "EvaluationEnd"),
new TimedTransition(6000, "EvaluationEnd")
),
new State("EvaluationEnd",
new HpLessTransition(0.875, "HugeMob"),
new HpLessTransition(0.952, "Mob"),
new HpLessTransition(0.985, "SmallGroup"),
new HpLessTransition(0.99999, "Solo")
),
new State("HugeMob",
new Taunt("You are many, yet the sum of your years is nothing."),
new Spawn("Greater Nature Sprite", 6, 0, 400),
new TossObject("Ent", 3, 0, 100000),
new TossObject("Ent", 3, 180, 100000),
new TossObject("Ent", 5, 10, 100000),
new TossObject("Ent", 5, 190, 100000),
new TossObject("Ent", 5, 70, 100000),
new TossObject("Ent", 7, 20, 100000),
new TossObject("Ent", 7, 200, 100000),
new TossObject("Ent", 7, 80, 100000),
new TossObject("Ent", 10, 30, 100000),
new TossObject("Ent", 10, 210, 100000),
new TossObject("Ent", 10, 90, 100000),
new TimedTransition(5000, "Wait")
),
new State("Mob",
new Taunt("Little flies, little flies... we will swat you."),
new Spawn("Greater Nature Sprite", 3, 0, 1000),
new TossObject("Ent", 3, 0, 100000),
new TossObject("Ent", 4, 180, 100000),
new TossObject("Ent", 5, 10, 100000),
new TossObject("Ent", 6, 190, 100000),
new TossObject("Ent", 7, 20, 100000),
new TimedTransition(5000, "Wait")
),
new State("SmallGroup",
new Taunt("It will be trivial to dispose of you."),
new Spawn("Greater Nature Sprite", 1, 1, 100000),
new TossObject("Ent", 3, 0, 100000),
new TossObject("Ent", 4.5, 180, 100000),
new TimedTransition(3000, "Wait")
),
new State("Solo",
new Taunt("Mmm? Did you say something, mortal?"),
new TimedTransition(3000, "Wait")
),
new State("Wait",
new Transform("Actual Ent Ancient")
)
)
)
.Init("Actual Ent Ancient",
new State(
new Prioritize(
new StayCloseToSpawn(0.2, 6),
new Wander(0.2)
),
new Spawn("Ent Sapling", 3, 0, 3000),
new State("Start",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 160),
new Shoot(10, projectileIndex: 0, count: 1),
new TimedTransition(1600, "Growing1"),
new HpLessTransition(0.9, "Growing1")
),
new State("Growing1",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 180),
new Shoot(10, projectileIndex: 1, count: 3, shootAngle: 120),
new TimedTransition(1600, "Growing2"),
new HpLessTransition(0.8, "Growing2")
),
new State("Growing2",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 200),
new Taunt(0.35, "Little mortals, your years are my minutes."),
new Shoot(10, projectileIndex: 2, count: 1),
new TimedTransition(1600, "Growing3"),
new HpLessTransition(0.7, "Growing3")
),
new State("Growing3",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 220),
new Shoot(10, projectileIndex: 3, count: 1),
new TimedTransition(1600, "Growing4"),
new HpLessTransition(0.6, "Growing4")
),
new State("Growing4",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 240),
new Taunt(0.35, "No axe can fell me!"),
new Shoot(10, projectileIndex: 4, count: 3, shootAngle: 120),
new TimedTransition(1600, "Growing5"),
new HpLessTransition(0.5, "Growing5")
),
new State("Growing5",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 260),
new Shoot(10, projectileIndex: 5, count: 1),
new TimedTransition(1600, "Growing6"),
new HpLessTransition(0.45, "Growing6")
),
new State("Growing6",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 280),
new Taunt(0.35, "Yes, YES..."),
new Shoot(10, projectileIndex: 6, count: 1),
new TimedTransition(1600, "Growing7"),
new HpLessTransition(0.4, "Growing7")
),
new State("Growing7",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 300),
new Shoot(10, projectileIndex: 7, count: 3, shootAngle: 120),
new TimedTransition(1600, "Growing8"),
new HpLessTransition(0.36, "Growing8")
),
new State("Growing8",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ChangeSize(11, 320),
new Taunt(0.35, "I am the FOREST!!"),
new Shoot(10, projectileIndex: 8, count: 1),
new TimedTransition(1600, "Growing9"),
new HpLessTransition(0.32, "Growing9")
),
new State("Growing9",
new ChangeSize(11, 340),
new Taunt(1.0, "YOU WILL DIE!!!"),
new Shoot(10, projectileIndex: 9, count: 1),
new State("convert_sprites",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new Order(50, "Greater Nature Sprite", "Transform"),
new TimedTransition(2000, "shielded")
),
new State("received_armor",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new ConditionalEffect(ConditionEffectIndex.Armored, true),
new TimedTransition(1000, "shielded")
),
new State("shielded",
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new TimedTransition(4000, "unshielded")
),
new State("unshielded",
new Shoot(10, projectileIndex: 3, count: 3, shootAngle: 120, coolDown: 700),
new TimedTransition(4000, "shielded")
)
)
),
new TierLoot(2, ItemType.Ring, 0.15),
new TierLoot(3, ItemType.Ring, 0.04),
new TierLoot(6, ItemType.Weapon, 0.3),
new TierLoot(7, ItemType.Weapon, 0.1),
new TierLoot(6, ItemType.Armor, 0.3),
new TierLoot(7, ItemType.Armor, 0.1),
new TierLoot(1, ItemType.Ability, 0.95),
new TierLoot(2, ItemType.Ability, 0.25),
new TierLoot(3, ItemType.Ability, 0.05),
new ItemLoot("Health Potion", 0.7),
new ItemLoot("Magic Potion", 0.7)
)
.Init("Ent",
new State(
new Prioritize(
new Protect(0.25, "Ent Ancient", 12, 7, 7),
new Follow(0.25, range: 1, acquireRange: 9),
new Shoot(10, 5, 72, fixedAngle: 30, coolDown: 1600, coolDownOffset: 800)
),
new Shoot(10, predictive: 0.4, coolDown: 600),
new Decay(90000)
),
new ItemLoot("Tincture of Dexterity", 0.02)
)
.Init("Ent Sapling",
new State(
new Prioritize(
new Protect(0.55, "Ent Ancient", 10, 4, 4),
new Wander(0.55)
),
new Shoot(10, coolDown: 1000)
)
)
.Init("Greater Nature Sprite",
new State(
new ConditionalEffect(ConditionEffectIndex.Invulnerable),
new Shoot(10, 4, 10),
new Prioritize(
new StayCloseToSpawn(1.5, 11),
new Orbit(1.5, 4, 7),
new Follow(200, 7, 2),
new Follow(0.3, 7, 0.2)
),
new State("Idle"),
new State("Transform",
new Transform("Actual Greater Nature Sprite")
),
new Decay(90000)
)
)
.Init("Actual Greater Nature Sprite",
new State(
new Flash(0xff484848, 0.6, 1000),
new Spawn("Ent", 2, 0, 3000),
new Heal(15, "Heros", 200),
new State("armor_ent_ancient",
new Order(30, "Actual Ent Ancient", "received_armor"),
new TimedTransition(1000, "last_fight")
),
new State("last_fight",
new Shoot(10, 4, 10),
new Prioritize(
new StayCloseToSpawn(1.5, 11),
new Orbit(1.5, 4, 7),
new Follow(200, 7, 2),
new Follow(0.3, 7, 0.2)
)
),
new Decay(60000)
),
new ItemLoot("Magic Potion", 0.25),
new ItemLoot("Tincture of Life", 0.06),
new ItemLoot("Green Drake Egg", 0.08),
new ItemLoot("Quiver of Thunder", 0.002),
new TierLoot(8, ItemType.Armor, 0.3)
)
;
}
} | agpl-3.0 |
akretion/stock-logistics-workflow | stock_scanner/demo/Tutorial/Step_types/scanner_scenario_step_step_types_number_integer.py | 464 | # flake8: noqa
# Use <m> or <message> to retrieve the data transmitted by the scanner.
# Use <t> or <terminal> to retrieve the running terminal browse record.
# Put the returned action code in <act>, as a single character.
# Put the returned result or message in <res>, as a list of strings.
# Put the returned value in <val>, as an integer
act = 'N'
res = [
_('|Number (integer) step'),
'',
_('This step allows the user to send integer numbers.'),
]
| agpl-3.0 |
zeroseven/shopware | tests/Shopware/Tests/Service/Price/GraduatedPricesTest.php | 5171 | <?php
namespace Shopware\Tests\Service\Price;
use Shopware\Bundle\StoreFrontBundle\Struct\Product\Price;
use Shopware\Bundle\StoreFrontBundle\Struct\ProductContext;
use Shopware\Models\Category\Category;
use Shopware\Tests\Service\TestCase;
class GraduatedPricesTest extends TestCase
{
protected function getContext()
{
$context = parent::getContext();
$context->setFallbackCustomerGroup(
$this->converter->convertCustomerGroup($this->helper->createCustomerGroup(array('key'=> 'BACK')))
);
return $context;
}
protected function getProduct(
$number,
ProductContext $context,
Category $category = null
) {
$data = parent::getProduct($number, $context, $category);
$data['mainDetail']['prices'] = array_merge(
$data['mainDetail']['prices'],
$this->helper->getGraduatedPrices(
$context->getFallbackCustomerGroup()->getKey(),
-20
)
);
return $data;
}
public function testSimpleGraduation()
{
$number = __FUNCTION__;
$context = $this->getContext();
$data = $this->getProduct($number, $context);
$this->helper->createArticle($data);
$listProduct = $this->helper->getListProduct($number, $context);
$graduation = $listProduct->getPrices();
$this->assertCount(3, $graduation);
foreach ($graduation as $price) {
$this->assertEquals('PHP', $price->getCustomerGroup()->getKey());
$this->assertGreaterThan(0, $price->getCalculatedPrice());
}
}
public function testFallbackGraduation()
{
$number = __FUNCTION__;
$context = $this->getContext();
$data = $this->getProduct($number, $context);
$this->helper->createArticle($data);
$context->getCurrentCustomerGroup()->setKey('NOT');
$listProduct = $this->helper->getListProduct($number, $context);
$graduation = $listProduct->getPrices();
$this->assertCount(3, $graduation);
foreach ($graduation as $price) {
$this->assertEquals('BACK', $price->getCustomerGroup()->getKey());
$this->assertGreaterThan(0, $price->getCalculatedPrice());
}
}
public function testVariantGraduation()
{
$number = __FUNCTION__;
$context = $this->getContext();
$data = $this->getProduct($number, $context);
$configurator = $this->helper->getConfigurator(
$context->getCurrentCustomerGroup(),
$number
);
$data = array_merge($data, $configurator);
foreach ($data['variants'] as &$variant) {
$variant['prices'] = $this->helper->getGraduatedPrices(
$context->getCurrentCustomerGroup()->getKey(),
100
);
}
$variantNumber = $data['variants'][1]['number'];
$this->helper->createArticle($data);
/**@var $first Price*/
$listProduct = $this->helper->getListProduct($number, $context);
$this->assertCount(3, $listProduct->getPrices());
$first = array_shift($listProduct->getPrices());
$this->assertEquals(100, $first->getCalculatedPrice());
/**@var $first Price*/
$listProduct = $this->helper->getListProduct($variantNumber, $context);
$this->assertCount(3, $listProduct->getPrices());
$first = array_shift($listProduct->getPrices());
$this->assertEquals(200, $first->getCalculatedPrice());
}
public function testGraduationByPriceGroup()
{
$number = __FUNCTION__;
$context = $this->getContext();
$data = $this->getProduct($number, $context);
$data['mainDetail']['prices'] = array(array(
'from' => 1,
'to' => null,
'price' => 40,
'customerGroupKey' => $context->getCurrentCustomerGroup()->getKey(),
'pseudoPrice' => 110
));
$priceGroup = $this->helper->createPriceGroup();
$priceGroupStruct = $this->converter->convertPriceGroup($priceGroup);
$context->setPriceGroups(array(
$priceGroupStruct->getId() => $priceGroupStruct
));
$data['priceGroupId'] = $priceGroup->getId();
$data['priceGroupActive'] = true;
$this->helper->createArticle($data);
$listProduct = $this->helper->getListProduct($number, $context);
$graduations = $listProduct->getPrices();
$this->assertCount(3, $graduations);
$this->assertEquals(36, $graduations[0]->getCalculatedPrice());
$this->assertEquals(1, $graduations[0]->getFrom());
$this->assertEquals(4, $graduations[0]->getTo());
$this->assertEquals(32, $graduations[1]->getCalculatedPrice());
$this->assertEquals(5, $graduations[1]->getFrom());
$this->assertEquals(9, $graduations[1]->getTo());
$this->assertEquals(28, $graduations[2]->getCalculatedPrice());
$this->assertEquals(10, $graduations[2]->getFrom());
$this->assertEquals(null, $graduations[2]->getTo());
}
}
| agpl-3.0 |
maestrano/sugarcrm_dev | modules/oqc_ProductCatalog/metadata/SearchFields.php | 2871 | <?php
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
/*********************************************************************************
* SugarCRM is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004 - 2007 SugarCRM Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU 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 or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo. If the display of the logo is not reasonably feasible for
* technical reasons, the Appropriate Legal Notices must display the words
* "Powered by SugarCRM".
********************************************************************************/
$module_name = 'oqc_ProductCatalog';
$_object_name = 'oqc_productcatalog';
$searchFields[$module_name] =
array (
'name' => array( 'query_type'=>'default'),
'status'=> array('query_type'=>'default', 'options' => $_object_name.'_status_dom', 'template_var' => 'STATUS_OPTIONS'),
'priority'=> array('query_type'=>'default', 'options' => $_object_name. '_priority_dom', 'template_var' => 'PRIORITY_OPTIONS'),
'resolution'=> array('query_type'=>'default', 'options' => $_object_name. '_resolution_dom', 'template_var' => 'RESOLUTION_OPTIONS'),
$_object_name. '_number'=> array('query_type'=>'default','operator'=>'in'),
'current_user_only'=> array('query_type'=>'default','db_field'=>array('assigned_user_id'),'my_items'=>true),
'assigned_user_id'=> array('query_type'=>'default'),
);
?>
| agpl-3.0 |
n-gupta/JFreeChart | tests/org/jfree/chart/labels/junit/StandardCategoryToolTipGeneratorTests.java | 6630 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2008, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Java is a trademark or registered trademark of Sun Microsystems, Inc.
* in the United States and other countries.]
*
* ------------------------------------------
* StandardCategoryToolTipGeneratorTests.java
* ------------------------------------------
* (C) Copyright 2004-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 11-May-2004 : Version 1 (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 03-May-2006 : Added testEquals1481087() (DG);
* 23-Apr-2008 : Added testPublicCloneable() (DG);
*
*/
package org.jfree.chart.labels.junit;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardCategoryToolTipGenerator;
import org.jfree.chart.util.PublicCloneable;
/**
* Tests for the {@link StandardCategoryToolTipGenerator} class.
*/
public class StandardCategoryToolTipGeneratorTests extends TestCase {
/**
* Returns the tests as a test suite.
*
* @return The test suite.
*/
public static Test suite() {
return new TestSuite(StandardCategoryToolTipGeneratorTests.class);
}
/**
* Constructs a new set of tests.
*
* @param name the name of the tests.
*/
public StandardCategoryToolTipGeneratorTests(String name) {
super(name);
}
/**
* Tests the equals() method.
*/
public void testEquals() {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator();
StandardCategoryToolTipGenerator g2
= new StandardCategoryToolTipGenerator();
assertTrue(g1.equals(g2));
assertTrue(g2.equals(g1));
g1 = new StandardCategoryToolTipGenerator("{0}",
new DecimalFormat("0.000"));
assertFalse(g1.equals(g2));
g2 = new StandardCategoryToolTipGenerator("{0}",
new DecimalFormat("0.000"));
assertTrue(g1.equals(g2));
g1 = new StandardCategoryToolTipGenerator("{1}",
new DecimalFormat("0.000"));
assertFalse(g1.equals(g2));
g2 = new StandardCategoryToolTipGenerator("{1}",
new DecimalFormat("0.000"));
assertTrue(g1.equals(g2));
g1 = new StandardCategoryToolTipGenerator("{2}",
new SimpleDateFormat("d-MMM"));
assertFalse(g1.equals(g2));
g2 = new StandardCategoryToolTipGenerator("{2}",
new SimpleDateFormat("d-MMM"));
assertTrue(g1.equals(g2));
}
/**
* Simple check that hashCode is implemented.
*/
public void testHashCode() {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator();
StandardCategoryToolTipGenerator g2
= new StandardCategoryToolTipGenerator();
assertTrue(g1.equals(g2));
assertTrue(g1.hashCode() == g2.hashCode());
}
/**
* Confirm that cloning works.
*/
public void testCloning() {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator();
StandardCategoryToolTipGenerator g2 = null;
try {
g2 = (StandardCategoryToolTipGenerator) g1.clone();
}
catch (CloneNotSupportedException e) {
e.printStackTrace();
}
assertTrue(g1 != g2);
assertTrue(g1.getClass() == g2.getClass());
assertTrue(g1.equals(g2));
}
/**
* Check to ensure that this class implements PublicCloneable.
*/
public void testPublicCloneable() {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator();
assertTrue(g1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
public void testSerialization() {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator("{2}",
DateFormat.getInstance());
StandardCategoryToolTipGenerator g2 = null;
try {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(buffer);
out.writeObject(g1);
out.close();
ObjectInput in = new ObjectInputStream(
new ByteArrayInputStream(buffer.toByteArray()));
g2 = (StandardCategoryToolTipGenerator) in.readObject();
in.close();
}
catch (Exception e) {
e.printStackTrace();
}
assertEquals(g1, g2);
}
/**
* A test for bug 1481087.
*/
public void testEquals1481087() {
StandardCategoryToolTipGenerator g1
= new StandardCategoryToolTipGenerator("{0}",
new DecimalFormat("0.00"));
StandardCategoryItemLabelGenerator g2
= new StandardCategoryItemLabelGenerator("{0}",
new DecimalFormat("0.00"));
assertFalse(g1.equals(g2));
}
}
| lgpl-2.1 |
whdc/ieo-beast | src/dr/math/distributions/TruncatedDistribution.java | 4724 | package dr.math.distributions;
import dr.math.UnivariateFunction;
import org.apache.commons.math.MathException;
import org.apache.commons.math.distribution.AbstractContinuousDistribution;
/**
* @author Andrew Rambaut
*/
public class TruncatedDistribution extends AbstractContinuousDistribution implements Distribution {
public double getLower() {
return lower;
}
public double getUpper() {
return upper;
}
public TruncatedDistribution(Distribution source, double lower, double upper) {
this.source = source;
if (lower == upper) {
throw new IllegalArgumentException("upper equals lower");
}
if (source.getProbabilityDensityFunction().getLowerBound() > lower) {
lower = source.getProbabilityDensityFunction().getLowerBound();
}
if (source.getProbabilityDensityFunction().getUpperBound() < upper) {
upper = source.getProbabilityDensityFunction().getUpperBound();
}
this.lower = lower;
this.upper = upper;
if (!Double.isInfinite(this.lower)) {
this.lowerCDF = source.cdf(lower);
} else {
this.lowerCDF = 0;
}
if (!Double.isInfinite(this.upper)) {
this.normalization = source.cdf(upper) - lowerCDF;
} else {
this.normalization = 1.0 - lowerCDF;
}
}
public double pdf(double x) {
if (x >= upper && x < lower)
return 0.0;
else
return source.pdf(x) / normalization;
}
public double logPdf(double x) {
return Math.log(pdf(x));
}
public double cdf(double x) {
double cdf;
if (x < lower)
cdf = 0.0;
else if (x >= lower && x < upper)
cdf = (source.cdf(x) - lowerCDF) / normalization;
else
cdf = 1.0;
return cdf;
}
public double quantile(double y) {
if (y == 0)
return lower;
if (y == 1.0)
return upper;
if (Double.isInfinite(lower) && Double.isInfinite(upper)) {
return source.quantile(y);
}
try {
return super.inverseCumulativeProbability(y);
} catch (MathException e) {
// throw MathRuntimeException.createIllegalArgumentException( // AR - throwing exceptions deep in numerical code causes trouble. Catching runtime
// exceptions is bad. Better to return NaN and let the calling code deal with it.
return Double.NaN;
// "Couldn't calculate beta quantile for alpha = " + alpha + ", beta = " + beta + ": " +e.getMessage());
}
}
/**
* mean of the distribution
*
* @return mean
*/
public double mean() {
if (source != null) {
return source.mean();
} else {
throw new IllegalArgumentException("Distribution is null");
}
}
/**
* variance of the distribution
*
* @return variance
*/
public double variance() {
if (source != null) {
return source.variance();
} else {
throw new IllegalArgumentException("Distribution is null");
}
}
public UnivariateFunction getProbabilityDensityFunction() {
return pdfFunction;
}
private UnivariateFunction pdfFunction = new UnivariateFunction() {
public final double evaluate(double x) {
return pdf(x);
}
public final double getLowerBound() {
return lower;
}
public final double getUpperBound() {
return upper;
}
};
private final Distribution source;
private final double lower;
private final double upper;
private final double normalization;
private final double lowerCDF;
@Override
protected double getInitialDomain(double v) {
if (!Double.isInfinite(lower) && !Double.isInfinite(upper)) {
return (upper + lower) / 2;
} else if (!Double.isInfinite(upper)) {
return upper / 2;
} else if (!Double.isInfinite(lower)) {
return lower * 2;
}
return v;
}
@Override
protected double getDomainLowerBound(double v) {
return lower;
}
@Override
protected double getDomainUpperBound(double v) {
return upper;
}
public double cumulativeProbability(double v) throws MathException {
return cdf(v);
}
}
| lgpl-2.1 |
crabman77/minetest-minetestforfun-server | mods/mobs/lavaslimes.lua | 5215 |
-- Lava Slimes by TomasJLuis & TenPlus1
-- sounds
local lava_sounds = {
damage = "mobs_slimes_damage",
death = "mobs_slimes_death",
jump = "mobs_slimes_jump",
attack = "mobs_slimes_attack",
}
-- lava slime textures
local lava_textures = {"mobs_lava_slime_sides.png", "mobs_lava_slime_sides.png", "mobs_lava_slime_sides.png", "mobs_lava_slime_sides.png", "mobs_lava_slime_front.png", "mobs_lava_slime_sides.png"}
-- register small lava slime
mobs:register_mob("mobs:lavasmall", {
-- animal, monster, npc, barbarian
type = "monster",
-- aggressive, deals 2 damage to player when hit
passive = false,
pathfinding = false,
reach = 2,
damage = 2,
attack_type = "dogfight",
attacks_monsters = true,
-- health and armor
hp_min = 4,
hp_max = 8,
armor = 200,
-- textures and model
collisionbox = {-0.25, -0.25, -0.25, 0.25, 0.25, 0.25},
visual = "cube",
textures = { lava_textures },
blood_texture = "mobs_lava_slime_blood.png",
visual_size = {x = 0.5, y = 0.5},
-- sounds a bit here, but mainly define in the beginning
makes_footstep_sound = false,
sounds = lava_sounds,
-- speed and jump, sinks in water
walk_velocity = 4,
run_velocity = 4,
walk_chance = 0,
jump = true,
jump_chance = 30,
jump_height = 6,
replace_rate = 20,
footstep = "fire:basic_flame",
view_range = 16,
floats = 1,
-- chance of dropping lava orb and coins
drops = {
{name = "mobs:lava_orb", chance = 15, min = 1, max = 1,},
{name = "maptools:silver_coin", chance = 4, min = 1, max = 1,},
},
-- damaged by
water_damage = 10,
lava_damage = 0,
light_damage = 0,
-- model animation
-- no model animation
})
mobs:register_egg("mobs:lavasmall", "Small Lava Slime", "mobs_lava_slime_medium_inv.png", 1)
-- register medium lava slime
mobs:register_mob("mobs:lavamedium", {
-- animal, monster, npc, barbarian
type = "monster",
-- aggressive, deals 4 damage to player when hit
passive = false,
reach = 2,
damage = 3,
attack_type = "dogfight",
attacks_monsters = true,
-- health and armor
hp_min = 15,
hp_max = 25,
armor = 100,
-- textures and model
collisionbox = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5},
visual = "cube",
textures = { lava_textures },
blood_texture = "mobs_lava_slime_blood.png",
visual_size = {x = 1, y = 1},
-- sounds a bit here, but mainly define in the beginning
makes_footstep_sound = false,
sounds = lava_sounds,
-- speed and jump, sinks in water
walk_velocity = 3,
run_velocity = 3,
walk_chance = 0,
jump = true,
jump_chance = 30,
jump_height = 6,
replace_rate = 20,
footstep = "fire:basic_flame",
view_range = 16,
floats = 1,
-- chance of dropping lava orb and coins
drops = {
},
-- damaged by
water_damage = 10,
lava_damage = 0,
light_damage = 0,
-- model animation
-- no model animation
-- do things when die
on_die = function(self, pos)
local num = math.random(2, 4)
for i=1,num do
minetest.add_entity({x=pos.x + math.random(-2, 2), y=pos.y + 1, z=pos.z + (math.random(-2, 2))}, "mobs:lavasmall")
end
end,
})
mobs:register_egg("mobs:lavamedium", "Medium Lava Slime", "mobs_lava_slime_medium_inv.png", 1)
-- register big lava slime
mobs:register_mob("mobs:lavabig", {
-- animal, monster, npc, barbarian
type = "monster",
-- aggressive, deals 6 damage to player when hit
passive = false,
reach = 2,
damage = 5,
attack_type = "dogfight",
attacks_monsters = true,
-- health and armor
hp_min = 30, hp_max = 50,
armor = 100,
-- textures and model
collisionbox = {-1, -1, -1, 1, 1, 1},
visual = "cube",
textures = { lava_textures },
blood_texture = "mobs_lava_slime_blood.png",
visual_size = {x = 2, y = 2},
-- sounds a bit here, but mainly define in the beginning
makes_footstep_sound = false,
sounds = lava_sounds,
-- speed and jump, sinks in water
walk_velocity = 2.5,
run_velocity = 2.5,
walk_chance = 0,
jump = true,
jump_chance = 30,
jump_height = 6,
replace_rate = 20,
replace_offset = -1,
footstep = "fire:basic_flame",
view_range = 16,
floats = 1,
knock_back = 0, --this is a test
-- chance of dropping lava orb and coins
drops = {
},
-- damaged by
water_damage = 10,
lava_damage = 0,
light_damage = 0,
-- model animation
-- no model animation
-- do things when die
on_die = function(self, pos)
local num = math.random(1, 2)
for i=1,num do
minetest.add_entity({x=pos.x + math.random(-2, 2), y=pos.y + 1, z=pos.z + (math.random(-2, 2))}, "mobs:lavamedium")
end
end,
})
mobs:register_egg("mobs:lavabig", "Big Lava Slime", "mobs_lava_slime_big_inv.png", 1)
--mobs:spawn_specific(name, nodes, neighbors, min_light, max_light, interval, chance, active_object_count, min_height, max_height)
mobs:spawn_specific("mobs:lavabig", {"default:lava_source"},{"default:lava_flowing"}, -1, 20, 30, 5000, 1, -32000, 32000, false)
mobs:spawn_specific("mobs:lavamedium", {"default:lava_source"},{"default:lava_flowing"}, -1, 20, 30, 5000, 2, -32000, 32000, false)
--mobs:spawn_specific("mobs:lavasmall", {"default:lava_source"},{"default:lava_flowing"}, -1, 20, 30, 10s000, 2, -32000, 32000, false)
-- lava orb
minetest.register_craftitem("mobs:lava_orb", {
description = "Lava orb",
inventory_image = "zmobs_lava_orb.png",
})
minetest.register_alias("zmobs:lava_orb", "mobs:lava_orb")
| unlicense |
tarikgwa/test | html/dev/tests/functional/tests/app/Magento/ProductVideo/Test/Constraint/AssertNoVideoProductView.php | 1439 | <?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ProductVideo\Test\Constraint;
use Magento\Catalog\Test\Page\Product\CatalogProductView;
use Magento\Mtf\Constraint\AbstractConstraint;
use Magento\Mtf\Client\BrowserInterface;
use Magento\Mtf\Fixture\InjectableFixture;
/**
* Assert that video is absent on product page.
*/
class AssertNoVideoProductView extends AbstractConstraint
{
/**
* Assert that video is absent on product page on Store front.
*
* @param BrowserInterface $browser
* @param CatalogProductView $catalogProductView
* @param InjectableFixture $initialProduct
*/
public function processAssert(
BrowserInterface $browser,
CatalogProductView $catalogProductView,
InjectableFixture $initialProduct
) {
$browser->open($_ENV['app_frontend_url'] . $initialProduct->getUrlKey() . '.html');
$catalogProductView->getViewBlock()->isGalleryVisible();
\PHPUnit_Framework_Assert::assertFalse(
$catalogProductView->getViewBlock()->isGalleryVisible(),
'Product video is displayed on product view when it should not.'
);
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString()
{
return 'No product video is displayed on product view.';
}
}
| apache-2.0 |
kmcallister/rust | src/test/run-pass/mut-function-arguments.rs | 687 | // Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
fn f(mut y: ~int) {
*y = 5;
assert_eq!(*y, 5);
}
fn g() {
let frob: &fn(~int) = |mut q| { *q = 2; assert!(*q == 2); };
let w = ~37;
frob(w);
}
pub fn main() {
let z = ~17;
f(z);
g();
}
| apache-2.0 |
tyge68/sling | bundles/extensions/i18n/src/main/java/org/apache/sling/i18n/impl/I18NFilter.java | 14367 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.sling.i18n.impl;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.TreeMap;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.apache.felix.scr.annotations.ReferencePolicy;
import org.apache.felix.scr.annotations.ReferencePolicyOption;
import org.apache.felix.scr.annotations.sling.SlingFilter;
import org.apache.felix.scr.annotations.sling.SlingFilterScope;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.wrappers.SlingHttpServletRequestWrapper;
import org.apache.sling.commons.osgi.ServiceUtil;
import org.apache.sling.i18n.DefaultLocaleResolver;
import org.apache.sling.i18n.LocaleResolver;
import org.apache.sling.i18n.RequestLocaleResolver;
import org.apache.sling.i18n.ResourceBundleProvider;
import org.osgi.framework.Constants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The <code>I18NFilter</code> class is a request level filter, which provides
* the resource bundle for the current request.
*/
@SlingFilter(generateService = true,
order = 700, scope = { SlingFilterScope.REQUEST, SlingFilterScope.ERROR })
@Properties({
@Property(name = "pattern", value="/.*"),
@Property(name = Constants.SERVICE_DESCRIPTION, value = "Internationalization Support Filter"),
@Property(name = Constants.SERVICE_VENDOR, value = "The Apache Software Foundation") })
public class I18NFilter implements Filter {
/** Logger */
private final static Logger LOG = LoggerFactory.getLogger(I18NFilter.class.getName());
private final DefaultLocaleResolver DEFAULT_LOCALE_RESOLVER = new DefaultLocaleResolver();
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY, policy = ReferencePolicy.DYNAMIC, policyOption=ReferencePolicyOption.GREEDY)
private volatile LocaleResolver localeResolver = DEFAULT_LOCALE_RESOLVER;
@Reference(cardinality = ReferenceCardinality.OPTIONAL_UNARY, policy = ReferencePolicy.DYNAMIC, policyOption=ReferencePolicyOption.GREEDY)
private volatile RequestLocaleResolver requestLocaleResolver = DEFAULT_LOCALE_RESOLVER;
@Reference(name = "resourceBundleProvider",
referenceInterface = ResourceBundleProvider.class,
cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE,
policy = ReferencePolicy.DYNAMIC)
private final Map<Object, ResourceBundleProvider> providers = new TreeMap<Object, ResourceBundleProvider>();
private volatile ResourceBundleProvider[] sortedProviders = new ResourceBundleProvider[0];
private final ResourceBundleProvider combinedProvider = new CombinedBundleProvider();
/** Count the number init() has been called. */
private volatile int initCount;
/**
* @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
*/
@Override
public void init(FilterConfig filterConfig) {
synchronized(this) {
initCount++;
}
}
/**
* @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
*/
@Override
public void doFilter(ServletRequest request,
final ServletResponse response,
final FilterChain chain)
throws IOException, ServletException {
final boolean runGlobal = this.initCount == 2;
if ( request instanceof SlingHttpServletRequest ) {
// check if we can use the simple version to wrap
if ( !runGlobal || this.requestLocaleResolver == DEFAULT_LOCALE_RESOLVER ) {
// wrap with our ResourceBundle provisioning
request = new I18NSlingHttpServletRequest(request,
combinedProvider, localeResolver);
} else {
request = new BaseI18NSlingHttpServletRequest(request, combinedProvider);
}
} else {
request = new I18NHttpServletRequest(request,
combinedProvider, requestLocaleResolver);
}
// and forward the request
chain.doFilter(request, response);
}
/**
* @see javax.servlet.Filter#destroy()
*/
@Override
public void destroy() {
synchronized(this) {
initCount--;
}
}
// ---------- SCR Integration ----------------------------------------------
protected void bindLocaleResolver(final LocaleResolver resolver) {
this.localeResolver = resolver;
}
protected void unbindLocaleResolver(final LocaleResolver resolver) {
if (this.localeResolver == resolver) {
this.localeResolver = DEFAULT_LOCALE_RESOLVER;
}
}
protected void bindRequestLocaleResolver(final RequestLocaleResolver resolver) {
this.requestLocaleResolver = resolver;
}
protected void unbindRequestLocaleResolver(final RequestLocaleResolver resolver) {
if (this.requestLocaleResolver == resolver) {
this.requestLocaleResolver = DEFAULT_LOCALE_RESOLVER;
}
}
protected void bindResourceBundleProvider(final ResourceBundleProvider provider, final Map<String, Object> props) {
synchronized ( this.providers ) {
this.providers.put(ServiceUtil.getComparableForServiceRanking(props), provider);
this.sortedProviders = this.providers.values().toArray(new ResourceBundleProvider[this.providers.size()]);
}
}
protected void unbindResourceBundleProvider(final ResourceBundleProvider provider, final Map<String, Object> props) {
synchronized ( this.providers ) {
this.providers.remove(ServiceUtil.getComparableForServiceRanking(props));
this.sortedProviders = this.providers.values().toArray(new ResourceBundleProvider[this.providers.size()]);
}
}
// ---------- internal -----------------------------------------------------
/** Provider that goes through a list of registered providers and takes the first non-null responses */
private class CombinedBundleProvider implements ResourceBundleProvider {
@Override
public Locale getDefaultLocale() {
// ask all registered providers, use the first one that returns
final ResourceBundleProvider[] providers = sortedProviders;
for(int i=providers.length-1; i >= 0; i--) {
final ResourceBundleProvider provider = providers[i];
final Locale locale = provider.getDefaultLocale();
if (locale != null) {
return locale;
}
}
return null;
}
@Override
public ResourceBundle getResourceBundle(final Locale locale) {
// ask all registered providers, use the first one that returns
final ResourceBundleProvider[] providers = sortedProviders;
for(int i=providers.length-1; i >= 0; i--) {
final ResourceBundleProvider provider = providers[i];
final ResourceBundle bundle = provider.getResourceBundle(locale);
if (bundle != null) {
return bundle;
}
}
return null;
}
@Override
public ResourceBundle getResourceBundle(final String baseName, final Locale locale) {
// ask all registered providers, use the first one that returns
final ResourceBundleProvider[] providers = sortedProviders;
for(int i=providers.length-1; i >= 0; i--) {
final ResourceBundleProvider provider = providers[i];
final ResourceBundle bundle = provider.getResourceBundle(baseName, locale);
if (bundle != null) {
return bundle;
}
}
return null;
}
}
// ---------- internal class -----------------------------------------------
private static class I18NHttpServletRequest
extends HttpServletRequestWrapper {
private final ResourceBundleProvider bundleProvider;
private final RequestLocaleResolver localeResolver;
private Locale locale;
private List<Locale> localeList;
private ResourceBundle resourceBundle;
I18NHttpServletRequest(final ServletRequest delegatee,
final ResourceBundleProvider bundleProvider,
final RequestLocaleResolver localeResolver) {
super((HttpServletRequest)delegatee);
this.bundleProvider = bundleProvider;
this.localeResolver = localeResolver;
}
@Override
public Locale getLocale() {
if (locale == null) {
locale = this.getLocaleList().get(0);
}
return locale;
}
@Override
public Enumeration<?> getLocales() {
return Collections.enumeration(getLocaleList());
}
@Override
public Object getAttribute(final String name) {
if ( ResourceBundleProvider.BUNDLE_REQ_ATTR.equals(name) ) {
if ( this.resourceBundle == null && this.bundleProvider != null) {
this.resourceBundle = this.bundleProvider.getResourceBundle(this.getLocale());
}
return this.resourceBundle;
}
return super.getAttribute(name);
}
private List<Locale> getLocaleList() {
if (localeList == null) {
List<Locale> resolved = localeResolver.resolveLocale((HttpServletRequest)this.getRequest());
this.localeList = (resolved != null && !resolved.isEmpty())
? resolved
: Collections.singletonList(this.bundleProvider.getDefaultLocale());
}
return localeList;
}
}
private static class BaseI18NSlingHttpServletRequest
extends SlingHttpServletRequestWrapper {
protected final ResourceBundleProvider bundleProvider;
BaseI18NSlingHttpServletRequest(final ServletRequest delegatee,
final ResourceBundleProvider bundleProvider) {
super((SlingHttpServletRequest) delegatee);
this.bundleProvider = bundleProvider;
}
@Override
public ResourceBundle getResourceBundle(Locale locale) {
return getResourceBundle(null, locale);
}
@Override
public ResourceBundle getResourceBundle(String baseName, Locale locale) {
if (bundleProvider != null) {
if (locale == null) {
locale = getLocale();
}
try {
return bundleProvider.getResourceBundle(baseName, locale);
} catch (MissingResourceException mre) {
LOG.warn(
"getResourceBundle: Cannot get ResourceBundle from provider",
mre);
}
} else {
LOG.info("getResourceBundle: ResourceBundleProvider not available, calling default implementation");
}
return super.getResourceBundle(baseName, locale);
}
}
private static class I18NSlingHttpServletRequest
extends BaseI18NSlingHttpServletRequest {
private final LocaleResolver localeResolver;
private Locale locale;
private List<Locale> localeList;
I18NSlingHttpServletRequest(final ServletRequest delegatee,
final ResourceBundleProvider bundleProvider,
final LocaleResolver localeResolver) {
super(delegatee, bundleProvider);
this.localeResolver = localeResolver;
}
@Override
public Object getAttribute(final String name) {
if ( ResourceBundleProvider.BUNDLE_REQ_ATTR.equals(name) ) {
final Object superValue = super.getAttribute(name);
return (superValue != null ? superValue : this.getResourceBundle(null));
}
return super.getAttribute(name);
}
@Override
public Locale getLocale() {
if (locale == null) {
locale = this.getLocaleList().get(0);
}
return locale;
}
@Override
public Enumeration<?> getLocales() {
return Collections.enumeration(getLocaleList());
}
private List<Locale> getLocaleList() {
if (localeList == null) {
List<Locale> resolved = localeResolver.resolveLocale(this.getSlingRequest());
this.localeList = (resolved != null && !resolved.isEmpty())
? resolved
: Collections.singletonList(this.bundleProvider.getDefaultLocale());
}
return localeList;
}
}
}
| apache-2.0 |
SpenceSouth/encog-java-core | src/test/java/org/encog/matrix/TestMatrixMath.java | 5466 | /*
* Encog(tm) Core v3.3 - Java Version
* http://www.heatonresearch.com/encog/
* https://github.com/encog/encog-java-core
* Copyright 2008-2014 Heaton Research, Inc.
*
* 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.
*
* For more information on Heaton Research copyrights, licenses
* and trademarks visit:
* http://www.heatonresearch.com/copyright
*/
package org.encog.matrix;
import junit.framework.TestCase;
import org.encog.mathutil.matrices.Matrix;
import org.encog.mathutil.matrices.MatrixError;
import org.encog.mathutil.matrices.MatrixMath;
public class TestMatrixMath extends TestCase {
public void testInverse() throws Throwable
{
double matrixData1[][] = {{1,2,3,4}};
double matrixData2[][] = {{1},
{2},
{3},
{4}
};
Matrix matrix1 = new Matrix(matrixData1);
Matrix checkMatrix = new Matrix(matrixData2);
Matrix matrix2 = MatrixMath.transpose(matrix1);
TestCase.assertTrue(matrix2.equals(checkMatrix));
}
public void testDotProduct() throws Throwable
{
double matrixData1[][] = {{1,2,3,4}};
double matrixData2[][] = {{5},
{6},
{7},
{8}
};
Matrix matrix1 = new Matrix(matrixData1);
Matrix matrix2 = new Matrix(matrixData2);
double dotProduct = MatrixMath.dotProduct(matrix1,matrix2);
TestCase.assertEquals(dotProduct, 70.0);
// test dot product errors
double nonVectorData[][] = {{1.0,2.0},{3.0,4.0}};
double differentLengthData[][] = {{1.0}};
Matrix nonVector = new Matrix(nonVectorData);
Matrix differentLength = new Matrix(differentLengthData);
try
{
MatrixMath.dotProduct(matrix1, nonVector);
TestCase.assertTrue(false);
}
catch(MatrixError e)
{
}
try
{
MatrixMath.dotProduct(nonVector, matrix2);
TestCase.assertTrue(false);
}
catch(MatrixError e)
{
}
try
{
MatrixMath.dotProduct(matrix1, differentLength);
TestCase.assertTrue(false);
}
catch(MatrixError e)
{
}
}
public void testMultiply() throws Throwable
{
double matrixData1[][] = {{1,4},
{2,5},
{3,6}
};
double matrixData2[][] = {{7,8,9},
{10,11,12}};
double matrixData3[][] = {{47,52,57},
{64,71,78},
{81,90,99}
};
Matrix matrix1 = new Matrix(matrixData1);
Matrix matrix2 = new Matrix(matrixData2);
Matrix matrix3 = new Matrix(matrixData3);
Matrix result = MatrixMath.multiply(matrix1,matrix2);
TestCase.assertTrue(result.equals(matrix3));
}
public static void testVerifySame()
{
double dataBase[][] = {{1.0,2.0},{3.0,4.0}};
double dataTooManyRows[][] = {{1.0,2.0},{3.0,4.0},{5.0,6.0}};
double dataTooManyCols[][] = {{1.0,2.0,3.0},{4.0,5.0,6.0}};
Matrix base = new Matrix(dataBase);
Matrix tooManyRows = new Matrix(dataTooManyRows);
Matrix tooManyCols = new Matrix(dataTooManyCols);
MatrixMath.add(base, base);
try
{
MatrixMath.add(base, tooManyRows);
TestCase.assertFalse(true);
}
catch(MatrixError e)
{
}
try
{
MatrixMath.add(base, tooManyCols);
TestCase.assertFalse(true);
}
catch(MatrixError e)
{
}
}
public void testDivide() throws Throwable
{
double data[][] = {{2.0,4.0},{6.0,8.0}};
Matrix matrix = new Matrix(data);
Matrix result = MatrixMath.divide(matrix, 2.0);
TestCase.assertEquals(1.0, result.get(0,0));
}
public void testIdentity() throws Throwable
{
try
{
MatrixMath.identity(0);
TestCase.assertTrue(false);
}
catch(MatrixError e)
{
}
double checkData[][] = {{1,0},{0,1}};
Matrix check = new Matrix(checkData);
Matrix matrix = MatrixMath.identity(2);
TestCase.assertTrue(check.equals(matrix));
}
public void testMultiplyScalar() throws Throwable
{
double data[][] = {{2.0,4.0},{6.0,8.0}};
Matrix matrix = new Matrix(data);
Matrix result = MatrixMath.multiply(matrix, 2.0);
TestCase.assertEquals(4.0, result.get(0,0));
}
public void testDeleteRow() throws Throwable
{
double origData[][] = {{1.0,2.0},{3.0,4.0}};
double checkData[][] = {{3.0,4.0}};
Matrix orig = new Matrix(origData);
Matrix matrix = MatrixMath.deleteRow(orig, 0);
Matrix check = new Matrix(checkData);
TestCase.assertTrue(check.equals(matrix));
try
{
MatrixMath.deleteRow(orig, 10);
TestCase.assertTrue(false);
}
catch(MatrixError e)
{
}
}
public void testDeleteCol() throws Throwable
{
double origData[][] = {{1.0,2.0},{3.0,4.0}};
double checkData[][] = {{2.0},{4.0}};
Matrix orig = new Matrix(origData);
Matrix matrix = MatrixMath.deleteCol(orig, 0);
Matrix check = new Matrix(checkData);
TestCase.assertTrue(check.equals(matrix));
try
{
MatrixMath.deleteCol(orig, 10);
TestCase.assertTrue(false);
}
catch(MatrixError e)
{
}
}
public void testCopy()
{
double data[][] = {{1.0,2.0},{3.0,4.0}};
Matrix source = new Matrix(data);
Matrix target = new Matrix(2,2);
MatrixMath.copy(source, target);
TestCase.assertTrue(source.equals(target));
}
}
| apache-2.0 |
yonglehou/spring-net | src/Spring/Spring.Core/Objects/Factory/Parsing/Location.cs | 1943 | #region License
/*
* Copyright © 2002-2011 the original author or authors.
*
* 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.
*/
#endregion
using Spring.Core.IO;
namespace Spring.Objects.Factory.Parsing
{
public class Location
{
private IResource resource;
private object source;
/// <summary>
/// Initializes a new instance of the Location class.
/// </summary>
/// <param name="resource"></param>
/// <param name="source"></param>
public Location(IResource resource, object source)
{
//TODO: look into re-enabling this since resource *is* NULL when parsing config classes vs. acquiring IResources
//AssertUtils.ArgumentNotNull(resource, "resource");
this.resource = resource;
this.source = source;
}
/// <summary>
/// Initializes a new instance of the Location class.
/// </summary>
/// <param name="resource"></param>
public Location(IResource resource)
: this(resource, null)
{
}
public IResource Resource
{
get
{
return resource;
}
}
public object Source
{
get
{
return source;
}
}
}
}
| apache-2.0 |
tony810430/flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/FunctionDefinitionFactory.java | 1484 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.flink.table.factories;
import org.apache.flink.annotation.PublicEvolving;
import org.apache.flink.table.catalog.CatalogFunction;
import org.apache.flink.table.functions.FunctionDefinition;
/** A factory to create {@link FunctionDefinition}. */
@PublicEvolving
public interface FunctionDefinitionFactory {
/**
* Creates a {@link FunctionDefinition} from given {@link CatalogFunction}.
*
* @param name name of the {@link CatalogFunction}
* @param catalogFunction the catalog function
* @return a {@link FunctionDefinition}
*/
FunctionDefinition createFunctionDefinition(String name, CatalogFunction catalogFunction);
}
| apache-2.0 |
jayantgolhar/Hadoop-0.21.0 | mapred/src/contrib/dynamic-scheduler/src/java/org/apache/hadoop/mapred/PriorityScheduler.java | 17367 | /**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.mapred;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.List;
import java.util.LinkedList;
import java.util.Set;
import java.util.HashSet;
import java.util.HashMap;
import java.util.TreeMap;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Map;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.mapreduce.server.jobtracker.TaskTracker;
/**
* A {@link TaskScheduler} that
* provides the following features:
* (1) allows continuous enforcement of user controlled dynamic queue shares,
* (2) preempts tasks exceeding their queue shares instantaneously when new
* jobs arrive,
* (3) is work conserving,
* (4) tracks queue usage to only charge when jobs are pending or running,
* (5) authorizes queue submissions based on symmetric private key HMAC/SHA1
* signatures.
*/
class PriorityScheduler extends QueueTaskScheduler {
private class InitThread extends Thread {
JobInProgress job;
InitThread(JobInProgress job) {
this.job = job;
}
@Override
public void run() {
taskTrackerManager.initJob(job);
}
}
private class JobListener extends JobInProgressListener {
@Override
public void jobAdded(JobInProgress job) {
new InitThread(job).start();
synchronized (PriorityScheduler.this) {
String queue = authorize(job);
if (queue.equals("")) {
job.kill();
return;
}
jobQueue.add(job);
QueueJobs jobs = queueJobs.get(queue);
if (jobs == null) {
jobs = new QueueJobs(queue);
queueJobs.put(queue,jobs);
}
jobs.jobs.add(job);
if (debug) {
LOG.debug("Add job " + job.getProfile().getJobID());
}
}
}
@Override
public void jobRemoved(JobInProgress job) {
synchronized (PriorityScheduler.this) {
jobQueue.remove(job);
String queue = getQueue(job);
queueJobs.get(queue).jobs.remove(job);
}
}
@Override
public void jobUpdated(JobChangeEvent event) {
}
}
static final Comparator<TaskInProgress> TASK_COMPARATOR
= new Comparator<TaskInProgress>() {
public int compare(TaskInProgress o1, TaskInProgress o2) {
int res = 0;
if (o1.getProgress() < o2.getProgress()) {
res = -1;
} else {
res = (o1.getProgress() == o2.getProgress() ? 0 : 1);
}
if (res == 0) {
if (o1.getExecStartTime() > o2.getExecStartTime()) {
res = -1;
} else {
res = (o1.getExecStartTime() == o2.getExecStartTime() ? 0 : 1);
}
}
return res;
}
};
static final Comparator<KillQueue> QUEUE_COMPARATOR
= new Comparator<KillQueue>() {
public int compare(KillQueue o1, KillQueue o2) {
if (o1.startTime < o2.startTime) {
return 1;
}
if (o1.startTime > o2.startTime) {
return -1;
}
return 0;
}
};
class QueueJobs {
String name;
LinkedList<JobInProgress> jobs = new LinkedList<JobInProgress>();
QueueJobs(String name) {
this.name = name;
}
}
class QueueQuota {
int quota;
int map_used;
int reduce_used;
int map_pending;
int reduce_pending;
int mappers;
int reducers;
String name;
QueueQuota(String name) {
this.name = name;
}
}
private QueueAllocator allocator;
private static final Log LOG =
LogFactory.getLog(PriorityScheduler.class);
static final boolean MAP = true;
static final boolean REDUCE = false;
private static final boolean FILL = true;
private static final boolean NO_FILL = false;
private JobListener jobListener = new JobListener();
private static final boolean debug = LOG.isDebugEnabled();
private boolean sortTasks = true;
private long lastKill = 0;
private long killInterval = 0;
private PriorityAuthorization auth = new PriorityAuthorization();
private LinkedList<JobInProgress> jobQueue =
new LinkedList<JobInProgress>();
private HashMap<String,QueueJobs> queueJobs =
new HashMap<String,QueueJobs>();
@Override
public void start() throws IOException {
taskTrackerManager.addJobInProgressListener(jobListener);
sortTasks = conf.getBoolean("mapred.priority-scheduler.sort-tasks", true);
killInterval = conf.getLong("mapred.priority-scheduler.kill-interval", 0);
auth.init(conf);
}
@Override
public void terminate() throws IOException {
}
@Override
public void setAllocator(QueueAllocator allocator) {
this.allocator = allocator;
}
private boolean assignMapRedTask(JobInProgress job,
TaskTrackerStatus taskTracker, int numTrackers, List<Task> assignedTasks,
Map<String,QueueQuota> queueQuota, boolean fill, boolean map)
throws IOException {
String queue = getQueue(job);
QueueQuota quota = queueQuota.get(queue);
if (quota == null) {
LOG.error("Queue " + queue + " not configured properly");
return false;
}
if (quota.quota < 1 && !fill) {
return false;
}
Task t = null;
if (map) {
t = job.obtainNewLocalMapTask(taskTracker, numTrackers,
taskTrackerManager.getNumberOfUniqueHosts());
if (t != null) {
if (debug) {
LOG.debug("assigned local task for job " + job.getProfile().getJobID() +
" " + taskType(map) );
}
assignedTasks.add(t);
if (map) {
quota.map_used++;
} else {
quota.reduce_used++;
}
quota.quota--;
return true;
}
t = job.obtainNewNonLocalMapTask(taskTracker, numTrackers,
taskTrackerManager.getNumberOfUniqueHosts());
} else {
t = job.obtainNewReduceTask(taskTracker, numTrackers,
taskTrackerManager.getNumberOfUniqueHosts());
}
if (t != null) {
if (debug) {
LOG.debug("assigned remote task for job " + job.getProfile().getJobID() +
" " + taskType(map));
}
assignedTasks.add(t);
if (map) {
quota.map_used++;
} else {
quota.reduce_used++;
}
quota.quota--;
return true;
}
return false;
}
Map<String,QueueQuota> getQueueQuota(int maxMapTasks, int maxReduceTasks,
boolean map) {
if (debug) {
LOG.debug("max map tasks " + Integer.toString(maxMapTasks) + " " +
taskType(map));
LOG.debug("max reduce tasks " + Integer.toString(maxReduceTasks) + " " +
taskType(map));
}
int maxTasks = (map) ? maxMapTasks : maxReduceTasks;
Map<String,QueueAllocation> shares = allocator.getAllocation();
Map<String,QueueQuota> quotaMap = new HashMap<String,QueueQuota>();
for (QueueAllocation share: shares.values()) {
QueueQuota quota = new QueueQuota(share.getName());
quota.mappers = Math.round(share.getShare() * maxMapTasks);
quota.reducers = Math.round(share.getShare() * maxReduceTasks);
quota.quota = (map) ? quota.mappers : quota.reducers;
if (debug) {
LOG.debug("queue " + quota.name + " initial quota " +
Integer.toString(quota.quota) + " " + taskType(map));
}
quota.map_used = 0;
quota.reduce_used = 0;
quota.map_pending = 0;
quota.reduce_pending = 0;
Collection<JobInProgress> jobs = getJobs(quota.name);
for (JobInProgress job : jobs) {
quota.map_pending += job.pendingMaps();
quota.reduce_pending += job.pendingReduces();
int running = (map) ? job.runningMapTasks : job.runningReduceTasks;
quota.quota -= running;
quota.map_used += job.runningMapTasks ;
quota.reduce_used += job.runningReduceTasks;
}
if (debug) {
LOG.debug("queue " + quota.name + " quota " +
Integer.toString(quota.quota) + " " + taskType(map));
}
quotaMap.put(quota.name,quota);
}
return quotaMap;
}
private void scheduleJobs(int availableSlots, boolean map, boolean fill,
TaskTrackerStatus taskTracker, int numTrackers, List<Task> assignedTasks,
Map<String,QueueQuota> queueQuota) throws IOException {
for (int i = 0; i < availableSlots; i++) {
for (JobInProgress job : jobQueue) {
if ((job.getStatus().getRunState() != JobStatus.RUNNING) ||
(!map && job.numReduceTasks == 0)) {
continue;
}
if (assignMapRedTask(job, taskTracker, numTrackers, assignedTasks,
queueQuota, fill, map)) {
break;
}
}
}
}
private int countTasksToKill(Map<String,QueueQuota> queueQuota, boolean map) {
int killTasks = 0;
for (QueueQuota quota : queueQuota.values()) {
killTasks += Math.min((map) ? quota.map_pending : quota.reduce_pending,
Math.max(quota.quota,0));
}
return killTasks;
}
protected void markIdle(Map<String, QueueQuota> queueQuota) {
for (QueueQuota quota: queueQuota.values()) {
allocator.setUsage(quota.name, Math.min(quota.map_used, quota.mappers) +
Math.min(quota.reduce_used, quota.reducers),
(quota.map_pending + quota.reduce_pending));
}
}
private synchronized void assignMapRedTasks(List<Task> assignedTasks,
TaskTrackerStatus taskTracker, int numTrackers, boolean map)
throws IOException {
int taskOffset = assignedTasks.size();
int maxTasks = (map) ? taskTracker.getMaxMapSlots() :
taskTracker.getMaxReduceSlots();
int countTasks = (map) ? taskTracker.countMapTasks() :
taskTracker.countReduceTasks();
int availableSlots = maxTasks - countTasks;
int map_capacity = 0;
int reduce_capacity = 0;
ClusterStatus status = taskTrackerManager.getClusterStatus();
if (status != null) {
map_capacity = status.getMaxMapTasks();
reduce_capacity = status.getMaxReduceTasks();
}
Map<String,QueueQuota> queueQuota = getQueueQuota(map_capacity,
reduce_capacity,map);
if (debug) {
LOG.debug("available slots " + Integer.toString(availableSlots) + " " +
taskType(map));
LOG.debug("queue size " + Integer.toString(jobQueue.size()));
LOG.debug("map capacity " + Integer.toString(map_capacity) + " " +
taskType(map));
LOG.debug("reduce capacity " + Integer.toString(reduce_capacity) + " " +
taskType(map));
}
scheduleJobs(availableSlots, map, NO_FILL, taskTracker, numTrackers,
assignedTasks, queueQuota);
availableSlots -= assignedTasks.size() + taskOffset;
scheduleJobs(availableSlots, map, FILL, taskTracker, numTrackers,
assignedTasks, queueQuota);
if (map) {
markIdle(queueQuota);
}
long currentTime = System.currentTimeMillis()/1000;
if ((killInterval > 0) && (currentTime - lastKill > killInterval)) {
lastKill = currentTime;
} else {
return;
}
int killTasks = countTasksToKill(queueQuota, map);
if (debug) {
LOG.debug("trying to kill " + Integer.toString(killTasks) + " tasks " +
taskType(map));
}
killMapRedTasks(killTasks, queueQuota, map);
}
class KillQueue {
String name;
long startTime;
QueueQuota quota;
}
private Collection<KillQueue> getKillQueues(Map<String,
QueueQuota> queueQuota) {
TreeMap killQueues = new TreeMap(QUEUE_COMPARATOR);
for (QueueJobs queueJob : queueJobs.values()) {
QueueQuota quota = queueQuota.get(queueJob.name);
if (quota.quota >= 0) {
continue;
}
for (JobInProgress job : queueJob.jobs) {
if (job.getStatus().getRunState() == JobStatus.RUNNING) {
KillQueue killQueue = new KillQueue();
killQueue.name = queueJob.name;
killQueue.startTime = job.getStartTime();
killQueue.quota = quota;
killQueues.put(killQueue, killQueue);
}
}
}
return killQueues.values();
}
private void killMapRedTasks(int killTasks, Map<String,QueueQuota> queueQuota,
boolean map) {
int killed = 0;
// sort queues exceeding quota in reverse order of time since starting
// a running job
Collection<KillQueue> killQueues = getKillQueues(queueQuota);
for (KillQueue killQueue : killQueues) {
if (killed == killTasks) {
return;
}
QueueQuota quota = killQueue.quota;
// don't kill more than needed and not more than quota exceeded
int toKill = Math.min(killTasks-killed,-quota.quota);
killQueueTasks(quota.name, toKill, map);
killed += toKill;
}
}
private String taskType(boolean map) {
return (map) ? "MAP" : "REDUCE";
}
private void killQueueTasks(String queue, int killTasks, boolean map) {
if (killTasks == 0) {
return;
}
if (debug) {
LOG.debug("trying to kill " + Integer.toString(killTasks) +
" tasks from queue " + queue + " " + taskType(map));
}
int killed = 0;
Collection<JobInProgress> jobs = getJobs(queue);
if (debug) {
LOG.debug("total jobs to kill from " + Integer.toString(jobs.size()) +
" " + taskType(map));
}
for (JobInProgress job : jobs) {
TaskInProgress tasks[] = (map) ? job.maps.clone() :
job.reduces.clone();
if (sortTasks) {
Arrays.sort(tasks, TASK_COMPARATOR);
}
if (debug) {
LOG.debug("total tasks to kill from " +
Integer.toString(tasks.length) + " " + taskType(map));
}
for (int i=0; i < tasks.length; i++) {
if (debug) {
LOG.debug("total active tasks to kill from " +
Integer.toString(tasks[i].getActiveTasks().keySet().size()) +
" " + taskType(map));
}
for (TaskAttemptID id: tasks[i].getActiveTasks().keySet()) {
if (tasks[i].isCommitPending(id)) {
continue;
}
tasks[i].killTask(id, false);
if (debug) {
LOG.debug("killed task " + id + " progress " +
Double.toString(tasks[i].getProgress()) +
" start time " + Long.toString(tasks[i].getExecStartTime()) +
" " + taskType(map));
}
killed += 1;
if (killed == killTasks) {
return;
}
}
}
}
}
@Override
public List<Task> assignTasks(TaskTracker taskTracker)
throws IOException {
long millis = 0;
if (debug) {
millis = System.currentTimeMillis();
}
ClusterStatus clusterStatus = taskTrackerManager.getClusterStatus();
int numTrackers = clusterStatus.getTaskTrackers();
List<Task> assignedTasks = new ArrayList<Task>();
assignMapRedTasks(assignedTasks, taskTracker.getStatus(), numTrackers, MAP);
assignMapRedTasks(assignedTasks, taskTracker.getStatus(), numTrackers, REDUCE);
if (debug) {
long elapsed = System.currentTimeMillis() - millis;
LOG.debug("assigned total tasks: " +
Integer.toString(assignedTasks.size()) + " in " +
Long.toString(elapsed) + " ms");
}
return assignedTasks;
}
@Override
public Collection<JobInProgress> getJobs(String queueName) {
QueueJobs jobs = queueJobs.get(queueName);
if (jobs == null) {
return new ArrayList<JobInProgress>();
}
return jobs.jobs;
}
private String getQueue(JobInProgress job) {
JobConf conf = job.getJobConf();
return conf.getQueueName();
}
private String getUser(JobInProgress job) {
JobConf conf = job.getJobConf();
return conf.getUser();
}
private String authorize(JobInProgress job) {
JobConf conf = job.getJobConf();
String user = conf.getUser();
String queue = conf.getQueueName();
if (!user.equals(queue)) {
return "";
}
String timestamp = conf.get("mapred.job.timestamp");
String signature = conf.get("mapred.job.signature");
int role = auth.authorize("&user=" + user + "×tamp=" + timestamp,
signature, user, timestamp);
if (role != PriorityAuthorization.NO_ACCESS) {
return queue;
}
return "";
}
}
| apache-2.0 |
tpaszkowski/quantum | quantum/db/migration/alembic_migrations/versions/1c33fa3cd1a1_extra_route_config.py | 2289 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Copyright 2013 OpenStack Foundation
#
# 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.
#
"""Support routring table configration on Router
Revision ID: 1c33fa3cd1a1
Revises: 45680af419f9
Create Date: 2013-01-17 14:35:09.386975
"""
# revision identifiers, used by Alembic.
revision = '1c33fa3cd1a1'
down_revision = '45680af419f9'
# Change to ['*'] if this migration applies to all plugins
migration_for_plugins = [
'quantum.plugins.openvswitch.ovs_quantum_plugin.OVSQuantumPluginV2',
'quantum.plugins.linuxbridge.lb_quantum_plugin.LinuxBridgePluginV2',
'quantum.plugins.nec.nec_plugin.NECPluginV2',
'quantum.plugins.ryu.ryu_quantum_plugin.RyuQuantumPluginV2',
'quantum.plugins.metaplugin.meta_quantum_plugin.MetaPluginV2'
]
from alembic import op
import sqlalchemy as sa
from quantum.db import migration
def upgrade(active_plugin=None, options=None):
if not migration.should_run(active_plugin, migration_for_plugins):
return
op.rename_table(
'routes',
'subnetroutes',
)
op.create_table(
'routerroutes',
sa.Column('destination', sa.String(length=64), nullable=False),
sa.Column(
'nexthop', sa.String(length=64), nullable=False),
sa.Column('router_id', sa.String(length=36), nullable=False),
sa.ForeignKeyConstraint(
['router_id'], ['routers.id'], ondelete='CASCADE'),
sa.PrimaryKeyConstraint('destination', 'nexthop', 'router_id')
)
def downgrade(active_plugin=None, options=None):
if not migration.should_run(active_plugin, migration_for_plugins):
return
op.rename_table(
'subnetroutes',
'routes',
)
op.drop_table('routerroutes')
| apache-2.0 |
mixerp5/frapid | src/Frapid.Web/Areas/Frapid.Calendar/Controllers/CalendarBackendController.cs | 425 | using Frapid.Dashboard.Controllers;
namespace Frapid.Calendar.Controllers
{
public class CalendarBackendController : DashboardController
{
public CalendarBackendController()
{
this.ViewBag.LayoutPath = this.GetLayoutPath();
}
private string GetLayoutPath()
{
return this.GetRazorView<AreaRegistration>("Layout.cshtml", this.Tenant);
}
}
} | apache-2.0 |
shybovycha/buck | src/com/facebook/buck/util/immutables/BuckStyleImmutable.java | 1761 | /*
* Copyright 2015-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.util.immutables;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.immutables.value.Value;
/**
* Style for code-generated Immutables.org immutable value types which:
*
* <ol>
* <li>Does not add the Immutable prefix on generated classes
* <li>Strips off the Abstract name prefix when processing the parent interface or abstract class
* <li>Supports isFoo() / getFoo() getters in the parent interface or abstract class
* <li>Supports setFoo() setters in the parent interface or abstract class
* <li>Ensures the generated class is public (even if the parent interface or abstract class is
* package private)
* </ol>
*/
@Value.Style(
typeImmutable = "*",
typeAbstract = "Abstract*",
get = {"is*", "get*"},
init = "set*",
visibility = Value.Style.ImplementationVisibility.PUBLIC,
forceJacksonPropertyNames = false
)
@Target({ElementType.TYPE, ElementType.PACKAGE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface BuckStyleImmutable {}
| apache-2.0 |
KarolKraskiewicz/kubernetes | test/e2e/storage/vsphere/vsphere_volume_diskformat.go | 8235 | /*
Copyright 2017 The Kubernetes Authors.
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 vsphere
import (
"os"
"path/filepath"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"github.com/vmware/govmomi/find"
"github.com/vmware/govmomi/vim25/types"
"golang.org/x/net/context"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
k8stype "k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/uuid"
clientset "k8s.io/client-go/kubernetes"
vsphere "k8s.io/kubernetes/pkg/cloudprovider/providers/vsphere"
"k8s.io/kubernetes/test/e2e/framework"
"k8s.io/kubernetes/test/e2e/storage/utils"
)
/*
Test to verify diskformat specified in storage-class is being honored while volume creation.
Valid and supported options are eagerzeroedthick, zeroedthick and thin
Steps
1. Create StorageClass with diskformat set to valid type
2. Create PVC which uses the StorageClass created in step 1.
3. Wait for PV to be provisioned.
4. Wait for PVC's status to become Bound
5. Create pod using PVC on specific node.
6. Wait for Disk to be attached to the node.
7. Get node VM's devices and find PV's Volume Disk.
8. Get Backing Info of the Volume Disk and obtain EagerlyScrub and ThinProvisioned
9. Based on the value of EagerlyScrub and ThinProvisioned, verify diskformat is correct.
10. Delete pod and Wait for Volume Disk to be detached from the Node.
11. Delete PVC, PV and Storage Class
*/
var _ = utils.SIGDescribe("Volume Disk Format [Feature:vsphere]", func() {
f := framework.NewDefaultFramework("volume-disk-format")
var (
client clientset.Interface
namespace string
nodeName string
isNodeLabeled bool
nodeKeyValueLabel map[string]string
nodeLabelValue string
)
BeforeEach(func() {
framework.SkipUnlessProviderIs("vsphere")
client = f.ClientSet
namespace = f.Namespace.Name
nodeList := framework.GetReadySchedulableNodesOrDie(f.ClientSet)
if len(nodeList.Items) != 0 {
nodeName = nodeList.Items[0].Name
} else {
framework.Failf("Unable to find ready and schedulable Node")
}
if !isNodeLabeled {
nodeLabelValue = "vsphere_e2e_" + string(uuid.NewUUID())
nodeKeyValueLabel = make(map[string]string)
nodeKeyValueLabel["vsphere_e2e_label"] = nodeLabelValue
framework.AddOrUpdateLabelOnNode(client, nodeName, "vsphere_e2e_label", nodeLabelValue)
isNodeLabeled = true
}
})
framework.AddCleanupAction(func() {
// Cleanup actions will be called even when the tests are skipped and leaves namespace unset.
if len(namespace) > 0 && len(nodeLabelValue) > 0 {
framework.RemoveLabelOffNode(client, nodeName, "vsphere_e2e_label")
}
})
It("verify disk format type - eagerzeroedthick is honored for dynamically provisioned pv using storageclass", func() {
By("Invoking Test for diskformat: eagerzeroedthick")
invokeTest(f, client, namespace, nodeName, nodeKeyValueLabel, "eagerzeroedthick")
})
It("verify disk format type - zeroedthick is honored for dynamically provisioned pv using storageclass", func() {
By("Invoking Test for diskformat: zeroedthick")
invokeTest(f, client, namespace, nodeName, nodeKeyValueLabel, "zeroedthick")
})
It("verify disk format type - thin is honored for dynamically provisioned pv using storageclass", func() {
By("Invoking Test for diskformat: thin")
invokeTest(f, client, namespace, nodeName, nodeKeyValueLabel, "thin")
})
})
func invokeTest(f *framework.Framework, client clientset.Interface, namespace string, nodeName string, nodeKeyValueLabel map[string]string, diskFormat string) {
framework.Logf("Invoking Test for DiskFomat: %s", diskFormat)
scParameters := make(map[string]string)
scParameters["diskformat"] = diskFormat
By("Creating Storage Class With DiskFormat")
storageClassSpec := getVSphereStorageClassSpec("thinsc", scParameters)
storageclass, err := client.StorageV1().StorageClasses().Create(storageClassSpec)
Expect(err).NotTo(HaveOccurred())
defer client.StorageV1().StorageClasses().Delete(storageclass.Name, nil)
By("Creating PVC using the Storage Class")
pvclaimSpec := getVSphereClaimSpecWithStorageClassAnnotation(namespace, "2Gi", storageclass)
pvclaim, err := client.CoreV1().PersistentVolumeClaims(namespace).Create(pvclaimSpec)
Expect(err).NotTo(HaveOccurred())
defer func() {
client.CoreV1().PersistentVolumeClaims(namespace).Delete(pvclaimSpec.Name, nil)
}()
By("Waiting for claim to be in bound phase")
err = framework.WaitForPersistentVolumeClaimPhase(v1.ClaimBound, client, pvclaim.Namespace, pvclaim.Name, framework.Poll, framework.ClaimProvisionTimeout)
Expect(err).NotTo(HaveOccurred())
// Get new copy of the claim
pvclaim, err = client.CoreV1().PersistentVolumeClaims(pvclaim.Namespace).Get(pvclaim.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
// Get the bound PV
pv, err := client.CoreV1().PersistentVolumes().Get(pvclaim.Spec.VolumeName, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())
/*
PV is required to be attached to the Node. so that using govmomi API we can grab Disk's Backing Info
to check EagerlyScrub and ThinProvisioned property
*/
By("Creating pod to attach PV to the node")
// Create pod to attach Volume to Node
podSpec := getVSpherePodSpecWithClaim(pvclaim.Name, nodeKeyValueLabel, "while true ; do sleep 2 ; done")
pod, err := client.CoreV1().Pods(namespace).Create(podSpec)
Expect(err).NotTo(HaveOccurred())
vsp, err := getVSphere(client)
Expect(err).NotTo(HaveOccurred())
verifyVSphereDiskAttached(client, vsp, pv.Spec.VsphereVolume.VolumePath, k8stype.NodeName(nodeName))
By("Waiting for pod to be running")
Expect(framework.WaitForPodNameRunningInNamespace(client, pod.Name, namespace)).To(Succeed())
Expect(verifyDiskFormat(nodeName, pv.Spec.VsphereVolume.VolumePath, diskFormat)).To(BeTrue(), "DiskFormat Verification Failed")
var volumePaths []string
volumePaths = append(volumePaths, pv.Spec.VsphereVolume.VolumePath)
By("Delete pod and wait for volume to be detached from node")
deletePodAndWaitForVolumeToDetach(f, client, pod, vsp, nodeName, volumePaths)
}
func verifyDiskFormat(nodeName string, pvVolumePath string, diskFormat string) bool {
By("Verifing disk format")
eagerlyScrub := false
thinProvisioned := false
diskFound := false
pvvmdkfileName := filepath.Base(pvVolumePath) + filepath.Ext(pvVolumePath)
govMoMiClient, err := vsphere.GetgovmomiClient(nil)
Expect(err).NotTo(HaveOccurred())
f := find.NewFinder(govMoMiClient.Client, true)
ctx, _ := context.WithCancel(context.Background())
vm, err := f.VirtualMachine(ctx, os.Getenv("VSPHERE_WORKING_DIR")+nodeName)
Expect(err).NotTo(HaveOccurred())
vmDevices, err := vm.Device(ctx)
Expect(err).NotTo(HaveOccurred())
disks := vmDevices.SelectByType((*types.VirtualDisk)(nil))
for _, disk := range disks {
backing := disk.GetVirtualDevice().Backing.(*types.VirtualDiskFlatVer2BackingInfo)
backingFileName := filepath.Base(backing.FileName) + filepath.Ext(backing.FileName)
if backingFileName == pvvmdkfileName {
diskFound = true
if backing.EagerlyScrub != nil {
eagerlyScrub = *backing.EagerlyScrub
}
if backing.ThinProvisioned != nil {
thinProvisioned = *backing.ThinProvisioned
}
break
}
}
Expect(diskFound).To(BeTrue(), "Failed to find disk")
isDiskFormatCorrect := false
if diskFormat == "eagerzeroedthick" {
if eagerlyScrub == true && thinProvisioned == false {
isDiskFormatCorrect = true
}
} else if diskFormat == "zeroedthick" {
if eagerlyScrub == false && thinProvisioned == false {
isDiskFormatCorrect = true
}
} else if diskFormat == "thin" {
if eagerlyScrub == false && thinProvisioned == true {
isDiskFormatCorrect = true
}
}
return isDiskFormatCorrect
}
| apache-2.0 |
alanch-ms/PTVS | Python/Tests/TestData/RemoveImport/Import5.py | 35 | import oar, baz, quox
oar
quox | apache-2.0 |
umeshdangat/elasticsearch | modules/percolator/src/main/java/org/elasticsearch/percolator/PercolateQuery.java | 10667 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
package org.elasticsearch.percolator;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.DocIdSetIterator;
import org.apache.lucene.search.Explanation;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Scorer;
import org.apache.lucene.search.ScorerSupplier;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.TwoPhaseIterator;
import org.apache.lucene.search.Weight;
import org.apache.lucene.util.Accountable;
import org.apache.lucene.util.Bits;
import org.elasticsearch.common.CheckedFunction;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.lucene.Lucene;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;
final class PercolateQuery extends Query implements Accountable {
// cost of matching the query against the document, arbitrary as it would be really complex to estimate
private static final float MATCH_COST = 1000;
private final QueryStore queryStore;
private final BytesReference documentSource;
private final Query candidateMatchesQuery;
private final Query verifiedMatchesQuery;
private final IndexSearcher percolatorIndexSearcher;
PercolateQuery(QueryStore queryStore, BytesReference documentSource,
Query candidateMatchesQuery, IndexSearcher percolatorIndexSearcher, Query verifiedMatchesQuery) {
this.documentSource = Objects.requireNonNull(documentSource);
this.candidateMatchesQuery = Objects.requireNonNull(candidateMatchesQuery);
this.queryStore = Objects.requireNonNull(queryStore);
this.percolatorIndexSearcher = Objects.requireNonNull(percolatorIndexSearcher);
this.verifiedMatchesQuery = Objects.requireNonNull(verifiedMatchesQuery);
}
@Override
public Query rewrite(IndexReader reader) throws IOException {
Query rewritten = candidateMatchesQuery.rewrite(reader);
if (rewritten != candidateMatchesQuery) {
return new PercolateQuery(queryStore, documentSource, rewritten, percolatorIndexSearcher, verifiedMatchesQuery);
} else {
return this;
}
}
@Override
public Weight createWeight(IndexSearcher searcher, boolean needsScores, float boost) throws IOException {
final Weight verifiedMatchesWeight = verifiedMatchesQuery.createWeight(searcher, false, boost);
final Weight candidateMatchesWeight = candidateMatchesQuery.createWeight(searcher, false, boost);
return new Weight(this) {
@Override
public void extractTerms(Set<Term> set) {
}
@Override
public Explanation explain(LeafReaderContext leafReaderContext, int docId) throws IOException {
Scorer scorer = scorer(leafReaderContext);
if (scorer != null) {
TwoPhaseIterator twoPhaseIterator = scorer.twoPhaseIterator();
int result = twoPhaseIterator.approximation().advance(docId);
if (result == docId) {
if (twoPhaseIterator.matches()) {
if (needsScores) {
CheckedFunction<Integer, Query, IOException> percolatorQueries = queryStore.getQueries(leafReaderContext);
Query query = percolatorQueries.apply(docId);
Explanation detail = percolatorIndexSearcher.explain(query, 0);
return Explanation.match(scorer.score(), "PercolateQuery", detail);
} else {
return Explanation.match(scorer.score(), "PercolateQuery");
}
}
}
}
return Explanation.noMatch("PercolateQuery");
}
@Override
public Scorer scorer(LeafReaderContext leafReaderContext) throws IOException {
final Scorer approximation = candidateMatchesWeight.scorer(leafReaderContext);
if (approximation == null) {
return null;
}
final CheckedFunction<Integer, Query, IOException> queries = queryStore.getQueries(leafReaderContext);
if (needsScores) {
return new BaseScorer(this, approximation, queries, percolatorIndexSearcher) {
float score;
@Override
boolean matchDocId(int docId) throws IOException {
Query query = percolatorQueries.apply(docId);
if (query != null) {
TopDocs topDocs = percolatorIndexSearcher.search(query, 1);
if (topDocs.totalHits > 0) {
score = topDocs.scoreDocs[0].score;
return true;
} else {
return false;
}
} else {
return false;
}
}
@Override
public float score() throws IOException {
return score;
}
};
} else {
ScorerSupplier verifiedDocsScorer = verifiedMatchesWeight.scorerSupplier(leafReaderContext);
Bits verifiedDocsBits = Lucene.asSequentialAccessBits(leafReaderContext.reader().maxDoc(), verifiedDocsScorer);
return new BaseScorer(this, approximation, queries, percolatorIndexSearcher) {
@Override
public float score() throws IOException {
return 0f;
}
boolean matchDocId(int docId) throws IOException {
// We use the verifiedDocsBits to skip the expensive MemoryIndex verification.
// If docId also appears in the verifiedDocsBits then that means during indexing
// we were able to extract all query terms and for this candidate match
// and we determined based on the nature of the query that it is safe to skip
// the MemoryIndex verification.
if (verifiedDocsBits.get(docId)) {
return true;
}
Query query = percolatorQueries.apply(docId);
return query != null && Lucene.exists(percolatorIndexSearcher, query);
}
};
}
}
};
}
IndexSearcher getPercolatorIndexSearcher() {
return percolatorIndexSearcher;
}
BytesReference getDocumentSource() {
return documentSource;
}
QueryStore getQueryStore() {
return queryStore;
}
// Comparing identity here to avoid being cached
// Note that in theory if the same instance gets used multiple times it could still get cached,
// however since we create a new query instance each time we this query this shouldn't happen and thus
// this risk neglectable.
@Override
public boolean equals(Object o) {
return this == o;
}
// Computing hashcode based on identity to avoid caching.
@Override
public int hashCode() {
return System.identityHashCode(this);
}
@Override
public String toString(String s) {
return "PercolateQuery{document_source={" + documentSource.utf8ToString() + "},inner={" +
candidateMatchesQuery.toString(s) + "}}";
}
@Override
public long ramBytesUsed() {
return documentSource.ramBytesUsed();
}
@FunctionalInterface
interface QueryStore {
CheckedFunction<Integer, Query, IOException> getQueries(LeafReaderContext ctx) throws IOException;
}
abstract static class BaseScorer extends Scorer {
final Scorer approximation;
final CheckedFunction<Integer, Query, IOException> percolatorQueries;
final IndexSearcher percolatorIndexSearcher;
BaseScorer(Weight weight, Scorer approximation, CheckedFunction<Integer, Query, IOException> percolatorQueries,
IndexSearcher percolatorIndexSearcher) {
super(weight);
this.approximation = approximation;
this.percolatorQueries = percolatorQueries;
this.percolatorIndexSearcher = percolatorIndexSearcher;
}
@Override
public final DocIdSetIterator iterator() {
return TwoPhaseIterator.asDocIdSetIterator(twoPhaseIterator());
}
@Override
public final TwoPhaseIterator twoPhaseIterator() {
return new TwoPhaseIterator(approximation.iterator()) {
@Override
public boolean matches() throws IOException {
return matchDocId(approximation.docID());
}
@Override
public float matchCost() {
return MATCH_COST;
}
};
}
@Override
public final int freq() throws IOException {
return approximation.freq();
}
@Override
public final int docID() {
return approximation.docID();
}
abstract boolean matchDocId(int docId) throws IOException;
}
}
| apache-2.0 |
abhitopia/tensorflow | tensorflow/core/ops/nn_grad.cc | 6893 | /* Copyright 2015 The TensorFlow Authors. 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.
==============================================================================*/
#include "tensorflow/core/framework/function.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/util/padding.h"
#include "tensorflow/core/util/tensor_format.h"
namespace tensorflow {
typedef FunctionDefHelper FDH;
Status SoftmaxGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
"SoftmaxGrad",
// Arg defs
{"x: T", "grad_softmax: T"},
// Ret val defs
{"grad_x: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
// Based on _SoftmaxGrad in nn_grad.py.
{
{{"softmax"}, "Softmax", {"x"}, {{"T", "$T"}}},
{{"n0"}, "Mul", {"grad_softmax", "softmax"}, {{"T", "$T"}}},
FDH::Const<int32>("indices", {1}),
{{"n1"}, "Sum", {"n0", "indices"}, {{"T", "$T"}}},
FDH::Const<int32>("newshape", {-1, 1}),
{{"n2"}, "Reshape", {"n1", "newshape"}, {{"T", "$T"}}},
{{"n3"}, "Sub", {"grad_softmax", "n2"}, {{"T", "$T"}}},
{{"grad_x"}, "Mul", {"n3", "softmax"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Softmax", SoftmaxGrad);
Status ReluGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"x: T", "dy: T"},
// Ret val defs
{"dx: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
{{"dx"}, "ReluGrad", {"dy", "x"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Relu", ReluGrad);
Status Relu6Grad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"x: T", "dy: T"},
// Ret val defs
{"dx: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
{{"dx"}, "Relu6Grad", {"dy", "x"}, {{"T", "$T"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Relu6", Relu6Grad);
Status CrossEntropyGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"features: T", "labels: T", "dcost_dloss: T", "donotcare: T"},
// Ret val defs
{"dcost_dfeatures: T", "dcost_dlabels: T"},
// Attr defs
{{"T: {float, double}"}},
// Nodes
{
// _, dloss_dfeatures = CrossEntropy(features, labels)
{{"donotcare_loss", "dloss_dfeatures"}, "CrossEntropy",
{"features", "labels"}, {{"T", "$T"}}},
// dcost_dloss is of shape [batch_size].
// dcost_dloss_mat is of shape [batch_size, 1].
FDH::Const("neg1", -1),
{{"dcost_dloss_mat"}, "ExpandDims", {"dcost_dloss", "neg1"},
{{"T", "$T"}}},
// chain rule: dcost/dfeatures = dcost/dloss * dloss/dfeatures
{{"dcost_dfeatures"}, "Mul", {"dcost_dloss_mat", "dloss_dfeatures"},
{{"T", "$T"}}},
{{"dcost_dlabels"}, "ZerosLike", {"labels"}, {{"T", "$T"}}},
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("CrossEntropy", CrossEntropyGrad);
Status Conv2DGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "filter: T", "grad: T"},
// Ret val defs
{"input_grad: T", "filter_grad: T"},
// Attr defs
{"T: {float, double}",
"strides: list(int)",
"use_cudnn_on_gpu: bool = true",
GetPaddingAttrString(),
GetConvnetDataFormatAttrString()},
// Nodes
{
{{"i_shape"}, "Shape", {"input"}, {{"T", "$T"}}},
{{"input_grad"}, "Conv2DBackpropInput", {"i_shape", "filter", "grad"},
/*Attrs=*/{{"T", "$T"},
{"strides", "$strides"},
{"padding", "$padding"},
{"data_format", "$data_format"},
{"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}},
{{"f_shape"}, "Shape", {"filter"}, {{"T", "$T"}}},
{{"filter_grad"}, "Conv2DBackpropFilter", {"input", "f_shape", "grad"},
/*Attrs=*/{{"T", "$T"},
{"strides", "$strides"},
{"padding", "$padding"},
{"data_format", "$data_format"},
{"use_cudnn_on_gpu", "$use_cudnn_on_gpu"}}},
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("Conv2D", Conv2DGrad);
Status MaxPoolGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
// Invoke MaxPool again to recompute the outputs (removed by CSE?).
{{"maxpool"}, "MaxPool", {"input"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}},
{{"output"}, "MaxPoolGrad", {"input", "maxpool", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("MaxPool", MaxPoolGrad);
Status MaxPoolGradGrad(const AttrSlice& attrs, FunctionDef* g) {
// clang-format off
*g = FDH::Define(
// Arg defs
{"input: T", "grad: T"},
// Ret val defs
{"output: T"},
// Attr defs
{"T: {float, half} = DT_FLOAT",
"ksize: list(int) >= 4",
"strides: list(int) >= 4",
GetPaddingAttrString()},
// Nodes
{
// Invoke MaxPool again to recompute the outputs (removed by CSE?).
{{"maxpool"}, "MaxPool", {"input"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}},
{{"output"}, "MaxPoolGradGrad", {"input", "maxpool", "grad"},
/*Attrs=*/{{"T", "$T"},
{"ksize", "$ksize"},
{"strides", "$strides"},
{"padding", "$padding"}}}
});
// clang-format on
return Status::OK();
}
REGISTER_OP_GRADIENT("MaxPoolGrad", MaxPoolGradGrad);
} // end namespace tensorflow
| apache-2.0 |
bennetelli/activemq-artemis | tests/unit-tests/src/test/java/org/apache/activemq/artemis/tests/unit/core/postoffice/impl/DuplicateDetectionUnitTest.java | 6575 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.unit.core.postoffice.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import org.apache.activemq.artemis.api.config.ActiveMQDefaultConfiguration;
import org.apache.activemq.artemis.api.core.Pair;
import org.apache.activemq.artemis.api.core.SimpleString;
import org.apache.activemq.artemis.core.config.Configuration;
import org.apache.activemq.artemis.core.persistence.AddressBindingInfo;
import org.apache.activemq.artemis.core.persistence.GroupingInfo;
import org.apache.activemq.artemis.core.persistence.QueueBindingInfo;
import org.apache.activemq.artemis.core.persistence.impl.journal.JournalStorageManager;
import org.apache.activemq.artemis.core.postoffice.PostOffice;
import org.apache.activemq.artemis.core.postoffice.impl.DuplicateIDCacheImpl;
import org.apache.activemq.artemis.core.server.impl.PostOfficeJournalLoader;
import org.apache.activemq.artemis.core.transaction.impl.ResourceManagerImpl;
import org.apache.activemq.artemis.tests.unit.core.server.impl.fakes.FakePostOffice;
import org.apache.activemq.artemis.tests.unit.util.FakePagingManager;
import org.apache.activemq.artemis.tests.util.ActiveMQTestBase;
import org.apache.activemq.artemis.utils.ActiveMQThreadFactory;
import org.apache.activemq.artemis.utils.ExecutorFactory;
import org.apache.activemq.artemis.utils.OrderedExecutorFactory;
import org.apache.activemq.artemis.utils.RandomUtil;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
public class DuplicateDetectionUnitTest extends ActiveMQTestBase {
// Constants -----------------------------------------------------
// Attributes ----------------------------------------------------
// Static --------------------------------------------------------
// Constructors --------------------------------------------------
ExecutorService executor;
ExecutorFactory factory;
@Override
@After
public void tearDown() throws Exception {
executor.shutdown();
super.tearDown();
}
@Override
@Before
public void setUp() throws Exception {
super.setUp();
executor = Executors.newFixedThreadPool(10, ActiveMQThreadFactory.defaultThreadFactory());
factory = new OrderedExecutorFactory(executor);
}
// Public --------------------------------------------------------
@Test
public void testReloadDuplication() throws Exception {
JournalStorageManager journal = null;
try {
clearDataRecreateServerDirs();
SimpleString ADDRESS = new SimpleString("address");
Configuration configuration = createDefaultInVMConfig();
PostOffice postOffice = new FakePostOffice();
ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(ActiveMQDefaultConfiguration.getDefaultScheduledThreadPoolMaxSize(), ActiveMQThreadFactory.defaultThreadFactory());
journal = new JournalStorageManager(configuration, factory, factory);
journal.start();
journal.loadBindingJournal(new ArrayList<QueueBindingInfo>(), new ArrayList<GroupingInfo>(), new ArrayList<AddressBindingInfo>());
HashMap<SimpleString, List<Pair<byte[], Long>>> mapDups = new HashMap<>();
FakePagingManager pagingManager = new FakePagingManager();
journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null));
Assert.assertEquals(0, mapDups.size());
DuplicateIDCacheImpl cacheID = new DuplicateIDCacheImpl(ADDRESS, 10, journal, true);
for (int i = 0; i < 100; i++) {
cacheID.addToCache(RandomUtil.randomBytes());
}
journal.stop();
journal = new JournalStorageManager(configuration, factory, factory);
journal.start();
journal.loadBindingJournal(new ArrayList<QueueBindingInfo>(), new ArrayList<GroupingInfo>(), new ArrayList<AddressBindingInfo>());
journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null));
Assert.assertEquals(1, mapDups.size());
List<Pair<byte[], Long>> values = mapDups.get(ADDRESS);
Assert.assertEquals(10, values.size());
cacheID = new DuplicateIDCacheImpl(ADDRESS, 10, journal, true);
cacheID.load(values);
for (int i = 0; i < 100; i++) {
cacheID.addToCache(RandomUtil.randomBytes(), null);
}
journal.stop();
mapDups.clear();
journal = new JournalStorageManager(configuration, factory, factory);
journal.start();
journal.loadBindingJournal(new ArrayList<QueueBindingInfo>(), new ArrayList<GroupingInfo>(), new ArrayList<AddressBindingInfo>());
journal.loadMessageJournal(postOffice, pagingManager, new ResourceManagerImpl(0, 0, scheduledThreadPool), null, mapDups, null, null, new PostOfficeJournalLoader(postOffice, pagingManager, null, null, null, null, null, null));
Assert.assertEquals(1, mapDups.size());
values = mapDups.get(ADDRESS);
Assert.assertEquals(10, values.size());
scheduledThreadPool.shutdown();
} finally {
if (journal != null) {
try {
journal.stop();
} catch (Throwable ignored) {
}
}
}
}
}
| apache-2.0 |
Torgo13/CarWashApp | node_modules/typescript/lib/lib.es2017.object.d.ts | 2108 | /*! *****************************************************************************
Copyright (c) Microsoft Corporation. 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
THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
MERCHANTABLITY OR NON-INFRINGEMENT.
See the Apache Version 2.0 License for specific language governing permissions
and limitations under the License.
***************************************************************************** */
/// <reference no-default-lib="true"/>
interface ObjectConstructor {
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values<T>(o: { [s: string]: T }): T[];
/**
* Returns an array of values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
values(o: any): any[];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries<T>(o: { [s: string]: T }): [string, T][];
/**
* Returns an array of key/values of the enumerable properties of an object
* @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object.
*/
entries(o: any): [string, any][];
}
| apache-2.0 |
thinkfree2015/p00 | cas-server-support-ldap/src/main/java/org/jasig/cas/adaptors/ldap/remote/RemoteAddressNonInteractiveCredentialsAction.java | 1799 | /*
* Licensed to Jasig under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Jasig 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 the following location:
*
* 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 org.jasig.cas.adaptors.ldap.remote;
import javax.servlet.http.HttpServletRequest;
import org.jasig.cas.authentication.Credential;
import org.jasig.cas.web.flow.AbstractNonInteractiveCredentialsAction;
import org.jasig.cas.web.support.WebUtils;
import org.springframework.util.StringUtils;
import org.springframework.webflow.execution.RequestContext;
/**
*
* @author Scott Battaglia
* @since 3.2.1
*
*/
public final class RemoteAddressNonInteractiveCredentialsAction extends
AbstractNonInteractiveCredentialsAction {
@Override
protected Credential constructCredentialsFromRequest(final RequestContext context) {
final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
final String remoteAddress = request.getRemoteAddr();
if (StringUtils.hasText(remoteAddress)) {
return new RemoteAddressCredential(remoteAddress);
}
logger.debug("No remote address found.");
return null;
}
}
| apache-2.0 |
nssales/OG-Platform | projects/OG-Financial/src/main/java/com/opengamma/financial/analytics/model/futureoption/EquityFutureOptionBAWFunction.java | 802 | /**
* Copyright (C) 2012 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.financial.analytics.model.futureoption;
import com.opengamma.financial.analytics.model.CalculationPropertyNamesAndValues;
/**
*
*/
public abstract class EquityFutureOptionBAWFunction extends EquityFutureOptionFunction {
/**
* @param valueRequirementName The value requirement name
*/
public EquityFutureOptionBAWFunction(final String... valueRequirementName) {
super(valueRequirementName);
}
@Override
protected String getCalculationMethod() {
return CalculationPropertyNamesAndValues.BAW_METHOD;
}
@Override
protected String getModelType() {
return CalculationPropertyNamesAndValues.ANALYTIC;
}
}
| apache-2.0 |
xingh/opendms-dot-net | OpenDMS.Networking/Protocols/Tcp/TcpConnectionException.cs | 480 | using System;
namespace OpenDMS.Networking.Protocols.Tcp
{
public class TcpConnectionException : Exception
{
public TcpConnectionException()
: base()
{
}
public TcpConnectionException(string message)
: base(message)
{
}
public TcpConnectionException(string message, Exception innerException)
: base(message, innerException)
{
}
}
}
| apache-2.0 |
GoogleCloudPlatform/prometheus-engine | third_party/prometheus_ui/base/web/ui/react-app/node_modules/jsx-ast-utils/src/hasProp.js | 1491 | import propName from './propName';
const DEFAULT_OPTIONS = {
spreadStrict: true,
ignoreCase: true,
};
/**
* Returns boolean indicating whether an prop exists on the props
* property of a JSX element node.
*/
export default function hasProp(props = [], prop = '', options = DEFAULT_OPTIONS) {
const propToCheck = options.ignoreCase ? prop.toUpperCase() : prop;
return props.some((attribute) => {
// If the props contain a spread prop, then refer to strict param.
if (attribute.type === 'JSXSpreadAttribute') {
return !options.spreadStrict;
}
const currentProp = options.ignoreCase
? propName(attribute).toUpperCase()
: propName(attribute);
return propToCheck === currentProp;
});
}
/**
* Given the props on a node and a list of props to check, this returns a boolean
* indicating if any of them exist on the node.
*/
export function hasAnyProp(nodeProps = [], props = [], options = DEFAULT_OPTIONS) {
const propsToCheck = typeof props === 'string' ? props.split(' ') : props;
return propsToCheck.some((prop) => hasProp(nodeProps, prop, options));
}
/**
* Given the props on a node and a list of props to check, this returns a boolean
* indicating if all of them exist on the node
*/
export function hasEveryProp(nodeProps = [], props = [], options = DEFAULT_OPTIONS) {
const propsToCheck = typeof props === 'string' ? props.split(' ') : props;
return propsToCheck.every((prop) => hasProp(nodeProps, prop, options));
}
| apache-2.0 |
JetBrains/intellij-haxe | src/common/com/intellij/plugins/haxe/model/fixer/HaxeCreateMethodFixer.java | 1042 | /*
* Copyright 2000-2013 JetBrains s.r.o.
* Copyright 2014-2015 AS3Boyan
* Copyright 2014-2014 Elias Ku
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.plugins.haxe.model.fixer;
import com.intellij.plugins.haxe.lang.psi.HaxeReferenceExpression;
import com.intellij.psi.PsiElement;
public class HaxeCreateMethodFixer extends HaxeFixer {
public HaxeCreateMethodFixer(String name, PsiElement context) {
super("Create method");
}
@Override
public void run() {
// @TODO: Stub. Implement.
}
}
| apache-2.0 |
rajasec/containerd | containers/containers.go | 1250 | package containers
import (
"context"
"time"
"github.com/gogo/protobuf/types"
)
// Container represents the set of data pinned by a container. Unless otherwise
// noted, the resources here are considered in use by the container.
//
// The resources specified in this object are used to create tasks from the container.
type Container struct {
ID string
Labels map[string]string
Image string
Runtime RuntimeInfo
Spec *types.Any
RootFS string
Snapshotter string
CreatedAt time.Time
UpdatedAt time.Time
}
type RuntimeInfo struct {
Name string
Options *types.Any
}
type Store interface {
Get(ctx context.Context, id string) (Container, error)
// List returns containers that match one or more of the provided filters.
List(ctx context.Context, filters ...string) ([]Container, error)
Create(ctx context.Context, container Container) (Container, error)
// Update the container with the provided container object. ID must be set.
//
// If one or more fieldpaths are provided, only the field corresponding to
// the fieldpaths will be mutated.
Update(ctx context.Context, container Container, fieldpaths ...string) (Container, error)
Delete(ctx context.Context, id string) error
}
| apache-2.0 |
OneGet/nuget | src/VisualStudio/Utility/VsVersionHelper.cs | 2210 | using System;
using EnvDTE;
namespace NuGet.VisualStudio
{
public static class VsVersionHelper
{
private const int MaxVsVersion = 12;
private static readonly Lazy<int> _vsMajorVersion = new Lazy<int>(GetMajorVsVersion);
private static readonly Lazy<string> _fullVsEdition = new Lazy<string>(GetFullVsVersionString);
public static int VsMajorVersion
{
get { return _vsMajorVersion.Value; }
}
public static bool IsVisualStudio2010
{
get { return VsMajorVersion == 10; }
}
public static bool IsVisualStudio2012
{
get { return VsMajorVersion == 11; }
}
public static bool IsVisualStudio2013
{
get { return VsMajorVersion == 12; }
}
public static string FullVsEdition
{
get { return _fullVsEdition.Value; }
}
private static int GetMajorVsVersion()
{
DTE dte = ServiceLocator.GetInstance<DTE>();
string vsVersion = dte.Version;
Version version;
if (Version.TryParse(vsVersion, out version))
{
return version.Major;
}
return MaxVsVersion;
}
private static string GetFullVsVersionString()
{
DTE dte = ServiceLocator.GetInstance<DTE>();
string edition = dte.Edition;
if (!edition.StartsWith("VS", StringComparison.OrdinalIgnoreCase))
{
edition = "VS " + edition;
}
return edition + "/" + dte.Version;
}
public static string GetSKU()
{
DTE dte = ServiceLocator.GetInstance<DTE>();
string sku = dte.Edition;
if (sku.Equals("Ultimate", StringComparison.OrdinalIgnoreCase) ||
sku.Equals("Premium", StringComparison.OrdinalIgnoreCase) ||
sku.Equals("Professional", StringComparison.OrdinalIgnoreCase))
{
sku = "Pro";
}
return sku;
}
}
} | apache-2.0 |
gerhardgossen/webarchive-commons | src/main/java/org/archive/io/BufferedSeekInputStream.java | 5468 | /*
* This file is part of the Heritrix web crawler (crawler.archive.org).
*
* Licensed to the Internet Archive (IA) by one or more individual
* contributors.
*
* The IA 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.
*/
package org.archive.io;
import java.io.IOException;
/**
* Buffers data from some other SeekInputStream.
*
* @author pjack
*/
public class BufferedSeekInputStream extends SeekInputStream {
/**
* The underlying input stream.
*/
final private SeekInputStream input;
/**
* The buffered data.
*/
final private byte[] buffer;
/**
* The maximum offset of valid data in the buffer. Usually the same
* as buffer.length, but may be shorter if we're in the last region
* of the stream.
*/
private int maxOffset;
/**
* The offset of within the buffer of the next byte to read.
*/
private int offset;
/**
* Constructor.
*
* @param input the underlying input stream
* @param capacity the size of the buffer
* @throws IOException if an IO occurs filling the first buffer
*/
public BufferedSeekInputStream(SeekInputStream input, int capacity)
throws IOException {
this.input = input;
this.buffer = new byte[capacity];
buffer();
}
/**
* Fills the buffer.
*
* @throws IOException if an IO error occurs
*/
private void buffer() throws IOException {
int remaining = buffer.length;
while (remaining > 0) {
int r = input.read(buffer, buffer.length - remaining, remaining);
if (r <= 0) {
// Not enough information to fill the buffer
offset = 0;
maxOffset = buffer.length - remaining;
return;
}
remaining -= r;
}
maxOffset = buffer.length;
offset = 0;
}
/**
* Ensures that the buffer is valid.
*
* @throws IOException if an IO error occurs
*/
private void ensureBuffer() throws IOException {
if (offset >= maxOffset) {
buffer();
}
}
/**
* Returns the number of unread bytes in the current buffer.
*
* @return the remaining bytes
*/
private int remaining() {
return maxOffset - offset;
}
@Override
public int read() throws IOException {
ensureBuffer();
if (maxOffset == 0) {
return -1;
}
int ch = buffer[offset] & 0xFF;
offset++;
return ch;
}
@Override
public int read(byte[] buf, int ofs, int len) throws IOException {
ensureBuffer();
if (maxOffset == 0) {
return 0;
}
len = Math.min(len, remaining());
System.arraycopy(buffer, offset, buf, ofs, len);
offset += len;
return len;
}
@Override
public int read(byte[] buf) throws IOException {
return read(buf, 0, buf.length);
}
@Override
public long skip(long c) throws IOException {
ensureBuffer();
if (maxOffset == 0) {
return 0;
}
int count = (c > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)c;
int skip = Math.min(count, remaining());
offset += skip;
return skip;
}
/**
* Returns the stream's current position.
*
* @return the current position
*/
public long position() throws IOException {
return input.position() - buffer.length + offset;
}
/**
* Seeks to the given position. This method avoids re-filling the buffer
* if at all possible.
*
* @param p the position to set
* @throws IOException if an IO error occurs
*/
public void position(long p) throws IOException {
long blockStart = (input.position() - maxOffset)
/ buffer.length * buffer.length;
long blockEnd = blockStart + maxOffset;
if ((p >= blockStart) && (p < blockEnd)) {
// Desired position is somewhere inside current buffer
long adj = p - blockStart;
offset = (int)adj;
return;
}
positionDirect(p);
}
/**
* Positions the underlying stream at the given position, then refills
* the buffer.
*
* @param p the position to set
* @throws IOException if an IO error occurs
*/
private void positionDirect(long p) throws IOException {
long newBlockStart = p / buffer.length * buffer.length;
input.position(newBlockStart);
buffer();
offset = (int)(p % buffer.length);
}
/**
* Close the stream, including the wrapped input stream.
*/
public void close() throws IOException {
super.close();
if(this.input!=null) {
this.input.close();
}
}
}
| apache-2.0 |
joshmgrant/selenium | javascript/atoms/action.js | 28416 | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.
/**
* @fileoverview Atoms for simulating user actions against the DOM.
* The bot.action namespace is required since these atoms would otherwise form a
* circular dependency between bot.dom and bot.events.
*
*/
goog.provide('bot.action');
goog.require('bot');
goog.require('bot.Device');
goog.require('bot.Error');
goog.require('bot.ErrorCode');
goog.require('bot.Keyboard');
goog.require('bot.Mouse');
goog.require('bot.Touchscreen');
goog.require('bot.dom');
goog.require('bot.events');
goog.require('bot.events.EventType');
goog.require('goog.array');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Vec2');
goog.require('goog.style');
/**
* Throws an exception if an element is not shown to the user, ignoring its
* opacity.
*
* @param {!Element} element The element to check.
* @see bot.dom.isShown.
* @private
*/
bot.action.checkShown_ = function(element) {
if (!bot.dom.isShown(element, /*ignoreOpacity=*/true)) {
throw new bot.Error(bot.ErrorCode.ELEMENT_NOT_VISIBLE,
'Element is not currently visible and may not be manipulated');
}
};
/**
* Throws an exception if the given element cannot be interacted with.
*
* @param {!Element} element The element to check.
* @throws {bot.Error} If the element cannot be interacted with.
* @see bot.dom.isInteractable.
* @private
*/
bot.action.checkInteractable_ = function(element) {
if (!bot.dom.isInteractable(element)) {
throw new bot.Error(bot.ErrorCode.INVALID_ELEMENT_STATE,
'Element is not currently interactable and may not be manipulated');
}
};
/**
* Clears the given {@code element} if it is a editable text field.
*
* @param {!Element} element The element to clear.
* @throws {bot.Error} If the element is not an editable text field.
*/
bot.action.clear = function(element) {
bot.action.checkInteractable_(element);
if (!bot.dom.isEditable(element)) {
throw new bot.Error(bot.ErrorCode.INVALID_ELEMENT_STATE,
'Element must be user-editable in order to clear it.');
}
if (element.value) {
bot.action.LegacyDevice_.focusOnElement(element);
if (goog.userAgent.IE && bot.dom.isInputType(element, 'range')) {
var min = element.min ? element.min : 0;
var max = element.max ? element.max : 100;
element.value = (max < min) ? min : min + (max - min) / 2;
} else {
element.value = '';
}
bot.events.fire(element, bot.events.EventType.CHANGE);
bot.events.fire(element, bot.events.EventType.BLUR);
var body = bot.getDocument().body;
if (body) {
bot.action.LegacyDevice_.focusOnElement(body);
} else {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'Cannot unfocus element after clearing.');
}
} else if (bot.dom.isElement(element, goog.dom.TagName.INPUT) &&
(element.getAttribute('type') && element.getAttribute('type').toLowerCase() == "number")) {
// number input fields that have invalid inputs
// report their value as empty string with no way to tell if there is a
// current value or not
bot.action.LegacyDevice_.focusOnElement(element);
element.value = '';
}
if (bot.dom.isContentEditable(element)) {
// A single space is required, if you put empty string here you'll not be
// able to interact with this element anymore in Firefox.
bot.action.LegacyDevice_.focusOnElement(element);
element.innerHTML = ' ';
// contentEditable does not generate onchange event.
}
};
/**
* Focuses on the given element if it is not already the active element.
*
* @param {!Element} element The element to focus on.
*/
bot.action.focusOnElement = function(element) {
bot.action.checkInteractable_(element);
bot.action.LegacyDevice_.focusOnElement(element);
};
/**
* Types keys on the given {@code element} with a virtual keyboard.
*
* <p>Callers can pass in a string, a key in bot.Keyboard.Key, or an array
* of strings or keys. If a modifier key is provided, it is pressed but not
* released, until it is either is listed again or the function ends.
*
* <p>Example:
* bot.keys.type(element, ['ab', bot.Keyboard.Key.LEFT,
* bot.Keyboard.Key.SHIFT, 'cd']);
*
* @param {!Element} element The element receiving the event.
* @param {(string|!bot.Keyboard.Key|!Array.<(string|!bot.Keyboard.Key)>)}
* values Value or values to type on the element.
* @param {bot.Keyboard=} opt_keyboard Keyboard to use; if not provided,
* constructs one.
* @param {boolean=} opt_persistModifiers Whether modifier keys should remain
* pressed when this function ends.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.type = function(
element, values, opt_keyboard, opt_persistModifiers) {
// If the element has already been brought into focus somewhow, typing is
// always allowed to proceed. Otherwise, we require the element be in an
// "interactable" state. For example, an element that is hidden by overflow
// can be typed on, so long as the user first tabs to it or the app calls
// focus() on the element first.
if (element != bot.dom.getActiveElement(element)) {
bot.action.checkInteractable_(element);
bot.action.scrollIntoView(element);
}
var keyboard = opt_keyboard || new bot.Keyboard();
keyboard.moveCursor(element);
function typeValue(value) {
if (goog.isString(value)) {
goog.array.forEach(value.split(''), function(ch) {
var keyShiftPair = bot.Keyboard.Key.fromChar(ch);
var shiftIsPressed = keyboard.isPressed(bot.Keyboard.Keys.SHIFT);
if (keyShiftPair.shift && !shiftIsPressed) {
keyboard.pressKey(bot.Keyboard.Keys.SHIFT);
}
keyboard.pressKey(keyShiftPair.key);
keyboard.releaseKey(keyShiftPair.key);
if (keyShiftPair.shift && !shiftIsPressed) {
keyboard.releaseKey(bot.Keyboard.Keys.SHIFT);
}
});
} else if (goog.array.contains(bot.Keyboard.MODIFIERS, value)) {
if (keyboard.isPressed(/** @type {!bot.Keyboard.Key} */ (value))) {
keyboard.releaseKey(value);
} else {
keyboard.pressKey(value);
}
} else {
keyboard.pressKey(value);
keyboard.releaseKey(value);
}
}
// mobile safari (iPhone / iPad). one cannot 'type' in a date field
// chrome implements this, but desktop Safari doesn't, what's webkit again?
if ((!(goog.userAgent.product.SAFARI && !goog.userAgent.MOBILE)) &&
goog.userAgent.WEBKIT && element.type == 'date') {
var val = goog.isArray(values)? values = values.join("") : values;
var datePattern = /\d{4}-\d{2}-\d{2}/;
if (val.match(datePattern)) {
// The following events get fired on iOS first
if (goog.userAgent.MOBILE && goog.userAgent.product.SAFARI) {
bot.events.fire(element, bot.events.EventType.TOUCHSTART);
bot.events.fire(element, bot.events.EventType.TOUCHEND);
}
bot.events.fire(element, bot.events.EventType.FOCUS);
element.value = val.match(datePattern)[0];
bot.events.fire(element, bot.events.EventType.CHANGE);
bot.events.fire(element, bot.events.EventType.BLUR);
return;
}
}
if (goog.isArray(values)) {
goog.array.forEach(values, typeValue);
} else {
typeValue(values);
}
if (!opt_persistModifiers) {
// Release all the modifier keys.
goog.array.forEach(bot.Keyboard.MODIFIERS, function(key) {
if (keyboard.isPressed(key)) {
keyboard.releaseKey(key);
}
});
}
};
/**
* Submits the form containing the given {@code element}.
*
* <p>Note this function submits the form, but does not simulate user input
* (a click or key press).
*
* @param {!Element} element The element to submit.
* @deprecated Click on a submit button or type ENTER in a text box instead.
*/
bot.action.submit = function(element) {
var form = bot.action.LegacyDevice_.findAncestorForm(element);
if (!form) {
throw new bot.Error(bot.ErrorCode.NO_SUCH_ELEMENT,
'Element was not in a form, so could not submit.');
}
bot.action.LegacyDevice_.submitForm(element, form);
};
/**
* Moves the mouse over the given {@code element} with a virtual mouse.
*
* @param {!Element} element The element to click.
* @param {goog.math.Coordinate=} opt_coords Mouse position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.moveMouse = function(element, opt_coords, opt_mouse) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
};
/**
* Clicks on the given {@code element} with a virtual mouse.
*
* @param {!Element} element The element to click.
* @param {goog.math.Coordinate=} opt_coords Mouse position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @param {boolean=} opt_force Whether the release event should be fired even if the
* element is not interactable.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.click = function(element, opt_coords, opt_mouse, opt_force) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
mouse.pressButton(bot.Mouse.Button.LEFT);
mouse.releaseButton(opt_force);
};
/**
* Right-clicks on the given {@code element} with a virtual mouse.
*
* @param {!Element} element The element to click.
* @param {goog.math.Coordinate=} opt_coords Mouse position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.rightClick = function(element, opt_coords, opt_mouse) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
mouse.pressButton(bot.Mouse.Button.RIGHT);
mouse.releaseButton();
};
/**
* Double-clicks on the given {@code element} with a virtual mouse.
*
* @param {!Element} element The element to click.
* @param {goog.math.Coordinate=} opt_coords Mouse position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.doubleClick = function(element, opt_coords, opt_mouse) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
mouse.pressButton(bot.Mouse.Button.LEFT);
mouse.releaseButton();
mouse.pressButton(bot.Mouse.Button.LEFT);
mouse.releaseButton();
};
/**
* Double-clicks on the given {@code element} with a virtual mouse.
*
* @param {!Element} element The element to click.
* @param {goog.math.Coordinate=} opt_coords Mouse position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.doubleClick2 = function(element, opt_coords, opt_mouse) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
mouse.pressButton(bot.Mouse.Button.LEFT, 2);
mouse.releaseButton(true, 2);
};
/**
* Scrolls the mouse wheel on the given {@code element} with a virtual mouse.
*
* @param {!Element} element The element to scroll the mouse wheel on.
* @param {number} ticks Number of ticks to scroll the mouse wheel; a positive
* number scrolls down and a negative scrolls up.
* @param {goog.math.Coordinate=} opt_coords Mouse position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.scrollMouse = function(element, ticks, opt_coords, opt_mouse) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
mouse.scroll(ticks);
};
/**
* Drags the given {@code element} by (dx, dy) with a virtual mouse.
*
* @param {!Element} element The element to drag.
* @param {number} dx Increment in x coordinate.
* @param {number} dy Increment in y coordinate.
* @param {number=} opt_steps The number of steps that should occur as part of
* the drag, default is 2.
* @param {goog.math.Coordinate=} opt_coords Drag start position relative to the
* element.
* @param {bot.Mouse=} opt_mouse Mouse to use; if not provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.drag = function(element, dx, dy, opt_steps, opt_coords, opt_mouse) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var initRect = bot.dom.getClientRect(element);
var mouse = opt_mouse || new bot.Mouse();
mouse.move(element, coords);
mouse.pressButton(bot.Mouse.Button.LEFT);
var steps = goog.isDef(opt_steps) ? opt_steps : 2;
if (steps < 1) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'There must be at least one step as part of a drag.');
}
for (var i = 1; i <= steps; i++) {
moveTo(Math.floor(i * dx / steps), Math.floor(i * dy / steps));
}
mouse.releaseButton();
function moveTo(x, y) {
var currRect = bot.dom.getClientRect(element);
var newPos = new goog.math.Coordinate(
coords.x + initRect.left + x - currRect.left,
coords.y + initRect.top + y - currRect.top);
mouse.move(element, newPos);
}
};
/**
* Taps on the given {@code element} with a virtual touch screen.
*
* @param {!Element} element The element to tap.
* @param {goog.math.Coordinate=} opt_coords Finger position relative to the
* target.
* @param {bot.Touchscreen=} opt_touchscreen Touchscreen to use; if not
* provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.tap = function(element, opt_coords, opt_touchscreen) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var touchscreen = opt_touchscreen || new bot.Touchscreen();
touchscreen.move(element, coords);
touchscreen.press();
touchscreen.release();
};
/**
* Swipes the given {@code element} by (dx, dy) with a virtual touch screen.
*
* @param {!Element} element The element to swipe.
* @param {number} dx Increment in x coordinate.
* @param {number} dy Increment in y coordinate.
* @param {number=} opt_steps The number of steps that should occurs as part of
* the swipe, default is 2.
* @param {goog.math.Coordinate=} opt_coords Swipe start position relative to
* the element.
* @param {bot.Touchscreen=} opt_touchscreen Touchscreen to use; if not
* provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.swipe = function(element, dx, dy, opt_steps, opt_coords,
opt_touchscreen) {
var coords = bot.action.prepareToInteractWith_(element, opt_coords);
var touchscreen = opt_touchscreen || new bot.Touchscreen();
var initRect = bot.dom.getClientRect(element);
touchscreen.move(element, coords);
touchscreen.press();
var steps = goog.isDef(opt_steps) ? opt_steps : 2;
if (steps < 1) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'There must be at least one step as part of a swipe.');
}
for (var i = 1; i <= steps; i++) {
moveTo(Math.floor(i * dx / steps), Math.floor(i * dy / steps));
}
touchscreen.release();
function moveTo(x, y) {
var currRect = bot.dom.getClientRect(element);
var newPos = new goog.math.Coordinate(
coords.x + initRect.left + x - currRect.left,
coords.y + initRect.top + y - currRect.top);
touchscreen.move(element, newPos);
}
};
/**
* Pinches the given {@code element} by the given distance with a virtual touch
* screen. A positive distance moves two fingers inward toward each and a
* negative distances spreds them outward. The optional coordinate is the point
* the fingers move towards (for positive distances) or away from (for negative
* distances); and if not provided, defaults to the center of the element.
*
* @param {!Element} element The element to pinch.
* @param {number} distance The distance by which to pinch the element.
* @param {goog.math.Coordinate=} opt_coords Position relative to the element
* at the center of the pinch.
* @param {bot.Touchscreen=} opt_touchscreen Touchscreen to use; if not
* provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.pinch = function(element, distance, opt_coords, opt_touchscreen) {
if (distance == 0) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'Cannot pinch by a distance of zero.');
}
function startSoThatEndsAtMax(offsetVec) {
if (distance < 0) {
var magnitude = offsetVec.magnitude();
offsetVec.scale(magnitude ? (magnitude + distance) / magnitude : 0);
}
}
var halfDistance = distance / 2;
function scaleByHalfDistance(offsetVec) {
var magnitude = offsetVec.magnitude();
offsetVec.scale(magnitude ? (magnitude - halfDistance) / magnitude : 0);
}
bot.action.multiTouchAction_(element,
startSoThatEndsAtMax,
scaleByHalfDistance,
opt_coords,
opt_touchscreen);
};
/**
* Rotates the given {@code element} by the given angle with a virtual touch
* screen. A positive angle moves two fingers clockwise and a negative angle
* moves them counter-clockwise. The optional coordinate is the point to
* rotate around; and if not provided, defaults to the center of the element.
*
* @param {!Element} element The element to rotate.
* @param {number} angle The angle by which to rotate the element.
* @param {goog.math.Coordinate=} opt_coords Position relative to the element
* at the center of the rotation.
* @param {bot.Touchscreen=} opt_touchscreen Touchscreen to use; if not
* provided, constructs one.
* @throws {bot.Error} If the element cannot be interacted with.
*/
bot.action.rotate = function(element, angle, opt_coords, opt_touchscreen) {
if (angle == 0) {
throw new bot.Error(bot.ErrorCode.UNKNOWN_ERROR,
'Cannot rotate by an angle of zero.');
}
function startHalfwayToMax(offsetVec) {
offsetVec.scale(0.5);
}
var halfRadians = Math.PI * (angle / 180) / 2;
function rotateByHalfAngle(offsetVec) {
offsetVec.rotate(halfRadians);
}
bot.action.multiTouchAction_(element,
startHalfwayToMax,
rotateByHalfAngle,
opt_coords,
opt_touchscreen);
};
/**
* Performs a multi-touch action with two fingers on the given element. This
* helper function works by manipulating an "offsetVector", which is the vector
* away from the center of the interaction at which the fingers are positioned.
* It computes the maximum offset vector and passes it to transformStart to
* find the starting position of the fingers; it then passes it to transformHalf
* twice to find the midpoint and final position of the fingers.
*
* @param {!Element} element Element to interact with.
* @param {function(goog.math.Vec2)} transformStart Function to transform the
* maximum offset vector to the starting offset vector.
* @param {function(goog.math.Vec2)} transformHalf Function to transform the
* offset vector halfway to its destination.
* @param {goog.math.Coordinate=} opt_coords Position relative to the element
* at the center of the pinch.
* @param {bot.Touchscreen=} opt_touchscreen Touchscreen to use; if not
* provided, constructs one.
* @private
*/
bot.action.multiTouchAction_ = function(element, transformStart, transformHalf,
opt_coords, opt_touchscreen) {
var center = bot.action.prepareToInteractWith_(element, opt_coords);
var size = bot.action.getInteractableSize(element);
var offsetVec = new goog.math.Vec2(
Math.min(center.x, size.width - center.x),
Math.min(center.y, size.height - center.y));
var touchScreen = opt_touchscreen || new bot.Touchscreen();
transformStart(offsetVec);
var start1 = goog.math.Vec2.sum(center, offsetVec);
var start2 = goog.math.Vec2.difference(center, offsetVec);
touchScreen.move(element, start1, start2);
touchScreen.press(/*Two Finger Press*/ true);
var initRect = bot.dom.getClientRect(element);
transformHalf(offsetVec);
var mid1 = goog.math.Vec2.sum(center, offsetVec);
var mid2 = goog.math.Vec2.difference(center, offsetVec);
touchScreen.move(element, mid1, mid2);
var midRect = bot.dom.getClientRect(element);
var movedVec = goog.math.Vec2.difference(
new goog.math.Vec2(midRect.left, midRect.top),
new goog.math.Vec2(initRect.left, initRect.top));
transformHalf(offsetVec);
var end1 = goog.math.Vec2.sum(center, offsetVec).subtract(movedVec);
var end2 = goog.math.Vec2.difference(center, offsetVec).subtract(movedVec);
touchScreen.move(element, end1, end2);
touchScreen.release();
};
/**
* Prepares to interact with the given {@code element}. It checks if the the
* element is shown, scrolls the element into view, and returns the coordinates
* of the interaction, which if not provided, is the center of the element.
*
* @param {!Element} element The element to be interacted with.
* @param {goog.math.Coordinate=} opt_coords Position relative to the target.
* @return {!goog.math.Vec2} Coordinates at the center of the interaction.
* @throws {bot.Error} If the element cannot be interacted with.
* @private
*/
bot.action.prepareToInteractWith_ = function(element, opt_coords) {
bot.action.checkShown_(element);
bot.action.scrollIntoView(element, opt_coords || undefined);
// NOTE: Ideally, we would check that any provided coordinates fall
// within the bounds of the element, but this has proven difficult, because:
// (1) Browsers sometimes lie about the true size of elements, e.g. when text
// overflows the bounding box of an element, browsers report the size of the
// box even though the true area that can be interacted with is larger; and
// (2) Elements with children styled as position:absolute will often not have
// a bounding box that surrounds all of their children, but it is useful for
// the user to be able to interact with this parent element as if it does.
if (opt_coords) {
return goog.math.Vec2.fromCoordinate(opt_coords);
} else {
var size = bot.action.getInteractableSize(element);
return new goog.math.Vec2(size.width / 2, size.height / 2);
}
};
/**
* Returns the interactable size of an element.
*
* @param {!Element} elem Element.
* @return {!goog.math.Size} size Size of the element.
*/
bot.action.getInteractableSize = function(elem) {
var size = goog.style.getSize(elem);
return ((size.width > 0 && size.height > 0) || !elem.offsetParent) ? size :
bot.action.getInteractableSize(elem.offsetParent);
};
/**
* A Device that is intended to allows access to protected members of the
* Device superclass. A singleton.
*
* @constructor
* @extends {bot.Device}
* @private
*/
bot.action.LegacyDevice_ = function() {
goog.base(this);
};
goog.inherits(bot.action.LegacyDevice_, bot.Device);
goog.addSingletonGetter(bot.action.LegacyDevice_);
/**
* Focuses on the given element. See {@link bot.device.focusOnElement}.
* @param {!Element} element The element to focus on.
* @return {boolean} True if element.focus() was called on the element.
*/
bot.action.LegacyDevice_.focusOnElement = function(element) {
var instance = bot.action.LegacyDevice_.getInstance();
instance.setElement(element);
return instance.focusOnElement();
};
/**
* Submit the form for the element. See {@link bot.device.submit}.
* @param {!Element} element The element to submit a form on.
* @param {!Element} form The form to submit.
*/
bot.action.LegacyDevice_.submitForm = function(element, form) {
var instance = bot.action.LegacyDevice_.getInstance();
instance.setElement(element);
instance.submitForm(form);
};
/**
* Find FORM element that is an ancestor of the passed in element. See
* {@link bot.device.findAncestorForm}.
* @param {!Element} element The element to find an ancestor form.
* @return {Element} form The ancestor form, or null if none.
*/
bot.action.LegacyDevice_.findAncestorForm = function(element) {
return bot.Device.findAncestorForm(element);
};
/**
* Scrolls the given {@code element} in to the current viewport. Aims to do the
* minimum scrolling necessary, but prefers too much scrolling to too little.
*
* If an optional coordinate or rectangle region is provided, scrolls that
* region relative to the element into view. A coordinate is treated as a 1x1
* region whose top-left corner is positioned at that coordinate.
*
* @param {!Element} element The element to scroll in to view.
* @param {!(goog.math.Coordinate|goog.math.Rect)=} opt_region
* Region relative to the top-left corner of the element.
* @return {boolean} Whether the element is in view after scrolling.
*/
bot.action.scrollIntoView = function(element, opt_region) {
// If the element is already in view, return true; if hidden, return false.
var overflow = bot.dom.getOverflowState(element, opt_region);
if (overflow != bot.dom.OverflowState.SCROLL) {
return overflow == bot.dom.OverflowState.NONE;
}
// Some elements may not have a scrollIntoView function - for example,
// elements under an SVG element. Call those only if they exist.
if (element.scrollIntoView) {
element.scrollIntoView();
if (bot.dom.OverflowState.NONE ==
bot.dom.getOverflowState(element, opt_region)) {
return true;
}
}
// There may have not been a scrollIntoView function, or the specified
// coordinate may not be in view, so scroll "manually".
var region = bot.dom.getClientRegion(element, opt_region);
for (var container = bot.dom.getParentElement(element);
container;
container = bot.dom.getParentElement(container)) {
scrollClientRegionIntoContainerView(container);
}
return bot.dom.OverflowState.NONE ==
bot.dom.getOverflowState(element, opt_region);
function scrollClientRegionIntoContainerView(container) {
// Based largely from goog.style.scrollIntoContainerView.
var containerRect = bot.dom.getClientRect(container);
var containerBorder = goog.style.getBorderBox(container);
// Relative position of the region to the container's content box.
var relX = region.left - containerRect.left - containerBorder.left;
var relY = region.top - containerRect.top - containerBorder.top;
// How much the region can move in the container. Use the container's
// clientWidth/Height, not containerRect, to account for the scrollbar.
var spaceX = container.clientWidth + region.left - region.right;
var spaceY = container.clientHeight + region.top - region.bottom;
// Scroll the element into view of the container.
container.scrollLeft += Math.min(relX, Math.max(relX - spaceX, 0));
container.scrollTop += Math.min(relY, Math.max(relY - spaceY, 0));
}
};
| apache-2.0 |
puramshetty/sakai | sitestats/sitestats-tool/src/java/org/sakaiproject/sitestats/tool/wicket/pages/BasePage.java | 3660 | /**
* $URL$
* $Id$
*
* Copyright (c) 2006-2009 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 org.sakaiproject.sitestats.tool.wicket.pages;
import javax.servlet.http.HttpServletRequest;
import org.apache.wicket.Component;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.markup.html.IHeaderContributor;
import org.apache.wicket.markup.head.IHeaderResponse;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.TransparentWebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.markup.head.CssHeaderItem;
import org.apache.wicket.markup.head.JavaScriptHeaderItem;
import org.apache.wicket.markup.head.OnLoadHeaderItem;
import org.apache.wicket.markup.head.StringHeaderItem;
import org.apache.wicket.devutils.debugbar.DebugBar;
import org.sakaiproject.sitestats.api.StatsManager;
import org.sakaiproject.util.ResourceLoader;
public class BasePage extends WebPage implements IHeaderContributor {
private static final long serialVersionUID = 1L;
public static final String COMMONSCRIPT = StatsManager.SITESTATS_WEBAPP+"/script/common.js";
public static final String JQUERYSCRIPT = "/library/js/jquery/jquery-1.9.1.min.js";
public static final String BODY_ONLOAD_ADDTL = "setMainFrameHeightNoScroll(window.name, 0, 400)";
public static final String LAST_PAGE = "lastSiteStatsPage";
public BasePage(){
// Set Sakai Locale
ResourceLoader rl = new ResourceLoader();
getSession().setLocale(rl.getLocale());
TransparentWebMarkupContainer html = new TransparentWebMarkupContainer("html");
String locale = getSession().getLocale().toString();
html.add(AttributeModifier.replace("lang", locale));
html.add(AttributeModifier.replace("xml:lang", locale));
add(html);
add(new DebugBar("debug"));
}
@Override
public void renderHead(IHeaderResponse response) {
//get the Sakai skin header fragment from the request attribute
HttpServletRequest request = (HttpServletRequest) getRequest().getContainerRequest();
response.render(StringHeaderItem.forString(request.getAttribute("sakai.html.head").toString()));
response.render(OnLoadHeaderItem.forScript(BODY_ONLOAD_ADDTL));
response.render(JavaScriptHeaderItem.forUrl(COMMONSCRIPT));
// include (this) tool style (CSS)
response.render(CssHeaderItem.forUrl(StatsManager.SITESTATS_WEBAPP+"/css/sitestats.css"));
}
@Override
protected void onBeforeRender() {
/** Component used for debugging pagemaps
// WARNING: produce unexpected results - use only for debugging!
PageView componentTree = new PageView("componentTree", this);
add(componentTree);
*/
super.onBeforeRender();
}
protected Label newResourceLabel(String id, Component component) {
return new Label(id, new StringResourceModel(id, component, null));
}
public String getResourceModel(String resourceKey, IModel model) {
return new StringResourceModel(resourceKey, this, model).getString();
}
}
| apache-2.0 |
dpursehouse/elasticsearch | core/src/main/java/org/elasticsearch/cluster/metadata/MetaDataUpdateSettingsService.java | 18750 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch 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.
*/
package org.elasticsearch.cluster.metadata;
import org.elasticsearch.ExceptionsHelper;
import org.elasticsearch.Version;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsClusterStateUpdateRequest;
import org.elasticsearch.action.admin.indices.upgrade.post.UpgradeSettingsClusterStateUpdateRequest;
import org.elasticsearch.cluster.AckedClusterStateUpdateTask;
import org.elasticsearch.cluster.ClusterChangedEvent;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.ClusterStateListener;
import org.elasticsearch.cluster.ack.ClusterStateUpdateResponse;
import org.elasticsearch.cluster.block.ClusterBlock;
import org.elasticsearch.cluster.block.ClusterBlocks;
import org.elasticsearch.cluster.routing.RoutingTable;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.Priority;
import org.elasticsearch.common.collect.Tuple;
import org.elasticsearch.common.component.AbstractComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.IndexScopedSettings;
import org.elasticsearch.common.settings.Setting;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.NodeServicesProvider;
import org.elasticsearch.indices.IndicesService;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/**
* Service responsible for submitting update index settings requests
*/
public class MetaDataUpdateSettingsService extends AbstractComponent implements ClusterStateListener {
private final ClusterService clusterService;
private final AllocationService allocationService;
private final IndexScopedSettings indexScopedSettings;
private final IndicesService indicesService;
private final NodeServicesProvider nodeServiceProvider;
@Inject
public MetaDataUpdateSettingsService(Settings settings, ClusterService clusterService, AllocationService allocationService,
IndexScopedSettings indexScopedSettings, IndicesService indicesService, NodeServicesProvider nodeServicesProvider) {
super(settings);
this.clusterService = clusterService;
this.clusterService.add(this);
this.allocationService = allocationService;
this.indexScopedSettings = indexScopedSettings;
this.indicesService = indicesService;
this.nodeServiceProvider = nodeServicesProvider;
}
@Override
public void clusterChanged(ClusterChangedEvent event) {
// update an index with number of replicas based on data nodes if possible
if (!event.state().nodes().isLocalNodeElectedMaster()) {
return;
}
// we will want to know this for translating "all" to a number
final int dataNodeCount = event.state().nodes().getDataNodes().size();
Map<Integer, List<Index>> nrReplicasChanged = new HashMap<>();
// we need to do this each time in case it was changed by update settings
for (final IndexMetaData indexMetaData : event.state().metaData()) {
AutoExpandReplicas autoExpandReplicas = IndexMetaData.INDEX_AUTO_EXPAND_REPLICAS_SETTING.get(indexMetaData.getSettings());
if (autoExpandReplicas.isEnabled()) {
/*
* we have to expand the number of replicas for this index to at least min and at most max nodes here
* so we are bumping it up if we have to or reduce it depending on min/max and the number of datanodes.
* If we change the number of replicas we just let the shard allocator do it's thing once we updated it
* since it goes through the index metadata to figure out if something needs to be done anyway. Do do that
* we issue a cluster settings update command below and kicks off a reroute.
*/
final int min = autoExpandReplicas.getMinReplicas();
final int max = autoExpandReplicas.getMaxReplicas(dataNodeCount);
int numberOfReplicas = dataNodeCount - 1;
if (numberOfReplicas < min) {
numberOfReplicas = min;
} else if (numberOfReplicas > max) {
numberOfReplicas = max;
}
// same value, nothing to do there
if (numberOfReplicas == indexMetaData.getNumberOfReplicas()) {
continue;
}
if (numberOfReplicas >= min && numberOfReplicas <= max) {
if (!nrReplicasChanged.containsKey(numberOfReplicas)) {
nrReplicasChanged.put(numberOfReplicas, new ArrayList<>());
}
nrReplicasChanged.get(numberOfReplicas).add(indexMetaData.getIndex());
}
}
}
if (nrReplicasChanged.size() > 0) {
// update settings and kick of a reroute (implicit) for them to take effect
for (final Integer fNumberOfReplicas : nrReplicasChanged.keySet()) {
Settings settings = Settings.builder().put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, fNumberOfReplicas).build();
final List<Index> indices = nrReplicasChanged.get(fNumberOfReplicas);
UpdateSettingsClusterStateUpdateRequest updateRequest = new UpdateSettingsClusterStateUpdateRequest()
.indices(indices.toArray(new Index[indices.size()])).settings(settings)
.ackTimeout(TimeValue.timeValueMillis(0)) //no need to wait for ack here
.masterNodeTimeout(TimeValue.timeValueMinutes(10));
updateSettings(updateRequest, new ActionListener<ClusterStateUpdateResponse>() {
@Override
public void onResponse(ClusterStateUpdateResponse response) {
for (Index index : indices) {
logger.info("{} auto expanded replicas to [{}]", index, fNumberOfReplicas);
}
}
@Override
public void onFailure(Exception t) {
for (Index index : indices) {
logger.warn("{} fail to auto expand replicas to [{}]", index, fNumberOfReplicas);
}
}
});
}
}
}
public void updateSettings(final UpdateSettingsClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener) {
final Settings normalizedSettings = Settings.builder().put(request.settings()).normalizePrefix(IndexMetaData.INDEX_SETTING_PREFIX).build();
Settings.Builder settingsForClosedIndices = Settings.builder();
Settings.Builder settingsForOpenIndices = Settings.builder();
Settings.Builder skipppedSettings = Settings.builder();
indexScopedSettings.validate(normalizedSettings);
// never allow to change the number of shards
for (Map.Entry<String, String> entry : normalizedSettings.getAsMap().entrySet()) {
if (entry.getKey().equals(IndexMetaData.SETTING_NUMBER_OF_SHARDS)) {
listener.onFailure(new IllegalArgumentException("can't change the number of shards for an index"));
return;
}
Setting setting = indexScopedSettings.get(entry.getKey());
assert setting != null; // we already validated the normalized settings
settingsForClosedIndices.put(entry.getKey(), entry.getValue());
if (setting.isDynamic()) {
settingsForOpenIndices.put(entry.getKey(), entry.getValue());
} else {
skipppedSettings.put(entry.getKey(), entry.getValue());
}
}
final Settings skippedSettigns = skipppedSettings.build();
final Settings closedSettings = settingsForClosedIndices.build();
final Settings openSettings = settingsForOpenIndices.build();
final boolean preserveExisting = request.isPreserveExisting();
clusterService.submitStateUpdateTask("update-settings",
new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(Priority.URGENT, request, listener) {
@Override
protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
return new ClusterStateUpdateResponse(acknowledged);
}
@Override
public ClusterState execute(ClusterState currentState) {
RoutingTable.Builder routingTableBuilder = RoutingTable.builder(currentState.routingTable());
MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData());
// allow to change any settings to a close index, and only allow dynamic settings to be changed
// on an open index
Set<Index> openIndices = new HashSet<>();
Set<Index> closeIndices = new HashSet<>();
final String[] actualIndices = new String[request.indices().length];
for (int i = 0; i < request.indices().length; i++) {
Index index = request.indices()[i];
actualIndices[i] = index.getName();
final IndexMetaData metaData = currentState.metaData().getIndexSafe(index);
if (metaData.getState() == IndexMetaData.State.OPEN) {
openIndices.add(index);
} else {
closeIndices.add(index);
}
}
if (closeIndices.size() > 0 && closedSettings.get(IndexMetaData.SETTING_NUMBER_OF_REPLICAS) != null) {
throw new IllegalArgumentException(String.format(Locale.ROOT,
"Can't update [%s] on closed indices %s - can leave index in an unopenable state", IndexMetaData.SETTING_NUMBER_OF_REPLICAS,
closeIndices
));
}
if (!skippedSettigns.getAsMap().isEmpty() && !openIndices.isEmpty()) {
throw new IllegalArgumentException(String.format(Locale.ROOT,
"Can't update non dynamic settings [%s] for open indices %s",
skippedSettigns.getAsMap().keySet(),
openIndices
));
}
int updatedNumberOfReplicas = openSettings.getAsInt(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, -1);
if (updatedNumberOfReplicas != -1 && preserveExisting == false) {
routingTableBuilder.updateNumberOfReplicas(updatedNumberOfReplicas, actualIndices);
metaDataBuilder.updateNumberOfReplicas(updatedNumberOfReplicas, actualIndices);
logger.info("updating number_of_replicas to [{}] for indices {}", updatedNumberOfReplicas, actualIndices);
}
ClusterBlocks.Builder blocks = ClusterBlocks.builder().blocks(currentState.blocks());
maybeUpdateClusterBlock(actualIndices, blocks, IndexMetaData.INDEX_READ_ONLY_BLOCK, IndexMetaData.INDEX_READ_ONLY_SETTING, openSettings);
maybeUpdateClusterBlock(actualIndices, blocks, IndexMetaData.INDEX_METADATA_BLOCK, IndexMetaData.INDEX_BLOCKS_METADATA_SETTING, openSettings);
maybeUpdateClusterBlock(actualIndices, blocks, IndexMetaData.INDEX_WRITE_BLOCK, IndexMetaData.INDEX_BLOCKS_WRITE_SETTING, openSettings);
maybeUpdateClusterBlock(actualIndices, blocks, IndexMetaData.INDEX_READ_BLOCK, IndexMetaData.INDEX_BLOCKS_READ_SETTING, openSettings);
if (!openIndices.isEmpty()) {
for (Index index : openIndices) {
IndexMetaData indexMetaData = metaDataBuilder.getSafe(index);
Settings.Builder updates = Settings.builder();
Settings.Builder indexSettings = Settings.builder().put(indexMetaData.getSettings());
if (indexScopedSettings.updateDynamicSettings(openSettings, indexSettings, updates, index.getName())) {
if (preserveExisting) {
indexSettings.put(indexMetaData.getSettings());
}
metaDataBuilder.put(IndexMetaData.builder(indexMetaData).settings(indexSettings));
}
}
}
if (!closeIndices.isEmpty()) {
for (Index index : closeIndices) {
IndexMetaData indexMetaData = metaDataBuilder.getSafe(index);
Settings.Builder updates = Settings.builder();
Settings.Builder indexSettings = Settings.builder().put(indexMetaData.getSettings());
if (indexScopedSettings.updateSettings(closedSettings, indexSettings, updates, index.getName())) {
if (preserveExisting) {
indexSettings.put(indexMetaData.getSettings());
}
metaDataBuilder.put(IndexMetaData.builder(indexMetaData).settings(indexSettings));
}
}
}
ClusterState updatedState = ClusterState.builder(currentState).metaData(metaDataBuilder).routingTable(routingTableBuilder.build()).blocks(blocks).build();
// now, reroute in case things change that require it (like number of replicas)
RoutingAllocation.Result routingResult = allocationService.reroute(updatedState, "settings update");
updatedState = ClusterState.builder(updatedState).routingResult(routingResult).build();
try {
for (Index index : openIndices) {
final IndexMetaData currentMetaData = currentState.getMetaData().getIndexSafe(index);
final IndexMetaData updatedMetaData = updatedState.metaData().getIndexSafe(index);
indicesService.verifyIndexMetadata(nodeServiceProvider, currentMetaData, updatedMetaData);
}
for (Index index : closeIndices) {
final IndexMetaData currentMetaData = currentState.getMetaData().getIndexSafe(index);
final IndexMetaData updatedMetaData = updatedState.metaData().getIndexSafe(index);
indicesService.verifyIndexMetadata(nodeServiceProvider, currentMetaData, updatedMetaData);
}
} catch (IOException ex) {
throw ExceptionsHelper.convertToElastic(ex);
}
return updatedState;
}
});
}
/**
* Updates the cluster block only iff the setting exists in the given settings
*/
private static void maybeUpdateClusterBlock(String[] actualIndices, ClusterBlocks.Builder blocks, ClusterBlock block, Setting<Boolean> setting, Settings openSettings) {
if (setting.exists(openSettings)) {
final boolean updateReadBlock = setting.get(openSettings);
for (String index : actualIndices) {
if (updateReadBlock) {
blocks.addIndexBlock(index, block);
} else {
blocks.removeIndexBlock(index, block);
}
}
}
}
public void upgradeIndexSettings(final UpgradeSettingsClusterStateUpdateRequest request, final ActionListener<ClusterStateUpdateResponse> listener) {
clusterService.submitStateUpdateTask("update-index-compatibility-versions", new AckedClusterStateUpdateTask<ClusterStateUpdateResponse>(Priority.URGENT, request, listener) {
@Override
protected ClusterStateUpdateResponse newResponse(boolean acknowledged) {
return new ClusterStateUpdateResponse(acknowledged);
}
@Override
public ClusterState execute(ClusterState currentState) {
MetaData.Builder metaDataBuilder = MetaData.builder(currentState.metaData());
for (Map.Entry<String, Tuple<Version, String>> entry : request.versions().entrySet()) {
String index = entry.getKey();
IndexMetaData indexMetaData = metaDataBuilder.get(index);
if (indexMetaData != null) {
if (Version.CURRENT.equals(indexMetaData.getCreationVersion()) == false) {
// No reason to pollute the settings, we didn't really upgrade anything
metaDataBuilder.put(IndexMetaData.builder(indexMetaData)
.settings(Settings.builder().put(indexMetaData.getSettings())
.put(IndexMetaData.SETTING_VERSION_MINIMUM_COMPATIBLE, entry.getValue().v2())
.put(IndexMetaData.SETTING_VERSION_UPGRADED, entry.getValue().v1())
)
);
}
}
}
return ClusterState.builder(currentState).metaData(metaDataBuilder).build();
}
});
}
}
| apache-2.0 |
liqin75/vse-vpnaas-plugin | quantum/tests/unit/test_auth.py | 4693 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2012 OpenStack Foundation
# 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.
import webob
from quantum import auth
from quantum.tests import base
class QuantumKeystoneContextTestCase(base.BaseTestCase):
def setUp(self):
super(QuantumKeystoneContextTestCase, self).setUp()
@webob.dec.wsgify
def fake_app(req):
self.context = req.environ['quantum.context']
return webob.Response()
self.context = None
self.middleware = auth.QuantumKeystoneContext(fake_app)
self.request = webob.Request.blank('/')
self.request.headers['X_AUTH_TOKEN'] = 'testauthtoken'
def test_no_user_no_user_id(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '401 Unauthorized')
def test_with_user(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_USER_ID'] = 'testuserid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuserid')
def test_with_user_id(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuser')
def test_user_id_trumps_user(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_USER'] = 'testuser'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.user_id, 'testuserid')
def test_with_tenant_id(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_USER_ID'] = 'test_user_id'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.tenant_id, 'testtenantid')
def test_with_tenant(self):
self.request.headers['X_TENANT'] = 'testtenant'
self.request.headers['X_USER_ID'] = 'test_user_id'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.tenant_id, 'testtenant')
def test_tenant_id_trumps_tenant(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_TENANT'] = 'testtenant'
self.request.headers['X_USER_ID'] = 'testuserid'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.tenant_id, 'testtenantid')
def test_roles_no_admin(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_ROLE'] = 'role1, role2 , role3,role4,role5'
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.roles, ['role1', 'role2', 'role3',
'role4', 'role5'])
self.assertEqual(self.context.is_admin, False)
def test_roles_with_admin(self):
self.request.headers['X_TENANT_ID'] = 'testtenantid'
self.request.headers['X_USER_ID'] = 'testuserid'
self.request.headers['X_ROLE'] = ('role1, role2 , role3,role4,role5,'
'AdMiN')
response = self.request.get_response(self.middleware)
self.assertEqual(response.status, '200 OK')
self.assertEqual(self.context.roles, ['role1', 'role2', 'role3',
'role4', 'role5', 'AdMiN'])
self.assertEqual(self.context.is_admin, True)
| apache-2.0 |