code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
define('lodash/object/get', ['exports', 'lodash/internal/baseGet', 'lodash/internal/toPath'], function (exports, _lodashInternalBaseGet, _lodashInternalToPath) {
'use strict';
/**
* Gets the property value at `path` of `object`. If the resolved value is
* `undefined` the `defaultValue` is used in its place.
*
* @static
* @memberOf _
* @category Object
* @param {Object} object The object to query.
* @param {Array|string} path The path of the property to get.
* @param {*} [defaultValue] The value returned if the resolved value is `undefined`.
* @returns {*} Returns the resolved value.
* @example
*
* var object = { 'a': [{ 'b': { 'c': 3 } }] };
*
* _.get(object, 'a[0].b.c');
* // => 3
*
* _.get(object, ['a', '0', 'b', 'c']);
* // => 3
*
* _.get(object, 'a.b.c', 'default');
* // => 'default'
*/
function get(object, path, defaultValue) {
var result = object == null ? undefined : (0, _lodashInternalBaseGet['default'])(object, (0, _lodashInternalToPath['default'])(path), path + '');
return result === undefined ? defaultValue : result;
}
exports['default'] = get;
}); | hoka-plus/p-01-web | tmp/babel-output_path-hOv4KMmE.tmp/lodash/object/get.js | JavaScript | mit | 1,164 |
var env = process.env.ISUCON_ENV || "local"
module.exports = require("./../config/" + env);
| isucon/isucon3 | final/webapp/nodejs/config.js | JavaScript | mit | 92 |
<?php
/**
* This file is part of CodeIgniter 4 framework.
*
* (c) CodeIgniter Foundation <admin@codeigniter.com>
*
* For the full copyright and license information, please view
* the LICENSE file that was distributed with this source code.
*/
namespace CodeIgniter\Test\Interfaces;
use Faker\Generator;
use ReflectionException;
/**
* FabricatorModel
*
* An interface defining the required methods and properties
* needed for a model to qualify for use with the Fabricator class.
* While interfaces cannot enforce properties, the following
* are required for use with Fabricator:
*
* @property string $returnType
* @property string $primaryKey
* @property string $dateFormat
*/
interface FabricatorModel
{
/**
* Fetches the row of database from $this->table with a primary key
* matching $id.
*
* @param array|mixed|null $id One primary key or an array of primary keys
*
* @return array|object|null The resulting row of data, or null.
*/
public function find($id = null);
/**
* Inserts data into the current table. If an object is provided,
* it will attempt to convert it to an array.
*
* @param array|object $data
* @param bool $returnID Whether insert ID should be returned or not.
*
* @throws ReflectionException
*
* @return bool|int|string
*/
public function insert($data = null, bool $returnID = true);
/**
* The following properties and methods are optional, but if present should
* adhere to their definitions.
*
* @property array $allowedFields
* @property string $useSoftDeletes
* @property string $useTimestamps
* @property string $createdField
* @property string $updatedField
* @property string $deletedField
*/
/*
* Sets $useSoftDeletes value so that we can temporarily override
* the softdeletes settings. Can be used for all find* methods.
*
* @param boolean $val
*
* @return Model
*/
// public function withDeleted($val = true);
/**
* Faked data for Fabricator.
*
* @param Generator $faker
*
* @return array|object
*/
// public function fake(Generator &$faker);
}
| bcit-ci/CodeIgniter4 | system/Test/Interfaces/FabricatorModel.php | PHP | mit | 2,251 |
/* ====================================================================
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.poi.poifs.storage;
import java.io.IOException;
/**
* An interface for blocks managed by a list that works with a
* BlockAllocationTable to keep block sequences straight
*
* @author Marc Johnson (mjohnson at apache dot org
*/
public interface ListManagedBlock
{
/**
* Get the data from the block
*
* @return the block's data as a byte array
*
* @exception IOException if there is no data
*/
public byte [] getData()
throws IOException;
} // end public interface ListManagedBlock
| tobyclemson/msci-project | vendor/poi-3.6/src/java/org/apache/poi/poifs/storage/ListManagedBlock.java | Java | mit | 1,502 |
CfContainersBroker::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static asset server for tests with Cache-Control for performance.
config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
# config.action_mailer.delivery_method = :test
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
end
| dynatrace-innovationlab/easyTravel-Cloud-Foundry | deploy/config/cf-containers-broker/environments/test.rb | Ruby | mit | 1,573 |
var originalLookup, App, originalModelInjections;
module("Ember.Application Dependency Injection – toString",{
setup: function() {
originalModelInjections = Ember.MODEL_FACTORY_INJECTIONS;
Ember.MODEL_FACTORY_INJECTIONS = true;
originalLookup = Ember.lookup;
Ember.run(function(){
App = Ember.Application.create();
Ember.lookup = {
App: App
};
});
App.Post = Ember.Object.extend();
},
teardown: function() {
Ember.lookup = originalLookup;
Ember.run(App, 'destroy');
Ember.MODEL_FACTORY_INJECTIONS = originalModelInjections;
}
});
test("factories", function() {
var PostFactory = App.__container__.lookupFactory('model:post');
equal(PostFactory.toString(), 'App.Post', 'expecting the model to be post');
});
test("instances", function() {
var post = App.__container__.lookup('model:post');
var guid = Ember.guidFor(post);
equal(post.toString(), '<App.Post:' + guid + '>', 'expecting the model to be post');
});
test("with a custom resolver", function() {
Ember.run(App,'destroy');
Ember.run(function(){
App = Ember.Application.create({
Resolver: Ember.DefaultResolver.extend({
makeToString: function(factory, fullName) {
return fullName;
}
})
});
});
App.__container__.register('model:peter', Ember.Object.extend());
var peter = App.__container__.lookup('model:peter');
var guid = Ember.guidFor(peter);
equal(peter.toString(), '<model:peter:' + guid + '>', 'expecting the supermodel to be peter');
});
| ssured/ember.js | packages/ember-application/tests/system/dependency_injection/to_string_test.js | JavaScript | mit | 1,557 |
#!/usr/bin/env python
# *-* coding: UTF-8 *-*
"""Împăratul a primit serie de mesaje importante pe care este
important să le descifreze cât mai repede.
Din păcate mesagerul nu a apucat să îi spună împăratul care au fost
cheile alese pentru fiecare mesaj și tu ai fost ales să descifrezi
misterul.
Informații:
În criptografie, cifrul lui Caesar este o metodă simplă de a cripta
un mesaj prin înlocuirea fiecărei litere cu litera de pe poziția aflată
la un n pași de ea în alfabet (unde este n este un număr întreg cunoscut
"""
# existau 2 variante de a rezolva problema cu parantezele la print
# am preferat sa o folosesc pe asta pentru a evita si eventualele probleme
# cu care ziceai tu ca o sa ne stresezi ;)
from __future__ import print_function
LETTERS = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
# tot timpul se va gasi litera in string-ul "LETTERS"
# deci circularitatea e suficient
# reprezentata prin a-z de doua ori
def shift_letter(let, number):
"""Shifts a letter by number places in LETTERS"""
if let.isalpha():
# procesam doar literele
return LETTERS[ord(let) - 97 + number]
# returnam litera de peste n locuri in LETTERS
else:
return let
# daca nu e litera, returnam caracterul original
def decripteaza(mesaj, number):
"""Decrypts every line in <mesaj>"""
new_msg = ""
for char in mesaj:
new_msg += shift_letter(char, number)
if "ave" in new_msg:
print(new_msg)
def main():
"""Have a main docstring, pylint"""
try:
fisier = open("mesaje.secret", "r")
mesaje = fisier.read()
fisier.close()
except IOError:
print("Nu am putut obține mesajele.")
return
for mesaj in mesaje.splitlines():
for i in range(26):
decripteaza(mesaj, i)
if __name__ == "__main__":
main()
| iulianbute/labs | python/solutii/alex_mitan/caesar.py | Python | mit | 1,892 |
class Capybara::RackTest::Form < Capybara::RackTest::Node
# This only needs to inherit from Rack::Test::UploadedFile because Rack::Test checks for
# the class specifically when determing whether to consturct the request as multipart.
# That check should be based solely on the form element's 'enctype' attribute value,
# which should probably be provided to Rack::Test in its non-GET request methods.
class NilUploadedFile < Rack::Test::UploadedFile
def initialize
@empty_file = Tempfile.new("nil_uploaded_file")
@empty_file.close
end
def original_filename; ""; end
def content_type; "application/octet-stream"; end
def path; @empty_file.path; end
end
def params(button)
params = {}
native.xpath("(.//input|.//select|.//textarea)[not(@disabled)]").map do |field|
case field.name
when 'input'
if %w(radio checkbox).include? field['type']
merge_param!(params, field['name'].to_s, field['value'].to_s) if field['checked']
elsif %w(submit image).include? field['type']
# TO DO identify the click button here (in document order, rather
# than leaving until the end of the params)
elsif field['type'] =='file'
if multipart?
file = \
if (value = field['value']).to_s.empty?
NilUploadedFile.new
else
content_type = MIME::Types.type_for(value).first.to_s
Rack::Test::UploadedFile.new(value, content_type)
end
merge_param!(params, field['name'].to_s, file)
else
merge_param!(params, field['name'].to_s, File.basename(field['value'].to_s))
end
else
merge_param!(params, field['name'].to_s, field['value'].to_s)
end
when 'select'
if field['multiple'] == 'multiple'
options = field.xpath(".//option[@selected]")
options.each do |option|
merge_param!(params, field['name'].to_s, (option['value'] || option.text).to_s)
end
else
option = field.xpath(".//option[@selected]").first
option ||= field.xpath('.//option').first
merge_param!(params, field['name'].to_s, (option['value'] || option.text).to_s) if option
end
when 'textarea'
merge_param!(params, field['name'].to_s, field.text.to_s)
end
end
merge_param!(params, button[:name], button[:value] || "") if button[:name]
params
end
def submit(button)
driver.submit(method, native['action'].to_s, params(button))
end
def multipart?
self[:enctype] == "multipart/form-data"
end
private
def method
self[:method] =~ /post/i ? :post : :get
end
def merge_param!(params, key, value)
Rack::Utils.normalize_params(params, key, value)
end
end
| Jarob22/sc2_app_fyp_backend | vendor/bundle/ruby/1.9.1/gems/capybara-1.1.2/lib/capybara/rack_test/form.rb | Ruby | mit | 2,846 |
import React, { cloneElement } from 'react';
import classNames from 'classnames';
import ValidComponentChildren from './utils/ValidComponentChildren';
class ListGroup extends React.Component {
render() {
let items = ValidComponentChildren.map(
this.props.children,
(item, index) => cloneElement(item, { key: item.key ? item.key : index })
);
let shouldRenderDiv = false;
if (!this.props.children) {
shouldRenderDiv = true;
} else {
React.Children.forEach(this.props.children, (child) => {
if (this.isAnchorOrButton(child.props)) {
shouldRenderDiv = true;
}
});
}
if (shouldRenderDiv) {
return this.renderDiv(items);
} else {
return this.renderUL(items);
}
}
isAnchorOrButton(props) {
return (props.href || props.onClick);
}
renderUL(items) {
let listItems = ValidComponentChildren.map(items,
(item) => cloneElement(item, { listItem: true })
);
return (
<ul
{...this.props}
className={classNames(this.props.className, 'list-group')}>
{listItems}
</ul>
);
}
renderDiv(items) {
return (
<div
{...this.props}
className={classNames(this.props.className, 'list-group')}>
{items}
</div>
);
}
}
ListGroup.propTypes = {
className: React.PropTypes.string,
id: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
};
export default ListGroup;
| jontewks/react-bootstrap | src/ListGroup.js | JavaScript | mit | 1,507 |
<?php
/**
* Copyright © 2013-2017 Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
$objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager();
/** @var \Magento\Framework\Registry $registry */
$registry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\Framework\Registry');
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', true);
/** @var \Magento\Catalog\Api\ProductRepositoryInterface $productRepository */
$productRepository = $objectManager->create('Magento\Catalog\Api\ProductRepositoryInterface');
try {
$firstProduct = $productRepository->get('simple', false, null, true);
$productRepository->delete($firstProduct);
} catch (\Magento\Framework\Exception\NoSuchEntityException $exception) {
//Product already removed
}
try {
$secondProduct = $productRepository->get('simple_with_cross', false, null, true);
$productRepository->delete($secondProduct);
} catch (\Magento\Framework\Exception\NoSuchEntityException $exception) {
//Product already removed
}
$registry->unregister('isSecureArea');
$registry->register('isSecureArea', false);
| j-froehlich/magento2_wk | vendor/magento/magento2-base/dev/tests/integration/testsuite/Magento/Catalog/_files/products_related_rollback.php | PHP | mit | 1,176 |
/*
* Copyright (c) 2009 WiQuery team
*
* 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.
*/
package org.odlabs.wiquery.ui.progressbar;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.IHeaderResponse;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.odlabs.wiquery.core.IWiQueryPlugin;
import org.odlabs.wiquery.core.javascript.JsQuery;
import org.odlabs.wiquery.core.javascript.JsStatement;
import org.odlabs.wiquery.core.options.Options;
import org.odlabs.wiquery.ui.commons.WiQueryUIPlugin;
import org.odlabs.wiquery.ui.core.JsScopeUiEvent;
import org.odlabs.wiquery.ui.options.UiOptionsRenderer;
import org.odlabs.wiquery.ui.widget.WidgetJavaScriptResourceReference;
/**
* $Id$
* <p>
* Creates a progressBar UI component from this {@link WebMarkupContainer}'s HTML markup.
* </p>
*
* @author Lionel Armanet
* @since 1.0
*/
@WiQueryUIPlugin
public class ProgressBar extends WebMarkupContainer implements IWiQueryPlugin
{
// Constants
/** Constant of serialization */
private static final long serialVersionUID = 8268721447610956664L;
// Properties
private Options options;
/**
* Builds a new progress bar.
*/
public ProgressBar(String id)
{
super(id);
this.options = new Options(this);
this.options.setRenderer(new UiOptionsRenderer("progressbar", this));
}
@Override
protected void detachModel()
{
super.detachModel();
options.detach();
}
@Override
public void renderHead(IHeaderResponse response)
{
response.renderJavaScriptReference(WidgetJavaScriptResourceReference.get());
response.renderJavaScriptReference(ProgressBarJavaScriptResourceReference.get());
}
public JsStatement statement()
{
JsStatement componentStatement = new JsQuery(this).$().chain("progressbar");
JsStatement wholeStatement = new JsStatement();
wholeStatement.append(componentStatement.render());
wholeStatement.append(options.getJavaScriptOptions());
return wholeStatement;
}
/**
* Method retrieving the options of the component
*
* @return the options
*/
protected Options getOptions()
{
return options;
}
public JsStatement update()
{
JsStatement wholeStatement = new JsStatement();
wholeStatement.append(options.getJavaScriptOptions());
return wholeStatement;
}
/*---- Options section ---*/
/**
* Disables (true) or enables (false) the progressBar. Can be set when initialising
* (first creating) the progressBar.
*
* @param disabled
* @return instance of the current behavior
*/
public ProgressBar setDisabled(boolean disabled)
{
this.options.put("disabled", disabled);
return this;
}
/**
* @return the disabled option
*/
public boolean isDisabled()
{
if (this.options.containsKey("disabled"))
{
return this.options.getBoolean("disabled");
}
return false;
}
/**
* Sets the current value of the progressBar
*
* @param value
* @return instance of the current component
*/
public ProgressBar setValue(int value)
{
this.options.put("value", value);
return this;
}
/**
* @return the current value of the progressBar
*/
public int getValue()
{
if (this.options.containsKey("value"))
{
return options.getInt("value");
}
return 0;
}
/*---- Events section ---*/
/**
* Set's the callback when the value of the progressBar changes.
*
* @param change
* @return instance of the current component
*/
public ProgressBar setChangeEvent(JsScopeUiEvent change)
{
this.options.put("change", change);
return this;
}
/*---- Methods section ---*/
/**
* Method to destroy the progressBar This will return the element back to its pre-init
* state.
*
* @return the associated JsStatement
*/
public JsStatement destroy()
{
return new JsQuery(this).$().chain("progressbar", "'destroy'");
}
/**
* Method to destroy the progressBar within the ajax request
*
* @param ajaxRequestTarget
*/
public void destroy(AjaxRequestTarget ajaxRequestTarget)
{
ajaxRequestTarget.appendJavaScript(this.destroy().render().toString());
}
/**
* Method to disable the progressBar
*
* @return the associated JsStatement
*/
public JsStatement disable()
{
return new JsQuery(this).$().chain("progressbar", "'disable'");
}
/**
* Method to disable the progressBar within the ajax request
*
* @param ajaxRequestTarget
*/
public void disable(AjaxRequestTarget ajaxRequestTarget)
{
ajaxRequestTarget.appendJavaScript(this.disable().render().toString());
}
/**
* Method to enable the progressBar
*
* @return the associated JsStatement
*/
public JsStatement enable()
{
return new JsQuery(this).$().chain("progressbar", "'enable'");
}
/**
* Method to enable the progressBar within the ajax request
*
* @param ajaxRequestTarget
*/
public void enable(AjaxRequestTarget ajaxRequestTarget)
{
ajaxRequestTarget.appendJavaScript(this.enable().render().toString());
}
/**
* Method to get the current value of the progressBar
*
* @return the associated JsStatement
*/
public JsStatement value()
{
return new JsQuery(this).$().chain("progressbar", "'value'");
}
/**
* Method to set the current value of the progressBar
*
* @param value
* @return the associated JsStatement
*/
public JsStatement value(int value)
{
return new JsQuery(this).$().chain("progressbar", "'value'", Integer.toString(value));
}
/**
* Method to set the current value of the progressBar within the ajax request
*
* @param ajaxRequestTarget
* @param value
*/
public void value(AjaxRequestTarget ajaxRequestTarget, int value)
{
ajaxRequestTarget.appendJavaScript(this.value(value).render().toString());
}
/*---- wiQuery Methods section ---*/
/**
* Method to increment the value of the progressBar
*
* @return the associated JsStatement
*/
public JsStatement increment()
{
return increment(1);
}
/**
* Method to increment the value of the progressBar
*
* @param increment
* The increment to add to the current value
* @return the associated JsStatement
*/
public JsStatement increment(int increment)
{
JsStatement statement = new JsStatement();
statement.append(new JsQuery(this)
.$()
.chain(
"progressbar",
"'value'",
new JsQuery(this).$().chain("progressbar", "'value'").render(false) + " + "
+ increment).render());
return statement;
}
/**
* Method to increment the value of the progressBar within the ajax request
*
* @param ajaxRequestTarget
*/
public void increment(AjaxRequestTarget ajaxRequestTarget)
{
ajaxRequestTarget.appendJavaScript(this.increment().render().toString());
}
/**
* Method to increment the value of the progressBar within the ajax request
*
* @param ajaxRequestTarget
* @param increment
* The increment to add to the current value
*/
public void increment(AjaxRequestTarget ajaxRequestTarget, int increment)
{
ajaxRequestTarget.appendJavaScript(this.increment(increment).render().toString());
}
/**
* Method to decrement the value of the progressBar
*
* @return the associated JsStatement
*/
public JsStatement decrement()
{
return decrement(1);
}
/**
* Method to decrement the value of the progressBar
*
* @param decrement
* The decrement to add to the current value
* @return the associated JsStatement
*/
public JsStatement decrement(int decrement)
{
JsStatement statement = new JsStatement();
statement.append(new JsQuery(this)
.$()
.chain(
"progressbar",
"'value'",
new JsQuery(this).$().chain("progressbar", "'value'").render(false) + " - "
+ decrement).render());
return statement;
}
/**
* Method to decrement the value of the progressBar within the ajax request
*
* @param ajaxRequestTarget
*/
public void decrement(AjaxRequestTarget ajaxRequestTarget)
{
ajaxRequestTarget.appendJavaScript(this.decrement().render().toString());
}
/**
* Method to decrement the value of the progressBar within the ajax request
*
* @param ajaxRequestTarget
* @param decrement
* The decrement to add to the current value
*/
public void decrement(AjaxRequestTarget ajaxRequestTarget, int decrement)
{
ajaxRequestTarget.appendJavaScript(this.decrement(decrement).render().toString());
}
/**
* Method to returns the .ui-progressbar element
*
* @return the associated JsStatement
*/
public JsStatement widget()
{
return new JsQuery(this).$().chain("progressbar", "'widget'");
}
/**
* Method to returns the .ui-progressbar element within the ajax request
*
* @param ajaxRequestTarget
*/
public void widget(AjaxRequestTarget ajaxRequestTarget)
{
ajaxRequestTarget.appendJavaScript(this.widget().render().toString());
}
}
| google-code-export/wiquery | wiquery-jquery-ui/src/main/java/org/odlabs/wiquery/ui/progressbar/ProgressBar.java | Java | mit | 9,828 |
// Copyright 2016 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package models
import (
"fmt"
"strings"
"testing"
. "github.com/smartystreets/goconvey/convey"
"github.com/gogits/gogs/pkg/setting"
)
func init() {
setting.NewContext()
}
func Test_SSHParsePublicKey(t *testing.T) {
testKeys := map[string]struct {
typeName string
length int
content string
}{
"dsa-1024": {"dsa", 1024, "ssh-dss AAAAB3NzaC1kc3MAAACBAOChCC7lf6Uo9n7BmZ6M8St19PZf4Tn59NriyboW2x/DZuYAz3ibZ2OkQ3S0SqDIa0HXSEJ1zaExQdmbO+Ux/wsytWZmCczWOVsaszBZSl90q8UnWlSH6P+/YA+RWJm5SFtuV9PtGIhyZgoNuz5kBQ7K139wuQsecdKktISwTakzAAAAFQCzKsO2JhNKlL+wwwLGOcLffoAmkwAAAIBpK7/3xvduajLBD/9vASqBQIHrgK2J+wiQnIb/Wzy0UsVmvfn8A+udRbBo+csM8xrSnlnlJnjkJS3qiM5g+eTwsLIV1IdKPEwmwB+VcP53Cw6lSyWyJcvhFb0N6s08NZysLzvj0N+ZC/FnhKTLzIyMtkHf/IrPCwlM+pV/M/96YgAAAIEAqQcGn9CKgzgPaguIZooTAOQdvBLMI5y0bQjOW6734XOpqQGf/Kra90wpoasLKZjSYKNPjE+FRUOrStLrxcNs4BeVKhy2PYTRnybfYVk1/dmKgH6P1YSRONsGKvTsH6c5IyCRG0ncCgYeF8tXppyd642982daopE7zQ/NPAnJfag= nocomment"},
"rsa-1024": {"rsa", 1024, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQDAu7tvIvX6ZHrRXuZNfkR3XLHSsuCK9Zn3X58lxBcQzuo5xZgB6vRwwm/QtJuF+zZPtY5hsQILBLmF+BZ5WpKZp1jBeSjH2G7lxet9kbcH+kIVj0tPFEoyKI9wvWqIwC4prx/WVk2wLTJjzBAhyNxfEq7C9CeiX9pQEbEqJfkKCQ== nocomment\n"},
"rsa-2048": {"rsa", 2048, "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDMZXh+1OBUwSH9D45wTaxErQIN9IoC9xl7MKJkqvTvv6O5RR9YW/IK9FbfjXgXsppYGhsCZo1hFOOsXHMnfOORqu/xMDx4yPuyvKpw4LePEcg4TDipaDFuxbWOqc/BUZRZcXu41QAWfDLrInwsltWZHSeG7hjhpacl4FrVv9V1pS6Oc5Q1NxxEzTzuNLS/8diZrTm/YAQQ/+B+mzWI3zEtF4miZjjAljWd1LTBPvU23d29DcBmmFahcZ441XZsTeAwGxG/Q6j8NgNXj9WxMeWwxXV2jeAX/EBSpZrCVlCQ1yJswT6xCp8TuBnTiGWYMBNTbOZvPC4e0WI2/yZW/s5F nocomment"},
"ecdsa-256": {"ecdsa", 256, "ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFQacN3PrOll7PXmN5B/ZNVahiUIqI05nbBlZk1KXsO3d06ktAWqbNflv2vEmA38bTFTfJ2sbn2B5ksT52cDDbA= nocomment"},
"ecdsa-384": {"ecdsa", 384, "ecdsa-sha2-nistp384 AAAAE2VjZHNhLXNoYTItbmlzdHAzODQAAAAIbmlzdHAzODQAAABhBINmioV+XRX1Fm9Qk2ehHXJ2tfVxW30ypUWZw670Zyq5GQfBAH6xjygRsJ5wWsHXBsGYgFUXIHvMKVAG1tpw7s6ax9oA+dJOJ7tj+vhn8joFqT+sg3LYHgZkHrfqryRasQ== nocomment"},
// "ecdsa-521": {"ecdsa", 521, "ecdsa-sha2-nistp521 AAAAE2VjZHNhLXNoYTItbmlzdHA1MjEAAAAIbmlzdHA1MjEAAACFBACGt3UG3EzRwNOI17QR84l6PgiAcvCE7v6aXPj/SC6UWKg4EL8vW9ZBcdYL9wzs4FZXh4MOV8jAzu3KRWNTwb4k2wFNUpGOt7l28MztFFEtH5BDDrtAJSPENPy8pvPLMfnPg5NhvWycqIBzNcHipem5wSJFN5PdpNOC2xMrPWKNqj+ZjQ== nocomment"},
}
Convey("Parse public keys in both native and ssh-keygen", t, func() {
for name, key := range testKeys {
fmt.Println("\nTesting key:", name)
keyTypeN, lengthN, errN := SSHNativeParsePublicKey(key.content)
So(errN, ShouldBeNil)
So(keyTypeN, ShouldEqual, key.typeName)
So(lengthN, ShouldEqual, key.length)
keyTypeK, lengthK, errK := SSHKeyGenParsePublicKey(key.content)
if errK != nil {
// Some server just does not support ecdsa format.
if strings.Contains(errK.Error(), "line 1 too long:") {
continue
}
So(errK, ShouldBeNil)
}
So(keyTypeK, ShouldEqual, key.typeName)
So(lengthK, ShouldEqual, key.length)
}
})
}
| xaionaro/gogs | models/ssh_key_test.go | GO | mit | 3,217 |
import get from 'ember-metal/property_get';
import { SuiteModuleBuilder } from 'ember-runtime/tests/suites/suite';
const suite = SuiteModuleBuilder.create();
suite.module('removeObject');
suite.test('should return receiver', function() {
let before = this.newFixture(3);
let obj = this.newObject(before);
equal(obj.removeObject(before[1]), obj, 'should return receiver');
});
suite.test('[A,B,C].removeObject(B) => [A,C] + notify', function() {
let before = this.newFixture(3);
let after = [before[0], before[2]];
let obj = this.newObject(before);
let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
obj.removeObject(before[1]);
deepEqual(this.toArray(obj), after, 'post item results');
equal(get(obj, 'length'), after.length, 'length');
if (observer.isEnabled) {
equal(observer.timesCalled('[]'), 1, 'should have notified [] once');
equal(observer.timesCalled('@each'), 0, 'should not have notified @each once');
equal(observer.timesCalled('length'), 1, 'should have notified length once');
equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
}
});
suite.test('[A,B,C].removeObject(D) => [A,B,C]', function() {
let before = this.newFixture(3);
let after = before;
let item = this.newFixture(1)[0];
let obj = this.newObject(before);
let observer = this.newObserver(obj, '[]', '@each', 'length', 'firstObject', 'lastObject');
obj.getProperties('firstObject', 'lastObject'); /* Prime the cache */
obj.removeObject(item); // note: item not in set
deepEqual(this.toArray(obj), after, 'post item results');
equal(get(obj, 'length'), after.length, 'length');
if (observer.isEnabled) {
equal(observer.validate('[]'), false, 'should NOT have notified []');
equal(observer.validate('@each'), false, 'should NOT have notified @each');
equal(observer.validate('length'), false, 'should NOT have notified length');
equal(observer.validate('firstObject'), false, 'should NOT have notified firstObject once');
equal(observer.validate('lastObject'), false, 'should NOT have notified lastObject once');
}
});
export default suite;
| bmac/ember.js | packages/ember-runtime/tests/suites/mutable_array/removeObject.js | JavaScript | mit | 2,369 |
#include <vector>
#include <stdio.h>
#include <cstring>
#include <glm.hpp>
#include "objloader.hpp"
#pragma warning(disable:4996)
bool loadOBJ(
const char * path,
std::vector<glm::vec3> & out_vertices,
std::vector<glm::vec3> & out_normals,
std::vector<glm::vec2> & out_uvs) {
std::vector<unsigned int> vertexIndices, uvIndices, normalIndices;
std::vector<glm::vec3> temp_vertices;
std::vector<glm::vec2> temp_uvs;
std::vector<glm::vec3> temp_normals;
FILE * file = fopen(path, "r");
if (file == NULL) {
printf("Impossible to open the file ! Are you in the right path ?\n");
getchar();
return false;
}
while (1) {
char lineHeader[128];
// read the first word of the line
int res = fscanf(file, "%s", lineHeader);
if (res == EOF)
break; // EOF = End Of File. Quit the loop.
// else : parse lineHeader
if (strcmp(lineHeader, "v") == 0) {
glm::vec3 vertex;
fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z);
temp_vertices.push_back(vertex);
}
else if (strcmp(lineHeader, "vt") == 0) {
glm::vec2 uv;
fscanf(file, "%f %f\n", &uv.x, &uv.y);
uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders.
temp_uvs.push_back(uv);
}
else if (strcmp(lineHeader, "vn") == 0) {
glm::vec3 normal;
fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z);
temp_normals.push_back(normal);
}
else if (strcmp(lineHeader, "f") == 0) {
std::string vertex1, vertex2, vertex3;
unsigned int vertexIndex[3], uvIndex[3], normalIndex[3];
int matches = fscanf(file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]);
if (matches != 9) {
printf("File can't be read by our simple parser :-( Try exporting with other options\n");
return false;
}
vertexIndices.push_back(vertexIndex[0]);
vertexIndices.push_back(vertexIndex[1]);
vertexIndices.push_back(vertexIndex[2]);
uvIndices.push_back(uvIndex[0]);
uvIndices.push_back(uvIndex[1]);
uvIndices.push_back(uvIndex[2]);
normalIndices.push_back(normalIndex[0]);
normalIndices.push_back(normalIndex[1]);
normalIndices.push_back(normalIndex[2]);
}
else {
// Probably a comment, eat up the rest of the line
char stupidBuffer[1000];
fgets(stupidBuffer, 1000, file);
}
}
// For each vertex of each triangle
for (unsigned int i = 0; i<vertexIndices.size(); i++) {
// Get the indices of its attributes
unsigned int vertexIndex = vertexIndices[i];
unsigned int uvIndex = uvIndices[i];
unsigned int normalIndex = normalIndices[i];
// Get the attributes thanks to the index
glm::vec3 vertex = temp_vertices[vertexIndex - 1];
glm::vec2 uv = temp_uvs[uvIndex - 1];
glm::vec3 normal = temp_normals[normalIndex - 1];
// Put the attributes in buffers
out_vertices.push_back(vertex);
out_uvs.push_back(uv);
out_normals.push_back(normal);
}
return true;
}
| DanielPri/COMP371 | Skeleton/COMP371_Skeleton_code-master/Skeleton/VS_Solution/COMP371/COMP371/objloader.cpp | C++ | mit | 3,059 |
// Copyright (c) 2001-2010 Hartmut Kaiser
// Copyright (c) 2001-2010 Joel de Guzman
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#if !defined(BOOST_SPIRIT_PARSE_SEXPR_IMPL)
#define BOOST_SPIRIT_PARSE_SEXPR_IMPL
#include <iostream>
#include <string>
#include <boost/spirit/include/support_istream_iterator.hpp>
#include <boost/spirit/include/support_line_pos_iterator.hpp>
#include <boost/spirit/include/qi_parse.hpp>
#include <input/sexpr.hpp>
#include <input/parse_sexpr.hpp>
namespace scheme { namespace input
{
///////////////////////////////////////////////////////////////////////////
template <typename Char>
bool parse_sexpr(
std::basic_istream<Char>& is,
utree& result,
std::string const& source_file)
{
// no white space skipping in the stream!
is.unsetf(std::ios::skipws);
typedef
boost::spirit::basic_istream_iterator<Char>
stream_iterator_type;
stream_iterator_type sfirst(is);
stream_iterator_type slast;
typedef boost::spirit::line_pos_iterator<stream_iterator_type>
iterator_type;
iterator_type first(sfirst);
iterator_type last(slast);
scheme::input::sexpr<iterator_type> p(source_file);
scheme::input::sexpr_white_space<iterator_type> ws;
using boost::spirit::qi::phrase_parse;
return phrase_parse(first, last, p, ws, result);
}
///////////////////////////////////////////////////////////////////////////
template <typename Char>
bool parse_sexpr_list(
std::basic_istream<Char>& is,
utree& result,
std::string const& source_file)
{
// no white space skipping in the stream!
is.unsetf(std::ios::skipws);
typedef
boost::spirit::basic_istream_iterator<Char>
stream_iterator_type;
stream_iterator_type sfirst(is);
stream_iterator_type slast;
typedef boost::spirit::line_pos_iterator<stream_iterator_type>
iterator_type;
iterator_type first(sfirst);
iterator_type last(slast);
scheme::input::sexpr<iterator_type> p(source_file);
scheme::input::sexpr_white_space<iterator_type> ws;
using boost::spirit::qi::phrase_parse;
bool ok = phrase_parse(first, last, +p, ws, result);
result.tag(1); // line
return ok;
}
///////////////////////////////////////////////////////////////////////////
template <typename Range>
typename boost::disable_if<boost::is_base_of<std::ios_base, Range>, bool>::type
parse_sexpr(
Range const& rng,
utree& result,
std::string const& source_file)
{
typedef boost::spirit::line_pos_iterator<typename Range::const_iterator>
iterator_type;
scheme::input::sexpr<iterator_type> p(source_file);
scheme::input::sexpr_white_space<iterator_type> ws;
iterator_type first(rng.begin());
iterator_type last(rng.end());
using boost::spirit::qi::phrase_parse;
return phrase_parse(first, last, p, ws, result);
}
template <typename Range>
typename boost::disable_if<boost::is_base_of<std::ios_base, Range>, bool>::type
parse_sexpr_list(
Range const& rng,
utree& result,
std::string const& source_file)
{
typedef boost::spirit::line_pos_iterator<typename Range::const_iterator>
iterator_type;
scheme::input::sexpr<iterator_type> p(source_file);
scheme::input::sexpr_white_space<iterator_type> ws;
iterator_type first(rng.begin());
iterator_type last(rng.end());
using boost::spirit::qi::phrase_parse;
bool ok = phrase_parse(first, last, +p, ws, result);
result.tag(1); // line
return ok;
}
///////////////////////////////////////////////////////////////////////////
bool parse_sexpr(
utree const& in,
utree& result,
std::string const& source_file)
{
return parse_sexpr(in.get<utf8_string_range_type>(), result, source_file);
}
bool parse_sexpr_list(
utree const& in,
utree& result,
std::string const& source_file)
{
return parse_sexpr_list(in.get<utf8_string_range_type>(), result, source_file);
}
}}
#endif
| djsedulous/namecoind | libs/boost_1_50_0/libs/spirit/example/scheme/input/parse_sexpr_impl.hpp | C++ | mit | 4,452 |
/**
* Module dependencies.
*/
var express = require('express');
/**
* Initialize middleware.
*/
module.exports = function() {
this.use(express.urlencoded());
this.use(express.json());
this.use(this.router);
this.use(express.errorHandler());
}
| bosgood/electrolyte-examples | express/etc/init/02_middleware.js | JavaScript | mit | 262 |
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of the copyright holders may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the OpenCV Foundation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef __OPENCV_OPTIM_HPP__
#define __OPENCV_OPTIM_HPP__
#include "opencv2/core.hpp"
namespace cv
{
/** @addtogroup core_optim
The algorithms in this section minimize or maximize function value within specified constraints or
without any constraints.
@{
*/
/** @brief Basic interface for all solvers
*/
class CV_EXPORTS MinProblemSolver : public Algorithm
{
public:
/** @brief Represents function being optimized
*/
class CV_EXPORTS Function
{
public:
virtual ~Function() {}
virtual double calc(const double* x) const = 0;
virtual void getGradient(const double* /*x*/,double* /*grad*/) {}
};
/** @brief Getter for the optimized function.
The optimized function is represented by Function interface, which requires derivatives to
implement the sole method calc(double*) to evaluate the function.
@return Smart-pointer to an object that implements Function interface - it represents the
function that is being optimized. It can be empty, if no function was given so far.
*/
virtual Ptr<Function> getFunction() const = 0;
/** @brief Setter for the optimized function.
*It should be called at least once before the call to* minimize(), as default value is not usable.
@param f The new function to optimize.
*/
virtual void setFunction(const Ptr<Function>& f) = 0;
/** @brief Getter for the previously set terminal criteria for this algorithm.
@return Deep copy of the terminal criteria used at the moment.
*/
virtual TermCriteria getTermCriteria() const = 0;
/** @brief Set terminal criteria for solver.
This method *is not necessary* to be called before the first call to minimize(), as the default
value is sensible.
Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when
the function values at the vertices of simplex are within termcrit.epsilon range or simplex
becomes so small that it can enclosed in a box with termcrit.epsilon sides, whatever comes
first.
@param termcrit Terminal criteria to be used, represented as cv::TermCriteria structure.
*/
virtual void setTermCriteria(const TermCriteria& termcrit) = 0;
/** @brief actually runs the algorithm and performs the minimization.
The sole input parameter determines the centroid of the starting simplex (roughly, it tells
where to start), all the others (terminal criteria, initial step, function to be minimized) are
supposed to be set via the setters before the call to this method or the default values (not
always sensible) will be used.
@param x The initial point, that will become a centroid of an initial simplex. After the algorithm
will terminate, it will be setted to the point where the algorithm stops, the point of possible
minimum.
@return The value of a function at the point found.
*/
virtual double minimize(InputOutputArray x) = 0;
};
/** @brief This class is used to perform the non-linear non-constrained minimization of a function,
defined on an `n`-dimensional Euclidean space, using the **Nelder-Mead method**, also known as
**downhill simplex method**. The basic idea about the method can be obtained from
<http://en.wikipedia.org/wiki/Nelder-Mead_method>.
It should be noted, that this method, although deterministic, is rather a heuristic and therefore
may converge to a local minima, not necessary a global one. It is iterative optimization technique,
which at each step uses an information about the values of a function evaluated only at `n+1`
points, arranged as a *simplex* in `n`-dimensional space (hence the second name of the method). At
each step new point is chosen to evaluate function at, obtained value is compared with previous
ones and based on this information simplex changes it's shape , slowly moving to the local minimum.
Thus this method is using *only* function values to make decision, on contrary to, say, Nonlinear
Conjugate Gradient method (which is also implemented in optim).
Algorithm stops when the number of function evaluations done exceeds termcrit.maxCount, when the
function values at the vertices of simplex are within termcrit.epsilon range or simplex becomes so
small that it can enclosed in a box with termcrit.epsilon sides, whatever comes first, for some
defined by user positive integer termcrit.maxCount and positive non-integer termcrit.epsilon.
@note DownhillSolver is a derivative of the abstract interface
cv::MinProblemSolver, which in turn is derived from the Algorithm interface and is used to
encapsulate the functionality, common to all non-linear optimization algorithms in the optim
module.
@note term criteria should meet following condition:
@code
termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0
@endcode
*/
class CV_EXPORTS DownhillSolver : public MinProblemSolver
{
public:
/** @brief Returns the initial step that will be used in downhill simplex algorithm.
@param step Initial step that will be used in algorithm. Note, that although corresponding setter
accepts column-vectors as well as row-vectors, this method will return a row-vector.
@see DownhillSolver::setInitStep
*/
virtual void getInitStep(OutputArray step) const=0;
/** @brief Sets the initial step that will be used in downhill simplex algorithm.
Step, together with initial point (givin in DownhillSolver::minimize) are two `n`-dimensional
vectors that are used to determine the shape of initial simplex. Roughly said, initial point
determines the position of a simplex (it will become simplex's centroid), while step determines the
spread (size in each dimension) of a simplex. To be more precise, if \f$s,x_0\in\mathbb{R}^n\f$ are
the initial step and initial point respectively, the vertices of a simplex will be:
\f$v_0:=x_0-\frac{1}{2} s\f$ and \f$v_i:=x_0+s_i\f$ for \f$i=1,2,\dots,n\f$ where \f$s_i\f$ denotes
projections of the initial step of *n*-th coordinate (the result of projection is treated to be
vector given by \f$s_i:=e_i\cdot\left<e_i\cdot s\right>\f$, where \f$e_i\f$ form canonical basis)
@param step Initial step that will be used in algorithm. Roughly said, it determines the spread
(size in each dimension) of an initial simplex.
*/
virtual void setInitStep(InputArray step)=0;
/** @brief This function returns the reference to the ready-to-use DownhillSolver object.
All the parameters are optional, so this procedure can be called even without parameters at
all. In this case, the default values will be used. As default value for terminal criteria are
the only sensible ones, MinProblemSolver::setFunction() and DownhillSolver::setInitStep()
should be called upon the obtained object, if the respective parameters were not given to
create(). Otherwise, the two ways (give parameters to createDownhillSolver() or miss them out
and call the MinProblemSolver::setFunction() and DownhillSolver::setInitStep()) are absolutely
equivalent (and will drop the same errors in the same way, should invalid input be detected).
@param f Pointer to the function that will be minimized, similarly to the one you submit via
MinProblemSolver::setFunction.
@param initStep Initial step, that will be used to construct the initial simplex, similarly to the one
you submit via MinProblemSolver::setInitStep.
@param termcrit Terminal criteria to the algorithm, similarly to the one you submit via
MinProblemSolver::setTermCriteria.
*/
static Ptr<DownhillSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<MinProblemSolver::Function>(),
InputArray initStep=Mat_<double>(1,1,0.0),
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001));
};
/** @brief This class is used to perform the non-linear non-constrained minimization of a function
with known gradient,
defined on an *n*-dimensional Euclidean space, using the **Nonlinear Conjugate Gradient method**.
The implementation was done based on the beautifully clear explanatory article [An Introduction to
the Conjugate Gradient Method Without the Agonizing
Pain](http://www.cs.cmu.edu/~quake-papers/painless-conjugate-gradient.pdf) by Jonathan Richard
Shewchuk. The method can be seen as an adaptation of a standard Conjugate Gradient method (see, for
example <http://en.wikipedia.org/wiki/Conjugate_gradient_method>) for numerically solving the
systems of linear equations.
It should be noted, that this method, although deterministic, is rather a heuristic method and
therefore may converge to a local minima, not necessary a global one. What is even more disastrous,
most of its behaviour is ruled by gradient, therefore it essentially cannot distinguish between
local minima and maxima. Therefore, if it starts sufficiently near to the local maximum, it may
converge to it. Another obvious restriction is that it should be possible to compute the gradient of
a function at any point, thus it is preferable to have analytic expression for gradient and
computational burden should be born by the user.
The latter responsibility is accompilished via the getGradient method of a
MinProblemSolver::Function interface (which represents function being optimized). This method takes
point a point in *n*-dimensional space (first argument represents the array of coordinates of that
point) and comput its gradient (it should be stored in the second argument as an array).
@note class ConjGradSolver thus does not add any new methods to the basic MinProblemSolver interface.
@note term criteria should meet following condition:
@code
termcrit.type == (TermCriteria::MAX_ITER + TermCriteria::EPS) && termcrit.epsilon > 0 && termcrit.maxCount > 0
// or
termcrit.type == TermCriteria::MAX_ITER) && termcrit.maxCount > 0
@endcode
*/
class CV_EXPORTS ConjGradSolver : public MinProblemSolver
{
public:
/** @brief This function returns the reference to the ready-to-use ConjGradSolver object.
All the parameters are optional, so this procedure can be called even without parameters at
all. In this case, the default values will be used. As default value for terminal criteria are
the only sensible ones, MinProblemSolver::setFunction() should be called upon the obtained
object, if the function was not given to create(). Otherwise, the two ways (submit it to
create() or miss it out and call the MinProblemSolver::setFunction()) are absolutely equivalent
(and will drop the same errors in the same way, should invalid input be detected).
@param f Pointer to the function that will be minimized, similarly to the one you submit via
MinProblemSolver::setFunction.
@param termcrit Terminal criteria to the algorithm, similarly to the one you submit via
MinProblemSolver::setTermCriteria.
*/
static Ptr<ConjGradSolver> create(const Ptr<MinProblemSolver::Function>& f=Ptr<ConjGradSolver::Function>(),
TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5000,0.000001));
};
//! return codes for cv::solveLP() function
enum SolveLPResult
{
SOLVELP_UNBOUNDED = -2, //!< problem is unbounded (target function can achieve arbitrary high values)
SOLVELP_UNFEASIBLE = -1, //!< problem is unfeasible (there are no points that satisfy all the constraints imposed)
SOLVELP_SINGLE = 0, //!< there is only one maximum for target function
SOLVELP_MULTI = 1 //!< there are multiple maxima for target function - the arbitrary one is returned
};
/** @brief Solve given (non-integer) linear programming problem using the Simplex Algorithm (Simplex Method).
What we mean here by "linear programming problem" (or LP problem, for short) can be formulated as:
\f[\mbox{Maximize } c\cdot x\\
\mbox{Subject to:}\\
Ax\leq b\\
x\geq 0\f]
Where \f$c\f$ is fixed `1`-by-`n` row-vector, \f$A\f$ is fixed `m`-by-`n` matrix, \f$b\f$ is fixed `m`-by-`1`
column vector and \f$x\f$ is an arbitrary `n`-by-`1` column vector, which satisfies the constraints.
Simplex algorithm is one of many algorithms that are designed to handle this sort of problems
efficiently. Although it is not optimal in theoretical sense (there exist algorithms that can solve
any problem written as above in polynomial type, while simplex method degenerates to exponential
time for some special cases), it is well-studied, easy to implement and is shown to work well for
real-life purposes.
The particular implementation is taken almost verbatim from **Introduction to Algorithms, third
edition** by T. H. Cormen, C. E. Leiserson, R. L. Rivest and Clifford Stein. In particular, the
Bland's rule <http://en.wikipedia.org/wiki/Bland%27s_rule> is used to prevent cycling.
@param Func This row-vector corresponds to \f$c\f$ in the LP problem formulation (see above). It should
contain 32- or 64-bit floating point numbers. As a convenience, column-vector may be also submitted,
in the latter case it is understood to correspond to \f$c^T\f$.
@param Constr `m`-by-`n+1` matrix, whose rightmost column corresponds to \f$b\f$ in formulation above
and the remaining to \f$A\f$. It should containt 32- or 64-bit floating point numbers.
@param z The solution will be returned here as a column-vector - it corresponds to \f$c\f$ in the
formulation above. It will contain 64-bit floating point numbers.
@return One of cv::SolveLPResult
*/
CV_EXPORTS_W int solveLP(const Mat& Func, const Mat& Constr, Mat& z);
//! @}
}// cv
#endif
| chliam/OpenCV_IOS_3.0RC1 | opencv2.framework/Versions/A/Headers/core/optim.hpp | C++ | mit | 15,775 |
// Generated by CoffeeScript 1.3.3
(function() {
var Path, createApiTree, extensions, fs,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; },
__hasProp = {}.hasOwnProperty;
fs = require('fs');
Path = require('path');
extensions = function() {
var k, v, _ref, _results;
if (typeof require !== "undefined" && require !== null ? require.extensions : void 0) {
_ref = require.extensions;
_results = [];
for (k in _ref) {
v = _ref[k];
if (k !== '.json') {
_results.push(k);
}
}
return _results;
} else {
return ['.coffee'];
}
};
exports.createApiTree = createApiTree = function(directory, options) {
var child, item, k, key, name, names, node, tree, v, _i, _len;
if (options == null) {
options = {};
}
options.loadItem || (options.loadItem = require);
options.nameToKey || (options.nameToKey = function(name) {
return name.split('.')[0].replace(/_*\W+_*/g, '_');
});
options.readdirSync || (options.readdirSync = function(path) {
return fs.readdirSync(path);
});
options.isDirectory || (options.isDirectory = function(path) {
return fs.lstatSync(path).isDirectory();
});
options.filter || (options.filter = function(name, names) {
var ext, _ref;
ext = Path.extname(name);
return ext === '.js' || (__indexOf.call(extensions(), ext) >= 0 && !(_ref = Path.basename(name, ext).concat('.js'), __indexOf.call(names, _ref) >= 0));
});
tree = {};
names = options.readdirSync(directory);
for (_i = 0, _len = names.length; _i < _len; _i++) {
name = names[_i];
if (name.match(/^[._#]|[#~]$/)) {
continue;
}
child = Path.join(directory, name);
key = options.nameToKey(name);
item = options.isDirectory(child) ? createApiTree(child, options) : options.filter(name, names) ? options.loadItem(child) : void 0;
if (item && Object.keys(item).length) {
node = (tree[key] || (tree[key] = {}));
for (k in item) {
if (!__hasProp.call(item, k)) continue;
v = item[k];
if (node[k] != null) {
throw new Error("API tree name conflict for '" + k + "' in " + child);
}
node[k] = v;
}
}
}
return tree;
};
}).call(this);
| rybon/Remocial | node_modules/ss-angular/node_modules/apitree/lib/apitree.js | JavaScript | mit | 2,451 |
class GetterWithDollar1 {
@lombok.Getter int $i;
GetterWithDollar1() {
super();
}
public @java.lang.SuppressWarnings("all") int get$i() {
return this.$i;
}
}
class GetterWithDollar2 {
@lombok.Getter int $i;
@lombok.Getter int i;
GetterWithDollar2() {
super();
}
public @java.lang.SuppressWarnings("all") int get$i() {
return this.$i;
}
public @java.lang.SuppressWarnings("all") int getI() {
return this.i;
}
}
| domix/lombok | test/transform/resource/after-ecj/GetterWithDollar.java | Java | mit | 456 |
YUI.add('gallery-plugin-node-io', function(Y) {
/**
* Node IO provides a simple interface to load text into a node
*
* @class NodeIo
* @extends Base
* @version 1.1.0
*/
var YL = Y.Lang;
Y.Plugin.NodeIo = Y.Base.create('node-io', Y.Base, [], {
/////// P U B L I C //////
/**
* Set up ioHandler and bind events
* @since 1.1.0
* @method initializer
*/
initializer : function(){
this.publish('success', {defaultFn: this._defSuccessFn });
this.after('uriChange', this._afterUriChange);
this._ioHandlers = {
complete: Y.bind(this._handleResponse, this, 'complete'),
success: Y.bind(this._handleResponse, this, 'success'),
failure: Y.bind(this._handleResponse, this, 'failure'),
end: Y.bind(this._handleResponse, this, 'end')
};
},
/**
* Set uri and start io
* @since 1.0.0
* @method load
* @chainable
* @return {NodeIo} A reference to this object
*/
load : function(uri) {
var config = this.get('ioConfig');
if(!uri) {
uri = this.get('uri');
}else{
this.set('uri', uri);
}
config.on = this._ioHandlers;
this._io = Y.io(uri, config);
return this;
},
/**
* Sugar method to refresh the content
* Not recommended if placement is not `replace`
* @since 1.0.0
* @method refresh
* @chainable
* @return {NodeIo} A reference to this object
*/
refresh : function(){
return this.load();
},
/**
* Stops any current io
* @since 1.0.0
* @method abort
* @chainable
* @return {NodeIo} A reference to this object
*/
abort : function() {
this._stopIO();
return this;
},
////// P R O T E C T E D //////
/**
* Local storage of the internal Y.io
* @since 1.0.0
* @protected
*/
_io: null,
/**
* Object used to set the on of the _io
* @since 1.1.0
* @protected
*/
_ioHandlers: null,
/**
* Aborts any current io
* @since 1.0.0
* @method _stopIO
* @protected
*/
_stopIO : function() {
if(this._io) {
this._io.abort();
this._io = null;
}
},
/**
* Single interface for io responses
* @since 1.1.0
* @method _handleResponse
* @protected
*/
_handleResponse : function (type, id, o) {
this.fire(type, {id: id, response: o});
this._io = null;
},
/**
* Default onSuccess method for io
* Inserts response text into the host by placement
* @since 1.1.0
* @method _defSuccessFn
* @protected
*/
_defSuccessFn : function(e) {
this.get('host').insert(e.response.responseText, this.get('placement'));
},
/**
* Aborts any io when the uri is changed
* @since 1.1.0
* @method _afterUriChange
* @protected
*/
_afterUriChange : function() {
this._stopIO();
}
}, {
NS : 'io',
ATTRS : {
/**
* Stores host node
* @since 1.0.0
* @attribute host
* @type Y.Plugin.Host
*/
host : {
writeOnce : true
},
/**
* Allows for advanced io configuration
* @since 1.0.0
* @attribute ioConfig
* @type object
* @default {}
*/
ioConfig : {
value : {},
validator : YL.isObject
},
/**
* Placement of responseText
* @since 1.0.0
* @attribute placement
* @type string
* @defautl replace
*/
placement : {
value : 'replace',
validator : function(val) {
return (/replace|(?:ap|pre)pend/).test(val);
}
},
/**
* Specifies the URI for the io
* @since 1.0.0
* @attribute uri
* @type string
*/
uri : {
validator : YL.isString
}
}
});
}, 'gallery-2010.09.08-19-45' ,{requires:['plugin','node-base','node-pluginhost','io-base','base-build']});
| inikoo/fact | libs/yui/yui3-gallery/build/gallery-plugin-node-io/gallery-plugin-node-io.js | JavaScript | mit | 4,086 |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Azure.ResourceManager.Resources.Models;
using Azure.ResourceManager.Sql;
using Azure.ResourceManager.Sql.Models;
using Azure.ResourceManager.Sql.Tests;
using NUnit.Framework;
namespace Sql.Tests
{
public class ServerCrudScenarioTests : SqlManagementClientBase
{
protected ServerCrudScenarioTests(bool isAsync)
: base(isAsync)
{
InitializeBase();
}
[Test]
public async Task TestCreateUpdateGetDropServer()
{
var resourceGroup = context.CreateResourceGroup();
var sqlClient = context.GetClient<SqlManagementClient>();
string serverNameV12 = SqlManagementTestUtilities.GenerateName();
string login = "dummylogin";
string password = "Un53cuRE!";
string version12 = "12.0";
Dictionary<string, string> tags = new Dictionary<string, string>()
{
{ "tagKey1", "TagValue1" }
};
// Create server
var server1 = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, serverNameV12, new Server()
{
AdministratorLogin = login,
AdministratorLoginPassword = password,
Version = version12,
Tags = {
{ "tagKey1", "TagValue1" }
},
Location = TestEnvironmentUtilities.DefaultLocationId,
})).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(server1, serverNameV12, login, version12, tags, TestEnvironmentUtilities.DefaultLocationId);
// Create second server
string server2 = SqlManagementTestUtilities.GenerateName();
var v2Server = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, server2, new Server()
{
AdministratorLogin = login,
AdministratorLoginPassword = password,
Tags = tags,
Location = TestEnvironmentUtilities.DefaultLocationId,
})).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(v2Server, server2, login, version12, tags, TestEnvironmentUtilities.DefaultLocationId);
// Get first server
var getServer1 = sqlClient.Servers.Get(resourceGroup.Name, serverNameV12);
SqlManagementTestUtilities.ValidateServer(getServer1, serverNameV12, login, version12, tags, TestEnvironmentUtilities.DefaultLocationId);
// Get second server
var getServer2 = sqlClient.Servers.Get(resourceGroup.Name, server2);
SqlManagementTestUtilities.ValidateServer(getServer2, server2, login, version12, tags, TestEnvironmentUtilities.DefaultLocationId);
var listServers = sqlClient.Servers.ListByResourceGroup(resourceGroup.Name);
Assert.AreEqual(2, listServers.Count());
// Update first server
Dictionary<string, string> newTags = new Dictionary<string, string>()
{
{ "asdf", "zxcv" }
};
var updateServer1 = sqlClient.Servers.Update(resourceGroup.Name, serverNameV12, new ServerUpdate { Tags = newTags });
SqlManagementTestUtilities.ValidateServer(updateServer1, serverNameV12, login, version12, newTags, TestEnvironmentUtilities.DefaultLocationId);
// Drop server, update count
await sqlClient.Servers.StartDeleteAsync(resourceGroup.Name, serverNameV12);
var listServers2 = sqlClient.Servers.ListByResourceGroup(resourceGroup.Name);
Assert.AreEqual(1, listServers2.Count());
}
}
[Test]
public async Task TestServerPublicNetworkAccess()
{
using (SqlManagementTestContext context = new SqlManagementTestContext(this))
{
var resourceGroup = context.CreateResourceGroup();
SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>();
string location = TestEnvironmentUtilities.DefaultEuapPrimaryLocationId;
string enabled = "Enabled";
string disabled = "Disabled";
string serverName1 = SqlManagementTestUtilities.GenerateName();
string serverName2 = SqlManagementTestUtilities.GenerateName();
string login = "dummylogin";
string password = "Un53cuRE!";
string version12 = "12.0";
Dictionary<string, string> tags = new Dictionary<string, string>()
{
{ "tagKey1", "TagValue1" }
};
// Create server with PublicNetworkAccess disabled and verify its been disabled
var server1 = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, serverName1, new Server()
{
AdministratorLogin = login,
AdministratorLoginPassword = password,
Version = version12,
Tags = tags,
Location = location,
PublicNetworkAccess = disabled
})).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(server1, serverName1, login, version12, tags, location, disabled);
// Get server and verify that server is disabled
server1 = sqlClient.Servers.Get(resourceGroup.Name, serverName1);
SqlManagementTestUtilities.ValidateServer(server1, serverName1, login, version12, tags, location, disabled);
// Create server with PublicNetworkAccess enabled and verify its been enabled
server1 = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, serverName1, new Server()
{
Location = location,
PublicNetworkAccess = enabled
})).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(server1, serverName1, login, version12, tags, location, enabled); ;
// Create second server with no PublicNetworkAccess verify it defaults to enabled
var server2 = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, serverName2, new Server()
{
AdministratorLogin = login,
AdministratorLoginPassword = password,
Version = version12,
Tags = tags,
Location = location,
})).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(server2, serverName2, login, version12, tags, location, enabled);
// Get servers and verify all are enabled
var serverList = sqlClient.Servers.List();
foreach (var server in serverList)
{
if (server.Name.Equals(serverName1) || server.Name.Equals(serverName2))
{
Assert.AreEqual(enabled, server.PublicNetworkAccess);
}
}
// Drop servers
await sqlClient.Servers.StartDeleteAsync(resourceGroup.Name, serverName1);
await sqlClient.Servers.StartDeleteAsync(resourceGroup.Name, serverName2);
}
}
[Test]
public async Task TestServerMinimalTlsVersion()
{
using (SqlManagementTestContext context = new SqlManagementTestContext(this))
{
var resourceGroup = context.CreateResourceGroup();
var sqlClient = context.GetClient<SqlManagementClient>();
string location = TestEnvironmentUtilities.DefaultEuapPrimaryLocationId;
string minTlsVersion1_1 = "1.1";
string minTlsVersion1_2 = "1.2";
string serverName = SqlManagementTestUtilities.GenerateName();
string login = "dummylogin";
string password = "Un53cuRE!";
string version12 = "12.0";
Dictionary<string, string> tags = new Dictionary<string, string>()
{
{ "tagKey1", "TagValue1" }
};
// Create a server with TLS version enforcement set to > 1.1
var vm = new Server(location)
{
AdministratorLogin = login,
AdministratorLoginPassword = password,
Version = version12,
Location = location,
MinimalTlsVersion = minTlsVersion1_1
};
vm.Tags.Clear();
// set tags
var server = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, serverName, vm)).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(server, serverName, login, version12, tags, location, minimalTlsVersion: minTlsVersion1_1);
// Get server and verify that minimal TLS version is correct
server = sqlClient.Servers.Get(resourceGroup.Name, serverName);
SqlManagementTestUtilities.ValidateServer(server, serverName, login, version12, tags, location, minimalTlsVersion: minTlsVersion1_1);
// Update TLS version enforcement on the server to > 1.2
server = await (await sqlClient.Servers.StartCreateOrUpdateAsync(resourceGroup.Name, serverName, new Server(location)
{
Location = location,
MinimalTlsVersion = minTlsVersion1_2
})).WaitForCompletionAsync();
SqlManagementTestUtilities.ValidateServer(server, serverName, login, version12, tags, location, minimalTlsVersion: minTlsVersion1_2); ;
// Drop the server
await sqlClient.Servers.StartDeleteAsync(resourceGroup.Name, serverName);
}
}
}
}
| ayeletshpigelman/azure-sdk-for-net | sdk/sqlmanagement/Azure.ResourceManager.Sql/tests/ServerCrudScenarioTests.cs | C# | mit | 9,957 |
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
/// <reference types="node" />
import * as p from 'path';
import {AbsoluteFsPath, PathSegment, PathString} from '../../src/types';
import {MockFileSystem} from './mock_file_system';
export class MockFileSystemPosix extends MockFileSystem {
resolve(...paths: string[]): AbsoluteFsPath {
const resolved = p.posix.resolve(this.pwd(), ...paths);
return this.normalize(resolved) as AbsoluteFsPath;
}
dirname<T extends string>(file: T): T {
return this.normalize(p.posix.dirname(file)) as T;
}
join<T extends string>(basePath: T, ...paths: string[]): T {
return this.normalize(p.posix.join(basePath, ...paths)) as T;
}
relative<T extends PathString>(from: T, to: T): PathSegment|AbsoluteFsPath {
return this.normalize(p.posix.relative(from, to)) as PathSegment | AbsoluteFsPath;
}
basename(filePath: string, extension?: string): PathSegment {
return p.posix.basename(filePath, extension) as PathSegment;
}
isRooted(path: string): boolean {
return path.startsWith('/');
}
protected splitPath<T extends PathString>(path: T): string[] {
return path.split('/');
}
normalize<T extends PathString>(path: T): T {
return path.replace(/^[a-z]:\//i, '/').replace(/\\/g, '/') as T;
}
}
| mgechev/angular | packages/compiler-cli/src/ngtsc/file_system/testing/src/mock_file_system_posix.ts | TypeScript | mit | 1,448 |
// Copyright 2012-2019 Oliver Eilhard. All rights reserved.
// Use of this source code is governed by a MIT-license.
// See http://olivere.mit-license.org/license.txt for details.
package elastic
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/olivere/elastic/v7/uritemplates"
)
// XPackSecurityGetUserService retrieves a user by its name.
// See https://www.elastic.co/guide/en/elasticsearch/reference/7.0/security-api-get-user.html.
type XPackSecurityGetUserService struct {
client *Client
pretty *bool // pretty format the returned JSON response
human *bool // return human readable values for statistics
errorTrace *bool // include the stack trace of returned errors
filterPath []string // list of filters used to reduce the response
headers http.Header // custom request-level HTTP headers
usernames []string
}
// NewXPackSecurityGetUserService creates a new XPackSecurityGetUserService.
func NewXPackSecurityGetUserService(client *Client) *XPackSecurityGetUserService {
return &XPackSecurityGetUserService{
client: client,
}
}
// Pretty indicates that the JSON response be indented and human readable.
func (s *XPackSecurityGetUserService) Pretty(pretty bool) *XPackSecurityGetUserService {
s.pretty = &pretty
return s
}
// Human specifies whether human readable values should be returned in
// the JSON response, e.g. "7.5mb".
func (s *XPackSecurityGetUserService) Human(human bool) *XPackSecurityGetUserService {
s.human = &human
return s
}
// ErrorTrace specifies whether to include the stack trace of returned errors.
func (s *XPackSecurityGetUserService) ErrorTrace(errorTrace bool) *XPackSecurityGetUserService {
s.errorTrace = &errorTrace
return s
}
// FilterPath specifies a list of filters used to reduce the response.
func (s *XPackSecurityGetUserService) FilterPath(filterPath ...string) *XPackSecurityGetUserService {
s.filterPath = filterPath
return s
}
// Header adds a header to the request.
func (s *XPackSecurityGetUserService) Header(name string, value string) *XPackSecurityGetUserService {
if s.headers == nil {
s.headers = http.Header{}
}
s.headers.Add(name, value)
return s
}
// Headers specifies the headers of the request.
func (s *XPackSecurityGetUserService) Headers(headers http.Header) *XPackSecurityGetUserService {
s.headers = headers
return s
}
// Usernames are the names of one or more users to retrieve.
func (s *XPackSecurityGetUserService) Usernames(usernames ...string) *XPackSecurityGetUserService {
for _, username := range usernames {
if v := strings.TrimSpace(username); v != "" {
s.usernames = append(s.usernames, v)
}
}
return s
}
// buildURL builds the URL for the operation.
func (s *XPackSecurityGetUserService) buildURL() (string, url.Values, error) {
// Build URL
var (
path string
err error
)
if len(s.usernames) > 0 {
path, err = uritemplates.Expand("/_security/user/{username}", map[string]string{
"username": strings.Join(s.usernames, ","),
})
} else {
path = "/_security/user"
}
if err != nil {
return "", url.Values{}, err
}
// Add query string parameters
params := url.Values{}
if v := s.pretty; v != nil {
params.Set("pretty", fmt.Sprint(*v))
}
if v := s.human; v != nil {
params.Set("human", fmt.Sprint(*v))
}
if v := s.errorTrace; v != nil {
params.Set("error_trace", fmt.Sprint(*v))
}
if len(s.filterPath) > 0 {
params.Set("filter_path", strings.Join(s.filterPath, ","))
}
return path, params, nil
}
// Validate checks if the operation is valid.
func (s *XPackSecurityGetUserService) Validate() error {
return nil
}
// Do executes the operation.
func (s *XPackSecurityGetUserService) Do(ctx context.Context) (*XPackSecurityGetUserResponse, error) {
// Check pre-conditions
if err := s.Validate(); err != nil {
return nil, err
}
// Get URL for request
path, params, err := s.buildURL()
if err != nil {
return nil, err
}
// Get HTTP response
res, err := s.client.PerformRequest(ctx, PerformRequestOptions{
Method: "GET",
Path: path,
Params: params,
Headers: s.headers,
})
if err != nil {
return nil, err
}
// Return operation response
ret := XPackSecurityGetUserResponse{}
if err := json.Unmarshal(res.Body, &ret); err != nil {
return nil, err
}
return &ret, nil
}
// XPackSecurityGetUserResponse is the response of XPackSecurityGetUserService.Do.
type XPackSecurityGetUserResponse map[string]XPackSecurityUser
// XPackSecurityUser is the user object.
//
// The Java source for this struct is defined here:
// https://github.com/elastic/elasticsearch/blob/7.3/x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/user/User.java
type XPackSecurityUser struct {
Username string `json:"username"`
Roles []string `json:"roles"`
Fullname string `json:"full_name"`
Email string `json:"email"`
Metadata map[string]interface{} `json:"metadata"`
Enabled bool `json:"enabled"`
}
| olivere/elastic | xpack_security_get_user.go | GO | mit | 5,061 |
//
* @param aaa bbb ccc ddd eee fff ggg
//
| general-language-syntax/GLS | test/integration/CommentDocTag/long parameter.ts | TypeScript | mit | 46 |
package de.fhpotsdam.unfolding.marker;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.utils.GeoUtils;
/**
* A MultiMarker enables handling of multiple, logically grouped markers. Properties and display states are the same for
* all its markers.
*
* A MultiMarker can consist of various sub-markers, even of different types. For instance, a MultiMarker could have
* three polygon marker and one point marker.
*/
public class MultiMarker implements Marker {
protected List<Marker> markers = new ArrayList<Marker>();
public HashMap<String, Object> properties;
protected boolean selected;
protected boolean hidden;
protected String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setMarkers(List<Marker> markers) {
this.markers = markers;
}
public List<Marker> getMarkers() {
return markers;
}
public void addMarkers(Marker... markers) {
for (Marker marker : markers) {
this.markers.add(marker);
}
}
/**
* Return center of all markers.
*
*
* This uses marker.getLocation() which either returns single location, or centroid location (of shape marker), and
* then combines it. TODO Check whether to use {@link GeoUtils#getCentroid(List)} instead.
*/
@Override
public Location getLocation() {
Location center = new Location(0, 0);
for (Marker marker : markers) {
center.add(marker.getLocation());
}
center.div((float) markers.size());
return center;
}
@Override
public void setLocation(float lat, float lng) {
// TODO Auto-generated method stub
}
@Override
public void setLocation(Location location) {
// TODO Auto-generated method stub
}
/**
* return distance between location and the (to the location) closest marker
*/
// REVISIT alternatively method could return distance to the of all markers
// implement both in different methods? examples needed!
@Override
public double getDistanceTo(Location location) {
double minDistance = Double.MAX_VALUE;
for (Marker marker : markers) {
double dist = marker.getDistanceTo(location);
minDistance = dist < minDistance ? dist : minDistance;
}
return minDistance;
}
@Override
public void setProperties(HashMap<String, Object> properties) {
this.properties = properties;
}
@Override
public Object setProperty(String key, Object value) {
return properties.put(key, value);
}
@Override
public HashMap<String, Object> getProperties() {
return properties;
}
@Override
public Object getProperty(String key) {
return properties.get(key);
}
@Override
public String getStringProperty(String key) {
Object value = properties.get(key);
if (value != null && value instanceof String) {
return (String) value;
} else {
return null;
}
}
@Override
public Integer getIntegerProperty(String key) {
Object value = properties.get(key);
if (value != null && value instanceof Integer) {
return (Integer) value;
} else {
return null;
}
}
/**
* Returns true if at least one marker is hit.
*/
@Override
public boolean isInside(UnfoldingMap map, float checkX, float checkY) {
boolean inside = false;
for (Marker marker : markers) {
inside |= marker.isInside(map, checkX, checkY);
}
return inside;
}
@Override
public void draw(UnfoldingMap map) {
for (Marker marker : markers) {
marker.draw(map);
}
}
/**
* Sets the selected status of all its markers.
*/
@Override
public void setSelected(boolean selected) {
this.selected = selected;
for (Marker marker : markers) {
marker.setSelected(selected);
}
}
/**
* Indicates whether this multi marker is selected. This does not necessarily reflect the selected states of all its
* markers (i.e. a marker of a MultiMarker can have a different selection status):
*/
@Override
public boolean isSelected() {
return selected;
}
@Override
public void setHidden(boolean hidden) {
this.hidden = hidden;
for (Marker marker : markers) {
marker.setHidden(hidden);
}
}
@Override
public boolean isHidden() {
return hidden;
}
public void setColor(int color) {
for (Marker marker : markers) {
marker.setColor(color);
}
}
@Override
public void setStrokeColor(int color) {
for (Marker marker : markers) {
marker.setStrokeColor(color);
}
}
@Override
public void setStrokeWeight(int weight) {
for (Marker marker : markers) {
marker.setStrokeWeight(weight);
}
}
}
| ashr81/unfolding | src/de/fhpotsdam/unfolding/marker/MultiMarker.java | Java | mit | 4,593 |
var validate, $i;
var {{ schema | capitalize }}Validator = function(di) {
$i = di;
validate = $i.validate;
return {};
};
module.exports = exports = {{ schema | capitalize }}Validator; | marcelomf/graojs | skeletons/bundle/Validator.js | JavaScript | mit | 190 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Console\Command;
use Symfony\Component\Console\Helper\DescriptorHelper;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputDefinition;
/**
* ListCommand displays the list of all available commands for the application.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ListCommand extends Command
{
/**
* {@inheritdoc}
*/
protected function configure()
{
$this
->setName('list')
->setDefinition($this->createDefinition())
->setDescription('Lists commands')
->setHelp(<<<EOF
The <info>%command.name%</info> command lists all commands:
<info>php %command.full_name%</info>
You can also display the commands for a specific namespace:
<info>php %command.full_name% test</info>
You can also output the information in other formats by using the <comment>--format</comment> option:
<info>php %command.full_name% --format=xml</info>
It's also possible to get raw list of commands (useful for embedding command runner):
<info>php %command.full_name% --raw</info>
EOF
)
;
}
/**
* {@inheritdoc}
*/
public function getNativeDefinition()
{
return $this->createDefinition();
}
/**
* {@inheritdoc}
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
if ($input->getOption('xml')) {
$input->setOption('format', 'xml');
}
$helper = new DescriptorHelper();
$helper->describe($output, $this->getApplication(), $input->getOption('format'), $input->getOption('raw'));
}
/**
* {@inheritdoc}
*/
private function createDefinition()
{
return new InputDefinition(array(
new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),
new InputOption('xml', null, InputOption::VALUE_NONE, 'To output list as XML'),
new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'),
new InputOption('format', null, InputOption::VALUE_REQUIRED, 'To output list in other formats'),
));
}
}
| tjoskar/odot | vendor/symfony/console/Symfony/Component/Console/Command/ListCommand.php | PHP | mit | 2,612 |
Tinytest.add('options cacheLimit - exceed', function(test) {
var sm = new SubsManager({cacheLimit: 2});
sm._addSub(['posts']);
sm._addSub(['comments']);
sm._addSub(['singlePoint', 'one']);
sm._applyCacheLimit();
test.equal(sm._cacheList.length, 2);
var subsIds = sm._cacheList.map(function(sub) {
return sub.args[0];
});
test.equal(subsIds, ['comments', 'singlePoint']);
sm.clear();
});
Tinytest.add('options cacheLimit - not-exceed', function(test) {
var sm = new SubsManager({cacheLimit: 10});
sm._addSub(['posts']);
sm._addSub(['comments']);
sm._addSub(['singlePoint', 'one']);
sm._applyCacheLimit();
test.equal(sm._cacheList.length, 3);
var subsIds = sm._cacheList.map(function(sub) {
return sub.args[0];
});
test.equal(subsIds, ['posts', 'comments', 'singlePoint']);
sm.clear();
});
Tinytest.addAsync('options expireIn - expired', function(test, done) {
// expireIn 100 millis
var sm = new SubsManager({cacheLimit: 20, expireIn: 1/60/10});
sm._addSub(['posts']);
sm._addSub(['comments']);
test.equal(sm._cacheList.length, 2);
Meteor.call('wait', 200, function() {
sm._applyExpirations();
test.equal(sm._cacheList.length, 0);
sm.clear();
done();
});
});
Tinytest.addAsync('options expireIn - not expired', function(test, done) {
// expireIn 2 minutes
var sm = new SubsManager({cacheLimit: 20, expireIn: 2});
sm._addSub(['posts']);
sm._addSub(['comments']);
test.equal(sm._cacheList.length, 2);
Meteor.call('wait', 200, function() {
sm._applyExpirations();
test.equal(sm._cacheList.length, 2);
sm.clear();
done();
});
});
| parkerkimbell/subs-manager | tests/options.js | JavaScript | mit | 1,642 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AppBundle\DataFixtures\ORM;
use AppBundle\Entity\Comment;
use AppBundle\Entity\Post;
use AppBundle\Entity\User;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
/**
* Defines the sample data to load in the database when running the unit and
* functional tests.
*
* Execute this command to load the data:
*
* $ php bin/console doctrine:fixtures:load
*
* See http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html
*
* @author Ryan Weaver <weaverryan@gmail.com>
* @author Javier Eguiluz <javier.eguiluz@gmail.com>
*/
class LoadFixtures extends AbstractFixture implements ContainerAwareInterface
{
use ContainerAwareTrait;
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
$this->loadUsers($manager);
$this->loadPosts($manager);
}
private function loadUsers(ObjectManager $manager)
{
$passwordEncoder = $this->container->get('security.password_encoder');
$johnUser = new User();
$johnUser->setUsername('john_user');
$johnUser->setEmail('john_user@symfony.com');
$encodedPassword = $passwordEncoder->encodePassword($johnUser, 'kitten');
$johnUser->setPassword($encodedPassword);
$manager->persist($johnUser);
$this->addReference('john-user', $johnUser);
$annaAdmin = new User();
$annaAdmin->setUsername('anna_admin');
$annaAdmin->setEmail('anna_admin@symfony.com');
$annaAdmin->setRoles(['ROLE_ADMIN']);
$encodedPassword = $passwordEncoder->encodePassword($annaAdmin, 'kitten');
$annaAdmin->setPassword($encodedPassword);
$manager->persist($annaAdmin);
$this->addReference('anna-admin', $annaAdmin);
$manager->flush();
}
private function loadPosts(ObjectManager $manager)
{
foreach (range(1, 30) as $i) {
$post = new Post();
$post->setTitle($this->getRandomPostTitle());
$post->setSummary($this->getRandomPostSummary());
$post->setSlug($this->container->get('slugger')->slugify($post->getTitle()));
$post->setContent($this->getPostContent());
$post->setAuthor($this->getReference('anna-admin'));
$post->setPublishedAt(new \DateTime('now - '.$i.'days'));
foreach (range(1, 5) as $j) {
$comment = new Comment();
$comment->setAuthor($this->getReference('john-user'));
$comment->setPublishedAt(new \DateTime('now + '.($i + $j).'seconds'));
$comment->setContent($this->getRandomCommentContent());
$comment->setPost($post);
$manager->persist($comment);
$post->addComment($comment);
}
$manager->persist($post);
}
$manager->flush();
}
private function getPostContent()
{
return <<<'MARKDOWN'
Lorem ipsum dolor sit amet consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et **dolore magna aliqua**: Duis aute irure dolor in
reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia
deserunt mollit anim id est laborum.
* Ut enim ad minim veniam
* Quis nostrud exercitation *ullamco laboris*
* Nisi ut aliquip ex ea commodo consequat
Praesent id fermentum lorem. Ut est lorem, fringilla at accumsan nec, euismod at
nunc. Aenean mattis sollicitudin mattis. Nullam pulvinar vestibulum bibendum.
Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos
himenaeos. Fusce nulla purus, gravida ac interdum ut, blandit eget ex. Duis a
luctus dolor.
Integer auctor massa maximus nulla scelerisque accumsan. *Aliquam ac malesuada*
ex. Pellentesque tortor magna, vulputate eu vulputate ut, venenatis ac lectus.
Praesent ut lacinia sem. Mauris a lectus eget felis mollis feugiat. Quisque
efficitur, mi ut semper pulvinar, urna urna blandit massa, eget tincidunt augue
nulla vitae est.
Ut posuere aliquet tincidunt. Aliquam erat volutpat. **Class aptent taciti**
sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Morbi
arcu orci, gravida eget aliquam eu, suscipit et ante. Morbi vulputate metus vel
ipsum finibus, ut dapibus massa feugiat. Vestibulum vel lobortis libero. Sed
tincidunt tellus et viverra scelerisque. Pellentesque tincidunt cursus felis.
Sed in egestas erat.
Aliquam pulvinar interdum massa, vel ullamcorper ante consectetur eu. Vestibulum
lacinia ac enim vel placerat. Integer pulvinar magna nec dui malesuada, nec
congue nisl dictum. Donec mollis nisl tortor, at congue erat consequat a. Nam
tempus elit porta, blandit elit vel, viverra lorem. Sed sit amet tellus
tincidunt, faucibus nisl in, aliquet libero.
MARKDOWN;
}
private function getPhrases()
{
return [
'Lorem ipsum dolor sit amet consectetur adipiscing elit',
'Pellentesque vitae velit ex',
'Mauris dapibus risus quis suscipit vulputate',
'Eros diam egestas libero eu vulputate risus',
'In hac habitasse platea dictumst',
'Morbi tempus commodo mattis',
'Ut suscipit posuere justo at vulputate',
'Ut eleifend mauris et risus ultrices egestas',
'Aliquam sodales odio id eleifend tristique',
'Urna nisl sollicitudin id varius orci quam id turpis',
'Nulla porta lobortis ligula vel egestas',
'Curabitur aliquam euismod dolor non ornare',
'Sed varius a risus eget aliquam',
'Nunc viverra elit ac laoreet suscipit',
'Pellentesque et sapien pulvinar consectetur',
];
}
private function getRandomPostTitle()
{
$titles = $this->getPhrases();
return $titles[array_rand($titles)];
}
private function getRandomPostSummary($maxLength = 255)
{
$phrases = $this->getPhrases();
$numPhrases = mt_rand(6, 12);
shuffle($phrases);
return substr(implode(' ', array_slice($phrases, 0, $numPhrases - 1)), 0, $maxLength);
}
private function getRandomCommentContent()
{
$phrases = $this->getPhrases();
$numPhrases = mt_rand(2, 15);
shuffle($phrases);
return implode(' ', array_slice($phrases, 0, $numPhrases - 1));
}
}
| hkbrain/test | src/AppBundle/DataFixtures/ORM/LoadFixtures.php | PHP | mit | 6,826 |
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Downloadable
* @copyright Copyright (c) 2006-2016 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/* @var $installer Mage_Catalog_Model_Resource_Eav_Mysql4_Setup */
$installer = $this;
$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS `{$installer->getTable('catalog/product_index_price')}_downloadable_idx`;
CREATE TABLE `{$installer->getTable('downloadable/product_price_indexer_idx')}` (
`entity_id` int(10) unsigned NOT NULL,
`customer_group_id` smallint(5) unsigned NOT NULL,
`website_id` smallint(5) unsigned NOT NULL,
`min_price` decimal(12,4) default NULL,
`max_price` decimal(12,4) default NULL,
PRIMARY KEY (`entity_id`,`customer_group_id`,`website_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `{$installer->getTable('downloadable/product_price_indexer_tmp')}` (
`entity_id` int(10) unsigned NOT NULL,
`customer_group_id` smallint(5) unsigned NOT NULL,
`website_id` smallint(5) unsigned NOT NULL,
`min_price` decimal(12,4) default NULL,
`max_price` decimal(12,4) default NULL,
PRIMARY KEY (`entity_id`,`customer_group_id`,`website_id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
");
$installer->endSetup();
| hansbonini/cloud9-magento | www/app/code/core/Mage/Downloadable/sql/downloadable_setup/mysql4-upgrade-1.4.0.0-1.4.0.1.php | PHP | mit | 2,062 |
/*******************************************************************************
* Copyright (c) 2015
*
* 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.
*******************************************************************************/
package jsettlers.mapcreator.tools.shapes;
import jsettlers.common.movable.EDirection;
import jsettlers.common.position.ShortPoint2D;
public class LineShape extends ShapeType {
/**
* Constructor
*/
public LineShape() {
super("line");
}
@Override
public void setAffectedStatus(byte[][] fields, ShortPoint2D start, ShortPoint2D end) {
ShortPoint2D current = start;
if (shouldDrawAt(current)) {
setFieldToMax(fields, current);
}
while (!current.equals(end)) {
EDirection d = EDirection.getApproxDirection(current, end);
current = d.getNextHexPoint(current);
if (shouldDrawAt(current)) {
setFieldToMax(fields, current);
}
}
}
protected boolean shouldDrawAt(ShortPoint2D current) {
return true;
}
private static void setFieldToMax(byte[][] fields, ShortPoint2D current) {
short x = current.x;
short y = current.y;
if (x < fields.length && x >= 0 && y >= 0 && y < fields[x].length) {
fields[x][y] = Byte.MAX_VALUE;
}
}
@Override
public int getSize() {
return 1;
}
}
| Peter-Maximilian/settlers-remake | jsettlers.mapcreator/src/main/java/jsettlers/mapcreator/tools/shapes/LineShape.java | Java | mit | 2,269 |
# --
# Copyright 2007 Nominet UK
#
# 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 tmexpress or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ++
require_relative 'spec_helper'
require 'socket'
# @TODO@ We also need a test server so we can control behaviour of server to test
# different aspects of retry strategy.
# Of course, with Ruby's limit of 256 open sockets per process, we'd need to run
# the server in a different Ruby process.
class TestResolver < Minitest::Test
include Dnsruby
Thread::abort_on_exception = true
GOOD_DOMAIN_NAME = 'example.com'
BAD_DOMAIN_NAME = 'dnsruby-test-of-bad-domain-name.blah'
PORT = 42138
@@port = PORT
def setup
Dnsruby::Config.reset
end
def assert_valid_response(response)
assert(response.kind_of?(Message), "Expected response to be a message but was a #{response.class}")
end
def assert_nil_response(response)
assert(response.nil?, "Expected no response but got a #{response.class}:\n#{response}")
end
def assert_error_is_exception(error, error_class = Exception)
assert(error.is_a?(error_class), "Expected error to be an #{error_class}, but was a #{error.class}:\n#{error}")
end
def assert_nil_error(error)
assert(error.nil?, "Expected no error but got a #{error.class}:\n#{error}")
end
def test_send_message
response = Resolver.new.send_message(Message.new("example.com", Types.A))
assert_valid_response(response)
end
def test_send_message_bang_noerror
response, error = Resolver.new.send_message!(Message.new(GOOD_DOMAIN_NAME, Types.A))
assert_nil_error(error)
assert_valid_response(response)
end
def test_send_message_bang_error
message = Message.new(BAD_DOMAIN_NAME, Types.A)
response, error = Resolver.new.send_message!(message)
assert_nil_response(response)
assert_error_is_exception(error)
end
def test_send_plain_message
resolver = Resolver.new
response, error = resolver.send_plain_message(Message.new("cnn.com"))
assert_nil_error(error)
assert_valid_response(response)
m = Message.new(BAD_DOMAIN_NAME)
m.header.rd = true
response, error = resolver.send_plain_message(m)
assert_valid_response(response)
assert_error_is_exception(error, NXDomain)
end
def test_query
response = Resolver.new.query("example.com")
assert_valid_response(response)
end
def test_query_bang_noerror
response, error = Resolver.new.query!(GOOD_DOMAIN_NAME)
assert_nil_error(error)
assert_valid_response(response)
end
def test_query_bang_error
response, error = Resolver.new.query!(BAD_DOMAIN_NAME)
assert_nil_response(response)
assert_error_is_exception(error)
end
def test_query_async
q = Queue.new
Resolver.new.send_async(Message.new("example.com", Types.A),q,q)
id, response, error = q.pop
assert_equal(id, q, "Id wrong!")
assert_valid_response(response)
assert_nil_error(error)
end
def test_query_one_duff_server_one_good
res = Resolver.new({:nameserver => ["8.8.8.8", "8.8.8.7"]})
res.retry_delay=1
q = Queue.new
res.send_async(Message.new("example.com", Types.A),q,q)
id, response, error = q.pop
assert_equal(id, q, "Id wrong!")
assert_valid_response(response)
assert_nil_error(error)
end
# @TODO@ Implement!! But then, why would anyone want to do this?
# def test_many_threaded_clients
# assert(false, "IMPLEMENT!")
# end
def test_reverse_lookup
m = Message.new("8.8.8.8", Types.PTR)
r = Resolver.new
q=Queue.new
r.send_async(m,q,q)
id,ret, error=q.pop
assert(ret.kind_of?(Message))
no_pointer=true
ret.each_answer do |answer|
if (answer.type==Types.PTR)
no_pointer=false
assert(answer.domainname.to_s=~/google/)
end
end
assert(!no_pointer)
end
# def test_bad_host
# res = Resolver.new({:nameserver => "localhost"})
# res.retry_times=1
# res.retry_delay=0
# res.query_timeout = 1
# q = Queue.new
# res.send_async(Message.new("example.com", Types.A), q, q)
# id, m, err = q.pop
# assert(id==q)
# assert(m == nil)
# assert(err.kind_of?(OtherResolvError) || err.kind_of?(IOError), "OtherResolvError or IOError expected : got #{err.class}")
# end
#
def test_nxdomain
resolver = Resolver.new
q = Queue.new
resolver .send_async(Message.new(BAD_DOMAIN_NAME, Types.A), q, 1)
id, m, error = q.pop
assert(id==1, "Id should have been 1 but was #{id}")
assert(m.rcode == RCode.NXDOMAIN, "Expected NXDOMAIN but got #{m.rcode} instead.")
assert_error_is_exception(error, NXDomain)
end
def test_timeouts
# test timeout behaviour for different retry, retrans, total timeout etc.
# Problem here is that many sockets will be created for queries which time out.
# Run a query which will not respond, and check that the timeout works
if (!RUBY_PLATFORM=~/darwin/)
start=stop=0
retry_times = 3
retry_delay=1
packet_timeout=2
# Work out what time should be, then time it to check
expected = ((2**(retry_times-1))*retry_delay) + packet_timeout
begin
res = Dnsruby::Resolver.new({:nameserver => "10.0.1.128"})
# res = Resolver.new({:nameserver => "213.248.199.17"})
res.packet_timeout=packet_timeout
res.retry_times=retry_times
res.retry_delay=retry_delay
start=Time.now
m = res.send_message(Message.new("a.t.dnsruby.validation-test-servers.nominet.org.uk", Types.A))
fail
rescue ResolvTimeout
stop=Time.now
time = stop-start
assert(time <= expected * 1.3 && time >= expected * 0.9, "Wrong time take, expected #{expected}, took #{time}")
end
end
end
def test_packet_timeout
res = Dnsruby::Resolver.new({:nameserver => []})
# res = Resolver.new({:nameserver => "10.0.1.128"})
start=stop=0
retry_times = retry_delay = packet_timeout= 10
query_timeout=2
begin
res.packet_timeout=packet_timeout
res.retry_times=retry_times
res.retry_delay=retry_delay
res.query_timeout=query_timeout
# Work out what time should be, then time it to check
expected = query_timeout
start=Time.now
m = res.send_message(Message.new("a.t.dnsruby.validation-test-servers.nominet.org.uk", Types.A))
fail
rescue Dnsruby::ResolvTimeout
stop=Time.now
time = stop-start
assert(time <= expected * 1.3 && time >= expected * 0.9, "Wrong time take, expected #{expected}, took #{time}")
end #
end
def test_queue_packet_timeout
# if (!RUBY_PLATFORM=~/darwin/)
res = Dnsruby::Resolver.new({:nameserver => "10.0.1.128"})
# bad = SingleResolver.new("localhost")
res.add_server("localhost")
expected = 2
res.query_timeout=expected
q = Queue.new
start = Time.now
m = res.send_async(Message.new("a.t.dnsruby.validation-test-servers.nominet.org.uk", Types.A), q, q)
id,ret,err = q.pop
stop = Time.now
assert(id=q)
assert(ret==nil)
assert(err.class == ResolvTimeout, "#{err.class}, #{err}")
time = stop-start
assert(time <= expected * 1.3 && time >= expected * 0.9, "Wrong time take, expected #{expected}, took #{time}")
# end
end
def test_illegal_src_port
# Also test all singleresolver ports ok
# Try to set src_port to an illegal value - make sure error raised, and port OK
res = Dnsruby::Resolver.new
res.port = 56789
tests = [53, 387, 1265, 3210, 48619]
tests.each do |bad_port|
begin
res.src_port = bad_port
fail("bad port #{bad_port}")
rescue
end
end
assert(res.single_resolvers[0].src_port = 56789)
end
def test_add_src_port
# Try setting and adding port ranges, and invalid ports, and 0.
# Also test all singleresolver ports ok
res = Resolver.new
res.src_port = [56789,56790, 56793]
assert(res.src_port == [56789,56790, 56793])
res.src_port = 56889..56891
assert(res.src_port == [56889,56890,56891])
res.add_src_port(60000..60002)
assert(res.src_port == [56889,56890,56891,60000,60001,60002])
res.add_src_port([60004,60005])
assert(res.src_port == [56889,56890,56891,60000,60001,60002,60004,60005])
res.add_src_port(60006)
assert(res.src_port == [56889,56890,56891,60000,60001,60002,60004,60005,60006])
# Now test invalid src_ports
tests = [0, 53, [60007, 53], [60008, 0], 55..100]
tests.each do |x|
begin
res.add_src_port(x)
fail()
rescue
end
end
assert(res.src_port == [56889,56890,56891,60000,60001,60002,60004,60005,60006])
assert(res.single_resolvers[0].src_port == [56889,56890,56891,60000,60001,60002,60004,60005,60006])
end
def test_eventtype_api
# @TODO@ TEST THE Resolver::EventType interface!
end
end
# Tests to see that query_raw handles send_plain_message's return values correctly.
class TestRawQuery < Minitest::Test
KEY_NAME = 'key-name'
KEY = '0123456789'
ALGO = 'hmac-md5'
class CustomError < RuntimeError; end
# Returns a new resolver whose send_plain_message method always returns
# nil for the response, and a RuntimeError for the error.
def resolver_returning_error
resolver = Dnsruby::Resolver.new
def resolver.send_plain_message(_message)
[nil, CustomError.new]
end
resolver
end
# Returns a new resolver whose send_plain_message is overridden to return
# :response_from_send_plain_message instead of a real Dnsruby::Message,
# for easy comparison in the tests.
def resolver_returning_response
resolver = Dnsruby::Resolver.new
def resolver.send_plain_message(_message)
[:response_from_send_plain_message, nil]
end
resolver
end
# Test that when a strategy other than :raise or :return is passed,
# an ArgumentError is raised.
def test_bad_strategy
assert_raises(ArgumentError) do
resolver_returning_error.query_raw(Dnsruby::Message.new, :invalid_strategy)
end
end
# Test that when send_plain_message returns an error,
# and the error strategy is :raise, query_raw raises an error.
def test_raise_error
assert_raises(CustomError) do
resolver_returning_error.query_raw(Dnsruby::Message.new, :raise)
end
end
# Tests that if you don't specify an error strategy, an error will be
# returned rather than raised (i.e. strategy defaults to :return).
def test_return_error_is_default
_response, error = resolver_returning_error.query_raw(Dnsruby::Message.new)
assert error.is_a?(CustomError)
end
# Tests that when no error is returned, no error is raised.
def test_raise_no_error
response, _error = resolver_returning_response.query_raw(Dnsruby::Message.new, :raise)
assert_equal :response_from_send_plain_message, response
end
# Test that when send_plain_message returns an error, and the error strategy
# is set to :return, then an error is returned.
def test_return_error
_response, error = resolver_returning_error.query_raw(Dnsruby::Message.new, :return)
assert error.is_a?(CustomError)
end
# Test that when send_plain_message returns a valid and response
# and nil error, the same are returned by query_raw.
def test_return_no_error
response, error = resolver_returning_response.query_raw(Dnsruby::Message.new, :return)
assert_nil error
assert_equal :response_from_send_plain_message, response
end
def test_2_args_init
options = Dnsruby::Resolver.create_tsig_options(KEY_NAME, KEY)
assert_equal KEY_NAME, options[:name]
assert_equal KEY, options[:key]
assert_nil options[:algorithm]
end
def test_3_args_init
options = Dnsruby::Resolver.create_tsig_options(KEY_NAME,KEY,ALGO)
assert_equal KEY_NAME, options[:name]
assert_equal KEY, options[:key]
assert_equal ALGO, options[:algorithm]
end
def test_threads
resolver = Dnsruby::Resolver.new(nameserver: ["8.8.8.8", "8.8.4.4"])
resolver.query("google.com", "MX")
resolver.query("google.com", "MX")
resolver.query("google.com", "MX")
begin
resolver.query("googlöe.com", "MX")
rescue Dnsruby::ResolvError => e
# fine
end
resolver.query("google.com", "MX")
resolver.query("google.com", "MX")
begin
resolver.query("googlöe.com", "MX")
rescue Dnsruby::ResolvError => e
# fine
end
begin
resolver.query("googlöe.com", "MX")
rescue Dnsruby::ResolvError => e
# fine
end
# Dnsruby::Cache.delete("googlöe.com", "MX")
end
end
| NerdSec/nerdsec.github.io | vendor/bundle/ruby/2.7.0/gems/dnsruby-1.61.3/test/tc_resolver.rb | Ruby | cc0-1.0 | 13,226 |
/*
* Copyright (c) 2014 Cisco Systems, Inc. and others. 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
*/
package org.opendaylight.controller.northbound.commons.utils;
import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.core.Response;
import org.opendaylight.controller.containermanager.IContainerAuthorization;
import org.opendaylight.controller.sal.authorization.Privilege;
import org.opendaylight.controller.sal.authorization.UserLevel;
import org.opendaylight.controller.sal.core.Description;
import org.opendaylight.controller.sal.core.Name;
import org.opendaylight.controller.sal.core.Node;
import org.opendaylight.controller.sal.core.NodeConnector;
import org.opendaylight.controller.sal.utils.GlobalConstants;
import org.opendaylight.controller.sal.utils.ServiceHelper;
import org.opendaylight.controller.sal.utils.Status;
import org.opendaylight.controller.sal.utils.StatusCode;
import org.opendaylight.controller.switchmanager.ISwitchManager;
import org.opendaylight.controller.usermanager.IUserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NorthboundUtils {
private static final Map<StatusCode, Response.Status> ResponseStatusMapping = new HashMap<StatusCode, Response.Status>() {
private static final long serialVersionUID = 1L;
{
put(StatusCode.SUCCESS, Response.Status.OK);
put(StatusCode.BADREQUEST, Response.Status.BAD_REQUEST);
put(StatusCode.UNAUTHORIZED, Response.Status.UNAUTHORIZED);
put(StatusCode.FORBIDDEN, Response.Status.FORBIDDEN);
put(StatusCode.NOTFOUND, Response.Status.NOT_FOUND);
put(StatusCode.NOTALLOWED, Response.Status.FORBIDDEN);
put(StatusCode.NOTACCEPTABLE, Response.Status.NOT_ACCEPTABLE);
put(StatusCode.TIMEOUT, Response.Status.GONE);
put(StatusCode.CONFLICT, Response.Status.CONFLICT);
put(StatusCode.GONE, Response.Status.GONE);
put(StatusCode.UNSUPPORTED, Response.Status.BAD_REQUEST);
put(StatusCode.INTERNALERROR, Response.Status.INTERNAL_SERVER_ERROR);
put(StatusCode.NOTIMPLEMENTED, Response.Status.NOT_ACCEPTABLE);
put(StatusCode.NOSERVICE, Response.Status.SERVICE_UNAVAILABLE);
put(StatusCode.UNDEFINED, Response.Status.BAD_REQUEST);
}
};
private static final String AUDIT = "audit";
private static final Logger logger = LoggerFactory.getLogger(AUDIT);
// Suppress default constructor for noninstantiability
private NorthboundUtils() {
}
/**
* Returns Response.Status for a given status. If the status is null or if
* the corresponding StatusCode is not present in the ResponseStatusMapping,
* it returns null.
*
* @param status
* The Status
* @return The Response.Status for a given status
*/
public static Response.Status getResponseStatus(Status status) {
return ResponseStatusMapping.get(status.getCode());
}
/**
* Returns Response for a given status. If the status provided is null or if
* the corresponding StatusCode is not present in the ResponseStatusMapping,
* it returns Response with StatusType as INTERNAL_SERVER_ERROR.
*
* @param status
* The Status
* @return The Response for a given status.
*/
public static Response getResponse(Status status) {
if ((status == null) || (!ResponseStatusMapping.containsKey(status.getCode()))) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Action Result Unknown").build();
}
return Response.status(ResponseStatusMapping.get(status.getCode())).entity(status.getDescription()).build();
}
/**
* Returns whether the current user has the required privilege on the
* specified container
*
* @param userName
* The user name
* @param containerName
* The container name
* @param required
* Operation to be performed - READ/WRITE
* @param bundle
* Class from where the function is invoked
* @return The Status of the request, either Success or Unauthorized
*/
public static boolean isAuthorized(String userName, String containerName, Privilege required, Object bundle) {
if (containerName.equals(GlobalConstants.DEFAULT.toString())) {
IUserManager auth = (IUserManager) ServiceHelper.getGlobalInstance(IUserManager.class, bundle);
switch (required) {
case WRITE:
return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKADMIN.ordinal());
case READ:
return (auth.getUserLevel(userName).ordinal() <= UserLevel.NETWORKOPERATOR.ordinal());
default:
return false;
}
} else {
IContainerAuthorization auth = (IContainerAuthorization) ServiceHelper.getGlobalInstance(
IContainerAuthorization.class, bundle);
if (auth == null) {
return false;
}
Privilege current = auth.getResourcePrivilege(userName, containerName);
if (required.ordinal() > current.ordinal()) {
return false;
}
}
return true;
}
public static void auditlog(String moduleName, String user, String action, String resource,
String containerName) {
String auditMsg = "";
String mode = "REST";
if (containerName != null) {
auditMsg = "Mode: " + mode + " User " + user + " " + action + " " + moduleName + " " + resource + " in container "
+ containerName;
} else {
auditMsg = "Mode: " + mode + " User " + user + " " + action + " " + moduleName + " " + resource;
}
logger.trace(auditMsg);
}
public static void auditlog(String moduleName, String user, String action, String resource) {
auditlog(moduleName, user, action, resource, null);
}
public static String getNodeDesc(Node node, ISwitchManager switchManager) {
Description desc = (Description) switchManager.getNodeProp(node,
Description.propertyName);
String description = (desc == null) ? "" : desc.getValue();
return (description.isEmpty() || description.equalsIgnoreCase("none")) ? node
.toString() : description;
}
public static String getNodeDesc(Node node, String containerName,
Object bundle) {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, containerName, bundle);
if (switchManager == null) {
return null;
}
return getNodeDesc(node, switchManager);
}
public static String getNodeDesc(Node node, Object bundle) {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class,
GlobalConstants.DEFAULT.toString(), bundle);
if (switchManager == null) {
return null;
}
return getNodeDesc(node, switchManager);
}
public static String getPortName(NodeConnector nodeConnector,
String container, Object bundle) {
ISwitchManager switchManager = (ISwitchManager) ServiceHelper
.getInstance(ISwitchManager.class, container, bundle);
return getPortName(nodeConnector, switchManager);
}
public static String getPortName(NodeConnector nodeConnector, Object bundle) {
return getPortName(nodeConnector, GlobalConstants.DEFAULT.toString(), bundle);
}
public static String getPortName(NodeConnector nodeConnector,
ISwitchManager switchManager) {
Name ncName = ((Name) switchManager.getNodeConnectorProp(nodeConnector,
Name.NamePropName));
String nodeConnectorName = (ncName != null) ? ncName.getValue() : nodeConnector.getNodeConnectorIdAsString();
nodeConnectorName = nodeConnectorName + "@"
+ getNodeDesc(nodeConnector.getNode(), switchManager);
return nodeConnectorName.substring(0, nodeConnectorName.length());
}
}
| yuyf10/opendaylight-controller | opendaylight/northbound/commons/src/main/java/org/opendaylight/controller/northbound/commons/utils/NorthboundUtils.java | Java | epl-1.0 | 8,516 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.framework.help;
import javax.swing.JOptionPane;
import org.eclipse.persistence.tools.workbench.framework.action.AbstractFrameworkAction;
import org.eclipse.persistence.tools.workbench.framework.context.WorkbenchContext;
/**
* There should be one HelpTopicIDWindowAction per WorkbenchWindow.
* This command should ONLY be used in "development" mode.
*/
final class HelpTopicIDWindowAction extends AbstractFrameworkAction {
/**
* Construct an action that will open the Help Topic ID window.
* There is only one window per application.
*/
HelpTopicIDWindowAction(WorkbenchContext context) {
super(context);
}
/**
* initialize stuff
*/
protected void initialize() {
super.initialize();
this.initializeTextAndMnemonic("HELP_TOPIC_ID_WINDOW");
this.initializeToolTipText("HELP_TOPIC_ID_WINDOW.TOOL_TIP");
}
/**
* ignore the selected nodes
*/
protected void execute() {
// no need for localization - this should only occur in development
JOptionPane.showMessageDialog(this.currentWindow(), "Invalid Help Manager: ");
}
}
| RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench/framework/source/org/eclipse/persistence/tools/workbench/framework/help/HelpTopicIDWindowAction.java | Java | epl-1.0 | 1,916 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.tools.workbench.test.mappingsmodel.query;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.persistence.tools.workbench.test.models.projects.EmployeeProject;
import org.eclipse.persistence.tools.workbench.test.utility.TestTools;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.MWDescriptor;
import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.relational.MWTableDescriptor;
import org.eclipse.persistence.tools.workbench.mappingsmodel.descriptor.relational.MWUserDefinedQueryKey;
import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.relational.MWDirectToFieldMapping;
import org.eclipse.persistence.tools.workbench.mappingsmodel.mapping.relational.MWOneToOneMapping;
import org.eclipse.persistence.tools.workbench.mappingsmodel.project.MWProject;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.MWQueryManager;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.MWQueryParameter;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWBasicExpression;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWCompoundExpression;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWExpression;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWExpressionQueryFormat;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWLiteralArgument;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWNullArgument;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWQueryParameterArgument;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWQueryableArgument;
import org.eclipse.persistence.tools.workbench.mappingsmodel.query.relational.MWRelationalReadQuery;
/**
*
*/
public class MWExpressionTests extends TestCase
{
private MWProject employeeProject;
public static Test suite()
{
return new TestSuite(MWExpressionTests.class);
}
public MWExpressionTests(String name)
{
super(name);
}
private MWOneToOneMapping getAddressMapping()
{
return (MWOneToOneMapping)((MWTableDescriptor) getDescriptorWithShortName("Employee")).mappingNamed("address");
}
private MWDirectToFieldMapping getCityMapping()
{
return (MWDirectToFieldMapping) ((MWTableDescriptor) getDescriptorWithShortName("Address")).mappingNamed("city");
}
private MWDirectToFieldMapping getLastNameMapping()
{
return (MWDirectToFieldMapping) ((MWTableDescriptor) getDescriptorWithShortName("Employee")).mappingNamed("lastName");
}
protected void setUp() throws Exception {
super.setUp();
this.employeeProject = new EmployeeProject().getProject();
}
protected void tearDown() throws Exception {
TestTools.clear(this);
super.tearDown();
}
public void testAddingExpressions()
{
MWRelationalReadQuery query = buildTestQuery();
MWCompoundExpression mainExpression = ((MWExpressionQueryFormat)query.getQueryFormat()).getExpression();
assertTrue("An expression was not created by default for the query", mainExpression != null);
MWBasicExpression basicExpression = mainExpression.addBasicExpression();
assertTrue("An expression was not added",mainExpression.expressionsSize() == 1);
assertTrue("The first argument is not a queryable argument", MWQueryableArgument.class.isAssignableFrom(basicExpression.getFirstArgument().getClass()));
assertTrue("The expression added is not a MWBasicExpression", MWBasicExpression.class.isAssignableFrom(basicExpression.getClass()));
assertTrue("The second argument is not a literal argument", MWLiteralArgument.class.isAssignableFrom(basicExpression.getSecondArgument().getClass()));
MWTableDescriptor employeeDescriptor = (MWTableDescriptor) query.getProject().descriptorForTypeNamed("org.eclipse.persistence.tools.workbench.test.models.employee.Employee");
MWDirectToFieldMapping lastNameMapping = (MWDirectToFieldMapping) employeeDescriptor.mappingNamed("lastName");
basicExpression.getFirstArgument().setQueryableArgument(lastNameMapping);
assertTrue("The queryable argument was not set", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == lastNameMapping);
employeeDescriptor.removeMapping(lastNameMapping);
assertTrue("The queryable argument was not deleted as a result of the mapping being deleted", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
assertTrue("The queryable argument was not deleted as a result of the mapping being deleted", basicExpression.getFirstArgument().getQueryableArgumentElement().getJoinedQueryableElement() == null);
}
public void testChangingBasicExpressionOperatorType()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().getExpression(0);
basicExpression.setOperatorType(MWBasicExpression.IS_NULL);
basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().getExpression(0);
assertTrue("The operator type was not set to IS_NULL", basicExpression.getOperatorType() == MWBasicExpression.IS_NULL);
assertTrue("The second argument is not an instanceof MWNullArgument for the unary expression", basicExpression.getSecondArgument() instanceof MWNullArgument);
assertTrue("Changing the operator type did change the type of the expression", MWBasicExpression.class.isAssignableFrom(basicExpression.getClass()));
assertTrue("The parent of the queryableArgument was not set correctlyafter morphing to a UnaryExpression", basicExpression.getFirstArgument().getParent() == basicExpression);
basicExpression.setOperatorType(MWBasicExpression.LIKE_IGNORE_CASE);
basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().getExpression(0);
assertTrue("The operator type was not set to LIKE_IGNORE_CASE", basicExpression.getOperatorType() == MWBasicExpression.LIKE_IGNORE_CASE);
assertTrue("The second argument is null for the binary expression", basicExpression.getSecondArgument() != null);
assertTrue("Changing the operator type did change the type of the expression", MWBasicExpression.class.isAssignableFrom(basicExpression.getClass()));
assertTrue("The parent of the queryableArgument was not set correctly after morphing to a BinaryExpression", basicExpression.getFirstArgument().getParent() == basicExpression);
}
public void testChangingCompoundExpressionOperatorType()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWCompoundExpression expression = query.getQueryFormat().getExpression();
assertTrue("The operator was not set to AND by default", expression.getOperatorType().equals(MWCompoundExpression.AND));
expression.setOperatorType(MWCompoundExpression.NOR);
assertTrue("The operator was not set to NOR", expression.getOperatorType().equals(MWCompoundExpression.NOR));
}
public void testMorphingDescriptor()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
assertTrue("The queryable argument was not set", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == getCityMapping());
assertTrue("The joined queryable argument was not set", basicExpression.getFirstArgument().getQueryableArgumentElement().getJoinedQueryableElement().getQueryable() == getAddressMapping());
//test morphing the address descriptor
((MWTableDescriptor) getDescriptorWithShortName("Address")).asMWAggregateDescriptor();
assertTrue("The first argument was set to null when the reference descriptor was morphed", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() != null);
}
public void testRemovingDescriptor()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
//test removing the address descriptor
MWTableDescriptor descriptor = ((MWTableDescriptor) getDescriptorWithShortName("Address"));
descriptor.getProject().removeDescriptor(descriptor);
assertTrue("The first argument was not set to null when the reference descriptor was removed, thus set to null", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
}
public void testRenamingDescriptor()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
MWDirectToFieldMapping cityMapping = getCityMapping();
//test renaming the address descriptor
MWTableDescriptor descriptor = ((MWTableDescriptor) getDescriptorWithShortName("Address"));
descriptor.getMWClass().setName("MyAddress");
descriptor.setName("MyAddress");
assertTrue("The first argument is no longer the same", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == cityMapping);
assertTrue("The descriptor was renamed but the queryable is still holding on to an old copy", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable().getParentDescriptor().getName().equals("MyAddress"));
}
public void testRemovingMapping()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
//test removing the city mapping
MWTableDescriptor descriptor = ((MWTableDescriptor) getDescriptorWithShortName("Address"));
descriptor.removeMapping(getCityMapping());
assertTrue("The first argument queryable element was not removed when the mapping was removed", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
}
public void testUnmappingJoinedQueryable()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
//test unmapping the address mapping
MWOneToOneMapping addressMapping = getAddressMapping();
addressMapping.getParentDescriptor().removeMapping(addressMapping);
assertTrue("The first argument queryable element was not removed when the joined mapping was unmapped", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
}
public void testMorhpingJoinedQueryable()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
//test unmapping the address mapping
MWOneToOneMapping addressMapping = getAddressMapping();
addressMapping.asMWOneToManyMapping();
assertTrue("The first argument queryable element was removed when the joined mapping was morhphed into a 1-many", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == getCityMapping());
}
public void testRemovingJoinedQueryable()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
//test removing the address mapping
MWOneToOneMapping addressMapping = getAddressMapping();
addressMapping.getParentDescriptor().removeMapping(addressMapping);
assertTrue("The first argument queryable element was not removed when the joined mapping was removed", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
}
public void testRenamingMapping()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
//test renaming the city mapping
MWDirectToFieldMapping cityMapping = getCityMapping();
cityMapping.getInstanceVariable().setName("myCity");
cityMapping.setName("myCity");
assertTrue("The first argument queryable element was not renamed", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable().getName().equals("myCity"));
}
public void testMappingReferenceDescriptorSetToNull()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression) ((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
MWOneToOneMapping addressMapping = getAddressMapping();
addressMapping.setReferenceDescriptor(null);
assertTrue("The first argument queryable element was not removed", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
}
public void testMappingReferenceDescriptorChanged()
{
MWRelationalReadQuery query = buildTestQueryWithExpression();
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().getExpression(0);
MWOneToOneMapping addressMapping = getAddressMapping();
addressMapping.setReferenceDescriptor(getDescriptorWithShortName("Project"));
assertTrue("The first argument queryable element was not removed", basicExpression.getFirstArgument().getQueryableArgumentElement().getQueryable() == null);
}
public void testQueryParameterDeleted()
{
MWRelationalReadQuery query = buildTestQueryWithExpressionWithParameterArgument();
query.removeParameter(query.getParameter(0));
MWBasicExpression basicExpression = (MWBasicExpression)((MWExpressionQueryFormat)query.getQueryFormat()).getExpression().expressions().next();
assertTrue("The parameter arugment was not deleted when the parameter was deleted", ((MWQueryParameterArgument)basicExpression.getSecondArgument()).getQueryParameter() == null);
}
public void testRemovingExpression()
{
MWRelationalReadQuery query = buildTestQueryWithCompoundExpression();
MWCompoundExpression subCompoundExpression = (MWCompoundExpression) query.getQueryFormat().getExpression().expressions().next();
MWExpression expressionToRemove = (MWExpression) subCompoundExpression.expressions().next();
subCompoundExpression.removeExpression(expressionToRemove);
assertTrue("", subCompoundExpression.expressionsSize() == 1);
}
public void testRemovingQueryKey()
{
MWRelationalReadQuery query = buildTestQueryWithCompoundExpression();
MWCompoundExpression subCompoundExpression = (MWCompoundExpression) query.getQueryFormat().getExpression().expressions().next();
MWBasicExpression basicExpression = (MWBasicExpression) subCompoundExpression.getExpression(1);
MWTableDescriptor desc = (MWTableDescriptor) getDescriptorWithShortName("Employee");
desc.removeQueryKey((MWUserDefinedQueryKey) desc.queryKeyNamed("foo"));
assertTrue("The queryable was not set to null when the query key was removed", ((MWQueryableArgument) basicExpression.getSecondArgument()).getQueryableArgumentElement().getQueryable() == null);
}
//test removing expressions
//test adding sub compound expressions
//test removing expressions and make sure sub expressions are removed
//test MWCompoundExpression.removeAllSubExpressions
private MWRelationalReadQuery buildTestQueryWithExpression()
{
MWRelationalReadQuery query = buildTestQuery();
MWCompoundExpression mainExpression = ((MWExpressionQueryFormat)query.getQueryFormat()).getExpression();
MWBasicExpression basicExpression = mainExpression.addBasicExpression();
//set up the basic expression address.city equals ""
MWOneToOneMapping addressMapping = getAddressMapping();
MWDirectToFieldMapping cityMapping = getCityMapping();
List joinedQueryables = new ArrayList();
joinedQueryables.add(cityMapping);
joinedQueryables.add(addressMapping);
basicExpression.getFirstArgument().setQueryableArgument(joinedQueryables.iterator());
return query;
}
private MWRelationalReadQuery buildTestQueryWithCompoundExpression()
{
MWRelationalReadQuery query = buildTestQuery();
MWCompoundExpression mainExpression = ((MWExpressionQueryFormat)query.getQueryFormat()).getExpression();
MWCompoundExpression subCompoundExpression = mainExpression.addSubCompoundExpression();
MWBasicExpression basicExpression = subCompoundExpression.addBasicExpression();
//set up the basic expression address.city equals ""
MWOneToOneMapping addressMapping = getAddressMapping();
MWDirectToFieldMapping cityMapping = getCityMapping();
List joinedQueryables = new ArrayList();
joinedQueryables.add(cityMapping);
joinedQueryables.add(addressMapping);
basicExpression.getFirstArgument().setQueryableArgument(joinedQueryables.iterator());
MWTableDescriptor desc = (MWTableDescriptor) getDescriptorWithShortName("Employee");
MWUserDefinedQueryKey queryKey = desc.addQueryKey("foo", null);
basicExpression.setSecondArgumentToQueryable();
((MWQueryableArgument) basicExpression.getSecondArgument()).setQueryableArgument(queryKey);
return query;
}
private MWRelationalReadQuery buildTestQueryWithExpressionWithParameterArgument()
{
MWRelationalReadQuery query = buildTestQuery();
MWQueryParameter parameter = query.addParameter(this.employeeProject.typeNamed("java.lang.String"));
parameter.setName("lastName");
MWCompoundExpression mainExpression = ((MWExpressionQueryFormat)query.getQueryFormat()).getExpression();
MWBasicExpression basicExpression = mainExpression.addBasicExpression();
//set up the basic expression lastName equals lastName(parameter)
MWDirectToFieldMapping cityMapping = getLastNameMapping();
basicExpression.getFirstArgument().setQueryableArgument(cityMapping);
basicExpression.setSecondArgumentToParameter();
((MWQueryParameterArgument)basicExpression.getSecondArgument()).setQueryParameter(parameter);
return query;
}
private MWRelationalReadQuery buildTestQuery()
{
MWTableDescriptor desc = (MWTableDescriptor) getDescriptorWithShortName("Employee");
MWQueryManager qm = desc.getQueryManager();
MWRelationalReadQuery query = (MWRelationalReadQuery) qm.addReadObjectQuery("test-query");
return query;
}
public MWDescriptor getDescriptorWithShortName(String name) {
for (Iterator stream = this.employeeProject.descriptors(); stream.hasNext(); ) {
MWDescriptor descriptor = (MWDescriptor) stream.next();
if (descriptor.getMWClass().shortName().equals(name)) {
return descriptor;
}
}
throw new IllegalArgumentException(name);
}
}
| RallySoftware/eclipselink.runtime | utils/eclipselink.utils.workbench.test/mappingsplugin/source/org/eclipse/persistence/tools/workbench/test/mappingsmodel/query/MWExpressionTests.java | Java | epl-1.0 | 21,076 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.testing.models.jpa.datatypes.arraypks;
import java.util.UUID;
import javax.persistence.*;
@Entity
@Table(name = "CMP3_PBYTEARRAYPK_TYPE")
public class PrimByteArrayPKType implements java.io.Serializable{
public PrimByteArrayPKType() {
}
private byte[] id;
public PrimByteArrayPKType(byte[] primitiveByteArrayData)
{
this.id = primitiveByteArrayData;
}
@Id
public byte[] getId()
{
return id;
}
public void setId(byte[] id)
{
this.id= id;
}
private static final int UUID_LENGTH = 0x10;
private static int BITSPERLONG = 0x40;
private static int BITSPERBYTE = 0x8;
public void createRandomId() {
UUID uuid = UUID.randomUUID();
id = getBytes(uuid);
}
public static byte[] getBytes(UUID u) {
byte [] raw = new byte [UUID_LENGTH];
long msb = u.getMostSignificantBits();
long lsb = u.getLeastSignificantBits();
/*
* Convert 2 longs to 16 bytes.
*/
int i = 0;
for (int sh = BITSPERLONG - BITSPERBYTE; sh >= 0; sh -= BITSPERBYTE) {
raw [i++] = (byte) (msb >> sh);
}
for (int sh = BITSPERLONG - BITSPERBYTE; sh >= 0; sh -= BITSPERBYTE) {
raw [i++] = (byte) (lsb >> sh);
}
return raw;
}
}
| RallySoftware/eclipselink.runtime | jpa/eclipselink.jpa.test/src/org/eclipse/persistence/testing/models/jpa/datatypes/arraypks/PrimByteArrayPKType.java | Java | epl-1.0 | 2,086 |
/*******************************************************************************
* Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Oracle - initial API and implementation from Oracle TopLink
******************************************************************************/
package org.eclipse.persistence.internal.eis.adapters.jms;
import javax.resource.cci.*;
/**
* INTERNAL:
* Interaction spec for JMS JCA adapter.
*
* @author Dave McCann
* @since OracleAS TopLink 10<i>g</i> (10.0.3)
*/
public abstract class CciJMSInteractionSpec implements InteractionSpec {
protected String destinationURL;// JNDI name (URL) of the destination (queue/topic)
protected String destination;// if no JNDI, the destination name
protected String messageSelector;// message selector to link the request and response messages
/**
* Default constructor.
*/
public CciJMSInteractionSpec() {
destinationURL = "";
destination = "";
messageSelector = "";
}
/**
* Indicates if a JNDI lookup is to be performed to locate the destination.
*
* @return true if a destination URL has been specified, false otherwise
*/
public boolean hasDestinationURL() {
return (destinationURL != null) && (destinationURL.length() > 0);
}
/**
* Set the destination URL to be looked up.
*
* @param url - the destination name as registered in JNDI
*/
public void setDestinationURL(String url) {
destinationURL = url;
}
/**
* Return the URL of the destination.
*
* @return the destination name as registered in JNDI
*/
public String getDestinationURL() {
return destinationURL;
}
/**
* Set the name of the destination to be used. This is required if JNDI is
* not being used to lookup the destination.
*
* @param dest
*/
public void setDestination(String dest) {
destination = dest;
}
/**
* Return the name of the destination - required if JNDI is not being used.
*
* @return the name of the destination to be used
*/
public String getDestination() {
return destination;
}
/**
* Sets the message selector to be used to link the request and response messages.
* If this value is not set, it is assumed that the entity processing the request
* will set the JMSCorrelationID of the reponse message using the JMSMessageID of
* the request messsage.
*
* @param selector
*/
public void setMessageSelector(String selector) {
messageSelector = selector;
}
/**
* Returns the message selector to be used to link the request and response messages.
*
* @return the message selector.
*/
public String getMessageSelector() {
return messageSelector;
}
/**
* Returns the message selector in the appropriate format. The selector is
* set in JMS message selector format: "JMSCorrelationID = 'message_selector'
*
* @return formatted message selector - uses JMSCorrelationID
*/
public String getFormattedMessageSelector() {
return "JMSCorrelationID = '" + messageSelector + "'";
}
/**
* Indicates if the user has set a message selector.
*
* @return true if a message selector has been set, false otherwise
*/
public boolean hasMessageSelector() {
return (messageSelector != null) && (messageSelector.length() > 0);
}
/**
* Returns the destination URL or class
*
* @return destination URL or destination class
*/
public String toString() {
if (hasDestinationURL()) {
return getClass().getName() + "(" + getDestinationURL() + ")";
}
return getClass().getName() + "(" + getDestination() + ")";
}
}
| RallySoftware/eclipselink.runtime | foundation/org.eclipse.persistence.nosql/src/org/eclipse/persistence/internal/eis/adapters/jms/CciJMSInteractionSpec.java | Java | epl-1.0 | 4,313 |
/*
* Copyright (C) 2008-2017 TrinityCore <http://www.trinitycore.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "SpellScript.h"
#include "Cell.h"
#include "CellImpl.h"
#include "GridNotifiers.h"
#include "GridNotifiersImpl.h"
#include "ulduar.h"
enum FreyaYells
{
// Freya
SAY_AGGRO = 0,
SAY_AGGRO_WITH_ELDER = 1,
SAY_SLAY = 2,
SAY_DEATH = 3,
SAY_BERSERK = 4,
SAY_SUMMON_CONSERVATOR = 5,
SAY_SUMMON_TRIO = 6,
SAY_SUMMON_LASHERS = 7,
EMOTE_LIFEBINDERS_GIFT = 8,
EMOTE_ALLIES_OF_NATURE = 9,
EMOTE_GROUND_TREMOR = 10,
EMOTE_IRON_ROOTS = 11,
// Elder Brightleaf / Elder Ironbranch / Elder Stonebark
SAY_ELDER_AGGRO = 0,
SAY_ELDER_SLAY = 1,
SAY_ELDER_DEATH = 2
};
enum FreyaSpells
{
// Freya
SPELL_ATTUNED_TO_NATURE = 62519,
SPELL_TOUCH_OF_EONAR = 62528,
SPELL_SUNBEAM = 62623,
SPELL_ENRAGE = 47008,
SPELL_FREYA_GROUND_TREMOR = 62437,
SPELL_ROOTS_FREYA = 62283,
SPELL_STONEBARK_ESSENCE = 62483,
SPELL_IRONBRANCH_ESSENCE = 62484,
SPELL_BRIGHTLEAF_ESSENCE = 62485,
SPELL_DRAINED_OF_POWER = 62467,
SPELL_SUMMON_EONAR_GIFT = 62572,
// Stonebark
SPELL_FISTS_OF_STONE = 62344,
SPELL_GROUND_TREMOR = 62325,
SPELL_PETRIFIED_BARK = 62337,
SPELL_PETRIFIED_BARK_DMG = 62379,
// Ironbranch
SPELL_IMPALE = 62310,
SPELL_ROOTS_IRONBRANCH = 62438,
SPELL_THORN_SWARM = 62285,
// Brightleaf
SPELL_FLUX_AURA = 62239,
SPELL_FLUX = 62262,
SPELL_FLUX_PLUS = 62251,
SPELL_FLUX_MINUS = 62252,
SPELL_SOLAR_FLARE = 62240,
SPELL_UNSTABLE_SUN_BEAM_SUMMON = 62207, // Trigger 62221
// Stack Removing of Attuned to Nature
SPELL_REMOVE_25STACK = 62521,
SPELL_REMOVE_10STACK = 62525,
SPELL_REMOVE_2STACK = 62524,
// Achievement spells
SPELL_DEFORESTATION_CREDIT = 65015,
SPELL_KNOCK_ON_WOOD_CREDIT = 65074,
// Wave summoning spells
SPELL_SUMMON_LASHERS = 62687,
SPELL_SUMMON_TRIO = 62686,
SPELL_SUMMON_ANCIENT_CONSERVATOR = 62685,
// Detonating Lasher
SPELL_DETONATE = 62598,
SPELL_FLAME_LASH = 62608,
// Ancient Water Spirit
SPELL_TIDAL_WAVE = 62653,
SPELL_TIDAL_WAVE_EFFECT = 62654,
// Storm Lasher
SPELL_LIGHTNING_LASH = 62648,
SPELL_STORMBOLT = 62649,
// Snaplasher
SPELL_HARDENED_BARK = 62664,
SPELL_BARK_AURA = 62663,
// Ancient Conservator
SPELL_CONSERVATOR_GRIP = 62532,
SPELL_NATURE_FURY = 62589,
SPELL_SUMMON_PERIODIC = 62566,
SPELL_SPORE_SUMMON_NW = 62582, // Not used, triggered by SPELL_SUMMON_PERIODIC
SPELL_SPORE_SUMMON_NE = 62591,
SPELL_SPORE_SUMMON_SE = 62592,
SPELL_SPORE_SUMMON_SW = 62593,
// Healthly Spore
SPELL_HEALTHY_SPORE_VISUAL = 62538,
SPELL_GROW = 62559,
SPELL_POTENT_PHEROMONES = 62541,
// Eonar's Gift
SPELL_LIFEBINDERS_GIFT = 62584,
SPELL_PHEROMONES = 62619,
SPELL_EONAR_VISUAL = 62579,
// Nature Bomb
SPELL_NATURE_BOMB = 64587,
SPELL_OBJECT_BOMB = 64600,
SPELL_SUMMON_NATURE_BOMB = 64604,
// Unstable Sun Beam
SPELL_UNSTABLE_SUN_BEAM = 62211,
SPELL_UNSTABLE_ENERGY = 62217,
SPELL_PHOTOSYNTHESIS = 62209,
SPELL_UNSTABLE_SUN_BEAM_TRIGGERED = 62243,
SPELL_FREYA_UNSTABLE_SUNBEAM = 62450, // Or maybe 62866?
// Sun Beam
SPELL_FREYA_UNSTABLE_ENERGY = 62451,
SPELL_FREYA_UNSTABLE_ENERGY_VISUAL = 62216,
// Attuned To Nature spells
SPELL_ATTUNED_TO_NATURE_2_DOSE_REDUCTION = 62524,
SPELL_ATTUNED_TO_NATURE_10_DOSE_REDUCTION = 62525,
SPELL_ATTUNED_TO_NATURE_25_DOSE_REDUCTION = 62521
};
enum FreyaNpcs
{
NPC_SUN_BEAM = 33170,
NPC_DETONATING_LASHER = 32918,
NPC_ANCIENT_CONSERVATOR = 33203,
NPC_ANCIENT_WATER_SPIRIT = 33202,
NPC_STORM_LASHER = 32919,
NPC_SNAPLASHER = 32916,
NPC_NATURE_BOMB = 34129,
NPC_EONARS_GIFT = 33228,
NPC_HEALTHY_SPORE = 33215,
NPC_UNSTABLE_SUN_BEAM = 33050,
NPC_IRON_ROOTS = 33088,
NPC_STRENGTHENED_IRON_ROOTS = 33168,
OBJECT_NATURE_BOMB = 194902
};
enum FreyaActions
{
ACTION_ELDER_FREYA_KILLED = 1
};
enum FreyaEvents
{
// Freya
EVENT_WAVE = 1,
EVENT_EONAR_GIFT = 2,
EVENT_NATURE_BOMB = 3,
EVENT_UNSTABLE_ENERGY = 4,
EVENT_STRENGTHENED_IRON_ROOTS = 5,
EVENT_GROUND_TREMOR = 6,
EVENT_SUNBEAM = 7,
EVENT_ENRAGE = 8,
// Elder Stonebark
EVENT_TREMOR = 9,
EVENT_BARK = 10,
EVENT_FISTS = 11,
// Elder Ironbranch
EVENT_IMPALE = 12,
EVENT_IRON_ROOTS = 13,
EVENT_THORN_SWARM = 14,
// Elder Brightleaf
EVENT_SOLAR_FLARE = 15,
EVENT_UNSTABLE_SUN_BEAM = 16,
EVENT_FLUX = 17
};
enum Misc
{
WAVE_TIME = 60000, // Normal wave is one minute
TIME_DIFFERENCE = 10000, // If difference between waveTime and WAVE_TIME is bigger then TIME_DIFFERENCE, schedule EVENT_WAVE in 10 seconds
DATA_GETTING_BACK_TO_NATURE = 1,
DATA_KNOCK_ON_WOOD = 2
};
class npc_iron_roots : public CreatureScript
{
public:
npc_iron_roots() : CreatureScript("npc_iron_roots") { }
struct npc_iron_rootsAI : public ScriptedAI
{
npc_iron_rootsAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
me->ApplySpellImmune(0, IMMUNITY_ID, 49560, true); // Death Grip
me->setFaction(14);
me->SetReactState(REACT_PASSIVE);
}
void IsSummonedBy(Unit* summoner) override
{
if (summoner->GetTypeId() != TYPEID_PLAYER)
return;
// Summoner is a player, who should have root aura on self
summonerGUID = summoner->GetGUID();
me->SetFacingToObject(summoner);
me->SetInCombatWith(summoner);
}
void JustDied(Unit* /*killer*/) override
{
if (Player* target = ObjectAccessor::GetPlayer(*me, summonerGUID))
{
target->RemoveAurasDueToSpell(SPELL_ROOTS_IRONBRANCH);
target->RemoveAurasDueToSpell(SPELL_ROOTS_FREYA);
}
me->RemoveCorpse(false);
}
private:
ObjectGuid summonerGUID;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_iron_rootsAI(creature);
}
};
class boss_freya : public CreatureScript
{
public:
boss_freya() : CreatureScript("boss_freya") { }
struct boss_freyaAI : public BossAI
{
boss_freyaAI(Creature* creature) : BossAI(creature, BOSS_FREYA)
{
Initialize();
memset(elementalTimer, 0, sizeof(elementalTimer));
diffTimer = 0;
attunedToNature = 0;
}
void Initialize()
{
trioWaveCount = 0;
trioWaveController = 0;
waveCount = 0;
elderCount = 0;
for (uint8 i = 0; i < 3; ++i)
for (uint8 n = 0; n < 2; ++n)
ElementalGUID[i][n].Clear();
for (uint8 i = 0; i < 6; ++i)
for (uint8 n = 0; n < 2; ++n)
deforestation[i][n] = 0;
for (uint8 n = 0; n < 2; ++n)
{
checkElementalAlive[n] = true;
trioDefeated[n] = false;
}
for (uint8 n = 0; n < 3; ++n)
random[n] = false;
}
ObjectGuid ElementalGUID[3][2];
uint32 deforestation[6][2];
uint32 elementalTimer[2];
uint32 diffTimer;
uint8 trioWaveCount;
uint8 trioWaveController;
uint8 waveCount;
uint8 elderCount;
uint8 attunedToNature;
bool checkElementalAlive[2];
bool trioDefeated[2];
bool random[3];
void Reset() override
{
_Reset();
Initialize();
}
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_SLAY);
}
void DamageTaken(Unit* who, uint32& damage) override
{
if (damage >= me->GetHealth())
{
damage = 0;
JustDied(who);
}
}
void EnterCombat(Unit* who) override
{
_EnterCombat();
DoZoneInCombat();
Creature* Elder[3];
for (uint8 n = 0; n < 3; ++n)
{
Elder[n] = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_BRIGHTLEAF + n));
if (Elder[n] && Elder[n]->IsAlive())
{
me->AddAura(SPELL_DRAINED_OF_POWER, Elder[n]);
Elder[n]->CastSpell(me, SPELL_IRONBRANCH_ESSENCE, true);
Elder[n]->RemoveLootMode(LOOT_MODE_DEFAULT); //! Why?
Elder[n]->AI()->AttackStart(who);
Elder[n]->AddThreat(who, 250.0f);
Elder[n]->SetInCombatWith(who);
++elderCount;
}
}
if (Elder[0] && Elder[0]->IsAlive())
{
Elder[0]->CastSpell(me, SPELL_BRIGHTLEAF_ESSENCE, true);
events.ScheduleEvent(EVENT_UNSTABLE_ENERGY, urand(10000, 20000));
}
if (Elder[1] && Elder[1]->IsAlive())
{
Elder[1]->CastSpell(me, SPELL_STONEBARK_ESSENCE, true);
events.ScheduleEvent(EVENT_GROUND_TREMOR, urand(10000, 20000));
}
if (Elder[2] && Elder[2]->IsAlive())
{
Elder[2]->CastSpell(me, SPELL_IRONBRANCH_ESSENCE, true);
events.ScheduleEvent(EVENT_STRENGTHENED_IRON_ROOTS, urand(10000, 20000));
}
if (elderCount == 0)
Talk(SAY_AGGRO);
else
Talk(SAY_AGGRO_WITH_ELDER);
me->CastCustomSpell(SPELL_ATTUNED_TO_NATURE, SPELLVALUE_AURA_STACK, 150, me, true);
events.ScheduleEvent(EVENT_WAVE, 10000);
events.ScheduleEvent(EVENT_EONAR_GIFT, 25000);
events.ScheduleEvent(EVENT_ENRAGE, 600000);
events.ScheduleEvent(EVENT_SUNBEAM, urand(5000, 15000));
}
uint32 GetData(uint32 type) const override
{
switch (type)
{
case DATA_GETTING_BACK_TO_NATURE:
return attunedToNature;
case DATA_KNOCK_ON_WOOD:
return elderCount;
}
return 0;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ENRAGE:
Talk(SAY_BERSERK);
DoCast(me, SPELL_ENRAGE);
break;
case EVENT_SUNBEAM:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
DoCast(target, SPELL_SUNBEAM);
events.ScheduleEvent(EVENT_SUNBEAM, urand(10000, 15000));
break;
case EVENT_NATURE_BOMB:
DoCastAOE(SPELL_SUMMON_NATURE_BOMB, true);
events.ScheduleEvent(EVENT_NATURE_BOMB, urand(10000, 12000));
break;
case EVENT_UNSTABLE_ENERGY:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
DoCast(target, SPELL_FREYA_UNSTABLE_SUNBEAM, true);
events.ScheduleEvent(EVENT_UNSTABLE_ENERGY, urand(15000, 20000));
break;
case EVENT_WAVE:
SpawnWave();
if (waveCount <= 6) // If set to 6 The Bombs appear during the Final Add wave
events.ScheduleEvent(EVENT_WAVE, WAVE_TIME);
else
events.ScheduleEvent(EVENT_NATURE_BOMB, urand(10000, 20000));
break;
case EVENT_EONAR_GIFT:
Talk(EMOTE_LIFEBINDERS_GIFT);
DoCast(me, SPELL_SUMMON_EONAR_GIFT);
events.ScheduleEvent(EVENT_EONAR_GIFT, urand(40000, 50000));
break;
case EVENT_STRENGTHENED_IRON_ROOTS:
Talk(EMOTE_IRON_ROOTS);
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true, -SPELL_ROOTS_FREYA))
target->CastSpell(target, SPELL_ROOTS_FREYA, true); // This must be cast by Target self
events.ScheduleEvent(EVENT_STRENGTHENED_IRON_ROOTS, urand(12000, 20000));
break;
case EVENT_GROUND_TREMOR:
Talk(EMOTE_GROUND_TREMOR);
DoCastAOE(SPELL_FREYA_GROUND_TREMOR);
events.ScheduleEvent(EVENT_GROUND_TREMOR, urand(25000, 28000));
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
if (!me->HasAura(SPELL_TOUCH_OF_EONAR))
me->CastSpell(me, SPELL_TOUCH_OF_EONAR, true);
// For achievement check
if (Aura* aura = me->GetAura(SPELL_ATTUNED_TO_NATURE))
attunedToNature = aura->GetStackAmount();
else
attunedToNature = 0;
diffTimer += diff; // For getting time difference for Deforestation achievement
// Elementals must be killed within 12 seconds of each other, or they will all revive and heal
Creature* Elemental[3][2];
for (uint8 i = 0; i < 2; ++i)
{
if (checkElementalAlive[i])
elementalTimer[i] = 0;
else
{
elementalTimer[i] += diff;
for (uint8 k = 0; k < 3; ++k)
Elemental[k][i] = ObjectAccessor::GetCreature(*me, ElementalGUID[k][i]);
if (elementalTimer[i] > 12000)
{
if (!trioDefeated[i]) // Do *NOT* merge this bool with bool few lines below!
{
if (Elemental[0][i] && Elemental[1][i] && Elemental[2][i])
{
for (uint8 n = 0; n < 3; ++n)
{
if (Elemental[n][i]->IsAlive())
Elemental[n][i]->SetHealth(Elemental[n][i]->GetMaxHealth());
else
Elemental[n][i]->Respawn();
}
}
}
checkElementalAlive[i] = true;
}
else
{
if (!trioDefeated[i])
{
if (Elemental[0][i] && Elemental[1][i] && Elemental[2][i])
{
if (Elemental[0][i]->isDead() && Elemental[1][i]->isDead() && Elemental[2][i]->isDead())
{
for (uint8 n = 0; n < 3; ++n)
{
summons.Despawn(Elemental[n][i]);
Elemental[n][i]->DespawnOrUnsummon(5000);
trioDefeated[i] = true;
Elemental[n][i]->CastSpell(me, SPELL_REMOVE_10STACK, true);
}
}
}
}
}
}
}
DoMeleeAttackIfReady();
}
// Check if all Trio NPCs are dead - achievement check
void LasherDead(uint32 type) // Type must be in format of a binary mask
{
uint8 n = 0;
// Handling received data
for (uint8 i = 0; i < 5; ++i) // We have created "instances" for keeping informations about last 6 death lashers - needed because of respawning
{
deforestation[i][0] = deforestation[(i + 1)][0]; // Time
deforestation[i][1] = deforestation[(i + 1)][1]; // Type
}
deforestation[5][0] = diffTimer;
deforestation[5][1] = type;
// Check for achievement completion
if (deforestation[0][1]) // Check for proper functionality of binary masks (overflow would not be problem)
{
for (uint8 i = 0; i < 6; ++i) // Count binary mask
{
n += deforestation[i][1];
}
if ((deforestation[5][0] - deforestation[0][0]) < 10000) // Time check
{
if (n == 14 && instance) // Binary mask check - verification of lasher types
{
instance->DoCastSpellOnPlayers(SPELL_DEFORESTATION_CREDIT);
}
}
}
}
// Random order of spawning waves
int GetWaveId()
{
if (random[0] && random[1] && random[2])
for (uint8 n = 0; n < 3; ++n)
random[n] = false;
uint8 randomId = urand(0, 2);
while (random[randomId])
randomId = urand(0, 2);
random[randomId] = true;
return randomId;
}
void SpawnWave()
{
switch (GetWaveId())
{
case 0:
Talk(SAY_SUMMON_LASHERS);
for (uint8 n = 0; n < 10; ++n)
DoCast(SPELL_SUMMON_LASHERS);
break;
case 1:
Talk(SAY_SUMMON_TRIO);
DoCast(SPELL_SUMMON_TRIO);
trioWaveCount++;
break;
case 2:
Talk(SAY_SUMMON_CONSERVATOR);
DoCast(SPELL_SUMMON_ANCIENT_CONSERVATOR);
break;
}
Talk(EMOTE_ALLIES_OF_NATURE);
waveCount++;
}
void JustDied(Unit* /*killer*/) override
{
//! Freya's chest is dynamically spawned on death by different spells.
const uint32 summonSpell[2][4] =
{
/* 0Elder, 1Elder, 2Elder, 3Elder */
/* 10N */ {62950, 62952, 62953, 62954},
/* 25N */ {62955, 62956, 62957, 62958}
};
me->CastSpell((Unit*)NULL, summonSpell[me->GetMap()->GetDifficultyID() - DIFFICULTY_10_N][elderCount], true);
Talk(SAY_DEATH);
me->SetReactState(REACT_PASSIVE);
_JustDied();
me->RemoveAllAuras();
me->AttackStop();
me->setFaction(35);
me->DeleteThreatList();
me->CombatStop(true);
me->DespawnOrUnsummon(7500);
me->CastSpell(me, SPELL_KNOCK_ON_WOOD_CREDIT, true);
for (uint8 n = 0; n < 3; ++n)
{
Creature* Elder = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_BRIGHTLEAF + n));
if (Elder && Elder->IsAlive())
{
Elder->RemoveAllAuras();
Elder->AttackStop();
Elder->CombatStop(true);
Elder->DeleteThreatList();
Elder->AI()->DoAction(ACTION_ELDER_FREYA_KILLED);
}
}
}
void JustSummoned(Creature* summoned) override
{
switch (summoned->GetEntry())
{
case NPC_SNAPLASHER:
case NPC_ANCIENT_WATER_SPIRIT:
case NPC_STORM_LASHER:
ElementalGUID[trioWaveController][trioWaveCount] = summoned->GetGUID();
summons.Summon(summoned);
++trioWaveController;
if (trioWaveController > 2)
trioWaveController = 0;
break;
case NPC_DETONATING_LASHER:
case NPC_ANCIENT_CONSERVATOR:
default:
summons.Summon(summoned);
break;
}
// Need to have it there, or summoned units would do nothing untill attacked
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 250.0f, true))
{
summoned->AI()->AttackStart(target);
summoned->AddThreat(target, 250.0f);
DoZoneInCombat(summoned);
}
}
void SummonedCreatureDies(Creature* summoned, Unit* who) override
{
switch (summoned->GetEntry())
{
case NPC_DETONATING_LASHER:
summoned->CastSpell(me, SPELL_REMOVE_2STACK, true);
summoned->CastSpell(who, SPELL_DETONATE, true);
summoned->DespawnOrUnsummon(5000);
summons.Despawn(summoned);
break;
case NPC_ANCIENT_CONSERVATOR:
summoned->CastSpell(me, SPELL_REMOVE_25STACK, true);
summoned->DespawnOrUnsummon(5000);
summons.Despawn(summoned);
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetUlduarAI<boss_freyaAI>(creature);
}
};
class boss_elder_brightleaf : public CreatureScript
{
public:
boss_elder_brightleaf() : CreatureScript("boss_elder_brightleaf") { }
struct boss_elder_brightleafAI : public BossAI
{
boss_elder_brightleafAI(Creature* creature) : BossAI(creature, BOSS_BRIGHTLEAF)
{
}
void Reset() override
{
_Reset();
if (me->HasAura(SPELL_DRAINED_OF_POWER))
me->RemoveAurasDueToSpell(SPELL_DRAINED_OF_POWER);
events.ScheduleEvent(EVENT_SOLAR_FLARE, urand(5000, 7000));
events.ScheduleEvent(EVENT_UNSTABLE_SUN_BEAM, urand(7000, 12000));
events.ScheduleEvent(EVENT_FLUX, 5000);
}
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_ELDER_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_ELDER_DEATH);
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
if (!me->HasAura(SPELL_DRAINED_OF_POWER))
Talk(SAY_ELDER_AGGRO);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() || me->HasAura(SPELL_DRAINED_OF_POWER))
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_UNSTABLE_SUN_BEAM:
me->CastSpell(me, SPELL_UNSTABLE_SUN_BEAM_SUMMON, true);
events.ScheduleEvent(EVENT_UNSTABLE_SUN_BEAM, urand(10000, 15000));
break;
case EVENT_SOLAR_FLARE:
{
uint8 stackAmount = 0;
if (Aura* aura = me->GetAura(SPELL_FLUX_AURA))
stackAmount = aura->GetStackAmount();
me->CastCustomSpell(SPELL_SOLAR_FLARE, SPELLVALUE_MAX_TARGETS, stackAmount, me, false);
events.ScheduleEvent(EVENT_SOLAR_FLARE, urand(5000, 10000));
break;
}
case EVENT_FLUX:
me->RemoveAurasDueToSpell(SPELL_FLUX_AURA);
me->AddAura(SPELL_FLUX_AURA, me);
if (Aura* Flux = me->GetAura(SPELL_FLUX_AURA))
Flux->SetStackAmount(urand(1, 8));
events.ScheduleEvent(EVENT_FLUX, 7500);
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
void DoAction(int32 action) override
{
switch (action)
{
case ACTION_ELDER_FREYA_KILLED:
me->DespawnOrUnsummon(10000);
_JustDied();
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetUlduarAI<boss_elder_brightleafAI>(creature);
}
};
class boss_elder_stonebark : public CreatureScript
{
public:
boss_elder_stonebark() : CreatureScript("boss_elder_stonebark") { }
struct boss_elder_stonebarkAI : public BossAI
{
boss_elder_stonebarkAI(Creature* creature) : BossAI(creature, BOSS_STONEBARK)
{
}
void Reset() override
{
_Reset();
if (me->HasAura(SPELL_DRAINED_OF_POWER))
me->RemoveAurasDueToSpell(SPELL_DRAINED_OF_POWER);
events.ScheduleEvent(EVENT_TREMOR, urand(10000, 12000));
events.ScheduleEvent(EVENT_FISTS, urand(25000, 35000));
events.ScheduleEvent(EVENT_BARK, urand(37500, 40000));
}
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_ELDER_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_ELDER_DEATH);
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
if (!me->HasAura(SPELL_DRAINED_OF_POWER))
Talk(SAY_ELDER_AGGRO);
}
void DamageTaken(Unit* who, uint32& damage) override
{
if (who == me)
return;
if (me->HasAura(SPELL_PETRIFIED_BARK))
{
int32 reflect = damage;
who->CastCustomSpell(who, SPELL_PETRIFIED_BARK_DMG, &reflect, NULL, NULL, true);
damage = 0;
}
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() || me->HasAura(SPELL_DRAINED_OF_POWER))
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_BARK:
DoCast(me, SPELL_PETRIFIED_BARK);
events.ScheduleEvent(EVENT_BARK, urand(30000, 50000));
break;
case EVENT_FISTS:
DoCastVictim(SPELL_FISTS_OF_STONE);
events.ScheduleEvent(EVENT_FISTS, urand(20000, 30000));
break;
case EVENT_TREMOR:
if (!me->HasAura(SPELL_FISTS_OF_STONE))
DoCastVictim(SPELL_GROUND_TREMOR);
events.ScheduleEvent(EVENT_TREMOR, urand(10000, 20000));
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
void DoAction(int32 action) override
{
switch (action)
{
case ACTION_ELDER_FREYA_KILLED:
me->DespawnOrUnsummon(10000);
_JustDied();
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetUlduarAI<boss_elder_stonebarkAI>(creature);
}
};
class boss_elder_ironbranch : public CreatureScript
{
public:
boss_elder_ironbranch() : CreatureScript("boss_elder_ironbranch") { }
struct boss_elder_ironbranchAI : public BossAI
{
boss_elder_ironbranchAI(Creature* creature) : BossAI(creature, BOSS_IRONBRANCH)
{
}
void Reset() override
{
_Reset();
if (me->HasAura(SPELL_DRAINED_OF_POWER))
me->RemoveAurasDueToSpell(SPELL_DRAINED_OF_POWER);
events.ScheduleEvent(EVENT_IMPALE, urand(18000, 22000));
events.ScheduleEvent(EVENT_IRON_ROOTS, urand(12000, 17000));
events.ScheduleEvent(EVENT_THORN_SWARM, urand(7500, 12500));
}
void KilledUnit(Unit* who) override
{
if (who->GetTypeId() == TYPEID_PLAYER)
Talk(SAY_ELDER_SLAY);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
Talk(SAY_ELDER_DEATH);
}
void EnterCombat(Unit* /*who*/) override
{
_EnterCombat();
if (!me->HasAura(SPELL_DRAINED_OF_POWER))
Talk(SAY_ELDER_AGGRO);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim() || me->HasAura(SPELL_DRAINED_OF_POWER))
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_IMPALE:
DoCastVictim(SPELL_IMPALE);
events.ScheduleEvent(EVENT_IMPALE, urand(15000, 25000));
break;
case EVENT_IRON_ROOTS:
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true, -SPELL_ROOTS_IRONBRANCH))
target->CastSpell(target, SPELL_ROOTS_IRONBRANCH, true);
events.ScheduleEvent(EVENT_IRON_ROOTS, urand(10000, 20000));
break;
case EVENT_THORN_SWARM:
DoCastVictim(SPELL_THORN_SWARM);
events.ScheduleEvent(EVENT_THORN_SWARM, urand(8000, 13000));
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
void DoAction(int32 action) override
{
switch (action)
{
case ACTION_ELDER_FREYA_KILLED:
me->DespawnOrUnsummon(10000);
_JustDied();
break;
}
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetUlduarAI<boss_elder_ironbranchAI>(creature);
}
};
class npc_detonating_lasher : public CreatureScript
{
public:
npc_detonating_lasher() : CreatureScript("npc_detonating_lasher") { }
struct npc_detonating_lasherAI : public ScriptedAI
{
npc_detonating_lasherAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
me->ApplySpellImmune(0, IMMUNITY_STATE, SPELL_AURA_MOD_TAUNT, true);
}
void Initialize()
{
lashTimer = 5000;
changeTargetTimer = 7500;
}
void Reset() override
{
Initialize();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (lashTimer <= diff)
{
DoCast(SPELL_FLAME_LASH);
lashTimer = urand(5000, 10000);
}
else
lashTimer -= diff;
if (changeTargetTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
{
// Switching to other target - modify aggro of new target by 20% from current target's aggro
me->AddThreat(target, me->getThreatManager().getThreat(me->GetVictim(), false) * 1.2f);
AttackStart(target);
}
changeTargetTimer = urand(5000, 10000);
}
else
changeTargetTimer -= diff;
DoMeleeAttackIfReady();
}
private:
uint32 lashTimer;
uint32 changeTargetTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_detonating_lasherAI(creature);
}
};
class npc_ancient_water_spirit : public CreatureScript
{
public:
npc_ancient_water_spirit() : CreatureScript("npc_ancient_water_spirit") { }
struct npc_ancient_water_spiritAI : public ScriptedAI
{
npc_ancient_water_spiritAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = me->GetInstanceScript();
if (Creature* Freya = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_FREYA)))
waveCount = ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->trioWaveCount;
else
waveCount = 0;
}
void Initialize()
{
tidalWaveTimer = 10000;
}
void Reset() override
{
Initialize();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (tidalWaveTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
{
DoCast(target, SPELL_TIDAL_WAVE);
DoCast(target, SPELL_TIDAL_WAVE_EFFECT, true);
}
tidalWaveTimer = urand(12000, 25000);
}
else
tidalWaveTimer -= diff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/) override
{
if (Creature* Freya = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_FREYA)))
{
ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->checkElementalAlive[waveCount] = false;
ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->LasherDead(1);
}
}
private:
InstanceScript* instance;
uint32 tidalWaveTimer;
uint8 waveCount;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_ancient_water_spiritAI>(creature);
}
};
class npc_storm_lasher : public CreatureScript
{
public:
npc_storm_lasher() : CreatureScript("npc_storm_lasher") { }
struct npc_storm_lasherAI : public ScriptedAI
{
npc_storm_lasherAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = me->GetInstanceScript();
if (Creature* Freya = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_FREYA)))
waveCount = ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->trioWaveCount;
else
waveCount = 0;
}
void Initialize()
{
lightningLashTimer = 10000;
stormboltTimer = 5000;
}
void Reset() override
{
Initialize();
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (lightningLashTimer <= diff)
{
DoCast(SPELL_LIGHTNING_LASH);
lightningLashTimer = urand(7000, 14000);
}
else
lightningLashTimer -= diff;
if (stormboltTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true))
DoCast(target, SPELL_STORMBOLT);
stormboltTimer = urand(8000, 12000);
}
else
stormboltTimer -= diff;
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/) override
{
if (Creature* Freya = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_FREYA)))
{
ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->checkElementalAlive[waveCount] = false;
ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->LasherDead(2);
}
}
private:
InstanceScript* instance;
uint32 lightningLashTimer;
uint32 stormboltTimer;
uint8 waveCount;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_storm_lasherAI>(creature);
}
};
class npc_snaplasher : public CreatureScript
{
public:
npc_snaplasher() : CreatureScript("npc_snaplasher") { }
struct npc_snaplasherAI : public ScriptedAI
{
npc_snaplasherAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
if (Creature* Freya = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_FREYA)))
waveCount = ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->trioWaveCount;
else
waveCount = 0;
}
void UpdateAI(uint32 /*diff*/) override
{
if (!UpdateVictim())
return;
if (!me->HasAura(SPELL_BARK_AURA))
DoCast(SPELL_HARDENED_BARK);
DoMeleeAttackIfReady();
}
void JustDied(Unit* /*killer*/) override
{
if (Creature* Freya = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_FREYA)))
{
ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->checkElementalAlive[waveCount] = false;
ENSURE_AI(boss_freya::boss_freyaAI, Freya->AI())->LasherDead(4);
}
}
private:
InstanceScript* instance;
uint8 waveCount;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_snaplasherAI>(creature);
}
};
class npc_ancient_conservator : public CreatureScript
{
public:
npc_ancient_conservator() : CreatureScript("npc_ancient_conservator") { }
struct npc_ancient_conservatorAI : public ScriptedAI
{
npc_ancient_conservatorAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
}
void Initialize()
{
natureFuryTimer = 7500;
healthySporeTimer = 3500;
}
void Reset() override
{
Initialize();
SummonHealthySpores(2);
}
void SummonHealthySpores(uint8 sporesCount)
{
for (uint8 n = 0; n < sporesCount; ++n)
{
DoCast(SPELL_SUMMON_PERIODIC);
DoCast(SPELL_SPORE_SUMMON_NE);
DoCast(SPELL_SPORE_SUMMON_SE);
DoCast(SPELL_SPORE_SUMMON_SW);
}
}
void EnterCombat(Unit* who) override
{
DoCast(who, SPELL_CONSERVATOR_GRIP, true);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
if (healthySporeTimer <= diff)
{
SummonHealthySpores(1);
healthySporeTimer = urand(15000, 17500);
}
else
healthySporeTimer -= diff;
if (natureFuryTimer <= diff)
{
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100.0f, true, -SPELL_NATURE_FURY))
DoCast(target, SPELL_NATURE_FURY);
me->AddAura(SPELL_CONSERVATOR_GRIP, me);
natureFuryTimer = 5000;
}
else
natureFuryTimer -= diff;
DoMeleeAttackIfReady();
}
private:
uint32 natureFuryTimer;
uint32 healthySporeTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_ancient_conservatorAI(creature);
}
};
class npc_sun_beam : public CreatureScript
{
public:
npc_sun_beam() : CreatureScript("npc_sun_beam") { }
struct npc_sun_beamAI : public ScriptedAI
{
npc_sun_beamAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
me->SetReactState(REACT_PASSIVE);
DoCastAOE(SPELL_FREYA_UNSTABLE_ENERGY_VISUAL, true);
DoCast(SPELL_FREYA_UNSTABLE_ENERGY);
}
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_sun_beamAI(creature);
}
};
class npc_healthy_spore : public CreatureScript
{
public:
npc_healthy_spore() : CreatureScript("npc_healthy_spore") { }
struct npc_healthy_sporeAI : public ScriptedAI
{
npc_healthy_sporeAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE | UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC);
me->SetReactState(REACT_PASSIVE);
DoCast(me, SPELL_HEALTHY_SPORE_VISUAL);
DoCast(me, SPELL_POTENT_PHEROMONES);
DoCast(me, SPELL_GROW);
lifeTimer = urand(22000, 30000);
}
void UpdateAI(uint32 diff) override
{
if (lifeTimer <= diff)
{
me->RemoveAurasDueToSpell(SPELL_GROW);
me->DespawnOrUnsummon(2200);
lifeTimer = urand(22000, 30000);
}
else
lifeTimer -= diff;
}
private:
uint32 lifeTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_healthy_sporeAI(creature);
}
};
class npc_eonars_gift : public CreatureScript
{
public:
npc_eonars_gift() : CreatureScript("npc_eonars_gift") { }
struct npc_eonars_giftAI : public ScriptedAI
{
npc_eonars_giftAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
lifeBindersGiftTimer = 12000;
DoCast(me, SPELL_GROW);
DoCast(me, SPELL_PHEROMONES, true);
DoCast(me, SPELL_EONAR_VISUAL, true);
}
void UpdateAI(uint32 diff) override
{
if (lifeBindersGiftTimer <= diff)
{
me->RemoveAurasDueToSpell(SPELL_GROW);
DoCast(SPELL_LIFEBINDERS_GIFT);
me->DespawnOrUnsummon(2500);
lifeBindersGiftTimer = 12000;
}
else
lifeBindersGiftTimer -= diff;
}
private:
uint32 lifeBindersGiftTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_eonars_giftAI(creature);
}
};
class npc_nature_bomb : public CreatureScript
{
public:
npc_nature_bomb() : CreatureScript("npc_nature_bomb") { }
struct npc_nature_bombAI : public ScriptedAI
{
npc_nature_bombAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
bombTimer = urand(8000, 10000);
DoCast(SPELL_OBJECT_BOMB);
}
void UpdateAI(uint32 diff) override
{
if (bombTimer <= diff)
{
if (GameObject* go = me->FindNearestGameObject(OBJECT_NATURE_BOMB, 1.0f))
{
DoCast(me, SPELL_NATURE_BOMB);
me->RemoveGameObject(go, true);
me->RemoveFromWorld();
}
bombTimer = 10000;
}
else
bombTimer -= diff;
}
private:
uint32 bombTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return new npc_nature_bombAI(creature);
}
};
class npc_unstable_sun_beam : public CreatureScript
{
public:
npc_unstable_sun_beam() : CreatureScript("npc_unstable_sun_beam") { }
struct npc_unstable_sun_beamAI : public ScriptedAI
{
npc_unstable_sun_beamAI(Creature* creature) : ScriptedAI(creature)
{
SetCombatMovement(false);
despawnTimer = urand(7000, 12000);
instance = me->GetInstanceScript();
DoCast(me, SPELL_PHOTOSYNTHESIS);
DoCast(me, SPELL_UNSTABLE_SUN_BEAM);
me->SetReactState(REACT_PASSIVE);
}
void UpdateAI(uint32 diff) override
{
if (despawnTimer <= diff)
{
DoCastAOE(SPELL_UNSTABLE_ENERGY, true);
me->DisappearAndDie();
}
else
despawnTimer -= diff;
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (target && spell->Id == SPELL_UNSTABLE_ENERGY)
{
target->RemoveAurasDueToSpell(SPELL_UNSTABLE_SUN_BEAM);
target->RemoveAurasDueToSpell(SPELL_UNSTABLE_SUN_BEAM_TRIGGERED);
}
}
private:
InstanceScript* instance;
uint32 despawnTimer;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetInstanceAI<npc_unstable_sun_beamAI>(creature);
}
};
class spell_freya_attuned_to_nature_dose_reduction : public SpellScriptLoader
{
public:
spell_freya_attuned_to_nature_dose_reduction() : SpellScriptLoader("spell_freya_attuned_to_nature_dose_reduction") { }
class spell_freya_attuned_to_nature_dose_reduction_SpellScript : public SpellScript
{
PrepareSpellScript(spell_freya_attuned_to_nature_dose_reduction_SpellScript);
void HandleScript(SpellEffIndex /*effIndex*/)
{
Unit* target = GetHitUnit();
switch (GetSpellInfo()->Id)
{
case SPELL_ATTUNED_TO_NATURE_2_DOSE_REDUCTION:
if (target->HasAura(GetEffectValue()))
for (uint8 n = 0; n < 2; ++n)
target->RemoveAuraFromStack(GetEffectValue());
break;
case SPELL_ATTUNED_TO_NATURE_10_DOSE_REDUCTION:
if (target->HasAura(GetEffectValue()))
for (uint8 n = 0; n < 10; ++n)
target->RemoveAuraFromStack(GetEffectValue());
break;
case SPELL_ATTUNED_TO_NATURE_25_DOSE_REDUCTION:
if (target->HasAura(GetEffectValue()))
for (uint8 n = 0; n < 25; ++n)
target->RemoveAuraFromStack(GetEffectValue());
break;
default:
break;
}
}
void Register() override
{
OnEffectHitTarget += SpellEffectFn(spell_freya_attuned_to_nature_dose_reduction_SpellScript::HandleScript, EFFECT_0, SPELL_EFFECT_SCRIPT_EFFECT);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_freya_attuned_to_nature_dose_reduction_SpellScript();
}
};
class spell_freya_iron_roots : public SpellScriptLoader
{
public:
spell_freya_iron_roots() : SpellScriptLoader("spell_freya_iron_roots") { }
class spell_freya_iron_roots_SpellScript : public SpellScript
{
PrepareSpellScript(spell_freya_iron_roots_SpellScript);
void HandleSummon(SpellEffIndex effIndex)
{
PreventHitDefaultEffect(effIndex);
uint32 entry = uint32(GetSpellInfo()->GetEffect(effIndex)->MiscValue);
Position pos = GetCaster()->GetPosition();
// Not good at all, but this prevents having roots in a different position then player
if (Creature* Roots = GetCaster()->SummonCreature(entry, pos))
GetCaster()->NearTeleportTo(Roots->GetPositionX(), Roots->GetPositionY(), Roots->GetPositionZ(), GetCaster()->GetOrientation());
}
void Register() override
{
OnEffectHit += SpellEffectFn(spell_freya_iron_roots_SpellScript::HandleSummon, EFFECT_0, SPELL_EFFECT_SUMMON);
}
};
SpellScript* GetSpellScript() const override
{
return new spell_freya_iron_roots_SpellScript();
}
};
class achievement_getting_back_to_nature : public AchievementCriteriaScript
{
public:
achievement_getting_back_to_nature() : AchievementCriteriaScript("achievement_getting_back_to_nature") { }
bool OnCheck(Player* /*player*/, Unit* target) override
{
return target && target->GetAI()->GetData(DATA_GETTING_BACK_TO_NATURE) >= 25;
}
};
class achievement_knock_on_wood : public AchievementCriteriaScript
{
public:
achievement_knock_on_wood() : AchievementCriteriaScript("achievement_knock_on_wood") { }
bool OnCheck(Player* /*player*/, Unit* target) override
{
return target && target->GetAI()->GetData(DATA_KNOCK_ON_WOOD) >= 1;
}
};
class achievement_knock_knock_on_wood : public AchievementCriteriaScript
{
public:
achievement_knock_knock_on_wood() : AchievementCriteriaScript("achievement_knock_knock_on_wood") { }
bool OnCheck(Player* /*player*/, Unit* target) override
{
return target && target->GetAI()->GetData(DATA_KNOCK_ON_WOOD) >= 2;
}
};
class achievement_knock_knock_knock_on_wood : public AchievementCriteriaScript
{
public:
achievement_knock_knock_knock_on_wood() : AchievementCriteriaScript("achievement_knock_knock_knock_on_wood") { }
bool OnCheck(Player* /*player*/, Unit* target) override
{
return target && target->GetAI()->GetData(DATA_KNOCK_ON_WOOD) == 3;
}
};
void AddSC_boss_freya()
{
new boss_freya();
new boss_elder_brightleaf();
new boss_elder_ironbranch();
new boss_elder_stonebark();
new npc_ancient_conservator();
new npc_snaplasher();
new npc_storm_lasher();
new npc_ancient_water_spirit();
new npc_detonating_lasher();
new npc_sun_beam();
new npc_nature_bomb();
new npc_eonars_gift();
new npc_healthy_spore();
new npc_unstable_sun_beam();
new npc_iron_roots();
new spell_freya_attuned_to_nature_dose_reduction();
new spell_freya_iron_roots();
new achievement_getting_back_to_nature();
new achievement_knock_on_wood();
new achievement_knock_knock_on_wood();
new achievement_knock_knock_knock_on_wood();
}
| sidneeginger/TrinityCore | src/server/scripts/Northrend/Ulduar/Ulduar/boss_freya.cpp | C++ | gpl-2.0 | 59,692 |
////////////////////////////////////////////////////////////////////////////////////////
//
// Nestopia - NES/Famicom emulator written in C++
//
// Copyright (C) 2003-2007 Martin Freij
//
// This file is part of Nestopia.
//
// Nestopia 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.
//
// Nestopia 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 Nestopia; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef NST_MAPPER_243_H
#define NST_MAPPER_243_H
#ifdef NST_PRAGMA_ONCE
#pragma once
#endif
namespace Nes
{
namespace Core
{
class Mapper243 : public Mapper
{
public:
explicit Mapper243(Context& c)
: Mapper(c,PROM_MAX_64K|CROM_MAX_128K) {}
private:
~Mapper243() {}
void SubReset(bool);
void SubSave(State::Saver&) const;
void SubLoad(State::Loader&);
NES_DECL_POKE( 4100 );
NES_DECL_POKE( 4101 );
uint command;
};
}
}
#endif
| Joride/nestopia | core/mapper/NstMapper243.hpp | C++ | gpl-2.0 | 1,553 |
<?php
/**
* File containing the CreatedRole class
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
* @version 2014.11.1
*/
namespace eZ\Publish\Core\REST\Server\Values;
use eZ\Publish\API\Repository\Values\ValueObject;
/**
* Struct representing a freshly created role.
*/
class CreatedRole extends ValueObject
{
/**
* The created role
*
* @var \eZ\Publish\API\Repository\Values\User\Role
*/
public $role;
}
| wnsonsa/destin-foot | vendor/ezsystems/ezpublish-kernel/eZ/Publish/Core/REST/Server/Values/CreatedRole.php | PHP | gpl-2.0 | 569 |
/*
Copyright 2005-2010 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks.
Threading Building Blocks is free software; you can redistribute it
and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.
Threading Building Blocks 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 Threading Building Blocks; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software
library without restriction. Specifically, if other files instantiate
templates or use macros or inline functions from this file, or you compile
this file and link it with other files to produce an executable, this
file does not by itself cause the resulting executable to be covered by
the GNU General Public License. This exception does not however
invalidate any other reasons why the executable file might be covered by
the GNU General Public License.
*/
#include "tbb/parallel_while.h"
#include "harness.h"
const int N = 200;
typedef int Element;
//! Representation of an array index with only those signatures required by parallel_while.
class MinimalArgumentType {
void operator=( const MinimalArgumentType& );
long my_value;
enum {
DEAD=0xDEAD,
LIVE=0x2718,
INITIALIZED=0x3141
} my_state;
public:
~MinimalArgumentType() {
ASSERT( my_state==LIVE||my_state==INITIALIZED, NULL );
my_state = DEAD;
}
MinimalArgumentType() {
my_state = LIVE;
}
void set_value( long i ) {
ASSERT( my_state==LIVE||my_state==INITIALIZED, NULL );
my_value = i;
my_state = INITIALIZED;
}
long get_value() const {
ASSERT( my_state==INITIALIZED, NULL );
return my_value;
}
};
class IntegerStream {
long my_limit;
long my_index;
public:
IntegerStream( long n ) : my_limit(n), my_index(0) {}
bool pop_if_present( MinimalArgumentType& v ) {
if( my_index>=my_limit )
return false;
v.set_value( my_index );
my_index+=2;
return true;
}
};
class MatrixMultiplyBody: NoAssign {
Element (*a)[N];
Element (*b)[N];
Element (*c)[N];
const int n;
tbb::parallel_while<MatrixMultiplyBody>& my_while;
public:
typedef MinimalArgumentType argument_type;
void operator()( argument_type i_arg ) const {
long i = i_arg.get_value();
if( (i&1)==0 && i+1<N ) {
MinimalArgumentType value;
value.set_value(i+1);
my_while.add( value );
}
for( int j=0; j<n; ++j )
c[i][j] = 0;
for( int k=0; k<n; ++k ) {
Element aik = a[i][k];
for( int j=0; j<n; ++j )
c[i][j] += aik*b[k][j];
}
}
MatrixMultiplyBody( tbb::parallel_while<MatrixMultiplyBody>& w, Element c_[N][N], Element a_[N][N], Element b_[N][N], int n_ ) :
a(a_), b(b_), c(c_), n(n_), my_while(w)
{}
};
void WhileMatrixMultiply( Element c[N][N], Element a[N][N], Element b[N][N], int n ) {
IntegerStream stream( N );
tbb::parallel_while<MatrixMultiplyBody> w;
MatrixMultiplyBody body(w,c,a,b,n);
w.run( stream, body );
}
#include "tbb/tick_count.h"
#include <cstdlib>
#include <cstdio>
using namespace std;
static long Iterations = 5;
static void SerialMatrixMultiply( Element c[N][N], Element a[N][N], Element b[N][N], int n ) {
for( int i=0; i<n; ++i ) {
for( int j=0; j<n; ++j )
c[i][j] = 0;
for( int k=0; k<n; ++k ) {
Element aik = a[i][k];
for( int j=0; j<n; ++j )
c[i][j] += aik*b[k][j];
}
}
}
static void InitializeMatrix( Element x[N][N], int n, int salt ) {
for( int i=0; i<n; ++i )
for( int j=0; j<n; ++j )
x[i][j] = (i*n+j)^salt;
}
static Element A[N][N], B[N][N], C[N][N], D[N][N];
static void Run( int nthread, int n ) {
/* Initialize matrices */
InitializeMatrix(A,n,5);
InitializeMatrix(B,n,10);
InitializeMatrix(C,n,0);
InitializeMatrix(D,n,15);
tbb::tick_count t0 = tbb::tick_count::now();
for( long i=0; i<Iterations; ++i ) {
WhileMatrixMultiply( C, A, B, n );
}
tbb::tick_count t1 = tbb::tick_count::now();
SerialMatrixMultiply( D, A, B, n );
// Check result
for( int i=0; i<n; ++i )
for( int j=0; j<n; ++j )
ASSERT( C[i][j]==D[i][j], NULL );
REMARK("time=%g\tnthread=%d\tn=%d\n",(t1-t0).seconds(),nthread,n);
}
#include "tbb/task_scheduler_init.h"
#include "harness_cpu.h"
int TestMain () {
if( MinThread<1 ) {
REPORT("number of threads must be positive\n");
exit(1);
}
for( int p=MinThread; p<=MaxThread; ++p ) {
tbb::task_scheduler_init init( p );
for( int n=N/4; n<=N; n+=N/4 )
Run(p,n);
// Test that all workers sleep when no work
TestCPUUserTime(p);
}
return Harness::Done;
}
| dusek/tbb | src/test/test_parallel_while.cpp | C++ | gpl-2.0 | 5,445 |
<?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-2015 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_Response_ResponseAbstract
*/
#require_once 'Zend/Service/DeveloperGarden/Response/ResponseAbstract.php';
/**
* @category Zend
* @package Zend_Service
* @subpackage DeveloperGarden
* @copyright Copyright (c) 2005-2015 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_Response_BaseUserService_GetAccountBalanceResponse
extends Zend_Service_DeveloperGarden_Response_ResponseAbstract
{
}
| dvh11er/mage-cheatcode | magento/lib/Zend/Service/DeveloperGarden/Response/BaseUserService/GetAccountBalanceResponse.php | PHP | gpl-2.0 | 1,317 |
/*
* Copyright (C) 2008-2013 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.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.
*
* 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/>.
*/
/** \file
\ingroup u2w
*/
#include "WorldSocket.h" // must be first to make ACE happy with ACE includes in it
#include <zlib.h>
#include "Common.h"
#include "DatabaseEnv.h"
#include "Log.h"
#include "Opcodes.h"
#include "WorldPacket.h"
#include "WorldSession.h"
#include "Player.h"
#include "Vehicle.h"
#include "ObjectMgr.h"
#include "GuildMgr.h"
#include "Group.h"
#include "Guild.h"
#include "World.h"
#include "ObjectAccessor.h"
#include "BattlegroundMgr.h"
#include "OutdoorPvPMgr.h"
#include "MapManager.h"
#include "SocialMgr.h"
#include "zlib.h"
#include "ScriptMgr.h"
#include "Transport.h"
#include "WardenWin.h"
#include "WardenMac.h"
namespace {
std::string const DefaultPlayerName = "<none>";
} // namespace
bool MapSessionFilter::Process(WorldPacket* packet)
{
Opcodes opcode = DropHighBytes(packet->GetOpcode());
OpcodeHandler const* opHandle = opcodeTable[opcode];
//let's check if our opcode can be really processed in Map::Update()
if (opHandle->ProcessingPlace == PROCESS_INPLACE)
return true;
//we do not process thread-unsafe packets
if (opHandle->ProcessingPlace == PROCESS_THREADUNSAFE)
return false;
Player* player = m_pSession->GetPlayer();
if (!player)
return false;
//in Map::Update() we do not process packets where player is not in world!
return player->IsInWorld();
}
//we should process ALL packets when player is not in world/logged in
//OR packet handler is not thread-safe!
bool WorldSessionFilter::Process(WorldPacket* packet)
{
Opcodes opcode = DropHighBytes(packet->GetOpcode());
OpcodeHandler const* opHandle = opcodeTable[opcode];
//check if packet handler is supposed to be safe
if (opHandle->ProcessingPlace == PROCESS_INPLACE)
return true;
//thread-unsafe packets should be processed in World::UpdateSessions()
if (opHandle->ProcessingPlace == PROCESS_THREADUNSAFE)
return true;
//no player attached? -> our client! ^^
Player* player = m_pSession->GetPlayer();
if (!player)
return true;
//lets process all packets for non-in-the-world player
return (player->IsInWorld() == false);
}
/// WorldSession constructor
WorldSession::WorldSession(uint32 id, WorldSocket* sock, AccountTypes sec, uint8 expansion, time_t mute_time, LocaleConstant locale, uint32 recruiter, bool isARecruiter):
m_muteTime(mute_time),
m_timeOutTime(0),
_player(NULL),
m_Socket(sock),
_security(sec),
_accountId(id),
m_expansion(expansion),
_warden(NULL),
_logoutTime(0),
m_inQueue(false),
m_playerLoading(false),
m_playerLogout(false),
m_playerRecentlyLogout(false),
m_playerSave(false),
m_sessionDbcLocale(sWorld->GetAvailableDbcLocale(locale)),
m_sessionDbLocaleIndex(locale),
m_latency(0),
m_TutorialsChanged(false),
_filterAddonMessages(false),
recruiterId(recruiter),
isRecruiter(isARecruiter),
timeLastWhoCommand(0)
{
if (sock)
{
m_Address = sock->GetRemoteAddress();
sock->AddReference();
ResetTimeOutTime();
LoginDatabase.PExecute("UPDATE account SET online = 1 WHERE id = %u;", GetAccountId()); // One-time query
}
InitializeQueryCallbackParameters();
_compressionStream = new z_stream();
_compressionStream->zalloc = (alloc_func)NULL;
_compressionStream->zfree = (free_func)NULL;
_compressionStream->opaque = (voidpf)NULL;
_compressionStream->avail_in = 0;
_compressionStream->next_in = NULL;
int32 z_res = deflateInit(_compressionStream, sWorld->getIntConfig(CONFIG_COMPRESSION));
if (z_res != Z_OK)
{
sLog->outError(LOG_FILTER_NETWORKIO, "Can't initialize packet compression (zlib: deflateInit) Error code: %i (%s)", z_res, zError(z_res));
return;
}
}
/// WorldSession destructor
WorldSession::~WorldSession()
{
///- unload player if not unloaded
if (_player)
LogoutPlayer (true);
/// - If have unclosed socket, close it
if (m_Socket)
{
m_Socket->CloseSocket();
m_Socket->RemoveReference();
m_Socket = NULL;
}
if (_warden)
delete _warden;
///- empty incoming packet queue
WorldPacket* packet = NULL;
while (_recvQueue.next(packet))
delete packet;
LoginDatabase.PExecute("UPDATE account SET online = 0 WHERE id = %u;", GetAccountId()); // One-time query
int32 z_res = deflateEnd(_compressionStream);
if (z_res != Z_OK && z_res != Z_DATA_ERROR) // Z_DATA_ERROR signals that internal state was BUSY
{
sLog->outError(LOG_FILTER_NETWORKIO, "Can't close packet compression stream (zlib: deflateEnd) Error code: %i (%s)", z_res, zError(z_res));
return;
}
delete _compressionStream;
}
std::string const & WorldSession::GetPlayerName() const
{
return _player != NULL ? _player->GetName() : DefaultPlayerName;
}
std::string WorldSession::GetPlayerInfo() const
{
std::ostringstream ss;
ss << "[Player: " << GetPlayerName()
<< " (Guid: " << (_player != NULL ? _player->GetGUID() : 0)
<< ", Account: " << GetAccountId() << ")]";
return ss.str();
}
/// Get player guid if available. Use for logging purposes only
uint32 WorldSession::GetGuidLow() const
{
return GetPlayer() ? GetPlayer()->GetGUIDLow() : 0;
}
/// Send a packet to the client
void WorldSession::SendPacket(WorldPacket const* packet, bool forced /*= false*/)
{
if (!m_Socket)
return;
if (packet->GetOpcode() == NULL_OPCODE)
{
sLog->outError(LOG_FILTER_OPCODES, "Prevented sending of NULL_OPCODE to %s", GetPlayerInfo().c_str());
return;
}
else if (packet->GetOpcode() == UNKNOWN_OPCODE)
{
sLog->outError(LOG_FILTER_OPCODES, "Prevented sending of UNKNOWN_OPCODE to %s", GetPlayerInfo().c_str());
return;
}
if (!forced)
{
OpcodeHandler const* handler = opcodeTable[packet->GetOpcode()];
if (!handler || handler->Status == STATUS_UNHANDLED)
{
sLog->outError(LOG_FILTER_OPCODES, "Prevented sending disabled opcode %s to %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), GetPlayerInfo().c_str());
return;
}
}
#ifdef TRINITY_DEBUG
// Code for network use statistic
static uint64 sendPacketCount = 0;
static uint64 sendPacketBytes = 0;
static time_t firstTime = time(NULL);
static time_t lastTime = firstTime; // next 60 secs start time
static uint64 sendLastPacketCount = 0;
static uint64 sendLastPacketBytes = 0;
time_t cur_time = time(NULL);
if ((cur_time - lastTime) < 60)
{
sendPacketCount+=1;
sendPacketBytes+=packet->size();
sendLastPacketCount+=1;
sendLastPacketBytes+=packet->size();
}
else
{
uint64 minTime = uint64(cur_time - lastTime);
uint64 fullTime = uint64(lastTime - firstTime);
sLog->outInfo(LOG_FILTER_GENERAL, "Send all time packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f time: %u", sendPacketCount, sendPacketBytes, float(sendPacketCount)/fullTime, float(sendPacketBytes)/fullTime, uint32(fullTime));
sLog->outInfo(LOG_FILTER_GENERAL, "Send last min packets count: " UI64FMTD " bytes: " UI64FMTD " avr.count/sec: %f avr.bytes/sec: %f", sendLastPacketCount, sendLastPacketBytes, float(sendLastPacketCount)/minTime, float(sendLastPacketBytes)/minTime);
lastTime = cur_time;
sendLastPacketCount = 1;
sendLastPacketBytes = packet->wpos(); // wpos is real written size
}
#endif // !TRINITY_DEBUG
if (m_Socket->SendPacket(*packet) == -1)
m_Socket->CloseSocket();
}
/// Add an incoming packet to the queue
void WorldSession::QueuePacket(WorldPacket* new_packet)
{
_recvQueue.add(new_packet);
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnexpectedOpcode(WorldPacket* packet, const char* status, const char *reason)
{
sLog->outError(LOG_FILTER_OPCODES, "Received unexpected opcode %s Status: %s Reason: %s from %s",
GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), status, reason, GetPlayerInfo().c_str());
}
/// Logging helper for unexpected opcodes
void WorldSession::LogUnprocessedTail(WorldPacket* packet)
{
if (!sLog->ShouldLog(LOG_FILTER_OPCODES, LOG_LEVEL_TRACE) || packet->rpos() >= packet->wpos())
return;
sLog->outTrace(LOG_FILTER_OPCODES, "Unprocessed tail data (read stop at %u from %u) Opcode %s from %s",
uint32(packet->rpos()), uint32(packet->wpos()), GetOpcodeNameForLogging(packet->GetOpcode()).c_str(), GetPlayerInfo().c_str());
packet->print_storage();
}
/// Update the WorldSession (triggered by World update)
bool WorldSession::Update(uint32 diff, PacketFilter& updater)
{
/// Update Timeout timer.
UpdateTimeOutTime(diff);
///- Before we process anything:
/// If necessary, kick the player from the character select screen
if (IsConnectionIdle())
m_Socket->CloseSocket();
///- Retrieve packets from the receive queue and call the appropriate handlers
/// not process packets if socket already closed
WorldPacket* packet = NULL;
//! Delete packet after processing by default
bool deletePacket = true;
//! To prevent infinite loop
WorldPacket* firstDelayedPacket = NULL;
//! If _recvQueue.peek() == firstDelayedPacket it means that in this Update call, we've processed all
//! *properly timed* packets, and we're now at the part of the queue where we find
//! delayed packets that were re-enqueued due to improper timing. To prevent an infinite
//! loop caused by re-enqueueing the same packets over and over again, we stop updating this session
//! and continue updating others. The re-enqueued packets will be handled in the next Update call for this session.
while (m_Socket && !m_Socket->IsClosed() &&
!_recvQueue.empty() && _recvQueue.peek(true) != firstDelayedPacket &&
_recvQueue.next(packet, updater))
{
OpcodeHandler const* opHandle = opcodeTable[packet->GetOpcode()];
try
{
switch (opHandle->Status)
{
case STATUS_LOGGEDIN:
if (!_player)
{
// skip STATUS_LOGGEDIN opcode unexpected errors if player logout sometime ago - this can be network lag delayed packets
//! If player didn't log out a while ago, it means packets are being sent while the server does not recognize
//! the client to be in world yet. We will re-add the packets to the bottom of the queue and process them later.
if (!m_playerRecentlyLogout)
{
//! Prevent infinite loop
if (!firstDelayedPacket)
firstDelayedPacket = packet;
//! Because checking a bool is faster than reallocating memory
deletePacket = false;
QueuePacket(packet);
//! Log
sLog->outDebug(LOG_FILTER_NETWORKIO, "Re-enqueueing packet with opcode %s with with status STATUS_LOGGEDIN. "
"Player is currently not in world yet.", GetOpcodeNameForLogging(packet->GetOpcode()).c_str());
}
}
else if (_player->IsInWorld())
{
sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
(this->*opHandle->Handler)(*packet);
LogUnprocessedTail(packet);
}
// lag can cause STATUS_LOGGEDIN opcodes to arrive after the player started a transfer
break;
case STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT:
if (!_player && !m_playerRecentlyLogout && !m_playerLogout) // There's a short delay between _player = null and m_playerRecentlyLogout = true during logout
LogUnexpectedOpcode(packet, "STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT",
"the player has not logged in yet and not recently logout");
else
{
// not expected _player or must checked in packet hanlder
sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
(this->*opHandle->Handler)(*packet);
LogUnprocessedTail(packet);
}
break;
case STATUS_TRANSFER:
if (!_player)
LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player has not logged in yet");
else if (_player->IsInWorld())
LogUnexpectedOpcode(packet, "STATUS_TRANSFER", "the player is still in world");
else
{
sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
(this->*opHandle->Handler)(*packet);
LogUnprocessedTail(packet);
}
break;
case STATUS_AUTHED:
// prevent cheating with skip queue wait
if (m_inQueue)
{
LogUnexpectedOpcode(packet, "STATUS_AUTHED", "the player not pass queue yet");
break;
}
// some auth opcodes can be recieved before STATUS_LOGGEDIN_OR_RECENTLY_LOGGOUT opcodes
// however when we recieve CMSG_CHAR_ENUM we are surely no longer during the logout process.
if (packet->GetOpcode() == CMSG_CHAR_ENUM)
m_playerRecentlyLogout = false;
sScriptMgr->OnPacketReceive(m_Socket, WorldPacket(*packet));
(this->*opHandle->Handler)(*packet);
LogUnprocessedTail(packet);
break;
case STATUS_NEVER:
sLog->outError(LOG_FILTER_OPCODES, "Received not allowed opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str()
, GetPlayerInfo().c_str());
break;
case STATUS_UNHANDLED:
sLog->outError(LOG_FILTER_OPCODES, "Received not handled opcode %s from %s", GetOpcodeNameForLogging(packet->GetOpcode()).c_str()
, GetPlayerInfo().c_str());
break;
}
}
catch(ByteBufferException &)
{
sLog->outError(LOG_FILTER_NETWORKIO, "WorldSession::Update ByteBufferException occured while parsing a packet (opcode: %u) from client %s, accountid=%i. Skipped packet.",
packet->GetOpcode(), GetRemoteAddress().c_str(), GetAccountId());
packet->hexlike();
}
if (deletePacket)
delete packet;
}
if (m_Socket && !m_Socket->IsClosed() && _warden)
_warden->Update();
ProcessQueryCallbacks();
//check if we are safe to proceed with logout
//logout procedure should happen only in World::UpdateSessions() method!!!
if (updater.ProcessLogout())
{
time_t currTime = time(NULL);
///- If necessary, log the player out
if (ShouldLogOut(currTime) && !m_playerLoading)
LogoutPlayer(true);
if (m_Socket && GetPlayer() && _warden)
_warden->Update();
///- Cleanup socket pointer if need
if (m_Socket && m_Socket->IsClosed())
{
m_Socket->RemoveReference();
m_Socket = NULL;
}
if (!m_Socket)
return false; //Will remove this session from the world session map
}
return true;
}
/// %Log the player out
void WorldSession::LogoutPlayer(bool Save)
{
// finish pending transfers before starting the logout
while (_player && _player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode();
m_playerLogout = true;
m_playerSave = Save;
if (_player)
{
if (uint64 lguid = _player->GetLootGUID())
DoLootRelease(lguid);
///- If the player just died before logging out, make him appear as a ghost
//FIXME: logout must be delayed in case lost connection with client in time of combat
if (_player->GetDeathTimer())
{
_player->getHostileRefManager().deleteReferences();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (!_player->getAttackers().empty())
{
// build set of player who attack _player or who have pet attacking of _player
std::set<Player*> aset;
for (Unit::AttackerSet::const_iterator itr = _player->getAttackers().begin(); itr != _player->getAttackers().end(); ++itr)
{
Unit* owner = (*itr)->GetOwner(); // including player controlled case
if (owner && owner->GetTypeId() == TYPEID_PLAYER)
aset.insert(owner->ToPlayer());
else if ((*itr)->GetTypeId() == TYPEID_PLAYER)
aset.insert((Player*)(*itr));
}
// CombatStop() method is removing all attackers from the AttackerSet
// That is why it must be AFTER building current set of attackers
_player->CombatStop();
_player->getHostileRefManager().setOnlineOfflineState(false);
_player->RemoveAllAurasOnDeath();
_player->SetPvPDeath(!aset.empty());
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
// give honor to all attackers from set like group case
for (std::set<Player*>::const_iterator itr = aset.begin(); itr != aset.end(); ++itr)
(*itr)->RewardHonor(_player, aset.size());
// give bg rewards and update counters like kill by first from attackers
// this can't be called for all attackers.
if (!aset.empty())
if (Battleground* bg = _player->GetBattleground())
bg->HandleKillPlayer(_player, *aset.begin());
}
else if (_player->HasAuraType(SPELL_AURA_SPIRIT_OF_REDEMPTION))
{
// this will kill character by SPELL_AURA_SPIRIT_OF_REDEMPTION
_player->RemoveAurasByType(SPELL_AURA_MOD_SHAPESHIFT);
_player->KillPlayer();
_player->BuildPlayerRepop();
_player->RepopAtGraveyard();
}
else if (_player->HasPendingBind())
{
_player->RepopAtGraveyard();
_player->SetPendingBind(0, 0);
}
//drop a flag if player is carrying it
if (Battleground* bg = _player->GetBattleground())
bg->EventPlayerLoggedOut(_player);
///- Teleport to home if the player is in an invalid instance
if (!_player->m_InstanceValid && !_player->isGameMaster())
_player->TeleportTo(_player->m_homebindMapId, _player->m_homebindX, _player->m_homebindY, _player->m_homebindZ, _player->GetOrientation());
sOutdoorPvPMgr->HandlePlayerLeaveZone(_player, _player->GetZoneId());
for (int i=0; i < PLAYER_MAX_BATTLEGROUND_QUEUES; ++i)
{
if (BattlegroundQueueTypeId bgQueueTypeId = _player->GetBattlegroundQueueTypeId(i))
{
_player->RemoveBattlegroundQueueId(bgQueueTypeId);
BattlegroundQueue& queue = sBattlegroundMgr->GetBattlegroundQueue(bgQueueTypeId);
queue.RemovePlayer(_player->GetGUID(), true);
}
}
// Repop at GraveYard or other player far teleport will prevent saving player because of not present map
// Teleport player immediately for correct player save
while (_player->IsBeingTeleportedFar())
HandleMoveWorldportAckOpcode();
///- If the player is in a guild, update the guild roster and broadcast a logout message to other guild members
if (Guild* guild = sGuildMgr->GetGuildById(_player->GetGuildId()))
guild->HandleMemberLogout(this);
///- Remove pet
_player->RemovePet(NULL, PET_SAVE_AS_CURRENT, true);
///- empty buyback items and save the player in the database
// some save parts only correctly work in case player present in map/player_lists (pets, etc)
if (Save)
{
uint32 eslot;
for (int j = BUYBACK_SLOT_START; j < BUYBACK_SLOT_END; ++j)
{
eslot = j - BUYBACK_SLOT_START;
_player->SetUInt64Value(PLAYER_FIELD_VENDORBUYBACK_SLOT_1 + (eslot * 2), 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + eslot, 0);
_player->SetUInt32Value(PLAYER_FIELD_BUYBACK_TIMESTAMP_1 + eslot, 0);
}
_player->SaveToDB();
}
///- Leave all channels before player delete...
_player->CleanupChannels();
///- If the player is in a group (or invited), remove him. If the group if then only 1 person, disband the group.
_player->UninviteFromGroup();
// remove player from the group if he is:
// a) in group; b) not in raid group; c) logging out normally (not being kicked or disconnected)
if (_player->GetGroup() && !_player->GetGroup()->isRaidGroup() && m_Socket)
_player->RemoveFromGroup();
//! Send update to group and reset stored max enchanting level
if (_player->GetGroup())
{
_player->GetGroup()->SendUpdate();
_player->GetGroup()->ResetMaxEnchantingLevel();
}
//! Broadcast a logout message to the player's friends
sSocialMgr->SendFriendStatus(_player, FRIEND_OFFLINE, _player->GetGUIDLow(), true);
sSocialMgr->RemovePlayerSocial(_player->GetGUIDLow());
//! Call script hook before deletion
sScriptMgr->OnPlayerLogout(_player);
//! Remove the player from the world
// the player may not be in the world when logging out
// e.g if he got disconnected during a transfer to another map
// calls to GetMap in this case may cause crashes
_player->CleanupsBeforeDelete();
sLog->outInfo(LOG_FILTER_CHARACTER, "Account: %d (IP: %s) Logout Character:[%s] (GUID: %u) Level: %d",
GetAccountId(), GetRemoteAddress().c_str(), _player->GetName().c_str(), _player->GetGUIDLow(), _player->getLevel());
if (Map* _map = _player->FindMap())
_map->RemovePlayerFromMap(_player, true);
SetPlayer(NULL); //! Pointer already deleted during RemovePlayerFromMap
//! Send the 'logout complete' packet to the client
//! Client will respond by sending 3x CMSG_CANCEL_TRADE, which we currently dont handle
WorldPacket data(SMSG_LOGOUT_COMPLETE, 0);
SendPacket(&data);
sLog->outDebug(LOG_FILTER_NETWORKIO, "SESSION: Sent SMSG_LOGOUT_COMPLETE Message");
//! Since each account can only have one online character at any given time, ensure all characters for active account are marked as offline
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_UPD_ACCOUNT_ONLINE);
stmt->setUInt32(0, GetAccountId());
CharacterDatabase.Execute(stmt);
}
m_playerLogout = false;
m_playerSave = false;
m_playerRecentlyLogout = true;
LogoutRequest(0);
}
/// Kick a player out of the World
void WorldSession::KickPlayer()
{
if (m_Socket)
m_Socket->CloseSocket();
}
void WorldSession::SendNotification(const char *format, ...)
{
if (format)
{
va_list ap;
char szStr[1024];
szStr[0] = '\0';
va_start(ap, format);
vsnprintf(szStr, 1024, format, ap);
va_end(ap);
size_t len = strlen(szStr);
WorldPacket data(SMSG_NOTIFICATION, 2 + len);
data.WriteBits(len, 13);
data.FlushBits();
data.append(szStr, len);
SendPacket(&data);
}
}
void WorldSession::SendNotification(uint32 string_id, ...)
{
char const* format = GetTrinityString(string_id);
if (format)
{
va_list ap;
char szStr[1024];
szStr[0] = '\0';
va_start(ap, string_id);
vsnprintf(szStr, 1024, format, ap);
va_end(ap);
size_t len = strlen(szStr);
WorldPacket data(SMSG_NOTIFICATION, 2 + len);
data.WriteBits(len, 13);
data.FlushBits();
data.append(szStr, len);
SendPacket(&data);
}
}
const char *WorldSession::GetTrinityString(int32 entry) const
{
return sObjectMgr->GetTrinityString(entry, GetSessionDbLocaleIndex());
}
void WorldSession::Handle_NULL(WorldPacket& recvPacket)
{
sLog->outError(LOG_FILTER_OPCODES, "Received unhandled opcode %s from %s"
, GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
}
void WorldSession::Handle_EarlyProccess(WorldPacket& recvPacket)
{
sLog->outError(LOG_FILTER_OPCODES, "Received opcode %s that must be processed in WorldSocket::OnRead from %s"
, GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
}
void WorldSession::Handle_ServerSide(WorldPacket& recvPacket)
{
sLog->outError(LOG_FILTER_OPCODES, "Received server-side opcode %s from %s"
, GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
}
void WorldSession::Handle_Deprecated(WorldPacket& recvPacket)
{
sLog->outError(LOG_FILTER_OPCODES, "Received deprecated opcode %s from %s"
, GetOpcodeNameForLogging(recvPacket.GetOpcode()).c_str(), GetPlayerInfo().c_str());
}
void WorldSession::SendAuthWaitQue(uint32 position)
{
if (position == 0)
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 1);
packet.WriteBit(0); // has queue info
packet.WriteBit(0); // has account info
packet.FlushBits();
packet << uint8(AUTH_OK);
SendPacket(&packet);
}
else
{
WorldPacket packet(SMSG_AUTH_RESPONSE, 6);
packet.WriteBit(1); // has queue info
packet.WriteBit(0); // unk queue bool
packet.WriteBit(0); // has account info
packet.FlushBits();
packet << uint8(AUTH_WAIT_QUEUE);
packet << uint32(position);
SendPacket(&packet);
}
}
void WorldSession::LoadGlobalAccountData()
{
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_ACCOUNT_DATA);
stmt->setUInt32(0, GetAccountId());
LoadAccountData(CharacterDatabase.Query(stmt), GLOBAL_CACHE_MASK);
}
void WorldSession::LoadAccountData(PreparedQueryResult result, uint32 mask)
{
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if (mask & (1 << i))
m_accountData[i] = AccountData();
if (!result)
return;
do
{
Field* fields = result->Fetch();
uint32 type = fields[0].GetUInt8();
if (type >= NUM_ACCOUNT_DATA_TYPES)
{
sLog->outError(LOG_FILTER_GENERAL, "Table `%s` have invalid account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
if ((mask & (1 << type)) == 0)
{
sLog->outError(LOG_FILTER_GENERAL, "Table `%s` have non appropriate for table account data type (%u), ignore.",
mask == GLOBAL_CACHE_MASK ? "account_data" : "character_account_data", type);
continue;
}
m_accountData[type].Time = time_t(fields[1].GetUInt32());
m_accountData[type].Data = fields[2].GetString();
}
while (result->NextRow());
}
void WorldSession::SetAccountData(AccountDataType type, time_t tm, std::string const& data)
{
uint32 id = 0;
uint32 index = 0;
if ((1 << type) & GLOBAL_CACHE_MASK)
{
id = GetAccountId();
index = CHAR_REP_ACCOUNT_DATA;
}
else
{
// _player can be NULL and packet received after logout but m_GUID still store correct guid
if (!m_GUIDLow)
return;
id = m_GUIDLow;
index = CHAR_REP_PLAYER_ACCOUNT_DATA;
}
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(index);
stmt->setUInt32(0, id);
stmt->setUInt8 (1, type);
stmt->setUInt32(2, uint32(tm));
stmt->setString(3, data);
CharacterDatabase.Execute(stmt);
m_accountData[type].Time = tm;
m_accountData[type].Data = data;
}
void WorldSession::SendAccountDataTimes(uint32 mask)
{
WorldPacket data(SMSG_ACCOUNT_DATA_TIMES, 4+1+4+NUM_ACCOUNT_DATA_TYPES*4);
data << uint32(time(NULL)); // Server time
data << uint8(1);
data << uint32(mask); // type mask
for (uint32 i = 0; i < NUM_ACCOUNT_DATA_TYPES; ++i)
if (mask & (1 << i))
data << uint32(GetAccountData(AccountDataType(i))->Time);// also unix time
SendPacket(&data);
}
void WorldSession::LoadTutorialsData()
{
memset(m_Tutorials, 0, sizeof(uint32) * MAX_ACCOUNT_TUTORIAL_VALUES);
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_TUTORIALS);
stmt->setUInt32(0, GetAccountId());
if (PreparedQueryResult result = CharacterDatabase.Query(stmt))
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
m_Tutorials[i] = (*result)[i].GetUInt32();
m_TutorialsChanged = false;
}
void WorldSession::SendTutorialsData()
{
WorldPacket data(SMSG_TUTORIAL_FLAGS, 4 * MAX_ACCOUNT_TUTORIAL_VALUES);
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
data << m_Tutorials[i];
SendPacket(&data);
}
void WorldSession::SaveTutorialsData(SQLTransaction &trans)
{
if (!m_TutorialsChanged)
return;
PreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_HAS_TUTORIALS);
stmt->setUInt32(0, GetAccountId());
bool hasTutorials = !CharacterDatabase.Query(stmt).null();
// Modify data in DB
stmt = CharacterDatabase.GetPreparedStatement(hasTutorials ? CHAR_UPD_TUTORIALS : CHAR_INS_TUTORIALS);
for (uint8 i = 0; i < MAX_ACCOUNT_TUTORIAL_VALUES; ++i)
stmt->setUInt32(i, m_Tutorials[i]);
stmt->setUInt32(MAX_ACCOUNT_TUTORIAL_VALUES, GetAccountId());
trans->Append(stmt);
m_TutorialsChanged = false;
}
void WorldSession::ReadAddonsInfo(WorldPacket &data)
{
if (data.rpos() + 4 > data.size())
return;
uint32 size;
data >> size;
if (!size)
return;
if (size > 0xFFFFF)
{
sLog->outError(LOG_FILTER_GENERAL, "WorldSession::ReadAddonsInfo addon info too big, size %u", size);
return;
}
uLongf uSize = size;
uint32 pos = data.rpos();
ByteBuffer addonInfo;
addonInfo.resize(size);
if (uncompress(const_cast<uint8*>(addonInfo.contents()), &uSize, const_cast<uint8*>(data.contents() + pos), data.size() - pos) == Z_OK)
{
uint32 addonsCount;
addonInfo >> addonsCount; // addons count
for (uint32 i = 0; i < addonsCount; ++i)
{
std::string addonName;
uint8 enabled;
uint32 crc, unk1;
// check next addon data format correctness
if (addonInfo.rpos() + 1 > addonInfo.size())
return;
addonInfo >> addonName;
addonInfo >> enabled >> crc >> unk1;
sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: Name: %s, Enabled: 0x%x, CRC: 0x%x, Unknown2: 0x%x", addonName.c_str(), enabled, crc, unk1);
AddonInfo addon(addonName, enabled, crc, 2, true);
SavedAddon const* savedAddon = AddonMgr::GetAddonInfo(addonName);
if (savedAddon)
{
bool match = true;
if (addon.CRC != savedAddon->CRC)
match = false;
if (!match)
sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: %s was known, but didn't match known CRC (0x%x)!", addon.Name.c_str(), savedAddon->CRC);
else
sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: %s was known, CRC is correct (0x%x)", addon.Name.c_str(), savedAddon->CRC);
}
else
{
AddonMgr::SaveAddon(addon);
sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: %s (0x%x) was not known, saving...", addon.Name.c_str(), addon.CRC);
}
// TODO: Find out when to not use CRC/pubkey, and other possible states.
m_addonsList.push_back(addon);
}
uint32 currentTime;
addonInfo >> currentTime;
sLog->outDebug(LOG_FILTER_NETWORKIO, "ADDON: CurrentTime: %u", currentTime);
if (addonInfo.rpos() != addonInfo.size())
sLog->outDebug(LOG_FILTER_NETWORKIO, "packet under-read!");
}
else
sLog->outError(LOG_FILTER_GENERAL, "Addon packet uncompress error!");
}
void WorldSession::SendAddonsInfo()
{
uint8 addonPublicKey[256] =
{
0xC3, 0x5B, 0x50, 0x84, 0xB9, 0x3E, 0x32, 0x42, 0x8C, 0xD0, 0xC7, 0x48, 0xFA, 0x0E, 0x5D, 0x54,
0x5A, 0xA3, 0x0E, 0x14, 0xBA, 0x9E, 0x0D, 0xB9, 0x5D, 0x8B, 0xEE, 0xB6, 0x84, 0x93, 0x45, 0x75,
0xFF, 0x31, 0xFE, 0x2F, 0x64, 0x3F, 0x3D, 0x6D, 0x07, 0xD9, 0x44, 0x9B, 0x40, 0x85, 0x59, 0x34,
0x4E, 0x10, 0xE1, 0xE7, 0x43, 0x69, 0xEF, 0x7C, 0x16, 0xFC, 0xB4, 0xED, 0x1B, 0x95, 0x28, 0xA8,
0x23, 0x76, 0x51, 0x31, 0x57, 0x30, 0x2B, 0x79, 0x08, 0x50, 0x10, 0x1C, 0x4A, 0x1A, 0x2C, 0xC8,
0x8B, 0x8F, 0x05, 0x2D, 0x22, 0x3D, 0xDB, 0x5A, 0x24, 0x7A, 0x0F, 0x13, 0x50, 0x37, 0x8F, 0x5A,
0xCC, 0x9E, 0x04, 0x44, 0x0E, 0x87, 0x01, 0xD4, 0xA3, 0x15, 0x94, 0x16, 0x34, 0xC6, 0xC2, 0xC3,
0xFB, 0x49, 0xFE, 0xE1, 0xF9, 0xDA, 0x8C, 0x50, 0x3C, 0xBE, 0x2C, 0xBB, 0x57, 0xED, 0x46, 0xB9,
0xAD, 0x8B, 0xC6, 0xDF, 0x0E, 0xD6, 0x0F, 0xBE, 0x80, 0xB3, 0x8B, 0x1E, 0x77, 0xCF, 0xAD, 0x22,
0xCF, 0xB7, 0x4B, 0xCF, 0xFB, 0xF0, 0x6B, 0x11, 0x45, 0x2D, 0x7A, 0x81, 0x18, 0xF2, 0x92, 0x7E,
0x98, 0x56, 0x5D, 0x5E, 0x69, 0x72, 0x0A, 0x0D, 0x03, 0x0A, 0x85, 0xA2, 0x85, 0x9C, 0xCB, 0xFB,
0x56, 0x6E, 0x8F, 0x44, 0xBB, 0x8F, 0x02, 0x22, 0x68, 0x63, 0x97, 0xBC, 0x85, 0xBA, 0xA8, 0xF7,
0xB5, 0x40, 0x68, 0x3C, 0x77, 0x86, 0x6F, 0x4B, 0xD7, 0x88, 0xCA, 0x8A, 0xD7, 0xCE, 0x36, 0xF0,
0x45, 0x6E, 0xD5, 0x64, 0x79, 0x0F, 0x17, 0xFC, 0x64, 0xDD, 0x10, 0x6F, 0xF3, 0xF5, 0xE0, 0xA6,
0xC3, 0xFB, 0x1B, 0x8C, 0x29, 0xEF, 0x8E, 0xE5, 0x34, 0xCB, 0xD1, 0x2A, 0xCE, 0x79, 0xC3, 0x9A,
0x0D, 0x36, 0xEA, 0x01, 0xE0, 0xAA, 0x91, 0x20, 0x54, 0xF0, 0x72, 0xD8, 0x1E, 0xC7, 0x89, 0xD2
};
WorldPacket data(SMSG_ADDON_INFO, 4);
for (AddonsList::iterator itr = m_addonsList.begin(); itr != m_addonsList.end(); ++itr)
{
data << uint8(itr->State);
uint8 crcpub = itr->UsePublicKeyOrCRC;
data << uint8(crcpub);
if (crcpub)
{
uint8 usepk = (itr->CRC != STANDARD_ADDON_CRC); // If addon is Standard addon CRC
data << uint8(usepk);
if (usepk) // if CRC is wrong, add public key (client need it)
{
sLog->outInfo(LOG_FILTER_GENERAL, "ADDON: CRC (0x%x) for addon %s is wrong (does not match expected 0x%x), sending pubkey",
itr->CRC, itr->Name.c_str(), STANDARD_ADDON_CRC);
data.append(addonPublicKey, sizeof(addonPublicKey));
}
data << uint32(0); // TODO: Find out the meaning of this.
}
uint8 unk3 = 0; // 0 is sent here
data << uint8(unk3);
if (unk3)
{
// String, length 256 (null terminated)
data << uint8(0);
}
}
m_addonsList.clear();
data << uint32(0); // count for an unknown for loop
SendPacket(&data);
}
bool WorldSession::IsAddonRegistered(const std::string& prefix) const
{
if (!_filterAddonMessages) // if we have hit the softcap (64) nothing should be filtered
return true;
if (_registeredAddonPrefixes.empty())
return false;
std::vector<std::string>::const_iterator itr = std::find(_registeredAddonPrefixes.begin(), _registeredAddonPrefixes.end(), prefix);
return itr != _registeredAddonPrefixes.end();
}
void WorldSession::HandleUnregisterAddonPrefixesOpcode(WorldPacket& /*recvPacket*/) // empty packet
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_UNREGISTER_ALL_ADDON_PREFIXES");
_registeredAddonPrefixes.clear();
}
void WorldSession::HandleAddonRegisteredPrefixesOpcode(WorldPacket& recvPacket)
{
sLog->outDebug(LOG_FILTER_NETWORKIO, "WORLD: Received CMSG_ADDON_REGISTERED_PREFIXES");
// This is always sent after CMSG_UNREGISTER_ALL_ADDON_PREFIXES
uint32 count = recvPacket.ReadBits(25);
if (count > REGISTERED_ADDON_PREFIX_SOFTCAP)
{
// if we have hit the softcap (64) nothing should be filtered
_filterAddonMessages = false;
recvPacket.rfinish();
return;
}
std::vector<uint8> lengths(count);
for (uint32 i = 0; i < count; ++i)
lengths[i] = recvPacket.ReadBits(5);
for (uint32 i = 0; i < count; ++i)
_registeredAddonPrefixes.push_back(recvPacket.ReadString(lengths[i]));
if (_registeredAddonPrefixes.size() > REGISTERED_ADDON_PREFIX_SOFTCAP) // shouldn't happen
{
_filterAddonMessages = false;
return;
}
_filterAddonMessages = true;
}
void WorldSession::SetPlayer(Player* player)
{
_player = player;
// set m_GUID that can be used while player loggined and later until m_playerRecentlyLogout not reset
if (_player)
m_GUIDLow = _player->GetGUIDLow();
}
void WorldSession::InitializeQueryCallbackParameters()
{
// Callback parameters that have pointers in them should be properly
// initialized to NULL here.
_charCreateCallback.SetParam(NULL);
}
void WorldSession::ProcessQueryCallbacks()
{
PreparedQueryResult result;
//! HandleCharEnumOpcode
if (_charEnumCallback.ready())
{
_charEnumCallback.get(result);
HandleCharEnum(result);
_charEnumCallback.cancel();
}
if (_charCreateCallback.IsReady())
{
_charCreateCallback.GetResult(result);
HandleCharCreateCallback(result, _charCreateCallback.GetParam());
// Don't call FreeResult() here, the callback handler will do that depending on the events in the callback chain
}
//! HandlePlayerLoginOpcode
if (_charLoginCallback.ready())
{
SQLQueryHolder* param;
_charLoginCallback.get(param);
HandlePlayerLogin((LoginQueryHolder*)param);
_charLoginCallback.cancel();
}
//! HandleAddFriendOpcode
if (_addFriendCallback.IsReady())
{
std::string param = _addFriendCallback.GetParam();
_addFriendCallback.GetResult(result);
HandleAddFriendOpcodeCallBack(result, param);
_addFriendCallback.FreeResult();
}
//- HandleCharRenameOpcode
if (_charRenameCallback.IsReady())
{
std::string param = _charRenameCallback.GetParam();
_charRenameCallback.GetResult(result);
HandleChangePlayerNameOpcodeCallBack(result, param);
_charRenameCallback.FreeResult();
}
//- HandleCharAddIgnoreOpcode
if (_addIgnoreCallback.ready())
{
_addIgnoreCallback.get(result);
HandleAddIgnoreOpcodeCallBack(result);
_addIgnoreCallback.cancel();
}
//- SendStabledPet
if (_sendStabledPetCallback.IsReady())
{
uint64 param = _sendStabledPetCallback.GetParam();
_sendStabledPetCallback.GetResult(result);
SendStablePetCallback(result, param);
_sendStabledPetCallback.FreeResult();
}
//- HandleStablePet
if (_stablePetCallback.ready())
{
_stablePetCallback.get(result);
HandleStablePetCallback(result);
_stablePetCallback.cancel();
}
//- HandleUnstablePet
if (_unstablePetCallback.IsReady())
{
uint32 param = _unstablePetCallback.GetParam();
_unstablePetCallback.GetResult(result);
HandleUnstablePetCallback(result, param);
_unstablePetCallback.FreeResult();
}
//- HandleStableSwapPet
if (_stableSwapCallback.IsReady())
{
uint32 param = _stableSwapCallback.GetParam();
_stableSwapCallback.GetResult(result);
HandleStableSwapPetCallback(result, param);
_stableSwapCallback.FreeResult();
}
}
void WorldSession::InitWarden(BigNumber* k, std::string const& os)
{
if (os == "Win")
{
_warden = new WardenWin();
_warden->Init(this, k);
}
else if (os == "OSX")
{
// Disabled as it is causing the client to crash
// _warden = new WardenMac();
// _warden->Init(this, k);
}
}
| Ikesters/TrinityCore-5.0.5b | Нова папка/src/server/game/Server/WorldSession.cpp | C++ | gpl-2.0 | 42,375 |
/*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
*
* @bug 6388456
* @summary Need adjustable TLS max record size for interoperability
* with non-compliant
*
* @run main/othervm -Djsse.enableCBCProtection=false LargePacket
*
* @author Xuelei Fan
*/
import javax.net.ssl.*;
import java.nio.channels.*;
import java.net.*;
public class LargePacket extends SSLEngineService {
/*
* =============================================================
* Set the various variables needed for the tests, then
* specify what tests to run on each side.
*/
/*
* Should we run the client or server in a separate thread?
* Both sides can throw exceptions, but do you have a preference
* as to which side should be the main thread.
*/
static boolean separateServerThread = true;
// Is the server ready to serve?
volatile static boolean serverReady = false;
/*
* Turn on SSL debugging?
*/
static boolean debug = false;
/*
* Define the server side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doServerSide() throws Exception {
// create SSLEngine.
SSLEngine ssle = createSSLEngine(false);
// Create a server socket channel.
InetSocketAddress isa =
new InetSocketAddress(InetAddress.getLocalHost(), serverPort);
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(isa);
serverPort = ssc.socket().getLocalPort();
// Signal Client, we're ready for his connect.
serverReady = true;
// Accept a socket channel.
SocketChannel sc = ssc.accept();
// Complete connection.
while (!sc.finishConnect() ) {
// waiting for the connection completed.
}
// handshaking
handshaking(ssle, sc);
// receive application data
receive(ssle, sc);
// send out application data
deliver(ssle, sc);
// close the socket channel.
sc.close();
ssc.close();
}
/*
* Define the client side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doClientSide() throws Exception {
// create SSLEngine.
SSLEngine ssle = createSSLEngine(true);
/*
* Wait for server to get started.
*/
while (!serverReady) {
Thread.sleep(50);
}
// Create a non-blocking socket channel.
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
InetSocketAddress isa =
new InetSocketAddress(InetAddress.getLocalHost(), serverPort);
sc.connect(isa);
// Complete connection.
while (!sc.finishConnect() ) {
// waiting for the connection completed.
}
// handshaking
handshaking(ssle, sc);
// send out application data
deliver(ssle, sc);
// receive application data
receive(ssle, sc);
// close the socket channel.
sc.close();
}
/*
* =============================================================
* The remainder is just support stuff
*/
volatile Exception serverException = null;
volatile Exception clientException = null;
// use any free port by default
volatile int serverPort = 0;
public static void main(String args[]) throws Exception {
if (debug)
System.setProperty("javax.net.debug", "all");
new LargePacket();
}
Thread clientThread = null;
Thread serverThread = null;
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
LargePacket() throws Exception {
if (separateServerThread) {
startServer(true);
startClient(false);
} else {
startClient(true);
startServer(false);
}
/*
* Wait for other side to close down.
*/
if (separateServerThread) {
serverThread.join();
} else {
clientThread.join();
}
/*
* When we get here, the test is pretty much over.
*
* If the main thread excepted, that propagates back
* immediately. If the other thread threw an exception, we
* should report back.
*/
if (serverException != null) {
System.out.print("Server Exception:");
throw serverException;
}
if (clientException != null) {
System.out.print("Client Exception:");
throw clientException;
}
}
void startServer(boolean newThread) throws Exception {
if (newThread) {
serverThread = new Thread() {
public void run() {
try {
doServerSide();
} catch (Exception e) {
/*
* Our server thread just died.
*
* Release the client, if not active already...
*/
System.err.println("Server died...");
System.err.println(e);
serverReady = true;
serverException = e;
}
}
};
serverThread.start();
} else {
doServerSide();
}
}
void startClient(boolean newThread) throws Exception {
if (newThread) {
clientThread = new Thread() {
public void run() {
try {
doClientSide();
} catch (Exception e) {
/*
* Our client thread just died.
*/
System.err.println("Client died...");
clientException = e;
}
}
};
clientThread.start();
} else {
doClientSide();
}
}
}
| openjdk-mirror/jdk7u-jdk | test/sun/security/ssl/javax/net/ssl/NewAPIs/SSLEngine/LargePacket.java | Java | gpl-2.0 | 7,353 |
# -*- coding: utf-8 -*-
"""
@author: Fabio Erculiani <lxnay@sabayon.org>
@contact: lxnay@sabayon.org
@copyright: Fabio Erculiani
@license: GPL-2
B{Entropy Infrastructure Toolkit}.
"""
import sys
import argparse
import textwrap as _textwrap
from entropy.output import decolorize
class ColorfulFormatter(argparse.RawTextHelpFormatter):
"""
This is just a whacky HelpFormatter flavour to add some coloring.
"""
def __colors(self, tup_str, orig_str):
pre_spaces = len(tup_str) - len(tup_str.lstrip())
post_spaces = len(tup_str) - len(tup_str.rstrip())
return " "*pre_spaces + orig_str.strip() \
+ " "*post_spaces
def _format_action(self, action):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = self._width - help_position
action_width = help_position - self._current_indent - 2
orig_action_header = self._format_action_invocation(action)
action_header = decolorize(orig_action_header)
# ho nelp; start on same line and add a final newline
if not action.help:
tup = self._current_indent, '', action_header
action_header = '%*s%s\n' % tup
# short action name; start on the same line and pad two spaces
elif len(action_header) <= action_width:
tup = self._current_indent, '', action_width, action_header
tup_str = '%*s%-*s ' % tup
action_header = self.__colors(tup_str, orig_action_header)
indent_first = 0
# long action name; start on the next line
else:
tup = self._current_indent, '', action_header
tup_str = '%*s%-*s ' % tup
action_header = self.__colors(tup_str, orig_action_header)
indent_first = help_position
# collect the pieces of the action help
parts = [action_header]
# if there was help for the action, add lines of help text
if action.help:
orig_help_text = self._expand_help(action)
help_text = decolorize(orig_help_text)
help_lines = self._split_lines(help_text, help_width)
orig_help_lines = self._split_lines(orig_help_text, help_width)
tup_str = '%*s%s' % (indent_first, '', help_lines[0])
parts.append(self.__colors(tup_str, orig_help_lines[0]) + "\n")
for idx, line in enumerate(help_lines[1:]):
tup_str = '%*s%s' % (help_position, '', line)
parts.append(
self.__colors(tup_str, orig_help_lines[idx+1]) + "\n")
# or add a newline if the description doesn't end with one
elif not action_header.endswith('\n'):
parts.append('\n')
# if there are any sub-actions, add their help as well
for subaction in self._iter_indented_subactions(action):
parts.append(self._format_action(subaction))
# return a single string
return self._join_parts(parts)
| mudler/entropy | server/eit/colorful.py | Python | gpl-2.0 | 3,125 |
Ext.define('Ext.chart.theme.Default', {
extend: 'Ext.chart.theme.Base',
singleton: true,
alias: [
'chart.theme.default',
'chart.theme.Base'
]
}); | ybbkd2/publicweb | web/ext/packages/sencha-charts/src/chart/theme/Default.js | JavaScript | gpl-2.0 | 177 |
/*
* Copyright (C) 2010-2018 Team Kodi
* This file is part of Kodi - https://kodi.tv
*
* SPDX-License-Identifier: GPL-2.0-or-later
* See LICENSES/README.md for more information.
*/
#include "AEStreamInfo.h"
#include "utils/log.h"
#include <algorithm>
#include <string.h>
#define DTS_PREAMBLE_14BE 0x1FFFE800
#define DTS_PREAMBLE_14LE 0xFF1F00E8
#define DTS_PREAMBLE_16BE 0x7FFE8001
#define DTS_PREAMBLE_16LE 0xFE7F0180
#define DTS_PREAMBLE_HD 0x64582025
#define DTS_PREAMBLE_XCH 0x5a5a5a5a
#define DTS_PREAMBLE_XXCH 0x47004a03
#define DTS_PREAMBLE_X96K 0x1d95f262
#define DTS_PREAMBLE_XBR 0x655e315e
#define DTS_PREAMBLE_LBR 0x0a801921
#define DTS_PREAMBLE_XLL 0x41a29547
#define DTS_SFREQ_COUNT 16
#define MAX_EAC3_BLOCKS 6
#define UNKNOWN_DTS_EXTENSION 255
static const uint16_t AC3Bitrates [] = {32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 448, 512, 576, 640};
static const uint16_t AC3FSCod [] = {48000, 44100, 32000, 0};
static const uint8_t AC3BlkCod [] = {1, 2, 3, 6};
static const uint8_t AC3Channels [] = {2, 1, 2, 3, 3, 4, 4, 5};
static const uint8_t DTSChannels [] = {1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 6, 6, 6, 7, 8, 8};
static const uint8_t THDChanMap [] = {2, 1, 1, 2, 2, 2, 2, 1, 1, 2, 2, 1, 1};
static const uint32_t DTSSampleRates[DTS_SFREQ_COUNT] =
{
0 ,
8000 ,
16000 ,
32000 ,
64000 ,
128000,
11025 ,
22050 ,
44100 ,
88200 ,
176400,
12000 ,
24000 ,
48000 ,
96000 ,
192000
};
CAEStreamParser::CAEStreamParser() :
m_syncFunc (&CAEStreamParser::DetectType)
{
av_crc_init(m_crcTrueHD, 0, 16, 0x2D, sizeof(m_crcTrueHD));
}
double CAEStreamInfo::GetDuration() const
{
double duration = 0;
switch (m_type)
{
case STREAM_TYPE_AC3:
duration = 0.032;
break;
case STREAM_TYPE_EAC3:
duration = 6144.0 / m_sampleRate / 4;
break;
case STREAM_TYPE_TRUEHD:
int rate;
if (m_sampleRate == 48000 ||
m_sampleRate == 96000 ||
m_sampleRate == 192000)
rate = 192000;
else
rate = 176400;
duration = 3840.0 / rate;
break;
case STREAM_TYPE_DTS_512:
case STREAM_TYPE_DTSHD_CORE:
case STREAM_TYPE_DTSHD:
case STREAM_TYPE_DTSHD_MA:
duration = 512.0 / m_sampleRate;
break;
case STREAM_TYPE_DTS_1024:
duration = 1024.0 / m_sampleRate;
break;
case STREAM_TYPE_DTS_2048:
duration = 2048.0 / m_sampleRate;
break;
default:
CLog::Log(LOGERROR, "CAEStreamInfo::GetDuration - invalid stream type");
break;
}
return duration * 1000;
}
bool CAEStreamInfo::operator==(const CAEStreamInfo& info) const
{
if (m_type != info.m_type)
return false;
if (m_dataIsLE != info.m_dataIsLE)
return false;
if (m_repeat != info.m_repeat)
return false;
return true;
}
CAEStreamParser::~CAEStreamParser() = default;
void CAEStreamParser::Reset()
{
m_skipBytes = 0;
m_bufferSize = 0;
m_needBytes = 0;
m_hasSync = false;
}
int CAEStreamParser::AddData(uint8_t *data, unsigned int size, uint8_t **buffer/* = NULL */, unsigned int *bufferSize/* = 0 */)
{
if (size == 0)
{
if (bufferSize)
*bufferSize = 0;
return 0;
}
if (m_skipBytes)
{
unsigned int canSkip = std::min(size, m_skipBytes);
unsigned int room = sizeof(m_buffer) - m_bufferSize;
unsigned int copy = std::min(room, canSkip);
memcpy(m_buffer + m_bufferSize, data, copy);
m_bufferSize += copy;
m_skipBytes -= copy;
if (m_skipBytes)
{
if (bufferSize)
*bufferSize = 0;
return copy;
}
GetPacket(buffer, bufferSize);
return copy;
}
else
{
unsigned int consumed = 0;
unsigned int offset = 0;
unsigned int room = sizeof(m_buffer) - m_bufferSize;
while(1)
{
if (!size)
{
if (bufferSize)
*bufferSize = 0;
return consumed;
}
unsigned int copy = std::min(room, size);
memcpy(m_buffer + m_bufferSize, data, copy);
m_bufferSize += copy;
consumed += copy;
data += copy;
size -= copy;
room -= copy;
if (m_needBytes > m_bufferSize)
continue;
m_needBytes = 0;
offset = (this->*m_syncFunc)(m_buffer, m_bufferSize);
if (m_hasSync || m_needBytes)
break;
else
{
/* lost sync */
m_syncFunc = &CAEStreamParser::DetectType;
m_info.m_type = CAEStreamInfo::STREAM_TYPE_NULL;
m_info.m_repeat = 1;
/* if the buffer is full, or the offset < the buffer size */
if (m_bufferSize == sizeof(m_buffer) || offset < m_bufferSize)
{
m_bufferSize -= offset;
room += offset;
memmove(m_buffer, m_buffer + offset, m_bufferSize);
}
}
}
/* if we got here, we acquired sync on the buffer */
/* align the buffer */
if (offset)
{
m_bufferSize -= offset;
memmove(m_buffer, m_buffer + offset, m_bufferSize);
}
/* bytes to skip until the next packet */
m_skipBytes = std::max(0, (int)m_fsize - (int)m_bufferSize);
if (m_skipBytes)
{
if (bufferSize)
*bufferSize = 0;
return consumed;
}
if (!m_needBytes)
GetPacket(buffer, bufferSize);
else if (bufferSize)
*bufferSize = 0;
return consumed;
}
}
void CAEStreamParser::GetPacket(uint8_t **buffer, unsigned int *bufferSize)
{
/* if the caller wants the packet */
if (buffer)
{
/* if it is dtsHD and we only want the core, just fetch that */
unsigned int size = m_fsize;
if (m_info.m_type == CAEStreamInfo::STREAM_TYPE_DTSHD_CORE)
size = m_coreSize;
/* make sure the buffer is allocated and big enough */
if (!*buffer || !bufferSize || *bufferSize < size)
{
delete[] *buffer;
*buffer = new uint8_t[size];
}
/* copy the data into the buffer and update the size */
memcpy(*buffer, m_buffer, size);
if (bufferSize)
*bufferSize = size;
}
/* remove the parsed data from the buffer */
m_bufferSize -= m_fsize;
memmove(m_buffer, m_buffer + m_fsize, m_bufferSize);
m_fsize = 0;
m_coreSize = 0;
}
/* SYNC FUNCTIONS */
/*
This function looks for sync words across the types in parallel, and only does an exhaustive
test if it finds a syncword. Once sync has been established, the relevent sync function sets
m_syncFunc to itself. This function will only be called again if total sync is lost, which
allows is to switch stream types on the fly much like a real receiver does.
*/
unsigned int CAEStreamParser::DetectType(uint8_t *data, unsigned int size)
{
unsigned int skipped = 0;
unsigned int possible = 0;
while (size > 8)
{
/* if it could be DTS */
unsigned int header = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
if (header == DTS_PREAMBLE_14LE ||
header == DTS_PREAMBLE_14BE ||
header == DTS_PREAMBLE_16LE ||
header == DTS_PREAMBLE_16BE)
{
unsigned int skip = SyncDTS(data, size);
if (m_hasSync || m_needBytes)
return skipped + skip;
else
possible = skipped;
}
/* if it could be AC3 */
if (data[0] == 0x0b && data[1] == 0x77)
{
unsigned int skip = SyncAC3(data, size);
if (m_hasSync || m_needBytes)
return skipped + skip;
else
possible = skipped;
}
/* if it could be TrueHD */
if (data[4] == 0xf8 && data[5] == 0x72 && data[6] == 0x6f && data[7] == 0xba)
{
unsigned int skip = SyncTrueHD(data, size);
if (m_hasSync)
return skipped + skip;
else
possible = skipped;
}
/* move along one byte */
--size;
++skipped;
++data;
}
return possible ? possible : skipped;
}
bool CAEStreamParser::TrySyncAC3(uint8_t *data, unsigned int size, bool resyncing, bool wantEAC3dependent)
{
if (size < 8)
return false;
/* look for an ac3 sync word */
if (data[0] != 0x0b || data[1] != 0x77)
return false;
uint8_t bsid = data[5] >> 3;
uint8_t acmod = data[6] >> 5;
uint8_t lfeon;
int8_t pos = 4;
if ((acmod & 0x1) && (acmod != 0x1))
pos -= 2;
if (acmod & 0x4 )
pos -= 2;
if (acmod == 0x2)
pos -= 2;
if (pos < 0)
lfeon = (data[7] & 0x64) ? 1 : 0;
else
lfeon = ((data[6] >> pos) & 0x1) ? 1 : 0;
if (bsid > 0x11 || acmod > 7)
return false;
if (bsid <= 10)
{
/* Normal AC-3 */
if (wantEAC3dependent)
return false;
uint8_t fscod = data[4] >> 6;
uint8_t frmsizecod = data[4] & 0x3F;
if (fscod == 3 || frmsizecod > 37)
return false;
/* get the details we need to check crc1 and framesize */
unsigned int bitRate = AC3Bitrates[frmsizecod >> 1];
unsigned int framesize = 0;
switch (fscod)
{
case 0: framesize = bitRate * 2; break;
case 1: framesize = (320 * bitRate / 147 + (frmsizecod & 1 ? 1 : 0)); break;
case 2: framesize = bitRate * 4; break;
}
m_fsize = framesize << 1;
m_info.m_sampleRate = AC3FSCod[fscod];
/* dont do extensive testing if we have not lost sync */
if (m_info.m_type == CAEStreamInfo::STREAM_TYPE_AC3 && !resyncing)
return true;
/* this may be the main stream of EAC3 */
unsigned int fsizeMain = m_fsize;
unsigned int reqBytes = fsizeMain + 8;
if (size < reqBytes) {
/* not enough data to check for E-AC3 dependent frame, request more */
m_needBytes = reqBytes;
m_fsize = 0;
/* no need to resync => return true */
return true;
}
if (TrySyncAC3(data + fsizeMain, size - fsizeMain, resyncing, /*wantEAC3dependent*/ true)) {
/* concatenate the main and dependent frames */
m_fsize += fsizeMain;
return true;
}
unsigned int crc_size;
/* if we have enough data, validate the entire packet, else try to validate crc2 (5/8 of the packet) */
if (framesize <= size)
crc_size = framesize - 1;
else
crc_size = (framesize >> 1) + (framesize >> 3) - 1;
if (crc_size <= size)
if (av_crc(av_crc_get_table(AV_CRC_16_ANSI), 0, &data[2], crc_size * 2))
return false;
/* if we get here, we can sync */
m_hasSync = true;
m_info.m_channels = AC3Channels[acmod] + lfeon;
m_syncFunc = &CAEStreamParser::SyncAC3;
m_info.m_type = CAEStreamInfo::STREAM_TYPE_AC3;
m_info.m_ac3FrameSize = m_fsize;
m_info.m_repeat = 1;
CLog::Log(LOGINFO, "CAEStreamParser::TrySyncAC3 - AC3 stream detected (%d channels, %dHz)", m_info.m_channels, m_info.m_sampleRate);
return true;
}
else
{
// Enhanced AC-3
uint8_t strmtyp = data[2] >> 6;
if (strmtyp == 3)
return false;
if (strmtyp != 1 && wantEAC3dependent)
{
CLog::Log(LOGDEBUG, "CAEStreamParser::TrySyncAC3 - Unexpected stream type: %d (wantEAC3dependent: %d)",
strmtyp, wantEAC3dependent);
return false;
}
unsigned int framesize = (((data[2] & 0x7) << 8) | data[3]) + 1;
uint8_t fscod = (data[4] >> 6) & 0x3;
uint8_t cod = (data[4] >> 4) & 0x3;
uint8_t acmod = (data[4] >> 1) & 0x7;
uint8_t lfeon = data[4] & 0x1;
uint8_t blocks;
if (fscod == 0x3)
{
if (cod == 0x3)
return false;
blocks = 6;
m_info.m_sampleRate = AC3FSCod[cod] >> 1;
}
else
{
blocks = AC3BlkCod[cod];
m_info.m_sampleRate = AC3FSCod[fscod];
}
m_fsize = framesize << 1;
m_info.m_repeat = MAX_EAC3_BLOCKS / blocks;
if (m_info.m_type == CAEStreamInfo::STREAM_TYPE_EAC3 && m_hasSync && !resyncing)
return true;
// if we get here, we can sync
m_hasSync = true;
m_info.m_channels = AC3Channels[acmod] + lfeon;
m_syncFunc = &CAEStreamParser::SyncAC3;
m_info.m_type = CAEStreamInfo::STREAM_TYPE_EAC3;
m_info.m_ac3FrameSize = m_fsize;
CLog::Log(LOGINFO, "CAEStreamParser::TrySyncAC3 - E-AC3 stream detected (%d channels, %dHz)", m_info.m_channels, m_info.m_sampleRate);
return true;
}
}
unsigned int CAEStreamParser::SyncAC3(uint8_t *data, unsigned int size)
{
unsigned int skip = 0;
for (; size - skip > 7; ++skip, ++data)
{
bool resyncing = (skip != 0);
if (TrySyncAC3(data, size - skip, resyncing, /*wantEAC3dependent*/ false))
return skip;
}
// if we get here, the entire packet is invalid and we have lost sync
CLog::Log(LOGINFO, "CAEStreamParser::SyncAC3 - AC3 sync lost");
m_hasSync = false;
return skip;
}
unsigned int CAEStreamParser::SyncDTS(uint8_t *data, unsigned int size)
{
if (size < 13)
{
if (m_needBytes < 13)
m_needBytes = 14;
return 0;
}
unsigned int skip = 0;
for (; size - skip > 13; ++skip, ++data)
{
unsigned int header = data[0] << 24 | data[1] << 16 | data[2] << 8 | data[3];
unsigned int hd_sync = 0;
unsigned int dtsBlocks;
unsigned int amode;
unsigned int sfreq;
unsigned int target_rate;
unsigned int extension = 0;
unsigned int ext_type = UNKNOWN_DTS_EXTENSION;
unsigned int lfe;
int bits;
switch (header)
{
/* 14bit BE */
case DTS_PREAMBLE_14BE:
if (data[4] != 0x07 || (data[5] & 0xf0) != 0xf0)
continue;
dtsBlocks = (((data[5] & 0x7) << 4) | ((data[6] & 0x3C) >> 2)) + 1;
m_fsize = (((((data[6] & 0x3) << 8) | data[7]) << 4) | ((data[8] & 0x3C) >> 2)) + 1;
amode = ((data[8] & 0x3) << 4) | ((data[9] & 0xF0) >> 4);
target_rate = ((data[10] & 0x3e) >> 1);
extension = ((data[11] & 0x1));
ext_type = ((data[11] & 0xe) >> 1);
sfreq = data[9] & 0xF;
lfe = (data[12] & 0x18) >> 3;
m_info.m_dataIsLE = false;
bits = 14;
break;
/* 14bit LE */
case DTS_PREAMBLE_14LE:
if (data[5] != 0x07 || (data[4] & 0xf0) != 0xf0)
continue;
dtsBlocks = (((data[4] & 0x7) << 4) | ((data[7] & 0x3C) >> 2)) + 1;
m_fsize = (((((data[7] & 0x3) << 8) | data[6]) << 4) | ((data[9] & 0x3C) >> 2)) + 1;
amode = ((data[9] & 0x3) << 4) | ((data[8] & 0xF0) >> 4);
target_rate = ((data[11] & 0x3e) >> 1);
extension = ((data[10] & 0x1));
ext_type = ((data[10] & 0xe) >> 1);
sfreq = data[8] & 0xF;
lfe = (data[13] & 0x18) >> 3;
m_info.m_dataIsLE = true;
bits = 14;
break;
/* 16bit BE */
case DTS_PREAMBLE_16BE:
dtsBlocks = (((data[4] & 0x1) << 7) | ((data[5] & 0xFC) >> 2)) + 1;
m_fsize = (((((data[5] & 0x3) << 8) | data[6]) << 4) | ((data[7] & 0xF0) >> 4)) + 1;
amode = ((data[7] & 0x0F) << 2) | ((data[8] & 0xC0) >> 6);
sfreq = (data[8] & 0x3C) >> 2;
target_rate = ((data[8] & 0x03) << 3) | ((data[9] & 0xe0) >> 5);
extension = (data[10] & 0x10) >> 4;
ext_type = (data[10] & 0xe0) >> 5;
lfe = (data[10] >> 1) & 0x3;
m_info.m_dataIsLE = false;
bits = 16;
break;
/* 16bit LE */
case DTS_PREAMBLE_16LE:
dtsBlocks = (((data[5] & 0x1) << 7) | ((data[4] & 0xFC) >> 2)) + 1;
m_fsize = (((((data[4] & 0x3) << 8) | data[7]) << 4) | ((data[6] & 0xF0) >> 4)) + 1;
amode = ((data[6] & 0x0F) << 2) | ((data[9] & 0xC0) >> 6);
sfreq = (data[9] & 0x3C) >> 2;
target_rate = ((data[9] & 0x03) << 3) | ((data[8] & 0xe0) >> 5);
extension = (data[11] & 0x10) >> 4;
ext_type = (data[11] & 0xe0) >> 5;
lfe = (data[11] >> 1) & 0x3;
m_info.m_dataIsLE = true;
bits = 16;
break;
default:
continue;
}
if (sfreq == 0 || sfreq >= DTS_SFREQ_COUNT)
continue;
/* make sure the framesize is sane */
if (m_fsize < 96 || m_fsize > 16384)
continue;
bool invalid = false;
CAEStreamInfo::DataType dataType;
switch (dtsBlocks << 5)
{
case 512 : dataType = CAEStreamInfo::STREAM_TYPE_DTS_512 ; break;
case 1024: dataType = CAEStreamInfo::STREAM_TYPE_DTS_1024; break;
case 2048: dataType = CAEStreamInfo::STREAM_TYPE_DTS_2048; break;
default:
invalid = true;
break;
}
if (invalid)
continue;
/* adjust the fsize for 14 bit streams */
if (bits == 14)
m_fsize = m_fsize / 14 * 16;
/* we need enough data to check for DTS-HD */
if (size - skip < m_fsize + 10)
{
/* we can assume DTS sync at this point */
m_syncFunc = &CAEStreamParser::SyncDTS;
m_needBytes = m_fsize + 10;
m_fsize = 0;
return skip;
}
/* look for DTS-HD */
hd_sync = (data[m_fsize] << 24) | (data[m_fsize + 1] << 16) | (data[m_fsize + 2] << 8) | data[m_fsize + 3];
if (hd_sync == DTS_PREAMBLE_HD)
{
int hd_size;
bool blownup = (data[m_fsize + 5] & 0x20) != 0;
if (blownup)
hd_size = (((data[m_fsize + 6] & 0x01) << 19) | (data[m_fsize + 7] << 11) | (data[m_fsize + 8] << 3) | ((data[m_fsize + 9] & 0xe0) >> 5)) + 1;
else
hd_size = (((data[m_fsize + 6] & 0x1f) << 11) | (data[m_fsize + 7] << 3) | ((data[m_fsize + 8] & 0xe0) >> 5)) + 1;
int header_size;
if (blownup)
header_size = (((data[m_fsize + 5] & 0x1f) << 7) | ((data[m_fsize + 6] & 0xfe) >> 1)) + 1;
else
header_size = (((data[m_fsize + 5] & 0x1f) << 3) | ((data[m_fsize + 6] & 0xe0) >> 5)) + 1;
hd_sync = data[m_fsize + header_size] << 24 | data[m_fsize + header_size + 1] << 16 | data[m_fsize + header_size + 2] << 8 | data[m_fsize + header_size + 3];
/* set the type according to core or not */
if (m_coreOnly)
dataType = CAEStreamInfo::STREAM_TYPE_DTSHD_CORE;
else if (hd_sync == DTS_PREAMBLE_XLL)
dataType = CAEStreamInfo::STREAM_TYPE_DTSHD_MA;
else if (hd_sync == DTS_PREAMBLE_XCH ||
hd_sync == DTS_PREAMBLE_XXCH ||
hd_sync == DTS_PREAMBLE_X96K ||
hd_sync == DTS_PREAMBLE_XBR ||
hd_sync == DTS_PREAMBLE_LBR)
dataType = CAEStreamInfo::STREAM_TYPE_DTSHD;
else
dataType = m_info.m_type;
m_coreSize = m_fsize;
m_fsize += hd_size;
}
unsigned int sampleRate = DTSSampleRates[sfreq];
if (!m_hasSync || skip || dataType != m_info.m_type || sampleRate != m_info.m_sampleRate || dtsBlocks != m_dtsBlocks)
{
m_hasSync = true;
m_info.m_type = dataType;
m_info.m_sampleRate = sampleRate;
m_dtsBlocks = dtsBlocks;
m_info.m_channels = DTSChannels[amode] + (lfe ? 1 : 0);
m_syncFunc = &CAEStreamParser::SyncDTS;
m_info.m_repeat = 1;
if (dataType == CAEStreamInfo::STREAM_TYPE_DTSHD_MA)
{
m_info.m_channels += 2; /* FIXME: this needs to be read out, not sure how to do that yet */
m_info.m_dtsPeriod = (192000 * (8 >> 1)) * (m_dtsBlocks << 5) / m_info.m_sampleRate;
}
else if (dataType == CAEStreamInfo::STREAM_TYPE_DTSHD)
{
m_info.m_dtsPeriod = (192000 * (2 >> 1)) * (m_dtsBlocks << 5) / m_info.m_sampleRate;
}
else
{
m_info.m_dtsPeriod = (m_info.m_sampleRate * (2 >> 1)) * (m_dtsBlocks << 5) / m_info.m_sampleRate;
}
std::string type;
switch (dataType)
{
case CAEStreamInfo::STREAM_TYPE_DTSHD:
type = "dtsHD";
break;
case CAEStreamInfo::STREAM_TYPE_DTSHD_MA:
type = "dtsHD MA";
break;
case CAEStreamInfo::STREAM_TYPE_DTSHD_CORE:
type = "dtsHD (core)";
break;
default:
type = "dts";
break;
}
if (extension)
{
switch (ext_type)
{
case 0:
type += " XCH";
break;
case 2:
type += " X96";
break;
case 6:
type += " XXCH";
break;
default:
type += " ext unknown";
break;
}
}
CLog::Log(LOGINFO, "CAEStreamParser::SyncDTS - %s stream detected (%d channels, %dHz, %dbit %s, period: %u, syncword: 0x%x, target rate: 0x%x, framesize %u))",
type.c_str(), m_info.m_channels, m_info.m_sampleRate,
bits, m_info.m_dataIsLE ? "LE" : "BE",
m_info.m_dtsPeriod, hd_sync, target_rate, m_fsize);
}
return skip;
}
/* lost sync */
CLog::Log(LOGINFO, "CAEStreamParser::SyncDTS - DTS sync lost");
m_hasSync = false;
return skip;
}
inline unsigned int CAEStreamParser::GetTrueHDChannels(const uint16_t chanmap)
{
int channels = 0;
for (int i = 0; i < 13; ++i)
channels += THDChanMap[i] * ((chanmap >> i) & 1);
return channels;
}
unsigned int CAEStreamParser::SyncTrueHD(uint8_t *data, unsigned int size)
{
unsigned int left = size;
unsigned int skip = 0;
/* if MLP */
for (; left; ++skip, ++data, --left)
{
/* if we dont have sync and there is less the 8 bytes, then break out */
if (!m_hasSync && left < 8)
return size;
/* if its a major audio unit */
uint16_t length = ((data[0] & 0x0F) << 8 | data[1]) << 1;
uint32_t syncword = ((((data[4] << 8 | data[5]) << 8) | data[6]) << 8) | data[7];
if (syncword == 0xf8726fba)
{
/* we need 32 bytes to sync on a master audio unit */
if (left < 32)
return skip;
/* get the rate and ensure its valid */
int rate = (data[8] & 0xf0) >> 4;
if (rate == 0xF)
continue;
unsigned int major_sync_size = 28;
if (data[29] & 1)
{
/* extension(s) present, look up count */
int extension_count = data[30] >> 4;
major_sync_size += 2 + extension_count * 2;
}
if (left < 4 + major_sync_size)
return skip;
/* verify the crc of the audio unit */
uint16_t crc = av_crc(m_crcTrueHD, 0, data + 4, major_sync_size - 4);
crc ^= (data[4 + major_sync_size - 3] << 8) | data[4 + major_sync_size - 4];
if (((data[4 + major_sync_size - 1] << 8) | data[4 + major_sync_size - 2]) != crc)
continue;
/* get the sample rate and substreams, we have a valid master audio unit */
m_info.m_sampleRate = (rate & 0x8 ? 44100 : 48000) << (rate & 0x7);
m_substreams = (data[20] & 0xF0) >> 4;
/* get the number of encoded channels */
uint16_t channel_map = ((data[10] & 0x1F) << 8) | data[11];
if (!channel_map)
channel_map = (data[9] << 1) | (data[10] >> 7);
m_info.m_channels = CAEStreamParser::GetTrueHDChannels(channel_map);
if (!m_hasSync)
CLog::Log(LOGINFO, "CAEStreamParser::SyncTrueHD - TrueHD stream detected (%d channels, %dHz)", m_info.m_channels, m_info.m_sampleRate);
m_hasSync = true;
m_fsize = length;
m_info.m_type = CAEStreamInfo::STREAM_TYPE_TRUEHD;
m_syncFunc = &CAEStreamParser::SyncTrueHD;
m_info.m_repeat = 1;
return skip;
}
else
{
/* we cant sink to a subframe until we have the information from a master audio unit */
if (!m_hasSync)
continue;
/* if there is not enough data left to verify the packet, just return the skip amount */
if (left < (unsigned int)m_substreams * 4)
return skip;
/* verify the parity */
int p = 0;
uint8_t check = 0;
for (int i = -1; i < m_substreams; ++i)
{
check ^= data[p++];
check ^= data[p++];
if (i == -1 || data[p - 2] & 0x80)
{
check ^= data[p++];
check ^= data[p++];
}
}
/* if the parity nibble does not match */
if ((((check >> 4) ^ check) & 0xF) != 0xF)
{
/* lost sync */
m_hasSync = false;
CLog::Log(LOGINFO, "CAEStreamParser::SyncTrueHD - Sync Lost");
continue;
}
else
{
m_fsize = length;
return skip;
}
}
}
/* lost sync */
m_hasSync = false;
return skip;
}
| PIPplware/xbmc | xbmc/cores/AudioEngine/Utils/AEStreamInfo.cpp | C++ | gpl-2.0 | 23,883 |
/* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file newgrf_industries.cpp Handling of NewGRF industries. */
#include "stdafx.h"
#include "debug.h"
#include "industry.h"
#include "newgrf_industries.h"
#include "newgrf_town.h"
#include "newgrf_cargo.h"
#include "window_func.h"
#include "town.h"
#include "company_base.h"
#include "error.h"
#include "strings_func.h"
#include "core/random_func.hpp"
#include "table/strings.h"
#include "safeguards.h"
/* Since the industry IDs defined by the GRF file don't necessarily correlate
* to those used by the game, the IDs used for overriding old industries must be
* translated when the idustry spec is set. */
IndustryOverrideManager _industry_mngr(NEW_INDUSTRYOFFSET, NUM_INDUSTRYTYPES, INVALID_INDUSTRYTYPE);
IndustryTileOverrideManager _industile_mngr(NEW_INDUSTRYTILEOFFSET, NUM_INDUSTRYTILES, INVALID_INDUSTRYTILE);
/**
* Map the GRF local type to an industry type.
* @param grf_type The GRF local type.
* @param grf_id The GRF of the local type.
* @return The industry type in the global scope.
*/
IndustryType MapNewGRFIndustryType(IndustryType grf_type, uint32 grf_id)
{
if (grf_type == IT_INVALID) return IT_INVALID;
if (!HasBit(grf_type, 7)) return GB(grf_type, 0, 7);
return _industry_mngr.GetID(GB(grf_type, 0, 7), grf_id);
}
/**
* Make an analysis of a tile and check for its belonging to the same
* industry, and/or the same grf file
* @param tile TileIndex of the tile to query
* @param i Industry to which to compare the tile to
* @param cur_grfid GRFID of the current callback chain
* @return value encoded as per NFO specs
*/
uint32 GetIndustryIDAtOffset(TileIndex tile, const Industry *i, uint32 cur_grfid)
{
if (!i->TileBelongsToIndustry(tile)) {
/* No industry and/or the tile does not have the same industry as the one we match it with */
return 0xFFFF;
}
IndustryGfx gfx = GetCleanIndustryGfx(tile);
const IndustryTileSpec *indtsp = GetIndustryTileSpec(gfx);
if (gfx < NEW_INDUSTRYTILEOFFSET) { // Does it belongs to an old type?
/* It is an old tile. We have to see if it's been overridden */
if (indtsp->grf_prop.override == INVALID_INDUSTRYTILE) { // has it been overridden?
return 0xFF << 8 | gfx; // no. Tag FF + the gfx id of that tile
}
/* Overridden */
const IndustryTileSpec *tile_ovr = GetIndustryTileSpec(indtsp->grf_prop.override);
if (tile_ovr->grf_prop.grffile->grfid == cur_grfid) {
return tile_ovr->grf_prop.local_id; // same grf file
} else {
return 0xFFFE; // not the same grf file
}
}
/* Not an 'old type' tile */
if (indtsp->grf_prop.spritegroup[0] != NULL) { // tile has a spritegroup ?
if (indtsp->grf_prop.grffile->grfid == cur_grfid) { // same industry, same grf ?
return indtsp->grf_prop.local_id;
} else {
return 0xFFFE; // Defined in another grf file
}
}
/* The tile has no spritegroup */
return 0xFF << 8 | indtsp->grf_prop.subst_id; // so just give him the substitute
}
static uint32 GetClosestIndustry(TileIndex tile, IndustryType type, const Industry *current)
{
uint32 best_dist = UINT32_MAX;
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
if (i->type != type || i == current) continue;
best_dist = min(best_dist, DistanceManhattan(tile, i->location.tile));
}
return best_dist;
}
/**
* Implementation of both var 67 and 68
* since the mechanism is almost the same, it is easier to regroup them on the same
* function.
* @param param_setID parameter given to the callback, which is the set id, or the local id, in our terminology
* @param layout_filter on what layout do we filter?
* @param town_filter Do we filter on the same town as the current industry?
* @param current Industry for which the inquiry is made
* @return the formatted answer to the callback : rr(reserved) cc(count) dddd(manhattan distance of closest sister)
*/
static uint32 GetCountAndDistanceOfClosestInstance(byte param_setID, byte layout_filter, bool town_filter, const Industry *current)
{
uint32 GrfID = GetRegister(0x100); ///< Get the GRFID of the definition to look for in register 100h
IndustryType ind_index;
uint32 closest_dist = UINT32_MAX;
byte count = 0;
/* Determine what will be the industry type to look for */
switch (GrfID) {
case 0: // this is a default industry type
ind_index = param_setID;
break;
case 0xFFFFFFFF: // current grf
GrfID = GetIndustrySpec(current->type)->grf_prop.grffile->grfid;
FALLTHROUGH;
default: // use the grfid specified in register 100h
SetBit(param_setID, 7); // bit 7 means it is not an old type
ind_index = MapNewGRFIndustryType(param_setID, GrfID);
break;
}
/* If the industry type is invalid, there is none and the closest is far away. */
if (ind_index >= NUM_INDUSTRYTYPES) return 0 | 0xFFFF;
if (layout_filter == 0 && !town_filter) {
/* If the filter is 0, it could be because none was specified as well as being really a 0.
* In either case, just do the regular var67 */
closest_dist = GetClosestIndustry(current->location.tile, ind_index, current);
count = min(Industry::GetIndustryTypeCount(ind_index), UINT8_MAX); // clamp to 8 bit
} else {
/* Count only those who match the same industry type and layout filter
* Unfortunately, we have to do it manually */
const Industry *i;
FOR_ALL_INDUSTRIES(i) {
if (i->type == ind_index && i != current && (i->selected_layout == layout_filter || layout_filter == 0) && (!town_filter || i->town == current->town)) {
closest_dist = min(closest_dist, DistanceManhattan(current->location.tile, i->location.tile));
count++;
}
}
}
return count << 16 | GB(closest_dist, 0, 16);
}
/* virtual */ uint32 IndustriesScopeResolver::GetVariable(byte variable, uint32 parameter, bool *available) const
{
if (this->ro.callback == CBID_INDUSTRY_LOCATION) {
/* Variables available during construction check. */
switch (variable) {
case 0x80: return this->tile;
case 0x81: return GB(this->tile, 8, 8);
/* Pointer to the town the industry is associated with */
case 0x82: return this->industry->town->index;
case 0x83:
case 0x84:
case 0x85: DEBUG(grf, 0, "NewGRFs shouldn't be doing pointer magic"); break; // not supported
/* Number of the layout */
case 0x86: return this->industry->selected_layout;
/* Ground type */
case 0x87: return GetTerrainType(this->tile);
/* Town zone */
case 0x88: return GetTownRadiusGroup(this->industry->town, this->tile);
/* Manhattan distance of the closest town */
case 0x89: return min(DistanceManhattan(this->industry->town->xy, this->tile), 255);
/* Lowest height of the tile */
case 0x8A: return Clamp(GetTileZ(this->tile) * (this->ro.grffile->grf_version >= 8 ? 1 : TILE_HEIGHT), 0, 0xFF);
/* Distance to the nearest water/land tile */
case 0x8B: return GetClosestWaterDistance(this->tile, (GetIndustrySpec(this->industry->type)->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
/* Square of Euclidian distance from town */
case 0x8D: return min(DistanceSquare(this->industry->town->xy, this->tile), 65535);
/* 32 random bits */
case 0x8F: return this->random_bits;
}
}
const IndustrySpec *indspec = GetIndustrySpec(this->type);
if (this->industry == NULL) {
DEBUG(grf, 1, "Unhandled variable 0x%X (no available industry) in callback 0x%x", variable, this->ro.callback);
*available = false;
return UINT_MAX;
}
switch (variable) {
case 0x40:
case 0x41:
case 0x42: { // waiting cargo, but only if those two callback flags are set
uint16 callback = indspec->callback_mask;
if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) {
if ((indspec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) {
if (this->industry->prod_level == 0) return 0;
return min(this->industry->incoming_cargo_waiting[variable - 0x40] / this->industry->prod_level, (uint16)0xFFFF);
} else {
return min(this->industry->incoming_cargo_waiting[variable - 0x40], (uint16)0xFFFF);
}
} else {
return 0;
}
}
/* Manhattan distance of closes dry/water tile */
case 0x43:
if (this->tile == INVALID_TILE) break;
return GetClosestWaterDistance(this->tile, (indspec->behaviour & INDUSTRYBEH_BUILT_ONWATER) == 0);
/* Layout number */
case 0x44: return this->industry->selected_layout;
/* Company info */
case 0x45: {
byte colours = 0;
bool is_ai = false;
const Company *c = Company::GetIfValid(this->industry->founder);
if (c != NULL) {
const Livery *l = &c->livery[LS_DEFAULT];
is_ai = c->is_ai;
colours = l->colour1 + l->colour2 * 16;
}
return this->industry->founder | (is_ai ? 0x10000 : 0) | (colours << 24);
}
case 0x46: return this->industry->construction_date; // Date when built - long format - (in days)
/* Get industry ID at offset param */
case 0x60: return GetIndustryIDAtOffset(GetNearbyTile(parameter, this->industry->location.tile, false), this->industry, this->ro.grffile->grfid);
/* Get random tile bits at offset param */
case 0x61: {
if (this->tile == INVALID_TILE) break;
TileIndex tile = GetNearbyTile(parameter, this->tile, false);
return this->industry->TileBelongsToIndustry(tile) ? GetIndustryRandomBits(tile) : 0;
}
/* Land info of nearby tiles */
case 0x62:
if (this->tile == INVALID_TILE) break;
return GetNearbyIndustryTileInformation(parameter, this->tile, INVALID_INDUSTRY, false, this->ro.grffile->grf_version >= 8);
/* Animation stage of nearby tiles */
case 0x63: {
if (this->tile == INVALID_TILE) break;
TileIndex tile = GetNearbyTile(parameter, this->tile, false);
if (this->industry->TileBelongsToIndustry(tile)) {
return GetAnimationFrame(tile);
}
return 0xFFFFFFFF;
}
/* Distance of nearest industry of given type */
case 0x64:
if (this->tile == INVALID_TILE) break;
return GetClosestIndustry(this->tile, MapNewGRFIndustryType(parameter, indspec->grf_prop.grffile->grfid), this->industry);
/* Get town zone and Manhattan distance of closest town */
case 0x65:
if (this->tile == INVALID_TILE) break;
return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceManhattan(this->tile, this->industry->town->xy), 0xFFFF);
/* Get square of Euclidian distance of closes town */
case 0x66:
if (this->tile == INVALID_TILE) break;
return GetTownRadiusGroup(this->industry->town, this->tile) << 16 | min(DistanceSquare(this->tile, this->industry->town->xy), 0xFFFF);
/* Count of industry, distance of closest instance
* 68 is the same as 67, but with a filtering on selected layout */
case 0x67:
case 0x68: {
byte layout_filter = 0;
bool town_filter = false;
if (variable == 0x68) {
uint32 reg = GetRegister(0x101);
layout_filter = GB(reg, 0, 8);
town_filter = HasBit(reg, 8);
}
return GetCountAndDistanceOfClosestInstance(parameter, layout_filter, town_filter, this->industry);
}
/* Get a variable from the persistent storage */
case 0x7C: return (this->industry->psa != NULL) ? this->industry->psa->GetValue(parameter) : 0;
/* Industry structure access*/
case 0x80: return this->industry->location.tile;
case 0x81: return GB(this->industry->location.tile, 8, 8);
/* Pointer to the town the industry is associated with */
case 0x82: return this->industry->town->index;
case 0x83:
case 0x84:
case 0x85: DEBUG(grf, 0, "NewGRFs shouldn't be doing pointer magic"); break; // not supported
case 0x86: return this->industry->location.w;
case 0x87: return this->industry->location.h;// xy dimensions
case 0x88:
case 0x89: return this->industry->produced_cargo[variable - 0x88];
case 0x8A: return this->industry->produced_cargo_waiting[0];
case 0x8B: return GB(this->industry->produced_cargo_waiting[0], 8, 8);
case 0x8C: return this->industry->produced_cargo_waiting[1];
case 0x8D: return GB(this->industry->produced_cargo_waiting[1], 8, 8);
case 0x8E:
case 0x8F: return this->industry->production_rate[variable - 0x8E];
case 0x90:
case 0x91:
case 0x92: return this->industry->accepts_cargo[variable - 0x90];
case 0x93: return this->industry->prod_level;
/* amount of cargo produced so far THIS month. */
case 0x94: return this->industry->this_month_production[0];
case 0x95: return GB(this->industry->this_month_production[0], 8, 8);
case 0x96: return this->industry->this_month_production[1];
case 0x97: return GB(this->industry->this_month_production[1], 8, 8);
/* amount of cargo transported so far THIS month. */
case 0x98: return this->industry->this_month_transported[0];
case 0x99: return GB(this->industry->this_month_transported[0], 8, 8);
case 0x9A: return this->industry->this_month_transported[1];
case 0x9B: return GB(this->industry->this_month_transported[1], 8, 8);
/* fraction of cargo transported LAST month. */
case 0x9C:
case 0x9D: return this->industry->last_month_pct_transported[variable - 0x9C];
/* amount of cargo produced LAST month. */
case 0x9E: return this->industry->last_month_production[0];
case 0x9F: return GB(this->industry->last_month_production[0], 8, 8);
case 0xA0: return this->industry->last_month_production[1];
case 0xA1: return GB(this->industry->last_month_production[1], 8, 8);
/* amount of cargo transported last month. */
case 0xA2: return this->industry->last_month_transported[0];
case 0xA3: return GB(this->industry->last_month_transported[0], 8, 8);
case 0xA4: return this->industry->last_month_transported[1];
case 0xA5: return GB(this->industry->last_month_transported[1], 8, 8);
case 0xA6: return indspec->grf_prop.local_id;
case 0xA7: return this->industry->founder;
case 0xA8: return this->industry->random_colour;
case 0xA9: return Clamp(this->industry->last_prod_year - ORIGINAL_BASE_YEAR, 0, 255);
case 0xAA: return this->industry->counter;
case 0xAB: return GB(this->industry->counter, 8, 8);
case 0xAC: return this->industry->was_cargo_delivered;
case 0xB0: return Clamp(this->industry->construction_date - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Date when built since 1920 (in days)
case 0xB3: return this->industry->construction_type; // Construction type
case 0xB4: return Clamp(this->industry->last_cargo_accepted_at - DAYS_TILL_ORIGINAL_BASE_YEAR, 0, 65535); // Date last cargo accepted since 1920 (in days)
}
DEBUG(grf, 1, "Unhandled industry variable 0x%X", variable);
*available = false;
return UINT_MAX;
}
/* virtual */ uint32 IndustriesScopeResolver::GetRandomBits() const
{
return this->industry != NULL ? this->industry->random : 0;
}
/* virtual */ uint32 IndustriesScopeResolver::GetTriggers() const
{
return 0;
}
/* virtual */ void IndustriesScopeResolver::StorePSA(uint pos, int32 value)
{
if (this->industry->index == INVALID_INDUSTRY) return;
if (this->industry->psa == NULL) {
/* There is no need to create a storage if the value is zero. */
if (value == 0) return;
/* Create storage on first modification. */
const IndustrySpec *indsp = GetIndustrySpec(this->industry->type);
uint32 grfid = (indsp->grf_prop.grffile != NULL) ? indsp->grf_prop.grffile->grfid : 0;
assert(PersistentStorage::CanAllocateItem());
this->industry->psa = new PersistentStorage(grfid, GSF_INDUSTRIES, this->industry->location.tile);
}
this->industry->psa->StoreValue(pos, value);
}
/**
* Get the grf file associated with the given industry type.
* @param type Industry type to query.
* @return The associated GRF file, if any.
*/
static const GRFFile *GetGrffile(IndustryType type)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
return (indspec != NULL) ? indspec->grf_prop.grffile : NULL;
}
/**
* Constructor of the industries resolver.
* @param tile %Tile owned by the industry.
* @param industry %Industry being resolved.
* @param type Type of the industry.
* @param random_bits Random bits of the new industry.
* @param callback Callback ID.
* @param callback_param1 First parameter (var 10) of the callback.
* @param callback_param2 Second parameter (var 18) of the callback.
*/
IndustriesResolverObject::IndustriesResolverObject(TileIndex tile, Industry *indus, IndustryType type, uint32 random_bits,
CallbackID callback, uint32 callback_param1, uint32 callback_param2)
: ResolverObject(GetGrffile(type), callback, callback_param1, callback_param2),
industries_scope(*this, tile, indus, type, random_bits),
town_scope(NULL)
{
this->root_spritegroup = GetIndustrySpec(type)->grf_prop.spritegroup[0];
}
IndustriesResolverObject::~IndustriesResolverObject()
{
delete this->town_scope;
}
/**
* Get or create the town scope object associated with the industry.
* @return The associated town scope, if it exists.
*/
TownScopeResolver *IndustriesResolverObject::GetTown()
{
if (this->town_scope == NULL) {
Town *t = NULL;
bool readonly = true;
if (this->industries_scope.industry != NULL) {
t = this->industries_scope.industry->town;
readonly = this->industries_scope.industry->index == INVALID_INDUSTRY;
} else if (this->industries_scope.tile != INVALID_TILE) {
t = ClosestTownFromTile(this->industries_scope.tile, UINT_MAX);
}
if (t == NULL) return NULL;
this->town_scope = new TownScopeResolver(*this, t, readonly);
}
return this->town_scope;
}
/**
* Perform an industry callback.
* @param callback The callback to perform.
* @param param1 The first parameter.
* @param param2 The second parameter.
* @param industry The industry to do the callback for.
* @param type The type of industry to do the callback for.
* @param tile The tile associated with the callback.
* @return The callback result.
*/
uint16 GetIndustryCallback(CallbackID callback, uint32 param1, uint32 param2, Industry *industry, IndustryType type, TileIndex tile)
{
IndustriesResolverObject object(tile, industry, type, 0, callback, param1, param2);
return object.ResolveCallback();
}
/**
* Check that the industry callback allows creation of the industry.
* @param tile %Tile to build the industry.
* @param type Type of industry to build.
* @param layout Layout number.
* @param seed Seed for the random generator.
* @param initial_random_bits The random bits the industry is going to have after construction.
* @param founder Industry founder
* @param creation_type The circumstances the industry is created under.
* @return Succeeded or failed command.
*/
CommandCost CheckIfCallBackAllowsCreation(TileIndex tile, IndustryType type, uint layout, uint32 seed, uint16 initial_random_bits, Owner founder, IndustryAvailabilityCallType creation_type)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
Industry ind;
ind.index = INVALID_INDUSTRY;
ind.location.tile = tile;
ind.location.w = 0; // important to mark the industry invalid
ind.type = type;
ind.selected_layout = layout;
ind.town = ClosestTownFromTile(tile, UINT_MAX);
ind.random = initial_random_bits;
ind.founder = founder;
ind.psa = NULL;
IndustriesResolverObject object(tile, &ind, type, seed, CBID_INDUSTRY_LOCATION, 0, creation_type);
uint16 result = object.ResolveCallback();
/* Unlike the "normal" cases, not having a valid result means we allow
* the building of the industry, as that's how it's done in TTDP. */
if (result == CALLBACK_FAILED) return CommandCost();
return GetErrorMessageFromLocationCallbackResult(result, indspec->grf_prop.grffile, STR_ERROR_SITE_UNSUITABLE);
}
/**
* Check with callback #CBID_INDUSTRY_PROBABILITY whether the industry can be built.
* @param type Industry type to check.
* @param creation_type Reason to construct a new industry.
* @return If the industry has no callback or allows building, \c true is returned. Otherwise, \c false is returned.
*/
uint32 GetIndustryProbabilityCallback(IndustryType type, IndustryAvailabilityCallType creation_type, uint32 default_prob)
{
const IndustrySpec *indspec = GetIndustrySpec(type);
if (HasBit(indspec->callback_mask, CBM_IND_PROBABILITY)) {
uint16 res = GetIndustryCallback(CBID_INDUSTRY_PROBABILITY, 0, creation_type, NULL, type, INVALID_TILE);
if (res != CALLBACK_FAILED) {
if (indspec->grf_prop.grffile->grf_version < 8) {
/* Disallow if result != 0 */
if (res != 0) default_prob = 0;
} else {
/* Use returned probability. 0x100 to use default */
if (res < 0x100) {
default_prob = res;
} else if (res > 0x100) {
ErrorUnknownCallbackResult(indspec->grf_prop.grffile->grfid, CBID_INDUSTRY_PROBABILITY, res);
}
}
}
}
return default_prob;
}
static int32 DerefIndProd(int field, bool use_register)
{
return use_register ? (int32)GetRegister(field) : field;
}
/**
* Get the industry production callback and apply it to the industry.
* @param ind the industry this callback has to be called for
* @param reason the reason it is called (0 = incoming cargo, 1 = periodic tick callback)
*/
void IndustryProductionCallback(Industry *ind, int reason)
{
const IndustrySpec *spec = GetIndustrySpec(ind->type);
IndustriesResolverObject object(ind->location.tile, ind, ind->type);
if ((spec->behaviour & INDUSTRYBEH_PRODCALLBACK_RANDOM) != 0) object.callback_param1 = Random();
int multiplier = 1;
if ((spec->behaviour & INDUSTRYBEH_PROD_MULTI_HNDLING) != 0) multiplier = ind->prod_level;
object.callback_param2 = reason;
for (uint loop = 0;; loop++) {
/* limit the number of calls to break infinite loops.
* 'loop' is provided as 16 bits to the newgrf, so abort when those are exceeded. */
if (loop >= 0x10000) {
/* display error message */
SetDParamStr(0, spec->grf_prop.grffile->filename);
SetDParam(1, spec->name);
ShowErrorMessage(STR_NEWGRF_BUGGY, STR_NEWGRF_BUGGY_ENDLESS_PRODUCTION_CALLBACK, WL_WARNING);
/* abort the function early, this error isn't critical and will allow the game to continue to run */
break;
}
SB(object.callback_param2, 8, 16, loop);
const SpriteGroup *tgroup = object.Resolve();
if (tgroup == NULL || tgroup->type != SGT_INDUSTRY_PRODUCTION) break;
const IndustryProductionSpriteGroup *group = (const IndustryProductionSpriteGroup *)tgroup;
bool deref = (group->version == 1);
for (uint i = 0; i < 3; i++) {
ind->incoming_cargo_waiting[i] = Clamp(ind->incoming_cargo_waiting[i] - DerefIndProd(group->subtract_input[i], deref) * multiplier, 0, 0xFFFF);
}
for (uint i = 0; i < 2; i++) {
ind->produced_cargo_waiting[i] = Clamp(ind->produced_cargo_waiting[i] + max(DerefIndProd(group->add_output[i], deref), 0) * multiplier, 0, 0xFFFF);
}
int32 again = DerefIndProd(group->again, deref);
if (again == 0) break;
SB(object.callback_param2, 24, 8, again);
}
SetWindowDirty(WC_INDUSTRY_VIEW, ind->index);
}
/**
* Check whether an industry temporarily refuses to accept a certain cargo.
* @param ind The industry to query.
* @param cargo_type The cargo to get information about.
* @pre cargo_type is in ind->accepts_cargo.
* @return Whether the given industry refuses to accept this cargo type.
*/
bool IndustryTemporarilyRefusesCargo(Industry *ind, CargoID cargo_type)
{
assert(cargo_type == ind->accepts_cargo[0] || cargo_type == ind->accepts_cargo[1] || cargo_type == ind->accepts_cargo[2]);
const IndustrySpec *indspec = GetIndustrySpec(ind->type);
if (HasBit(indspec->callback_mask, CBM_IND_REFUSE_CARGO)) {
uint16 res = GetIndustryCallback(CBID_INDUSTRY_REFUSE_CARGO,
0, indspec->grf_prop.grffile->cargo_map[cargo_type],
ind, ind->type, ind->location.tile);
if (res != CALLBACK_FAILED) return !ConvertBooleanCallback(indspec->grf_prop.grffile, CBID_INDUSTRY_REFUSE_CARGO, res);
}
return false;
}
| andythenorth/NotRoadTypes | src/newgrf_industries.cpp | C++ | gpl-2.0 | 24,123 |
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.2 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2012 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
*
* @package CRM
* @copyright CiviCRM LLC (c) 2004-2012
* $Id$
*
*/
/**
* This class is for displaying alphabetical bar
*
*/
class CRM_Utils_PagerAToZ {
/**
* returns the alphabetic array for sorting by character
*
* @param array $query The query object
* @param string $sortByCharacter The character that we are potentially sorting on
*
* @return string The html formatted string
* @access public
* @static
*/
static
function getAToZBar(&$query, $sortByCharacter, $isDAO = FALSE) {
$AToZBar = self::createLinks($query, $sortByCharacter, $isDAO);
return $AToZBar;
}
/**
* Function to return the all the static characters
*
* @return array $staticAlphabets is a array of static characters
* @access private
* @static
*/
static
function getStaticCharacters() {
$staticAlphabets = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
return $staticAlphabets;
}
/**
* Function to return the all the dynamic characters
*
* @return array $dynamicAlphabets is a array of dynamic characters
* @access private
* @static
*/
static
function getDynamicCharacters(&$query, $isDAO) {
if ($isDAO) {
$result = $query;
}
else {
$result = $query->alphabetQuery();
}
if (!$result) {
return NULL;
}
$dynamicAlphabets = array();
while ($result->fetch()) {
$dynamicAlphabets[] = $result->sort_name;
}
return $dynamicAlphabets;
}
/**
* create the links
*
* @param array $query The form values for search
* @param string $sortByCharacter The character that we are potentially sorting on
*
* @return array with links
* @access private
* @static
*/
static
function createLinks(&$query, $sortByCharacter, $isDAO) {
$AToZBar = self::getStaticCharacters();
$dynamicAlphabets = self::getDynamicCharacters($query, $isDAO);
if (!$dynamicAlphabets) {
return NULL;
}
$AToZBar = array_merge($AToZBar, $dynamicAlphabets);
sort($AToZBar, SORT_STRING);
$AToZBar = array_unique($AToZBar);
//get the current path
$path = CRM_Utils_System::currentPath();
$qfKey = null;
if (isset($query->_formValues)) {
$qfKey = CRM_Utils_Array::value('qfKey', $query->_formValues);
}
if (empty($qfKey)) {
$qfKey = CRM_Utils_Request::retrieve('qfKey', 'String', $this, FALSE, NULL, $_REQUEST);
}
$aToZBar = array();
foreach ($AToZBar as $key => $link) {
if ($link === NULL) {
continue;
}
$element = array();
if (in_array($link, $dynamicAlphabets)) {
$klass = '';
if ($link == $sortByCharacter) {
$element['class'] = "active";
$klass = 'class="active"';
}
$url = CRM_Utils_System::url($path, "force=1&qfKey=$qfKey&sortByCharacter=");
// we do it this way since we want the url to be encoded but not the link character
// since that seems to mess up drupal utf-8 encoding etc
$url .= urlencode($link);
$element['item'] = sprintf('<a href="%s" %s>%s</a>',
$url,
$klass,
$link
);
}
else {
$element['item'] = $link;
}
$aToZBar[] = $element;
}
$url = sprintf('<a href="%s">%s</a>',
CRM_Utils_System::url($path, "force=1&qfKey=$qfKey&sortByCharacter=all"),
'All'
);
$aToZBar[] = array('item' => $url);
return $aToZBar;
}
}
| cfusch/drupal-sandbox | sites/all/modules/civicrm/CRM/Utils/PagerAToZ.php | PHP | gpl-2.0 | 5,279 |
(function() {
var extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
define(function(require) {
var AnimationProperty, StampingEffectProperty;
AnimationProperty = require('../base/module');
return StampingEffectProperty = (function(superClass) {
extend(StampingEffectProperty, superClass);
function StampingEffectProperty() {
StampingEffectProperty.__super__.constructor.call(this, {
id: 'stamping',
name: 'Stamping'
});
}
return StampingEffectProperty;
})(AnimationProperty);
});
}).call(this);
//# sourceMappingURL=../../../../../maps/modules/datasketch/animation/properties/stamping/module.js.map
| CalCoRE/DataSketch | DataSketchServerUpload/DataSketchWeb/DataSketch.Web/obj/Release/Package/PackageTmp/DataSketchApp3/cslib/modules/datasketch/animation/properties/stamping/module.js | JavaScript | gpl-2.0 | 954 |
<?php
namespace Drupal\Tests\ckeditor\FunctionalJavascript;
use Drupal\Core\Entity\Entity\EntityFormDisplay;
use Drupal\editor\Entity\Editor;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\filter\Entity\FilterFormat;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
use Drupal\node\Entity\NodeType;
use Drupal\Tests\ckeditor\Traits\CKEditorTestTrait;
/**
* Tests the integration of CKEditor.
*
* @group ckeditor
*/
class CKEditorIntegrationTest extends WebDriverTestBase {
use CKEditorTestTrait;
/**
* {@inheritdoc}
*/
protected $defaultTheme = 'stark';
/**
* The account.
*
* @var \Drupal\user\UserInterface
*/
protected $account;
/**
* The FilterFormat config entity used for testing.
*
* @var \Drupal\filter\FilterFormatInterface
*/
protected $filterFormat;
/**
* {@inheritdoc}
*/
public static $modules = ['node', 'ckeditor', 'filter', 'ckeditor_test'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create a text format and associate CKEditor.
$this->filterFormat = FilterFormat::create([
'format' => 'filtered_html',
'name' => 'Filtered HTML',
'weight' => 0,
]);
$this->filterFormat->save();
Editor::create([
'format' => 'filtered_html',
'editor' => 'ckeditor',
])->save();
// Create a node type for testing.
NodeType::create(['type' => 'page', 'name' => 'page'])->save();
$field_storage = FieldStorageConfig::loadByName('node', 'body');
// Create a body field instance for the 'page' node type.
FieldConfig::create([
'field_storage' => $field_storage,
'bundle' => 'page',
'label' => 'Body',
'settings' => ['display_summary' => TRUE],
'required' => TRUE,
])->save();
// Assign widget settings for the 'default' form mode.
EntityFormDisplay::create([
'targetEntityType' => 'node',
'bundle' => 'page',
'mode' => 'default',
'status' => TRUE,
])->setComponent('body', ['type' => 'text_textarea_with_summary'])
->save();
$this->account = $this->drupalCreateUser([
'administer nodes',
'create page content',
'use text format filtered_html',
]);
$this->drupalLogin($this->account);
}
/**
* Tests if the fragment link to a textarea works with CKEditor enabled.
*/
public function testFragmentLink() {
$session = $this->getSession();
$web_assert = $this->assertSession();
$ckeditor_id = '#cke_edit-body-0-value';
$this->drupalGet('node/add/page');
$session->getPage();
// Add a bottom margin to the title field to be sure the body field is not
// visible.
$session->executeScript("document.getElementById('edit-title-0-value').style.marginBottom = window.innerHeight*2 +'px';");
$this->assertSession()->waitForElementVisible('css', $ckeditor_id);
// Check that the CKEditor-enabled body field is currently not visible in
// the viewport.
$web_assert->assertNotVisibleInViewport('css', $ckeditor_id, 'topLeft', 'CKEditor-enabled body field is visible.');
$before_url = $session->getCurrentUrl();
// Trigger a hash change with as target the hidden textarea.
$session->executeScript("location.hash = '#edit-body-0-value';");
// Check that the CKEditor-enabled body field is visible in the viewport.
$web_assert->assertVisibleInViewport('css', $ckeditor_id, 'topLeft', 'CKEditor-enabled body field is not visible.');
// Use JavaScript to go back in the history instead of
// \Behat\Mink\Session::back() because that function doesn't work after a
// hash change.
$session->executeScript("history.back();");
$after_url = $session->getCurrentUrl();
// Check that going back in the history worked.
self::assertEquals($before_url, $after_url, 'History back works.');
}
/**
* Tests if the Image button appears and works as expected.
*/
public function testDrupalImageDialog() {
$session = $this->getSession();
$web_assert = $this->assertSession();
$this->drupalGet('node/add/page');
$session->getPage();
// Asserts the Image button is present in the toolbar.
$web_assert->elementExists('css', '#cke_edit-body-0-value .cke_button__drupalimage');
// Asserts the image dialog opens when clicking the Image button.
$this->click('.cke_button__drupalimage');
$this->assertNotEmpty($web_assert->waitForElement('css', '.ui-dialog'));
$web_assert->elementContains('css', '.ui-dialog .ui-dialog-titlebar', 'Insert Image');
}
/**
* Tests if the Drupal Image Caption plugin appears and works as expected.
*/
public function testDrupalImageCaptionDialog() {
$web_assert = $this->assertSession();
// Disable the caption filter.
$this->filterFormat->setFilterConfig('filter_caption', [
'status' => FALSE,
]);
$this->filterFormat->save();
// If the caption filter is disabled, its checkbox should be absent.
$this->drupalGet('node/add/page');
$this->waitForEditor();
$this->pressEditorButton('drupalimage');
$this->assertNotEmpty($web_assert->waitForElement('css', '.ui-dialog'));
$web_assert->elementNotExists('css', '.ui-dialog input[name="attributes[hasCaption]"]');
// Enable the caption filter again.
$this->filterFormat->setFilterConfig('filter_caption', [
'status' => TRUE,
]);
$this->filterFormat->save();
// If the caption filter is enabled, its checkbox should be present.
$this->drupalGet('node/add/page');
$this->waitForEditor();
$this->pressEditorButton('drupalimage');
$this->assertNotEmpty($web_assert->waitForElement('css', '.ui-dialog'));
$web_assert->elementExists('css', '.ui-dialog input[name="attributes[hasCaption]"]');
}
/**
* Tests if CKEditor is properly styled inside an off-canvas dialog.
*/
public function testOffCanvasStyles() {
$assert_session = $this->assertSession();
$page = $this->getSession()->getPage();
$this->drupalGet('/ckeditor_test/off_canvas');
// The "Add Node" link triggers an off-canvas dialog with an add node form
// that includes CKEditor.
$page->clickLink('Add Node');
$assert_session->waitForElementVisible('css', '#drupal-off-canvas');
$assert_session->assertWaitOnAjaxRequest();
// Check the background color of two CKEditor elements to confirm they are
// not overriden by the off-canvas css reset.
$assert_session->elementExists('css', '.cke_top');
$ckeditor_top_bg_color = $this->getSession()->evaluateScript('window.getComputedStyle(document.getElementsByClassName(\'cke_top\')[0]).backgroundColor');
$this->assertEqual($ckeditor_top_bg_color, 'rgb(248, 248, 248)');
$assert_session->elementExists('css', '.cke_button__source');
$ckeditor_source_button_bg_color = $this->getSession()->evaluateScript('window.getComputedStyle(document.getElementsByClassName(\'cke_button__source\')[0]).backgroundColor');
$this->assertEqual($ckeditor_source_button_bg_color, 'rgba(0, 0, 0, 0)');
}
}
| Wylbur/gj | core/modules/ckeditor/tests/src/FunctionalJavascript/CKEditorIntegrationTest.php | PHP | gpl-2.0 | 7,130 |
<?php
/*
** Zabbix
** Copyright (C) 2000-2012 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
class CJsonImportReader extends CImportReader {
/**
* convert string with data in JSON format to php array.
*
* @param string $string
*
* @return array
*/
public function read($string) {
$json = new CJSON;
return $json->decode($string, true);
}
}
| gheja/zabbix-ext | frontends/php/include/classes/import/readers/CJsonImportReader.php | PHP | gpl-2.0 | 1,052 |
<?php
/**
* Akeeba Engine
* The modular PHP5 site backup engine
*
* @copyright Copyright (c)2009-2014 Nicholas K. Dionysopoulos
* @license GNU GPL version 3 or, at your option, any later version
* @package akeebaengine
*
*/
namespace Akeeba\Engine\Filter;
// Protection against direct access
defined('AKEEBAENGINE') or die();
use Akeeba\Engine\Factory;
use Akeeba\Engine\Platform;
/**
* Subdirectories exclusion filter. Excludes temporary, cache and backup output
* directories' contents from being backed up.
*/
class Joomlaskipdirs extends Base
{
public function __construct()
{
$this->object = 'dir';
$this->subtype = 'children';
$this->method = 'direct';
$this->filter_name = 'Joomlaskipdirs';
// We take advantage of the filter class magic to inject our custom filters
$configuration = Factory::getConfiguration();
$jreg = \JFactory::getConfig();
$tmpdir = $jreg->get('tmp_path');
$logsdir = $jreg->get('log_path');
// Get the site's root
if ($configuration->get('akeeba.platform.override_root', 0))
{
$root = $configuration->get('akeeba.platform.newroot', '[SITEROOT]');
}
else
{
$root = '[SITEROOT]';
}
$this->filter_data[$root] = array(
// Output & temp directory of the component
$this->treatDirectory($configuration->get('akeeba.basic.output_directory')),
// Joomla! temporary directory
$this->treatDirectory($tmpdir),
// Joomla! logs directory
$this->treatDirectory($logsdir),
// default temp directory
'tmp',
// Joomla! front- and back-end cache, as reported by Joomla!
$this->treatDirectory(JPATH_CACHE),
$this->treatDirectory(JPATH_ADMINISTRATOR . '/cache'),
$this->treatDirectory(JPATH_ROOT . '/cache'),
// cache directories fallback
'cache',
'administrator/cache',
// This is not needed except on sites running SVN or beta releases
$this->treatDirectory(JPATH_ROOT . '/installation'),
// ...and the fallback
'installation',
// Joomla! front- and back-end cache, as calculated by us (redundancy, for funky server setups)
$this->treatDirectory(Platform::getInstance()->get_site_root() . '/cache'),
$this->treatDirectory(Platform::getInstance()->get_site_root() . '/administrator/cache'),
// Default backup output (many people change it, forget to remove old backup archives and they end up backing up old backups)
'administrator/components/com_akeeba/backup',
// MyBlog's cache
$this->treatDirectory(Platform::getInstance()->get_site_root() . '/components/libraries/cmslib/cache'),
// ...and fallback
'components/libraries/cmslib/cache',
// The logs and log directories, hardcoded
'logs',
'log'
);
parent::__construct();
}
} | ForAEdesWeb/AEW2 | administrator/components/com_akeeba/platform/joomla25/Filter/Joomlaskipdirs.php | PHP | gpl-2.0 | 2,728 |
/****************************************************************************
* *
* Project64 - A Nintendo 64 emulator. *
* http://www.pj64-emu.com/ *
* Copyright (C) 2016 Project64. All rights reserved. *
* Copyright (C) 2012 Bobby Smiles *
* Copyright (C) 2009 Richard Goedeken *
* Copyright (C) 2002 Hacktarux *
* *
* License: *
* GNU/GPLv2 http://www.gnu.org/licenses/gpl-2.0.html *
* version 2 of the License, or (at your option) any later version. *
* *
****************************************************************************/
#include "stdafx.h"
#include <stdlib.h>
#include "arithmetics.h"
#include "mem.h"
#define SUBBLOCK_SIZE 64
typedef void(*tile_line_emitter_t)(CHle * hle, const int16_t *y, const int16_t *u, uint32_t address);
typedef void(*subblock_transform_t)(int16_t *dst, const int16_t *src);
/* standard jpeg ucode decoder */
static void jpeg_decode_std(CHle * hle,
const char *const version,
const subblock_transform_t transform_luma,
const subblock_transform_t transform_chroma,
const tile_line_emitter_t emit_line);
/* helper functions */
static uint8_t clamp_u8(int16_t x);
static int16_t clamp_s12(int16_t x);
static uint16_t clamp_RGBA_component(int16_t x);
/* pixel conversion & formatting */
static uint32_t GetUYVY(int16_t y1, int16_t y2, int16_t u, int16_t v);
static uint16_t GetRGBA(int16_t y, int16_t u, int16_t v);
/* tile line emitters */
static void EmitYUVTileLine(CHle * hle, const int16_t *y, const int16_t *u, uint32_t address);
static void EmitRGBATileLine(CHle * hle, const int16_t *y, const int16_t *u, uint32_t address);
/* macroblocks operations */
static void decode_macroblock_ob(int16_t *macroblock, int32_t *y_dc, int32_t *u_dc, int32_t *v_dc, const int16_t *qtable);
static void decode_macroblock_std(const subblock_transform_t transform_luma,
const subblock_transform_t transform_chroma,
int16_t *macroblock,
unsigned int subblock_count,
const int16_t qtables[3][SUBBLOCK_SIZE]);
static void EmitTilesMode0(CHle * hle, const tile_line_emitter_t emit_line, const int16_t *macroblock, uint32_t address);
static void EmitTilesMode2(CHle * hle, const tile_line_emitter_t emit_line, const int16_t *macroblock, uint32_t address);
/* subblocks operations */
static void TransposeSubBlock(int16_t *dst, const int16_t *src);
static void ZigZagSubBlock(int16_t *dst, const int16_t *src);
static void ReorderSubBlock(int16_t *dst, const int16_t *src, const unsigned int *table);
static void MultSubBlocks(int16_t *dst, const int16_t *src1, const int16_t *src2, unsigned int shift);
static void ScaleSubBlock(int16_t *dst, const int16_t *src, int16_t scale);
static void RShiftSubBlock(int16_t *dst, const int16_t *src, unsigned int shift);
static void InverseDCT1D(const float *const x, float *dst, unsigned int stride);
static void InverseDCTSubBlock(int16_t *dst, const int16_t *src);
static void RescaleYSubBlock(int16_t *dst, const int16_t *src);
static void RescaleUVSubBlock(int16_t *dst, const int16_t *src);
/* transposed dequantization table */
static const int16_t DEFAULT_QTABLE[SUBBLOCK_SIZE] = {
16, 12, 14, 14, 18, 24, 49, 72,
11, 12, 13, 17, 22, 35, 64, 92,
10, 14, 16, 22, 37, 55, 78, 95,
16, 19, 24, 29, 56, 64, 87, 98,
24, 26, 40, 51, 68, 81, 103, 112,
40, 58, 57, 87, 109, 104, 121, 100,
51, 60, 69, 80, 103, 113, 120, 103,
61, 55, 56, 62, 77, 92, 101, 99
};
/* zig-zag indices */
static const unsigned int ZIGZAG_TABLE[SUBBLOCK_SIZE] = {
0, 1, 5, 6, 14, 15, 27, 28,
2, 4, 7, 13, 16, 26, 29, 42,
3, 8, 12, 17, 25, 30, 41, 43,
9, 11, 18, 24, 31, 40, 44, 53,
10, 19, 23, 32, 39, 45, 52, 54,
20, 22, 33, 38, 46, 51, 55, 60,
21, 34, 37, 47, 50, 56, 59, 61,
35, 36, 48, 49, 57, 58, 62, 63
};
/* transposition indices */
static const unsigned int TRANSPOSE_TABLE[SUBBLOCK_SIZE] = {
0, 8, 16, 24, 32, 40, 48, 56,
1, 9, 17, 25, 33, 41, 49, 57,
2, 10, 18, 26, 34, 42, 50, 58,
3, 11, 19, 27, 35, 43, 51, 59,
4, 12, 20, 28, 36, 44, 52, 60,
5, 13, 21, 29, 37, 45, 53, 61,
6, 14, 22, 30, 38, 46, 54, 62,
7, 15, 23, 31, 39, 47, 55, 63
};
/* IDCT related constants
* Cn = alpha * cos(n * PI / 16) (alpha is chosen such as C4 = 1) */
static const float IDCT_C3 = 1.175875602f;
static const float IDCT_C6 = 0.541196100f;
static const float IDCT_K[10] = {
0.765366865f, /* C2-C6 */
-1.847759065f, /* -C2-C6 */
-0.390180644f, /* C5-C3 */
-1.961570561f, /* -C5-C3 */
1.501321110f, /* C1+C3-C5-C7 */
2.053119869f, /* C1+C3-C5+C7 */
3.072711027f, /* C1+C3+C5-C7 */
0.298631336f, /* -C1+C3+C5-C7 */
-0.899976223f, /* C7-C3 */
-2.562915448f /* -C1-C3 */
};
/* global functions */
/***************************************************************************
* JPEG decoding ucode found in Japanese exclusive version of Pokemon Stadium.
**************************************************************************/
void jpeg_decode_PS0(CHle * hle)
{
jpeg_decode_std(hle, "PS0", RescaleYSubBlock, RescaleUVSubBlock, EmitYUVTileLine);
}
/***************************************************************************
* JPEG decoding ucode found in Ocarina of Time, Pokemon Stadium 1 and
* Pokemon Stadium 2.
**************************************************************************/
void jpeg_decode_PS(CHle * hle)
{
jpeg_decode_std(hle, "PS", NULL, NULL, EmitRGBATileLine);
}
/***************************************************************************
* JPEG decoding ucode found in Ogre Battle and Bottom of the 9th.
**************************************************************************/
void jpeg_decode_OB(CHle * hle)
{
int16_t qtable[SUBBLOCK_SIZE];
unsigned int mb;
int32_t y_dc = 0;
int32_t u_dc = 0;
int32_t v_dc = 0;
uint32_t address = *dmem_u32(hle, TASK_DATA_PTR);
const unsigned int macroblock_count = *dmem_u32(hle, TASK_DATA_SIZE);
const int qscale = *dmem_u32(hle, TASK_YIELD_DATA_SIZE);
hle->VerboseMessage("jpeg_decode_OB: *buffer=%x, #MB=%d, qscale=%d", address, macroblock_count, qscale);
if (qscale != 0)
{
if (qscale > 0)
{
ScaleSubBlock(qtable, DEFAULT_QTABLE, qscale);
}
else
{
RShiftSubBlock(qtable, DEFAULT_QTABLE, -qscale);
}
}
for (mb = 0; mb < macroblock_count; ++mb)
{
int16_t macroblock[6 * SUBBLOCK_SIZE];
dram_load_u16(hle, (uint16_t *)macroblock, address, 6 * SUBBLOCK_SIZE);
decode_macroblock_ob(macroblock, &y_dc, &u_dc, &v_dc, (qscale != 0) ? qtable : NULL);
EmitTilesMode2(hle, EmitYUVTileLine, macroblock, address);
address += (2 * 6 * SUBBLOCK_SIZE);
}
}
/* local functions */
static void jpeg_decode_std(CHle * hle, const char *const version, const subblock_transform_t transform_luma, const subblock_transform_t transform_chroma, const tile_line_emitter_t emit_line)
{
int16_t qtables[3][SUBBLOCK_SIZE];
unsigned int mb;
uint32_t address;
uint32_t macroblock_count;
uint32_t mode;
uint32_t qtableY_ptr;
uint32_t qtableU_ptr;
uint32_t qtableV_ptr;
unsigned int subblock_count;
unsigned int macroblock_size;
/* macroblock contains at most 6 subblocks */
int16_t macroblock[6 * SUBBLOCK_SIZE];
uint32_t data_ptr;
if (*dmem_u32(hle, TASK_FLAGS) & 0x1)
{
hle->WarnMessage("jpeg_decode_%s: task yielding not implemented", version);
return;
}
data_ptr = *dmem_u32(hle, TASK_DATA_PTR);
address = *dram_u32(hle, data_ptr);
macroblock_count = *dram_u32(hle, data_ptr + 4);
mode = *dram_u32(hle, data_ptr + 8);
qtableY_ptr = *dram_u32(hle, data_ptr + 12);
qtableU_ptr = *dram_u32(hle, data_ptr + 16);
qtableV_ptr = *dram_u32(hle, data_ptr + 20);
hle->VerboseMessage("jpeg_decode_%s: *buffer=%x, #MB=%d, mode=%d, *Qy=%x, *Qu=%x, *Qv=%x", version, address, macroblock_count, mode, qtableY_ptr, qtableU_ptr, qtableV_ptr);
if (mode != 0 && mode != 2)
{
hle->WarnMessage("jpeg_decode_%s: invalid mode %d", version, mode);
return;
}
subblock_count = mode + 4;
macroblock_size = subblock_count * SUBBLOCK_SIZE;
dram_load_u16(hle, (uint16_t *)qtables[0], qtableY_ptr, SUBBLOCK_SIZE);
dram_load_u16(hle, (uint16_t *)qtables[1], qtableU_ptr, SUBBLOCK_SIZE);
dram_load_u16(hle, (uint16_t *)qtables[2], qtableV_ptr, SUBBLOCK_SIZE);
for (mb = 0; mb < macroblock_count; ++mb)
{
dram_load_u16(hle, (uint16_t *)macroblock, address, macroblock_size);
decode_macroblock_std(transform_luma, transform_chroma, macroblock, subblock_count, (const int16_t(*)[SUBBLOCK_SIZE])qtables);
if (mode == 0)
{
EmitTilesMode0(hle, emit_line, macroblock, address);
}
else
{
EmitTilesMode2(hle, emit_line, macroblock, address);
}
address += 2 * macroblock_size;
}
}
static uint8_t clamp_u8(int16_t x)
{
return (x & (0xff00)) ? ((-x) >> 15) & 0xff : x;
}
static int16_t clamp_s12(int16_t x)
{
if (x < -0x800)
{
x = -0x800;
}
else if (x > 0x7f0)
{
x = 0x7f0;
}
return x;
}
static uint16_t clamp_RGBA_component(int16_t x)
{
if (x > 0xff0)
{
x = 0xff0;
}
else if (x < 0)
{
x = 0;
}
return (x & 0xf80);
}
static uint32_t GetUYVY(int16_t y1, int16_t y2, int16_t u, int16_t v)
{
return (uint32_t)clamp_u8(u) << 24 |
(uint32_t)clamp_u8(y1) << 16 |
(uint32_t)clamp_u8(v) << 8 |
(uint32_t)clamp_u8(y2);
}
static uint16_t GetRGBA(int16_t y, int16_t u, int16_t v)
{
const float fY = (float)y + 2048.0f;
const float fU = (float)u;
const float fV = (float)v;
const uint16_t r = clamp_RGBA_component((int16_t)(fY + 1.4025 * fV));
const uint16_t g = clamp_RGBA_component((int16_t)(fY - 0.3443 * fU - 0.7144 * fV));
const uint16_t b = clamp_RGBA_component((int16_t)(fY + 1.7729 * fU));
return (r << 4) | (g >> 1) | (b >> 6) | 1;
}
static void EmitYUVTileLine(CHle * hle, const int16_t *y, const int16_t *u, uint32_t address)
{
uint32_t uyvy[8];
const int16_t *const v = u + SUBBLOCK_SIZE;
const int16_t *const y2 = y + SUBBLOCK_SIZE;
uyvy[0] = GetUYVY(y[0], y[1], u[0], v[0]);
uyvy[1] = GetUYVY(y[2], y[3], u[1], v[1]);
uyvy[2] = GetUYVY(y[4], y[5], u[2], v[2]);
uyvy[3] = GetUYVY(y[6], y[7], u[3], v[3]);
uyvy[4] = GetUYVY(y2[0], y2[1], u[4], v[4]);
uyvy[5] = GetUYVY(y2[2], y2[3], u[5], v[5]);
uyvy[6] = GetUYVY(y2[4], y2[5], u[6], v[6]);
uyvy[7] = GetUYVY(y2[6], y2[7], u[7], v[7]);
dram_store_u32(hle, uyvy, address, 8);
}
static void EmitRGBATileLine(CHle * hle, const int16_t *y, const int16_t *u, uint32_t address)
{
uint16_t rgba[16];
const int16_t *const v = u + SUBBLOCK_SIZE;
const int16_t *const y2 = y + SUBBLOCK_SIZE;
rgba[0] = GetRGBA(y[0], u[0], v[0]);
rgba[1] = GetRGBA(y[1], u[0], v[0]);
rgba[2] = GetRGBA(y[2], u[1], v[1]);
rgba[3] = GetRGBA(y[3], u[1], v[1]);
rgba[4] = GetRGBA(y[4], u[2], v[2]);
rgba[5] = GetRGBA(y[5], u[2], v[2]);
rgba[6] = GetRGBA(y[6], u[3], v[3]);
rgba[7] = GetRGBA(y[7], u[3], v[3]);
rgba[8] = GetRGBA(y2[0], u[4], v[4]);
rgba[9] = GetRGBA(y2[1], u[4], v[4]);
rgba[10] = GetRGBA(y2[2], u[5], v[5]);
rgba[11] = GetRGBA(y2[3], u[5], v[5]);
rgba[12] = GetRGBA(y2[4], u[6], v[6]);
rgba[13] = GetRGBA(y2[5], u[6], v[6]);
rgba[14] = GetRGBA(y2[6], u[7], v[7]);
rgba[15] = GetRGBA(y2[7], u[7], v[7]);
dram_store_u16(hle, rgba, address, 16);
}
static void EmitTilesMode0(CHle * hle, const tile_line_emitter_t emit_line, const int16_t *macroblock, uint32_t address)
{
unsigned int i;
unsigned int y_offset = 0;
unsigned int u_offset = 2 * SUBBLOCK_SIZE;
for (i = 0; i < 8; ++i) {
emit_line(hle, ¯oblock[y_offset], ¯oblock[u_offset], address);
y_offset += 8;
u_offset += 8;
address += 32;
}
}
static void EmitTilesMode2(CHle * hle, const tile_line_emitter_t emit_line, const int16_t *macroblock, uint32_t address)
{
unsigned int i;
unsigned int y_offset = 0;
unsigned int u_offset = 4 * SUBBLOCK_SIZE;
for (i = 0; i < 8; ++i)
{
emit_line(hle, ¯oblock[y_offset], ¯oblock[u_offset], address);
emit_line(hle, ¯oblock[y_offset + 8], ¯oblock[u_offset], address + 32);
y_offset += (i == 3) ? SUBBLOCK_SIZE + 16 : 16;
u_offset += 8;
address += 64;
}
}
static void decode_macroblock_ob(int16_t *macroblock, int32_t *y_dc, int32_t *u_dc, int32_t *v_dc, const int16_t *qtable)
{
int sb;
for (sb = 0; sb < 6; ++sb) {
int16_t tmp_sb[SUBBLOCK_SIZE];
/* update DC */
int32_t dc = (int32_t)macroblock[0];
switch (sb) {
case 0:
case 1:
case 2:
case 3:
*y_dc += dc;
macroblock[0] = *y_dc & 0xffff;
break;
case 4:
*u_dc += dc;
macroblock[0] = *u_dc & 0xffff;
break;
case 5:
*v_dc += dc;
macroblock[0] = *v_dc & 0xffff;
break;
}
ZigZagSubBlock(tmp_sb, macroblock);
if (qtable != NULL)
{
MultSubBlocks(tmp_sb, tmp_sb, qtable, 0);
}
TransposeSubBlock(macroblock, tmp_sb);
InverseDCTSubBlock(macroblock, macroblock);
macroblock += SUBBLOCK_SIZE;
}
}
static void decode_macroblock_std(const subblock_transform_t transform_luma,
const subblock_transform_t transform_chroma,
int16_t *macroblock,
unsigned int subblock_count,
const int16_t qtables[3][SUBBLOCK_SIZE])
{
unsigned int sb;
unsigned int q = 0;
for (sb = 0; sb < subblock_count; ++sb)
{
int16_t tmp_sb[SUBBLOCK_SIZE];
const int isChromaSubBlock = (subblock_count - sb <= 2);
if (isChromaSubBlock)
{
++q;
}
MultSubBlocks(macroblock, macroblock, qtables[q], 4);
ZigZagSubBlock(tmp_sb, macroblock);
InverseDCTSubBlock(macroblock, tmp_sb);
if (isChromaSubBlock)
{
if (transform_chroma != NULL)
{
transform_chroma(macroblock, macroblock);
}
}
else
{
if (transform_luma != NULL)
{
transform_luma(macroblock, macroblock);
}
}
macroblock += SUBBLOCK_SIZE;
}
}
static void TransposeSubBlock(int16_t *dst, const int16_t *src)
{
ReorderSubBlock(dst, src, TRANSPOSE_TABLE);
}
static void ZigZagSubBlock(int16_t *dst, const int16_t *src)
{
ReorderSubBlock(dst, src, ZIGZAG_TABLE);
}
static void ReorderSubBlock(int16_t *dst, const int16_t *src, const unsigned int *table)
{
unsigned int i;
/* source and destination sublocks cannot overlap */
assert(abs(dst - src) > SUBBLOCK_SIZE);
for (i = 0; i < SUBBLOCK_SIZE; ++i)
dst[i] = src[table[i]];
}
static void MultSubBlocks(int16_t *dst, const int16_t *src1, const int16_t *src2, unsigned int shift)
{
unsigned int i;
for (i = 0; i < SUBBLOCK_SIZE; ++i)
{
int32_t v = src1[i] * src2[i];
dst[i] = clamp_s16(v) << shift;
}
}
static void ScaleSubBlock(int16_t *dst, const int16_t *src, int16_t scale)
{
unsigned int i;
for (i = 0; i < SUBBLOCK_SIZE; ++i) {
int32_t v = src[i] * scale;
dst[i] = clamp_s16(v);
}
}
static void RShiftSubBlock(int16_t *dst, const int16_t *src, unsigned int shift)
{
unsigned int i;
for (i = 0; i < SUBBLOCK_SIZE; ++i)
dst[i] = src[i] >> shift;
}
/***************************************************************************
* Fast 2D IDCT using separable formulation and normalization
* Computations use single precision floats
* Implementation based on Wikipedia :
* http://fr.wikipedia.org/wiki/Transform%C3%A9e_en_cosinus_discr%C3%A8te
**************************************************************************/
static void InverseDCT1D(const float *const x, float *dst, unsigned int stride)
{
float e[4];
float f[4];
float x26, x1357, x15, x37, x17, x35;
x15 = IDCT_K[2] * (x[1] + x[5]);
x37 = IDCT_K[3] * (x[3] + x[7]);
x17 = IDCT_K[8] * (x[1] + x[7]);
x35 = IDCT_K[9] * (x[3] + x[5]);
x1357 = IDCT_C3 * (x[1] + x[3] + x[5] + x[7]);
x26 = IDCT_C6 * (x[2] + x[6]);
f[0] = x[0] + x[4];
f[1] = x[0] - x[4];
f[2] = x26 + IDCT_K[0] * x[2];
f[3] = x26 + IDCT_K[1] * x[6];
e[0] = x1357 + x15 + IDCT_K[4] * x[1] + x17;
e[1] = x1357 + x37 + IDCT_K[6] * x[3] + x35;
e[2] = x1357 + x15 + IDCT_K[5] * x[5] + x35;
e[3] = x1357 + x37 + IDCT_K[7] * x[7] + x17;
*dst = f[0] + f[2] + e[0];
dst += stride;
*dst = f[1] + f[3] + e[1];
dst += stride;
*dst = f[1] - f[3] + e[2];
dst += stride;
*dst = f[0] - f[2] + e[3];
dst += stride;
*dst = f[0] - f[2] - e[3];
dst += stride;
*dst = f[1] - f[3] - e[2];
dst += stride;
*dst = f[1] + f[3] - e[1];
dst += stride;
*dst = f[0] + f[2] - e[0];
}
static void InverseDCTSubBlock(int16_t *dst, const int16_t *src)
{
float x[8];
float block[SUBBLOCK_SIZE];
unsigned int i, j;
/* idct 1d on rows (+transposition) */
for (i = 0; i < 8; ++i)
{
for (j = 0; j < 8; ++j)
{
x[j] = (float)src[i * 8 + j];
}
InverseDCT1D(x, &block[i], 8);
}
/* idct 1d on columns (thanks to previous transposition) */
for (i = 0; i < 8; ++i)
{
InverseDCT1D(&block[i * 8], x, 1);
/* C4 = 1 normalization implies a division by 8 */
for (j = 0; j < 8; ++j)
{
dst[i + j * 8] = (int16_t)x[j] >> 3;
}
}
}
static void RescaleYSubBlock(int16_t *dst, const int16_t *src)
{
unsigned int i;
for (i = 0; i < SUBBLOCK_SIZE; ++i)
{
dst[i] = (((uint32_t)(clamp_s12(src[i]) + 0x800) * 0xdb0) >> 16) + 0x10;
}
}
static void RescaleUVSubBlock(int16_t *dst, const int16_t *src)
{
unsigned int i;
for (i = 0; i < SUBBLOCK_SIZE; ++i)
{
dst[i] = (((int)clamp_s12(src[i]) * 0xe00) >> 16) + 0x80;
}
} | Frank-74/project64 | Source/Android/PluginRSP/jpeg.cpp | C++ | gpl-2.0 | 18,978 |
<?php
namespace Drupal\Tests\views\Unit\Plugin\views\field;
use Drupal\Tests\UnitTestCase;
use Drupal\views\Plugin\views\field\EntityOperations;
use Drupal\views\ResultRow;
/**
* @coversDefaultClass \Drupal\views\Plugin\views\field\EntityOperations
* @group Views
*/
class EntityOperationsUnitTest extends UnitTestCase {
/**
* The entity manager.
*
* @var \Drupal\Core\Entity\EntityManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $entityManager;
/**
* The language manager.
*
* @var \Drupal\Core\Language\LanguageManagerInterface|\PHPUnit_Framework_MockObject_MockObject
*/
protected $languageManager;
/**
* The plugin under test.
*
* @var \Drupal\views\Plugin\views\field\EntityOperations
*/
protected $plugin;
/**
* {@inheritdoc}
*
* @covers ::__construct
*/
protected function setUp() {
$this->entityManager = $this->getMock('\Drupal\Core\Entity\EntityManagerInterface');
$this->languageManager = $this->getMock('\Drupal\Core\Language\LanguageManagerInterface');
$configuration = [];
$plugin_id = $this->randomMachineName();
$plugin_definition = [
'title' => $this->randomMachineName(),
];
$this->plugin = new EntityOperations($configuration, $plugin_id, $plugin_definition, $this->entityManager, $this->languageManager);
$redirect_service = $this->getMock('Drupal\Core\Routing\RedirectDestinationInterface');
$redirect_service->expects($this->any())
->method('getAsArray')
->willReturn(['destination' => 'foobar']);
$this->plugin->setRedirectDestination($redirect_service);
$view = $this->getMockBuilder('\Drupal\views\ViewExecutable')
->disableOriginalConstructor()
->getMock();
$display = $this->getMockBuilder('\Drupal\views\Plugin\views\display\DisplayPluginBase')
->disableOriginalConstructor()
->getMockForAbstractClass();
$view->display_handler = $display;
$this->plugin->init($view, $display);
}
/**
* @covers ::usesGroupBy
*/
public function testUsesGroupBy() {
$this->assertFalse($this->plugin->usesGroupBy());
}
/**
* @covers ::defineOptions
*/
public function testDefineOptions() {
$options = $this->plugin->defineOptions();
$this->assertInternalType('array', $options);
$this->assertArrayHasKey('destination', $options);
}
/**
* @covers ::render
*/
public function testRenderWithDestination() {
$entity_type_id = $this->randomMachineName();
$entity = $this->getMockBuilder('\Drupal\user\Entity\Role')
->disableOriginalConstructor()
->getMock();
$entity->expects($this->any())
->method('getEntityTypeId')
->will($this->returnValue($entity_type_id));
$operations = [
'foo' => [
'title' => $this->randomMachineName(),
],
];
$list_builder = $this->getMock('\Drupal\Core\Entity\EntityListBuilderInterface');
$list_builder->expects($this->once())
->method('getOperations')
->with($entity)
->will($this->returnValue($operations));
$this->entityManager->expects($this->once())
->method('getListBuilder')
->with($entity_type_id)
->will($this->returnValue($list_builder));
$this->plugin->options['destination'] = TRUE;
$result = new ResultRow();
$result->_entity = $entity;
$expected_build = [
'#type' => 'operations',
'#links' => $operations,
];
$expected_build['#links']['foo']['query'] = ['destination' => 'foobar'];
$build = $this->plugin->render($result);
$this->assertSame($expected_build, $build);
}
/**
* @covers ::render
*/
public function testRenderWithoutDestination() {
$entity_type_id = $this->randomMachineName();
$entity = $this->getMockBuilder('\Drupal\user\Entity\Role')
->disableOriginalConstructor()
->getMock();
$entity->expects($this->any())
->method('getEntityTypeId')
->will($this->returnValue($entity_type_id));
$operations = [
'foo' => [
'title' => $this->randomMachineName(),
],
];
$list_builder = $this->getMock('\Drupal\Core\Entity\EntityListBuilderInterface');
$list_builder->expects($this->once())
->method('getOperations')
->with($entity)
->will($this->returnValue($operations));
$this->entityManager->expects($this->once())
->method('getListBuilder')
->with($entity_type_id)
->will($this->returnValue($list_builder));
$this->plugin->options['destination'] = FALSE;
$result = new ResultRow();
$result->_entity = $entity;
$expected_build = [
'#type' => 'operations',
'#links' => $operations,
];
$build = $this->plugin->render($result);
$this->assertSame($expected_build, $build);
}
}
| morethanthemes/magazine-lite | site/core/modules/views/tests/src/Unit/Plugin/views/field/EntityOperationsUnitTest.php | PHP | gpl-2.0 | 4,808 |
<?php
/**
* The template for displaying all pages.
*
* This is the template that displays all pages by default.
* Please note that this is the WordPress construct of pages
* and that other 'pages' on your WordPress site will use a
* different template.
*
* @package fastr
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'page' ); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() ) :
comments_template();
endif;
?>
<?php endwhile; // end of the loop. ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| di0fref/wordpress_fahlslstad | wp-content/themes/fastr/page.php | PHP | gpl-2.0 | 848 |
/*!
* Aloha Editor
* Author & Copyright (c) 2010 Gentics Software GmbH
* aloha-sales@gentics.com
* Licensed unter the terms of http://www.aloha-editor.com/license.html
*/
/**
* @name block.editor
* @namespace Block attribute editors
*/
define(['aloha/jquery', 'aloha/observable'],
function(jQuery, Observable) {
/**
* @name block.editor.AbstractEditor
* @class An abstract editor
*/
var AbstractEditor = Class.extend(Observable,
/** @lends block.editor.AbstractEditor */
{
schema: null,
/**
* @constructor
*/
_constructor: function(schema) {
this.schema = schema;
},
/**
* Template method to render the editor elements
* @return {jQuery}
*/
render: function() {
// Implement in subclass!
},
/**
* Template method to get the editor values
*/
getValue: function() {
// Implement in subclass!
},
/**
* We do not throw any change event here, as we need to break the loop "Block" -> "Editor" -> "Block"
*
* @param {String} value
*/
setValue: function(value) {
// Implement in subclass!
},
/**
* Destroy the editor elements and unbind events
*/
destroy: function() {
// Implement in subclass!
},
/**
* On deactivating, we still need to trigger a change event if the value has been modified.
*
* @private
*/
_deactivate: function() {
this.trigger('change', this.getValue());
this.destroy();
}
});
/**
* @name block.editor.AbstractFormElementEditor
* @class An abstract form editor with label
* @extends block.editor.AbstractEditor
*/
var AbstractFormElementEditor = AbstractEditor.extend(
/** @lends block.editor.AbstractFormElementEditor */
{
/**
* Input element HTML definition
* @type String
*
* @private
*/
formInputElementDefinition: null,
/**
* @type jQuery
*/
_$formInputElement: null,
/**
* Render the label and form element
* @return {jQuery}
*/
render: function() {
var $wrapper = jQuery('<div class="aloha-block-editor" />');
var guid = GENTICS.Utils.guid();
$wrapper.append(this.renderLabel().attr('id', guid));
$wrapper.append(this.renderFormElement().attr('id', guid));
return $wrapper;
},
/**
* Render the label for the editor
* @return {jQuery}
*/
renderLabel: function() {
var element = jQuery('<label />');
element.html(this.schema.label);
return element;
},
/**
* Render the form input element
* @return {jQuery}
*/
renderFormElement: function() {
var that = this;
this._$formInputElement = jQuery(this.formInputElementDefinition);
this._$formInputElement.change(function() {
that.trigger('change', that.getValue());
});
return this._$formInputElement;
},
/**
* @return {String}
*/
getValue: function() {
return this._$formInputElement.val();
},
/**
* We do not throw any change event here, as we need to break the loop "Block" -> "Editor" -> "Block"
*/
setValue: function(value) {
this._$formInputElement.val(value);
},
/**
* Cleanup and remove the input element
*/
destroy: function() {
this._$formInputElement.remove();
}
});
/**
* @name block.editor.StringEditor
* @class An editor for string input
* @extends block.editor.AbstractFormElementEditor
*/
var StringEditor = AbstractFormElementEditor.extend(
/** @lends block.editor.StringEditor */
{
formInputElementDefinition: '<input type="text" />'
});
/**
* @name block.editor.NumberEditor
* @class An editor for numbers
* @extends block.editor.AbstractFormElementEditor
*/
var NumberEditor = AbstractFormElementEditor.extend(
/** @lends block.editor.NumberEditor */
{
// TODO Range should be an option
formInputElementDefinition: '<input type="range" />'
});
/**
* @name block.editor.UrlEditor
* @class An editor for URLs
* @extends block.editor.AbstractFormElementEditor
*/
var UrlEditor = AbstractFormElementEditor.extend(
/** @lends block.editor.UrlEditor */
{
formInputElementDefinition: '<input type="url" />'
});
/**
* @name block.editor.EmailEditor
* @class An editor for email addresses
* @extends block.editor.AbstractFormElementEditor
*/
var EmailEditor = AbstractFormElementEditor.extend(
/** @lends block.editor.EmailEditor */
{
formInputElementDefinition: '<input type="email" />'
});
return {
AbstractEditor: AbstractEditor,
AbstractFormElementEditor: AbstractFormElementEditor,
StringEditor: StringEditor,
NumberEditor: NumberEditor,
UrlEditor: UrlEditor,
EmailEditor: EmailEditor
}
}); | berkmancenter/spectacle | web/js/lib/plugins/common/block/lib/editor.js | JavaScript | gpl-2.0 | 4,571 |
#define PNG_SKIP_SETJMP_CHECK
#include <png.h>
#include <fcntl.h>
#include <lib/gdi/picload.h>
#include <lib/gdi/picexif.h>
extern "C" {
#include <jpeglib.h>
#include <gif_lib.h>
}
extern const uint32_t crc32_table[256];
DEFINE_REF(ePicLoad);
static std::string getSize(const char* file)
{
struct stat64 s;
if (stat64(file, &s) < 0)
return "";
char tmp[20];
snprintf(tmp, 20, "%ld kB", (long)s.st_size / 1024);
return tmp;
}
static unsigned char *simple_resize_24(unsigned char *orgin, int ox, int oy, int dx, int dy)
{
unsigned char *cr = new unsigned char[dx * dy * 3];
if (cr == NULL)
{
eDebug("[Picload] Error malloc");
return orgin;
}
unsigned char* k = cr;
for (int j = 0; j < dy; ++j)
{
const unsigned char* p = orgin + (j * oy / dy * ox) * 3;
for (int i = 0; i < dx; i++)
{
const unsigned char* ip = p + (i * ox / dx) * 3;
*k++ = ip[0];
*k++ = ip[1];
*k++ = ip[2];
}
}
delete [] orgin;
return cr;
}
static unsigned char *simple_resize_8(unsigned char *orgin, int ox, int oy, int dx, int dy)
{
unsigned char* cr = new unsigned char[dx * dy];
if (cr == NULL)
{
eDebug("[Picload] Error malloc");
return(orgin);
}
unsigned char* k = cr;
for (int j = 0; j < dy; ++j)
{
const unsigned char* p = orgin + (j * oy / dy * ox);
for (int i = 0; i < dx; i++)
{
*k++ = p[i * ox / dx];
}
}
delete [] orgin;
return cr;
}
static unsigned char *color_resize(unsigned char * orgin, int ox, int oy, int dx, int dy)
{
unsigned char* cr = new unsigned char[dx * dy * 3];
if (cr == NULL)
{
eDebug("[Picload] Error malloc");
return orgin;
}
unsigned char* p = cr;
for (int j = 0; j < dy; j++)
{
int ya = j * oy / dy;
int yb = (j + 1) * oy / dy;
if (yb >= oy)
yb = oy - 1;
for (int i = 0; i < dx; i++, p += 3)
{
int xa = i * ox / dx;
int xb = (i + 1) * ox / dx;
if (xb >= ox)
xb = ox - 1;
int r = 0;
int g = 0;
int b = 0;
int sq = 0;
for (int l = ya; l <= yb; l++)
{
const unsigned char* q = orgin + ((l * ox + xa) * 3);
for (int k = xa; k <= xb; k++, q += 3, sq++)
{
r += q[0];
g += q[1];
b += q[2];
}
}
p[0] = r / sq;
p[1] = g / sq;
p[2] = b / sq;
}
}
delete [] orgin;
return cr;
}
//---------------------------------------------------------------------------------------------
#define BMP_TORASTER_OFFSET 10
#define BMP_SIZE_OFFSET 18
#define BMP_BPP_OFFSET 28
#define BMP_RLE_OFFSET 30
#define BMP_COLOR_OFFSET 54
#define fill4B(a) ((4 - ((a) % 4 )) & 0x03)
struct color {
unsigned char red;
unsigned char green;
unsigned char blue;
};
static void fetch_pallete(int fd, struct color pallete[], int count)
{
unsigned char buff[4];
lseek(fd, BMP_COLOR_OFFSET, SEEK_SET);
for (int i = 0; i < count; i++)
{
read(fd, buff, 4);
pallete[i].red = buff[2];
pallete[i].green = buff[1];
pallete[i].blue = buff[0];
}
}
static unsigned char *bmp_load(const char *file, int *x, int *y)
{
unsigned char buff[4];
struct color pallete[256];
int fd = open(file, O_RDONLY);
if (fd == -1) return NULL;
if (lseek(fd, BMP_SIZE_OFFSET, SEEK_SET) == -1) return NULL;
read(fd, buff, 4);
*x = buff[0] + (buff[1] << 8) + (buff[2] << 16) + (buff[3] << 24);
read(fd, buff, 4);
*y = buff[0] + (buff[1] << 8) + (buff[2] << 16) + (buff[3] << 24);
if (lseek(fd, BMP_TORASTER_OFFSET, SEEK_SET) == -1) return NULL;
read(fd, buff, 4);
int raster = buff[0] + (buff[1] << 8) + (buff[2] << 16) + (buff[3] << 24);
if (lseek(fd, BMP_BPP_OFFSET, SEEK_SET) == -1) return NULL;
read(fd, buff, 2);
int bpp = buff[0] + (buff[1] << 8);
unsigned char *pic_buffer = new unsigned char[(*x) * (*y) * 3];
unsigned char *wr_buffer = pic_buffer + (*x) * ((*y) - 1) * 3;
switch (bpp)
{
case 4:
{
int skip = fill4B((*x) / 2 + (*x) % 2);
fetch_pallete(fd, pallete, 16);
lseek(fd, raster, SEEK_SET);
unsigned char * tbuffer = new unsigned char[*x / 2 + 1];
if (tbuffer == NULL)
return NULL;
for (int i = 0; i < *y; i++)
{
read(fd, tbuffer, (*x) / 2 + *x % 2);
int j;
for (j = 0; j < (*x) / 2; j++)
{
unsigned char c1 = tbuffer[j] >> 4;
unsigned char c2 = tbuffer[j] & 0x0f;
*wr_buffer++ = pallete[c1].red;
*wr_buffer++ = pallete[c1].green;
*wr_buffer++ = pallete[c1].blue;
*wr_buffer++ = pallete[c2].red;
*wr_buffer++ = pallete[c2].green;
*wr_buffer++ = pallete[c2].blue;
}
if ((*x) % 2)
{
unsigned char c1 = tbuffer[j] >> 4;
*wr_buffer++ = pallete[c1].red;
*wr_buffer++ = pallete[c1].green;
*wr_buffer++ = pallete[c1].blue;
}
if (skip)
read(fd, buff, skip);
wr_buffer -= (*x) * 6;
}
delete tbuffer;
break;
}
case 8:
{
int skip = fill4B(*x);
fetch_pallete(fd, pallete, 256);
lseek(fd, raster, SEEK_SET);
unsigned char * tbuffer = new unsigned char[*x];
if (tbuffer == NULL)
return NULL;
for (int i = 0; i < *y; i++)
{
read(fd, tbuffer, *x);
for (int j = 0; j < *x; j++)
{
wr_buffer[j * 3] = pallete[tbuffer[j]].red;
wr_buffer[j * 3 + 1] = pallete[tbuffer[j]].green;
wr_buffer[j * 3 + 2] = pallete[tbuffer[j]].blue;
}
if (skip)
read(fd, buff, skip);
wr_buffer -= (*x) * 3;
}
delete tbuffer;
break;
}
case 24:
{
int skip = fill4B((*x) * 3);
lseek(fd, raster, SEEK_SET);
for (int i = 0; i < (*y); i++)
{
read(fd, wr_buffer, (*x) * 3);
for (int j = 0; j < (*x) * 3 ; j = j + 3)
{
unsigned char c = wr_buffer[j];
wr_buffer[j] = wr_buffer[j + 2];
wr_buffer[j + 2] = c;
}
if (skip)
read(fd, buff, skip);
wr_buffer -= (*x) * 3;
}
break;
}
default:
close(fd);
return NULL;
}
close(fd);
return(pic_buffer);
}
//---------------------------------------------------------------------
static void png_load(Cfilepara* filepara, int background)
{
png_uint_32 width, height;
unsigned int i;
int bit_depth, color_type, interlace_type;
png_byte *fbptr;
FILE *fh = fopen(filepara->file, "rb");
if (fh == NULL)
return;
png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, NULL, NULL);
if (png_ptr == NULL)
{
fclose(fh);
return;
}
png_infop info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL)
{
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
fclose(fh);
return;
}
if (setjmp(png_jmpbuf(png_ptr)))
{
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
fclose(fh);
return;
}
png_init_io(png_ptr, fh);
png_read_info(png_ptr, info_ptr);
png_get_IHDR(png_ptr, info_ptr, &width, &height, &bit_depth, &color_type, &interlace_type, NULL, NULL);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type & PNG_COLOR_MASK_PALETTE)
{
if (bit_depth < 8)
{
png_set_packing(png_ptr);
bit_depth = 8;
}
unsigned char *pic_buffer = new unsigned char[height * width];
filepara->ox = width;
filepara->oy = height;
filepara->pic_buffer = pic_buffer;
filepara->bits = 8;
png_bytep *rowptr=new png_bytep[height];
for (unsigned int i=0; i!=height; i++)
{
rowptr[i]=(png_byte*)pic_buffer;
pic_buffer += width;
}
png_read_rows(png_ptr, rowptr, 0, height);
delete [] rowptr;
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE))
{
png_color *palette;
int num_palette;
png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
filepara->palette_size = num_palette;
if (num_palette)
filepara->palette = new gRGB[num_palette];
for (int i=0; i<num_palette; i++)
{
filepara->palette[i].a=0;
filepara->palette[i].r=palette[i].red;
filepara->palette[i].g=palette[i].green;
filepara->palette[i].b=palette[i].blue;
}
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
{
png_byte *trans;
png_get_tRNS(png_ptr, info_ptr, &trans, &num_palette, 0);
for (int i=0; i<num_palette; i++)
filepara->palette[i].a=255-trans[i];
}
}
}
else
{
if (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS))
png_set_expand(png_ptr);
if (bit_depth == 16)
png_set_strip_16(png_ptr);
if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
png_set_gray_to_rgb(png_ptr);
if ((color_type == PNG_COLOR_TYPE_RGB_ALPHA) || (color_type == PNG_COLOR_TYPE_GRAY_ALPHA))
{
png_set_strip_alpha(png_ptr);
png_color_16 bg;
bg.red = (background >> 16) & 0xFF;
bg.green = (background >> 8) & 0xFF;
bg.blue = (background) & 0xFF;
bg.gray = bg.green;
bg.index = 0;
png_set_background(png_ptr, &bg, PNG_BACKGROUND_GAMMA_SCREEN, 0, 1.0);
}
int number_passes = png_set_interlace_handling(png_ptr);
png_read_update_info(png_ptr, info_ptr);
if (width * 3 != png_get_rowbytes(png_ptr, info_ptr))
{
eDebug("[Picload] Error processing (did not get RGB data from PNG file)");
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
fclose(fh);
return;
}
unsigned char *pic_buffer = new unsigned char[height * width * 3];
filepara->ox = width;
filepara->oy = height;
filepara->pic_buffer = pic_buffer;
for(int pass = 0; pass < number_passes; pass++)
{
fbptr = (png_byte *)pic_buffer;
for (i = 0; i < height; i++, fbptr += width * 3)
png_read_row(png_ptr, fbptr, NULL);
}
png_read_end(png_ptr, info_ptr);
}
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
fclose(fh);
}
//-------------------------------------------------------------------
struct r_jpeg_error_mgr
{
struct jpeg_error_mgr pub;
jmp_buf envbuffer;
};
void jpeg_cb_error_exit(j_common_ptr cinfo)
{
struct r_jpeg_error_mgr *mptr;
mptr = (struct r_jpeg_error_mgr *) cinfo->err;
(*cinfo->err->output_message) (cinfo);
longjmp(mptr->envbuffer, 1);
}
static unsigned char *jpeg_load(const char *file, int *ox, int *oy, unsigned int max_x, unsigned int max_y)
{
struct jpeg_decompress_struct cinfo;
struct jpeg_decompress_struct *ciptr = &cinfo;
struct r_jpeg_error_mgr emgr;
FILE *fh;
unsigned char *pic_buffer=NULL;
if (!(fh = fopen(file, "rb")))
return NULL;
ciptr->err = jpeg_std_error(&emgr.pub);
emgr.pub.error_exit = jpeg_cb_error_exit;
if (setjmp(emgr.envbuffer) == 1)
{
jpeg_destroy_decompress(ciptr);
fclose(fh);
return NULL;
}
jpeg_create_decompress(ciptr);
jpeg_stdio_src(ciptr, fh);
jpeg_read_header(ciptr, TRUE);
ciptr->out_color_space = JCS_RGB;
int s = 8;
if (max_x == 0) max_x = 1280; // sensible default
if (max_y == 0) max_y = 720;
while (s != 1)
{
if ((ciptr->image_width >= (s * max_x)) ||
(ciptr->image_height >= (s * max_y)))
break;
s /= 2;
}
ciptr->scale_num = 1;
ciptr->scale_denom = s;
jpeg_start_decompress(ciptr);
*ox=ciptr->output_width;
*oy=ciptr->output_height;
// eDebug("jpeg_read ox=%d oy=%d w=%d (%d), h=%d (%d) scale=%d rec_outbuf_height=%d", ciptr->output_width, ciptr->output_height, ciptr->image_width, max_x, ciptr->image_height, max_y, ciptr->scale_denom, ciptr->rec_outbuf_height);
if(ciptr->output_components == 3)
{
unsigned int stride = ciptr->output_width * ciptr->output_components;
pic_buffer = new unsigned char[ciptr->output_height * stride];
unsigned char *bp = pic_buffer;
while (ciptr->output_scanline < ciptr->output_height)
{
JDIMENSION lines = jpeg_read_scanlines(ciptr, &bp, ciptr->rec_outbuf_height);
bp += stride * lines;
}
}
jpeg_finish_decompress(ciptr);
jpeg_destroy_decompress(ciptr);
fclose(fh);
return(pic_buffer);
}
static int jpeg_save(const char * filename, int ox, int oy, unsigned char *pic_buffer)
{
struct jpeg_compress_struct cinfo;
struct jpeg_error_mgr jerr;
FILE * outfile;
JSAMPROW row_pointer[1];
int row_stride;
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_compress(&cinfo);
if ((outfile = fopen(filename, "wb")) == NULL)
{
eDebug("[Picload] jpeg can't open %s", filename);
return 1;
}
eDebug("[Picload] save Thumbnail... %s",filename);
jpeg_stdio_dest(&cinfo, outfile);
cinfo.image_width = ox;
cinfo.image_height = oy;
cinfo.input_components = 3;
cinfo.in_color_space = JCS_RGB;
jpeg_set_defaults(&cinfo);
jpeg_set_quality(&cinfo, 70, TRUE );
jpeg_start_compress(&cinfo, TRUE);
row_stride = ox * 3;
while (cinfo.next_scanline < cinfo.image_height)
{
row_pointer[0] = & pic_buffer[cinfo.next_scanline * row_stride];
(void) jpeg_write_scanlines(&cinfo, row_pointer, 1);
}
jpeg_finish_compress(&cinfo);
fclose(outfile);
jpeg_destroy_compress(&cinfo);
return 0;
}
//-------------------------------------------------------------------
inline void m_rend_gif_decodecolormap(unsigned char *cmb, unsigned char *rgbb, ColorMapObject *cm, int s, int l)
{
GifColorType *cmentry;
int i;
for (i = 0; i < l; i++)
{
cmentry = &cm->Colors[cmb[i]];
*(rgbb++) = cmentry->Red;
*(rgbb++) = cmentry->Green;
*(rgbb++) = cmentry->Blue;
}
}
static void gif_load(Cfilepara* filepara)
{
unsigned char *pic_buffer = NULL;
int px, py, i, j;
unsigned char *fbptr;
unsigned char *slb=NULL;
GifFileType *gft;
GifRecordType rt;
GifByteType *extension;
ColorMapObject *cmap;
int cmaps;
int extcode;
gft = DGifOpenFileName(filepara->file);
if (gft == NULL)
return;
do
{
if (DGifGetRecordType(gft, &rt) == GIF_ERROR)
goto ERROR_R;
switch(rt)
{
case IMAGE_DESC_RECORD_TYPE:
if (DGifGetImageDesc(gft) == GIF_ERROR)
goto ERROR_R;
filepara->ox = px = gft->Image.Width;
filepara->oy = py = gft->Image.Height;
pic_buffer = new unsigned char[px * py];
filepara->pic_buffer = pic_buffer;
filepara->bits = 8;
slb = pic_buffer;
if (pic_buffer != NULL)
{
cmap = (gft->Image.ColorMap ? gft->Image.ColorMap : gft->SColorMap);
cmaps = cmap->ColorCount;
filepara->palette_size = cmaps;
filepara->palette = new gRGB[cmaps];
for (i = 0; i != cmaps; ++i)
{
filepara->palette[i].a = 0;
filepara->palette[i].r = cmap->Colors[i].Red;
filepara->palette[i].g = cmap->Colors[i].Green;
filepara->palette[i].b = cmap->Colors[i].Blue;
}
fbptr = pic_buffer;
if (!(gft->Image.Interlace))
{
for (i = 0; i < py; i++, fbptr += px * 3)
{
if (DGifGetLine(gft, slb, px) == GIF_ERROR)
goto ERROR_R;
slb += px;
}
}
else
{
for (j = 0; j < 4; j++)
{
slb = pic_buffer;
for (i = 0; i < py; i++)
{
if (DGifGetLine(gft, slb, px) == GIF_ERROR)
goto ERROR_R;
slb += px;
}
}
}
}
break;
case EXTENSION_RECORD_TYPE:
if (DGifGetExtension(gft, &extcode, &extension) == GIF_ERROR)
goto ERROR_R;
while (extension != NULL)
if (DGifGetExtensionNext(gft, &extension) == GIF_ERROR)
goto ERROR_R;
break;
default:
break;
}
}
while (rt != TERMINATE_RECORD_TYPE);
DGifCloseFile(gft);
return;
ERROR_R:
eDebug("[Picload] <Error gif>");
DGifCloseFile(gft);
}
//---------------------------------------------------------------------------------------------
ePicLoad::ePicLoad():
m_filepara(NULL),
threadrunning(false),
m_conf(),
msg_thread(this,1),
msg_main(eApp,1)
{
CONNECT(msg_thread.recv_msg, ePicLoad::gotMessage);
CONNECT(msg_main.recv_msg, ePicLoad::gotMessage);
}
ePicLoad::PConf::PConf():
max_x(0),
max_y(0),
aspect_ratio(1.066400), //4:3
background(0),
resizetype(1),
usecache(false),
thumbnailsize(180)
{
}
void ePicLoad::waitFinished()
{
msg_thread.send(Message(Message::quit));
kill();
}
ePicLoad::~ePicLoad()
{
if (threadrunning)
waitFinished();
if(m_filepara != NULL)
delete m_filepara;
}
void ePicLoad::thread_finished()
{
threadrunning=false;
}
void ePicLoad::thread()
{
hasStarted();
threadrunning=true;
nice(4);
runLoop();
}
void ePicLoad::decodePic()
{
eDebug("[Picload] decode picture... %s",m_filepara->file);
switch(m_filepara->id)
{
case F_PNG: png_load(m_filepara, m_conf.background); break;
case F_JPEG: m_filepara->pic_buffer = jpeg_load(m_filepara->file, &m_filepara->ox, &m_filepara->oy, m_filepara->max_x, m_filepara->max_y); break;
case F_BMP: m_filepara->pic_buffer = bmp_load(m_filepara->file, &m_filepara->ox, &m_filepara->oy); break;
case F_GIF: gif_load(m_filepara); break;
}
if(m_filepara->pic_buffer != NULL)
resizePic();
}
void ePicLoad::decodeThumb()
{
eDebug("[Picload] get Thumbnail... %s",m_filepara->file);
bool exif_thumbnail = false;
bool cachefile_found = false;
std::string cachefile = "";
std::string cachedir = "/.Thumbnails";
if(m_filepara->id == F_JPEG)
{
Cexif *exif = new Cexif;
if(exif->DecodeExif(m_filepara->file, 1))
{
if(exif->m_exifinfo->IsExif)
{
if(exif->m_exifinfo->Thumnailstate==2)
{
free(m_filepara->file);
m_filepara->file = strdup(THUMBNAILTMPFILE);
exif_thumbnail = true;
eDebug("[Picload] Exif Thumbnail found");
}
m_filepara->addExifInfo(exif->m_exifinfo->CameraMake);
m_filepara->addExifInfo(exif->m_exifinfo->CameraModel);
m_filepara->addExifInfo(exif->m_exifinfo->DateTime);
char buf[20];
snprintf(buf, 20, "%d x %d", exif->m_exifinfo->Width, exif->m_exifinfo->Height);
m_filepara->addExifInfo(buf);
}
exif->ClearExif();
}
delete exif;
}
if((! exif_thumbnail) && m_conf.usecache)
{
if(FILE *f=fopen(m_filepara->file, "rb"))
{
int c;
int count = 1024*100;
unsigned long crc32 = 0;
char crcstr[9];*crcstr=0;
while ((c=getc(f))!=EOF)
{
crc32 = crc32_table[((crc32) ^ (c)) & 0xFF] ^ ((crc32) >> 8);
if(--count < 0) break;
}
fclose(f);
crc32 = ~crc32;
sprintf(crcstr, "%08lX", crc32);
cachedir = m_filepara->file;
unsigned int pos = cachedir.find_last_of("/");
if (pos != std::string::npos)
cachedir = cachedir.substr(0, pos) + "/.Thumbnails";
cachefile = cachedir + std::string("/pc_") + crcstr;
if(!access(cachefile.c_str(), R_OK))
{
cachefile_found = true;
free(m_filepara->file);
m_filepara->file = strdup(cachefile.c_str());
m_filepara->id = F_JPEG;
eDebug("[Picload] Cache File found");
}
}
}
switch(m_filepara->id)
{
case F_PNG: png_load(m_filepara, m_conf.background); break;
case F_JPEG: m_filepara->pic_buffer = jpeg_load(m_filepara->file, &m_filepara->ox, &m_filepara->oy, m_filepara->max_x, m_filepara->max_y); break;
case F_BMP: m_filepara->pic_buffer = bmp_load(m_filepara->file, &m_filepara->ox, &m_filepara->oy); break;
case F_GIF: gif_load(m_filepara); break;
}
if(exif_thumbnail)
::unlink(THUMBNAILTMPFILE);
if(m_filepara->pic_buffer != NULL)
{
//save cachefile
if(m_conf.usecache && (! exif_thumbnail) && (! cachefile_found))
{
if(access(cachedir.c_str(), R_OK))
::mkdir(cachedir.c_str(), 0755);
//resize for Thumbnail
int imx, imy;
if (m_filepara->ox <= m_filepara->oy)
{
imy = m_conf.thumbnailsize;
imx = (int)( (m_conf.thumbnailsize * ((double)m_filepara->ox)) / ((double)m_filepara->oy) );
}
else
{
imx = m_conf.thumbnailsize;
imy = (int)( (m_conf.thumbnailsize * ((double)m_filepara->oy)) / ((double)m_filepara->ox) );
}
m_filepara->pic_buffer = color_resize(m_filepara->pic_buffer, m_filepara->ox, m_filepara->oy, imx, imy);
m_filepara->ox = imx;
m_filepara->oy = imy;
if(jpeg_save(cachefile.c_str(), m_filepara->ox, m_filepara->oy, m_filepara->pic_buffer))
eDebug("[Picload] error saving cachefile");
}
resizePic();
}
}
void ePicLoad::resizePic()
{
int imx, imy;
if (m_conf.aspect_ratio == 0) // do not keep aspect ration but just fill the destination area
{
imx = m_filepara->max_x;
imy = m_filepara->max_y;
}
else if ((m_conf.aspect_ratio * m_filepara->oy * m_filepara->max_x / m_filepara->ox) <= m_filepara->max_y)
{
imx = m_filepara->max_x;
imy = (int)(m_conf.aspect_ratio * m_filepara->oy * m_filepara->max_x / m_filepara->ox);
}
else
{
imx = (int)((1.0/m_conf.aspect_ratio) * m_filepara->ox * m_filepara->max_y / m_filepara->oy);
imy = m_filepara->max_y;
}
if (m_filepara->bits == 8)
m_filepara->pic_buffer = simple_resize_8(m_filepara->pic_buffer, m_filepara->ox, m_filepara->oy, imx, imy);
else if (m_conf.resizetype)
m_filepara->pic_buffer = color_resize(m_filepara->pic_buffer, m_filepara->ox, m_filepara->oy, imx, imy);
else
m_filepara->pic_buffer = simple_resize_24(m_filepara->pic_buffer, m_filepara->ox, m_filepara->oy, imx, imy);
m_filepara->ox = imx;
m_filepara->oy = imy;
}
void ePicLoad::gotMessage(const Message &msg)
{
switch (msg.type)
{
case Message::decode_Pic:
decodePic();
msg_main.send(Message(Message::decode_finished));
break;
case Message::decode_Thumb:
decodeThumb();
msg_main.send(Message(Message::decode_finished));
break;
case Message::quit: // called from decode thread
eDebug("[Picload] decode thread ... got quit msg");
quit(0);
break;
case Message::decode_finished: // called from main thread
//eDebug("[Picload] decode finished... %s", m_filepara->file);
if(m_filepara->callback)
PictureData(m_filepara->picinfo.c_str());
else
{
if(m_filepara != NULL)
{
delete m_filepara;
m_filepara = NULL;
}
}
break;
default:
eDebug("unhandled thread message");
}
}
int ePicLoad::startThread(int what, const char *file, int x, int y, bool async)
{
if(async && threadrunning && m_filepara != NULL)
{
eDebug("[Picload] thread running");
m_filepara->callback = false;
return 1;
}
if(m_filepara != NULL)
{
delete m_filepara;
m_filepara = NULL;
}
int file_id = -1;
unsigned char id[10];
int fd = ::open(file, O_RDONLY);
if (fd == -1) return 1;
::read(fd, id, 10);
::close(fd);
if(id[1] == 'P' && id[2] == 'N' && id[3] == 'G') file_id = F_PNG;
else if(id[6] == 'J' && id[7] == 'F' && id[8] == 'I' && id[9] == 'F') file_id = F_JPEG;
else if(id[0] == 0xff && id[1] == 0xd8 && id[2] == 0xff) file_id = F_JPEG;
else if(id[0] == 'B' && id[1] == 'M' ) file_id = F_BMP;
else if(id[0] == 'G' && id[1] == 'I' && id[2] == 'F') file_id = F_GIF;
if(file_id < 0)
{
eDebug("[Picload] <format not supported>");
return 1;
}
m_filepara = new Cfilepara(file, file_id, getSize(file));
m_filepara->max_x = x > 0 ? x : m_conf.max_x;
m_filepara->max_y = x > 0 ? y : m_conf.max_y;
if(m_filepara->max_x <= 0 || m_filepara->max_y <= 0)
{
delete m_filepara;
m_filepara = NULL;
eDebug("[Picload] <error in Para>");
return 1;
}
if (async) {
if(what==1)
msg_thread.send(Message(Message::decode_Pic));
else
msg_thread.send(Message(Message::decode_Thumb));
run();
}
else if (what == 1)
decodePic();
else
decodeThumb();
return 0;
}
RESULT ePicLoad::startDecode(const char *file, int x, int y, bool async)
{
return startThread(1, file, x, y, async);
}
RESULT ePicLoad::getThumbnail(const char *file, int x, int y, bool async)
{
return startThread(0, file, x, y, async);
}
PyObject *ePicLoad::getInfo(const char *filename)
{
ePyObject list;
Cexif *exif = new Cexif;
if(exif->DecodeExif(filename))
{
if(exif->m_exifinfo->IsExif)
{
char tmp[256];
int pos=0;
list = PyList_New(23);
PyList_SET_ITEM(list, pos++, PyString_FromString(filename));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->Version));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->CameraMake));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->CameraModel));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->DateTime));
PyList_SET_ITEM(list, pos++, PyString_FromFormat("%d x %d", exif->m_exifinfo->Width, exif->m_exifinfo->Height));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->FlashUsed));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->Orientation));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->Comments));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->MeteringMode));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->ExposureProgram));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->LightSource));
PyList_SET_ITEM(list, pos++, PyString_FromFormat("%d", exif->m_exifinfo->CompressionLevel));
PyList_SET_ITEM(list, pos++, PyString_FromFormat("%d", exif->m_exifinfo->ISOequivalent));
sprintf(tmp, "%.2f", exif->m_exifinfo->Xresolution);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
sprintf(tmp, "%.2f", exif->m_exifinfo->Yresolution);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
PyList_SET_ITEM(list, pos++, PyString_FromString(exif->m_exifinfo->ResolutionUnit));
sprintf(tmp, "%.2f", exif->m_exifinfo->Brightness);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
sprintf(tmp, "%.5f sec.", exif->m_exifinfo->ExposureTime);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
sprintf(tmp, "%.5f", exif->m_exifinfo->ExposureBias);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
sprintf(tmp, "%.5f", exif->m_exifinfo->Distance);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
sprintf(tmp, "%.5f", exif->m_exifinfo->CCDWidth);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
sprintf(tmp, "%.2f", exif->m_exifinfo->ApertureFNumber);
PyList_SET_ITEM(list, pos++, PyString_FromString(tmp));
}
else
{
list = PyList_New(2);
PyList_SET_ITEM(list, 0, PyString_FromString(filename));
PyList_SET_ITEM(list, 1, PyString_FromString(exif->m_szLastError));
}
exif->ClearExif();
}
else
{
list = PyList_New(2);
PyList_SET_ITEM(list, 0, PyString_FromString(filename));
PyList_SET_ITEM(list, 1, PyString_FromString(exif->m_szLastError));
}
delete exif;
return list ? (PyObject*)list : (PyObject*)PyList_New(0);
}
int ePicLoad::getData(ePtr<gPixmap> &result)
{
result = 0;
if (m_filepara == NULL)
{
eDebug("picload - Weird situation, I wasn't decoding anything!");
return 1;
}
if(m_filepara->pic_buffer == NULL)
{
delete m_filepara;
m_filepara = NULL;
return 0;
}
if (m_filepara->bits == 8)
{
result=new gPixmap(m_filepara->max_x, m_filepara->max_y, 8, NULL, gPixmap::accelAlways);
gUnmanagedSurface *surface = result->surface;
surface->clut.data = m_filepara->palette;
surface->clut.colors = m_filepara->palette_size;
m_filepara->palette = NULL; // transfer ownership
int o_y=0, u_y=0, v_x=0, h_x=0;
int extra_stride = surface->stride - surface->x;
unsigned char *tmp_buffer=((unsigned char *)(surface->data));
unsigned char *origin = m_filepara->pic_buffer;
if(m_filepara->oy < m_filepara->max_y)
{
o_y = (m_filepara->max_y - m_filepara->oy) / 2;
u_y = m_filepara->max_y - m_filepara->oy - o_y;
}
if(m_filepara->ox < m_filepara->max_x)
{
v_x = (m_filepara->max_x - m_filepara->ox) / 2;
h_x = m_filepara->max_x - m_filepara->ox - v_x;
}
int background;
gRGB bg(m_conf.background);
background = surface->clut.findColor(bg);
if(m_filepara->oy < m_filepara->max_y)
{
memset(tmp_buffer, background, o_y * surface->stride);
tmp_buffer += o_y * surface->stride;
}
for(int a = m_filepara->oy; a > 0; --a)
{
if(m_filepara->ox < m_filepara->max_x)
{
memset(tmp_buffer, background, v_x);
tmp_buffer += v_x;
}
memcpy(tmp_buffer, origin, m_filepara->ox);
tmp_buffer += m_filepara->ox;
origin += m_filepara->ox;
if(m_filepara->ox < m_filepara->max_x)
{
memset(tmp_buffer, background, h_x);
tmp_buffer += h_x;
}
tmp_buffer += extra_stride;
}
if(m_filepara->oy < m_filepara->max_y)
{
memset(tmp_buffer, background, u_y * surface->stride);
}
}
else
{
result=new gPixmap(m_filepara->max_x, m_filepara->max_y, 32, NULL, gPixmap::accelAuto);
gUnmanagedSurface *surface = result->surface;
int o_y=0, u_y=0, v_x=0, h_x=0;
unsigned char *tmp_buffer=((unsigned char *)(surface->data));
unsigned char *origin = m_filepara->pic_buffer;
int extra_stride = surface->stride - (surface->x * surface->bypp);
if(m_filepara->oy < m_filepara->max_y)
{
o_y = (m_filepara->max_y - m_filepara->oy) / 2;
u_y = m_filepara->max_y - m_filepara->oy - o_y;
}
if(m_filepara->ox < m_filepara->max_x)
{
v_x = (m_filepara->max_x - m_filepara->ox) / 2;
h_x = m_filepara->max_x - m_filepara->ox - v_x;
}
int background = m_conf.background;
if(m_filepara->oy < m_filepara->max_y)
{
for (int y = o_y; y != 0; --y)
{
int* row_buffer = (int*)tmp_buffer;
for (int x = m_filepara->ox; x !=0; --x)
*row_buffer++ = background;
tmp_buffer += surface->stride;
}
}
for(int a = m_filepara->oy; a > 0; --a)
{
if(m_filepara->ox < m_filepara->max_x)
{
for(int b = v_x; b != 0; --b)
{
*(int*)tmp_buffer = background;
tmp_buffer += 4;
}
}
for(int b = m_filepara->ox; b != 0; --b)
{
tmp_buffer[2] = *origin;
++origin;
tmp_buffer[1] = *origin;
++origin;
tmp_buffer[0] = *origin;
++origin;
tmp_buffer[3] = 0xFF; // alpha
tmp_buffer += 4;
}
if(m_filepara->ox < m_filepara->max_x)
{
for(int b = h_x; b != 0; --b)
{
*(int*)tmp_buffer = background;
tmp_buffer += 4;
}
}
tmp_buffer += extra_stride;
}
if(m_filepara->oy < m_filepara->max_y)
{
for (int y = u_y; y != 0; --y)
{
int* row_buffer = (int*)tmp_buffer;
for (int x = m_filepara->ox; x !=0; --x)
*row_buffer++ = background;
tmp_buffer += surface->stride;
}
}
}
delete m_filepara;
m_filepara = NULL;
return 0;
}
RESULT ePicLoad::setPara(PyObject *val)
{
if (!PySequence_Check(val))
return 0;
if (PySequence_Size(val) < 7)
return 0;
else {
ePyObject fast = PySequence_Fast(val, "");
int width = PyInt_AsLong(PySequence_Fast_GET_ITEM(fast, 0));
int height = PyInt_AsLong(PySequence_Fast_GET_ITEM(fast, 1));
double aspectRatio = PyInt_AsLong(PySequence_Fast_GET_ITEM(fast, 2));
int as = PyInt_AsLong(PySequence_Fast_GET_ITEM(fast, 3));
bool useCache = PyInt_AsLong(PySequence_Fast_GET_ITEM(fast, 4));
int resizeType = PyInt_AsLong(PySequence_Fast_GET_ITEM(fast, 5));
const char *bg_str = PyString_AsString(PySequence_Fast_GET_ITEM(fast, 6));
return setPara(width, height, aspectRatio, as, useCache, resizeType, bg_str);
}
return 1;
}
RESULT ePicLoad::setPara(int width, int height, double aspectRatio, int as, bool useCache, int resizeType, const char *bg_str)
{
m_conf.max_x = width;
m_conf.max_y = height;
m_conf.aspect_ratio = as == 0 ? 0.0 : aspectRatio / as;
m_conf.usecache = useCache;
m_conf.resizetype = resizeType;
if(bg_str[0] == '#' && strlen(bg_str)==9)
m_conf.background = strtoul(bg_str+1, NULL, 16);
eDebug("[Picload] setPara max-X=%d max-Y=%d aspect_ratio=%lf cache=%d resize=%d bg=#%08X",
m_conf.max_x, m_conf.max_y, m_conf.aspect_ratio,
(int)m_conf.usecache, (int)m_conf.resizetype, m_conf.background);
return 1;
}
//------------------------------------------------------------------------------------
//for old plugins
SWIG_VOID(int) loadPic(ePtr<gPixmap> &result, std::string filename, int x, int y, int aspect, int resize_mode, int rotate, int background, std::string cachefile)
{
long asp1, asp2;
result = 0;
eDebug("deprecated loadPic function used!!! please use the non blocking version! you can see demo code in Pictureplayer plugin... this function is removed in the near future!");
ePicLoad mPL;
switch(aspect)
{
case 1: asp1 = 16*576, asp2 = 9*720; break; //16:9
case 2: asp1 = 16*576, asp2 = 10*720; break; //16:10
case 3: asp1 = 5*576, asp2 = 4*720; break; //5:4
default: asp1 = 4*576, asp2 = 3*720; break; //4:3
}
ePyObject tuple = PyTuple_New(7);
PyTuple_SET_ITEM(tuple, 0, PyLong_FromLong(x));
PyTuple_SET_ITEM(tuple, 1, PyLong_FromLong(y));
PyTuple_SET_ITEM(tuple, 2, PyLong_FromLong(asp1));
PyTuple_SET_ITEM(tuple, 3, PyLong_FromLong(asp2));
PyTuple_SET_ITEM(tuple, 4, PyLong_FromLong(0));
PyTuple_SET_ITEM(tuple, 5, PyLong_FromLong(resize_mode));
if(background)
PyTuple_SET_ITEM(tuple, 6, PyString_FromString("#ff000000"));
else
PyTuple_SET_ITEM(tuple, 6, PyString_FromString("#00000000"));
mPL.setPara(tuple);
if(!mPL.startDecode(filename.c_str(), 0, 0, false))
mPL.getData(result);
return 0;
}
| vit2/vit-e2 | lib/gdi/picload.cpp | C++ | gpl-2.0 | 32,254 |
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Image_Graph - PEAR PHP OO Graph Rendering Utility.
*
* PHP version 5
*
* LICENSE: 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., 59 Temple Place, Suite 330, Boston, MA
* 02111-1307 USA
*
* @category Images
* @package Image_Graph
* @subpackage Text
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @author Stefan Neufeind <pear.neufeind@speedpartner.de>
* @copyright 2003-2009 The PHP Group
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version SVN: $Id: Font.php 291170 2009-11-23 03:50:22Z neufeind $
* @link http://pear.php.net/package/Image_Graph
*/
/**
* Include file Image/Graph/Common.php
*/
require_once 'Image/Graph/Common.php';
/**
* A font.
*
* @category Images
* @package Image_Graph
* @subpackage Text
* @author Jesper Veggerby <pear.nosey@veggerby.dk>
* @author Stefan Neufeind <pear.neufeind@speedpartner.de>
* @copyright 2003-2009 The PHP Group
* @license http://www.gnu.org/copyleft/lesser.html LGPL License 2.1
* @version Release: @package_version@
* @link http://pear.php.net/package/Image_Graph
* @abstract
*/
class Image_Graph_Font extends Image_Graph_Common
{
/**
* The name of the font
* @var string
* @access private
*/
var $_name = false;
/**
* The angle of the output
* @var int
* @access private
*/
var $_angle = false;
/**
* The size of the font
* @var int
* @access private
*/
var $_size = 11;
/**
* The color of the font
* @var Color
* @access private
*/
var $_color = 'black';
/**
* Image_Graph_Font [Constructor]
*
* @param string $name Font name
* @param int $size Font size
*/
function Image_Graph_Font($name = false, $size = false)
{
parent::__construct();
if ($name !== false) {
$this->_name = $name;
}
if ($size !== false) {
$this->_size = $size;
}
}
/**
* Set the color of the font
*
* @param mixed $color The color object of the Font
*
* @return void
*/
function setColor($color)
{
$this->_color = $color;
}
/**
* Set the angle slope of the output font.
*
* 0 = normal, 90 = bottom and up, 180 = upside down, 270 = top and down
*
* @param int $angle The angle in degrees to slope the text
*
* @return void
*/
function setAngle($angle)
{
$this->_angle = $angle;
}
/**
* Set the size of the font
*
* @param int $size The size in pixels of the font
*
* @return void
*/
function setSize($size)
{
$this->_size = $size;
}
/**
* Get the font 'array'
*
* @param array $options Font options (optional)
*
* @return array The font 'summary' to pass to the canvas
* @access private
*/
function _getFont($options = false)
{
if ($options === false) {
$options = array();
}
if ($this->_name !== false) {
$options['name'] = $this->_name;
}
if (!isset($options['color'])) {
$options['color'] = $this->_color;
}
if (!isset($options['size'])) {
$options['size'] = $this->_size;
}
if ((!isset($options['angle'])) && ($this->_angle !== false)) {
$options['angle'] = $this->_angle;
}
return $options;
}
}
?>
| eireford/mahara | htdocs/lib/pear/Image/Graph/Font.php | PHP | gpl-3.0 | 4,265 |
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.hardware.location;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.IFusedGeofenceHardware;
import android.location.IGpsGeofenceHardware;
import android.location.Location;
import android.os.Handler;
import android.os.IBinder;
import android.os.IInterface;
import android.os.Message;
import android.os.PowerManager;
import android.os.RemoteException;
import android.util.Log;
import android.util.SparseArray;
import java.util.ArrayList;
import java.util.Iterator;
/**
* This class manages the geofences which are handled by hardware.
*
* @hide
*/
public final class GeofenceHardwareImpl {
private static final String TAG = "GeofenceHardwareImpl";
private static final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG);
private static final int FIRST_VERSION_WITH_CAPABILITIES = 2;
private final Context mContext;
private static GeofenceHardwareImpl sInstance;
private PowerManager.WakeLock mWakeLock;
private final SparseArray<IGeofenceHardwareCallback> mGeofences =
new SparseArray<IGeofenceHardwareCallback>();
private final ArrayList<IGeofenceHardwareMonitorCallback>[] mCallbacks =
new ArrayList[GeofenceHardware.NUM_MONITORS];
private final ArrayList<Reaper> mReapers = new ArrayList<Reaper>();
private IFusedGeofenceHardware mFusedService;
private IGpsGeofenceHardware mGpsService;
private int mCapabilities;
private int mVersion = 1;
private int[] mSupportedMonitorTypes = new int[GeofenceHardware.NUM_MONITORS];
// mGeofenceHandler message types
private static final int GEOFENCE_TRANSITION_CALLBACK = 1;
private static final int ADD_GEOFENCE_CALLBACK = 2;
private static final int REMOVE_GEOFENCE_CALLBACK = 3;
private static final int PAUSE_GEOFENCE_CALLBACK = 4;
private static final int RESUME_GEOFENCE_CALLBACK = 5;
private static final int GEOFENCE_CALLBACK_BINDER_DIED = 6;
// mCallbacksHandler message types
private static final int GEOFENCE_STATUS = 1;
private static final int CALLBACK_ADD = 2;
private static final int CALLBACK_REMOVE = 3;
private static final int MONITOR_CALLBACK_BINDER_DIED = 4;
// mReaperHandler message types
private static final int REAPER_GEOFENCE_ADDED = 1;
private static final int REAPER_MONITOR_CALLBACK_ADDED = 2;
private static final int REAPER_REMOVED = 3;
// The following constants need to match GpsLocationFlags enum in gps.h
private static final int LOCATION_INVALID = 0;
private static final int LOCATION_HAS_LAT_LONG = 1;
private static final int LOCATION_HAS_ALTITUDE = 2;
private static final int LOCATION_HAS_SPEED = 4;
private static final int LOCATION_HAS_BEARING = 8;
private static final int LOCATION_HAS_ACCURACY = 16;
// Resolution level constants used for permission checks.
// These constants must be in increasing order of finer resolution.
private static final int RESOLUTION_LEVEL_NONE = 1;
private static final int RESOLUTION_LEVEL_COARSE = 2;
private static final int RESOLUTION_LEVEL_FINE = 3;
// Capability constant corresponding to fused_location.h entry when geofencing supports GNNS.
private static final int CAPABILITY_GNSS = 1;
public synchronized static GeofenceHardwareImpl getInstance(Context context) {
if (sInstance == null) {
sInstance = new GeofenceHardwareImpl(context);
}
return sInstance;
}
private GeofenceHardwareImpl(Context context) {
mContext = context;
// Init everything to unsupported.
setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
GeofenceHardware.MONITOR_UNSUPPORTED);
setMonitorAvailability(
GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE,
GeofenceHardware.MONITOR_UNSUPPORTED);
}
private void acquireWakeLock() {
if (mWakeLock == null) {
PowerManager powerManager =
(PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
}
mWakeLock.acquire();
}
private void releaseWakeLock() {
if (mWakeLock.isHeld()) mWakeLock.release();
}
private void updateGpsHardwareAvailability() {
//Check which monitors are available.
boolean gpsSupported;
try {
gpsSupported = mGpsService.isHardwareGeofenceSupported();
} catch (RemoteException e) {
Log.e(TAG, "Remote Exception calling LocationManagerService");
gpsSupported = false;
}
if (gpsSupported) {
// Its assumed currently available at startup.
// native layer will update later.
setMonitorAvailability(GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE);
}
}
private void updateFusedHardwareAvailability() {
boolean fusedSupported;
try {
final boolean hasGnnsCapabilities = (mVersion < FIRST_VERSION_WITH_CAPABILITIES)
|| (mCapabilities & CAPABILITY_GNSS) != 0;
fusedSupported = (mFusedService != null
? mFusedService.isSupported() && hasGnnsCapabilities
: false);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException calling LocationManagerService");
fusedSupported = false;
}
if(fusedSupported) {
setMonitorAvailability(
GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE,
GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE);
}
}
public void setGpsHardwareGeofence(IGpsGeofenceHardware service) {
if (mGpsService == null) {
mGpsService = service;
updateGpsHardwareAvailability();
} else if (service == null) {
mGpsService = null;
Log.w(TAG, "GPS Geofence Hardware service seems to have crashed");
} else {
Log.e(TAG, "Error: GpsService being set again.");
}
}
public void onCapabilities(int capabilities) {
mCapabilities = capabilities;
updateFusedHardwareAvailability();
}
public void setVersion(int version) {
mVersion = version;
updateFusedHardwareAvailability();
}
public void setFusedGeofenceHardware(IFusedGeofenceHardware service) {
if(mFusedService == null) {
mFusedService = service;
updateFusedHardwareAvailability();
} else if(service == null) {
mFusedService = null;
Log.w(TAG, "Fused Geofence Hardware service seems to have crashed");
} else {
Log.e(TAG, "Error: FusedService being set again");
}
}
public int[] getMonitoringTypes() {
boolean gpsSupported;
boolean fusedSupported;
synchronized (mSupportedMonitorTypes) {
gpsSupported = mSupportedMonitorTypes[GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE]
!= GeofenceHardware.MONITOR_UNSUPPORTED;
fusedSupported = mSupportedMonitorTypes[GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE]
!= GeofenceHardware.MONITOR_UNSUPPORTED;
}
if(gpsSupported) {
if(fusedSupported) {
return new int[] {
GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE,
GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE };
} else {
return new int[] { GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE };
}
} else if (fusedSupported) {
return new int[] { GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE };
} else {
return new int[0];
}
}
public int getStatusOfMonitoringType(int monitoringType) {
synchronized (mSupportedMonitorTypes) {
if (monitoringType >= mSupportedMonitorTypes.length || monitoringType < 0) {
throw new IllegalArgumentException("Unknown monitoring type");
}
return mSupportedMonitorTypes[monitoringType];
}
}
public int getCapabilitiesForMonitoringType(int monitoringType) {
switch (mSupportedMonitorTypes[monitoringType]) {
case GeofenceHardware.MONITOR_CURRENTLY_AVAILABLE:
switch (monitoringType) {
case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
return CAPABILITY_GNSS;
case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
if (mVersion >= FIRST_VERSION_WITH_CAPABILITIES) {
return mCapabilities;
}
// This was the implied capability on old FLP HAL versions that didn't
// have the capability callback.
return CAPABILITY_GNSS;
}
break;
}
return 0;
}
public boolean addCircularFence(
int monitoringType,
GeofenceHardwareRequestParcelable request,
IGeofenceHardwareCallback callback) {
int geofenceId = request.getId();
// This API is not thread safe. Operations on the same geofence need to be serialized
// by upper layers
if (DEBUG) {
String message = String.format(
"addCircularFence: monitoringType=%d, %s",
monitoringType,
request);
Log.d(TAG, message);
}
boolean result;
// The callback must be added before addCircularHardwareGeofence is called otherwise the
// callback might not be called after the geofence is added in the geofence hardware.
// This also means that the callback must be removed if the addCircularHardwareGeofence
// operations is not called or fails.
synchronized (mGeofences) {
mGeofences.put(geofenceId, callback);
}
switch (monitoringType) {
case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
if (mGpsService == null) return false;
try {
result = mGpsService.addCircularHardwareGeofence(
request.getId(),
request.getLatitude(),
request.getLongitude(),
request.getRadius(),
request.getLastTransition(),
request.getMonitorTransitions(),
request.getNotificationResponsiveness(),
request.getUnknownTimer());
} catch (RemoteException e) {
Log.e(TAG, "AddGeofence: Remote Exception calling LocationManagerService");
result = false;
}
break;
case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
if(mFusedService == null) {
return false;
}
try {
mFusedService.addGeofences(
new GeofenceHardwareRequestParcelable[] { request });
result = true;
} catch(RemoteException e) {
Log.e(TAG, "AddGeofence: RemoteException calling LocationManagerService");
result = false;
}
break;
default:
result = false;
}
if (result) {
Message m = mReaperHandler.obtainMessage(REAPER_GEOFENCE_ADDED, callback);
m.arg1 = monitoringType;
mReaperHandler.sendMessage(m);
} else {
synchronized (mGeofences) {
mGeofences.remove(geofenceId);
}
}
if (DEBUG) Log.d(TAG, "addCircularFence: Result is: " + result);
return result;
}
public boolean removeGeofence(int geofenceId, int monitoringType) {
// This API is not thread safe. Operations on the same geofence need to be serialized
// by upper layers
if (DEBUG) Log.d(TAG, "Remove Geofence: GeofenceId: " + geofenceId);
boolean result = false;
synchronized (mGeofences) {
if (mGeofences.get(geofenceId) == null) {
throw new IllegalArgumentException("Geofence " + geofenceId + " not registered.");
}
}
switch (monitoringType) {
case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
if (mGpsService == null) return false;
try {
result = mGpsService.removeHardwareGeofence(geofenceId);
} catch (RemoteException e) {
Log.e(TAG, "RemoveGeofence: Remote Exception calling LocationManagerService");
result = false;
}
break;
case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
if(mFusedService == null) {
return false;
}
try {
mFusedService.removeGeofences(new int[] { geofenceId });
result = true;
} catch(RemoteException e) {
Log.e(TAG, "RemoveGeofence: RemoteException calling LocationManagerService");
result = false;
}
break;
default:
result = false;
}
if (DEBUG) Log.d(TAG, "removeGeofence: Result is: " + result);
return result;
}
public boolean pauseGeofence(int geofenceId, int monitoringType) {
// This API is not thread safe. Operations on the same geofence need to be serialized
// by upper layers
if (DEBUG) Log.d(TAG, "Pause Geofence: GeofenceId: " + geofenceId);
boolean result;
synchronized (mGeofences) {
if (mGeofences.get(geofenceId) == null) {
throw new IllegalArgumentException("Geofence " + geofenceId + " not registered.");
}
}
switch (monitoringType) {
case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
if (mGpsService == null) return false;
try {
result = mGpsService.pauseHardwareGeofence(geofenceId);
} catch (RemoteException e) {
Log.e(TAG, "PauseGeofence: Remote Exception calling LocationManagerService");
result = false;
}
break;
case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
if(mFusedService == null) {
return false;
}
try {
mFusedService.pauseMonitoringGeofence(geofenceId);
result = true;
} catch(RemoteException e) {
Log.e(TAG, "PauseGeofence: RemoteException calling LocationManagerService");
result = false;
}
break;
default:
result = false;
}
if (DEBUG) Log.d(TAG, "pauseGeofence: Result is: " + result);
return result;
}
public boolean resumeGeofence(int geofenceId, int monitoringType, int monitorTransition) {
// This API is not thread safe. Operations on the same geofence need to be serialized
// by upper layers
if (DEBUG) Log.d(TAG, "Resume Geofence: GeofenceId: " + geofenceId);
boolean result;
synchronized (mGeofences) {
if (mGeofences.get(geofenceId) == null) {
throw new IllegalArgumentException("Geofence " + geofenceId + " not registered.");
}
}
switch (monitoringType) {
case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
if (mGpsService == null) return false;
try {
result = mGpsService.resumeHardwareGeofence(geofenceId, monitorTransition);
} catch (RemoteException e) {
Log.e(TAG, "ResumeGeofence: Remote Exception calling LocationManagerService");
result = false;
}
break;
case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
if(mFusedService == null) {
return false;
}
try {
mFusedService.resumeMonitoringGeofence(geofenceId, monitorTransition);
result = true;
} catch(RemoteException e) {
Log.e(TAG, "ResumeGeofence: RemoteException calling LocationManagerService");
result = false;
}
break;
default:
result = false;
}
if (DEBUG) Log.d(TAG, "resumeGeofence: Result is: " + result);
return result;
}
public boolean registerForMonitorStateChangeCallback(int monitoringType,
IGeofenceHardwareMonitorCallback callback) {
Message reaperMessage =
mReaperHandler.obtainMessage(REAPER_MONITOR_CALLBACK_ADDED, callback);
reaperMessage.arg1 = monitoringType;
mReaperHandler.sendMessage(reaperMessage);
Message m = mCallbacksHandler.obtainMessage(CALLBACK_ADD, callback);
m.arg1 = monitoringType;
mCallbacksHandler.sendMessage(m);
return true;
}
public boolean unregisterForMonitorStateChangeCallback(int monitoringType,
IGeofenceHardwareMonitorCallback callback) {
Message m = mCallbacksHandler.obtainMessage(CALLBACK_REMOVE, callback);
m.arg1 = monitoringType;
mCallbacksHandler.sendMessage(m);
return true;
}
/**
* Used to report geofence transitions
*/
public void reportGeofenceTransition(
int geofenceId,
Location location,
int transition,
long transitionTimestamp,
int monitoringType,
int sourcesUsed) {
if(location == null) {
Log.e(TAG, String.format("Invalid Geofence Transition: location=null"));
return;
}
if(DEBUG) {
Log.d(
TAG,
"GeofenceTransition| " + location + ", transition:" + transition +
", transitionTimestamp:" + transitionTimestamp + ", monitoringType:" +
monitoringType + ", sourcesUsed:" + sourcesUsed);
}
GeofenceTransition geofenceTransition = new GeofenceTransition(
geofenceId,
transition,
transitionTimestamp,
location,
monitoringType,
sourcesUsed);
acquireWakeLock();
Message message = mGeofenceHandler.obtainMessage(
GEOFENCE_TRANSITION_CALLBACK,
geofenceTransition);
message.sendToTarget();
}
/**
* Used to report Monitor status changes.
*/
public void reportGeofenceMonitorStatus(
int monitoringType,
int monitoringStatus,
Location location,
int source) {
setMonitorAvailability(monitoringType, monitoringStatus);
acquireWakeLock();
GeofenceHardwareMonitorEvent event = new GeofenceHardwareMonitorEvent(
monitoringType,
monitoringStatus,
source,
location);
Message message = mCallbacksHandler.obtainMessage(GEOFENCE_STATUS, event);
message.sendToTarget();
}
/**
* Internal generic status report function for Geofence operations.
*
* @param operation The operation to be reported as defined internally.
* @param geofenceId The id of the geofence the operation is related to.
* @param operationStatus The status of the operation as defined in GeofenceHardware class. This
* status is independent of the statuses reported by different HALs.
*/
private void reportGeofenceOperationStatus(int operation, int geofenceId, int operationStatus) {
acquireWakeLock();
Message message = mGeofenceHandler.obtainMessage(operation);
message.arg1 = geofenceId;
message.arg2 = operationStatus;
message.sendToTarget();
}
/**
* Used to report the status of a Geofence Add operation.
*/
public void reportGeofenceAddStatus(int geofenceId, int status) {
if(DEBUG) Log.d(TAG, "AddCallback| id:" + geofenceId + ", status:" + status);
reportGeofenceOperationStatus(ADD_GEOFENCE_CALLBACK, geofenceId, status);
}
/**
* Used to report the status of a Geofence Remove operation.
*/
public void reportGeofenceRemoveStatus(int geofenceId, int status) {
if(DEBUG) Log.d(TAG, "RemoveCallback| id:" + geofenceId + ", status:" + status);
reportGeofenceOperationStatus(REMOVE_GEOFENCE_CALLBACK, geofenceId, status);
}
/**
* Used to report the status of a Geofence Pause operation.
*/
public void reportGeofencePauseStatus(int geofenceId, int status) {
if(DEBUG) Log.d(TAG, "PauseCallbac| id:" + geofenceId + ", status" + status);
reportGeofenceOperationStatus(PAUSE_GEOFENCE_CALLBACK, geofenceId, status);
}
/**
* Used to report the status of a Geofence Resume operation.
*/
public void reportGeofenceResumeStatus(int geofenceId, int status) {
if(DEBUG) Log.d(TAG, "ResumeCallback| id:" + geofenceId + ", status:" + status);
reportGeofenceOperationStatus(RESUME_GEOFENCE_CALLBACK, geofenceId, status);
}
// All operations on mGeofences
private Handler mGeofenceHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int geofenceId;
int status;
IGeofenceHardwareCallback callback;
switch (msg.what) {
case ADD_GEOFENCE_CALLBACK:
geofenceId = msg.arg1;
synchronized (mGeofences) {
callback = mGeofences.get(geofenceId);
}
if (callback != null) {
try {
callback.onGeofenceAdd(geofenceId, msg.arg2);
} catch (RemoteException e) {Log.i(TAG, "Remote Exception:" + e);}
}
releaseWakeLock();
break;
case REMOVE_GEOFENCE_CALLBACK:
geofenceId = msg.arg1;
synchronized (mGeofences) {
callback = mGeofences.get(geofenceId);
}
if (callback != null) {
try {
callback.onGeofenceRemove(geofenceId, msg.arg2);
} catch (RemoteException e) {}
IBinder callbackBinder = callback.asBinder();
boolean callbackInUse = false;
synchronized (mGeofences) {
mGeofences.remove(geofenceId);
// Check if the underlying binder is still useful for other geofences,
// if no, unlink the DeathRecipient to avoid memory leak.
for (int i = 0; i < mGeofences.size(); i++) {
if (mGeofences.valueAt(i).asBinder() == callbackBinder) {
callbackInUse = true;
break;
}
}
}
// Remove the reaper associated with this binder.
if (!callbackInUse) {
for (Iterator<Reaper> iterator = mReapers.iterator();
iterator.hasNext();) {
Reaper reaper = iterator.next();
if (reaper.mCallback != null &&
reaper.mCallback.asBinder() == callbackBinder) {
iterator.remove();
reaper.unlinkToDeath();
if (DEBUG) Log.d(TAG, String.format("Removed reaper %s " +
"because binder %s is no longer needed.",
reaper, callbackBinder));
}
}
}
}
releaseWakeLock();
break;
case PAUSE_GEOFENCE_CALLBACK:
geofenceId = msg.arg1;
synchronized (mGeofences) {
callback = mGeofences.get(geofenceId);
}
if (callback != null) {
try {
callback.onGeofencePause(geofenceId, msg.arg2);
} catch (RemoteException e) {}
}
releaseWakeLock();
break;
case RESUME_GEOFENCE_CALLBACK:
geofenceId = msg.arg1;
synchronized (mGeofences) {
callback = mGeofences.get(geofenceId);
}
if (callback != null) {
try {
callback.onGeofenceResume(geofenceId, msg.arg2);
} catch (RemoteException e) {}
}
releaseWakeLock();
break;
case GEOFENCE_TRANSITION_CALLBACK:
GeofenceTransition geofenceTransition = (GeofenceTransition)(msg.obj);
synchronized (mGeofences) {
callback = mGeofences.get(geofenceTransition.mGeofenceId);
// need to keep access to mGeofences synchronized at all times
if (DEBUG) Log.d(TAG, "GeofenceTransistionCallback: GPS : GeofenceId: " +
geofenceTransition.mGeofenceId +
" Transition: " + geofenceTransition.mTransition +
" Location: " + geofenceTransition.mLocation + ":" + mGeofences);
}
if (callback != null) {
try {
callback.onGeofenceTransition(
geofenceTransition.mGeofenceId, geofenceTransition.mTransition,
geofenceTransition.mLocation, geofenceTransition.mTimestamp,
geofenceTransition.mMonitoringType);
} catch (RemoteException e) {}
}
releaseWakeLock();
break;
case GEOFENCE_CALLBACK_BINDER_DIED:
// Find all geofences associated with this callback and remove them.
callback = (IGeofenceHardwareCallback) (msg.obj);
if (DEBUG) Log.d(TAG, "Geofence callback reaped:" + callback);
int monitoringType = msg.arg1;
synchronized (mGeofences) {
for (int i = 0; i < mGeofences.size(); i++) {
if (mGeofences.valueAt(i).equals(callback)) {
geofenceId = mGeofences.keyAt(i);
removeGeofence(mGeofences.keyAt(i), monitoringType);
mGeofences.remove(geofenceId);
}
}
}
}
}
};
// All operations on mCallbacks
private Handler mCallbacksHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
int monitoringType;
ArrayList<IGeofenceHardwareMonitorCallback> callbackList;
IGeofenceHardwareMonitorCallback callback;
switch (msg.what) {
case GEOFENCE_STATUS:
GeofenceHardwareMonitorEvent event = (GeofenceHardwareMonitorEvent) msg.obj;
callbackList = mCallbacks[event.getMonitoringType()];
if (callbackList != null) {
if (DEBUG) Log.d(TAG, "MonitoringSystemChangeCallback: " + event);
for (IGeofenceHardwareMonitorCallback c : callbackList) {
try {
c.onMonitoringSystemChange(event);
} catch (RemoteException e) {
Log.d(TAG, "Error reporting onMonitoringSystemChange.", e);
}
}
}
releaseWakeLock();
break;
case CALLBACK_ADD:
monitoringType = msg.arg1;
callback = (IGeofenceHardwareMonitorCallback) msg.obj;
callbackList = mCallbacks[monitoringType];
if (callbackList == null) {
callbackList = new ArrayList<IGeofenceHardwareMonitorCallback>();
mCallbacks[monitoringType] = callbackList;
}
if (!callbackList.contains(callback)) callbackList.add(callback);
break;
case CALLBACK_REMOVE:
monitoringType = msg.arg1;
callback = (IGeofenceHardwareMonitorCallback) msg.obj;
callbackList = mCallbacks[monitoringType];
if (callbackList != null) {
callbackList.remove(callback);
}
break;
case MONITOR_CALLBACK_BINDER_DIED:
callback = (IGeofenceHardwareMonitorCallback) msg.obj;
if (DEBUG) Log.d(TAG, "Monitor callback reaped:" + callback);
callbackList = mCallbacks[msg.arg1];
if (callbackList != null && callbackList.contains(callback)) {
callbackList.remove(callback);
}
}
}
};
// All operations on mReaper
private Handler mReaperHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
Reaper r;
IGeofenceHardwareCallback callback;
IGeofenceHardwareMonitorCallback monitorCallback;
int monitoringType;
switch (msg.what) {
case REAPER_GEOFENCE_ADDED:
callback = (IGeofenceHardwareCallback) msg.obj;
monitoringType = msg.arg1;
r = new Reaper(callback, monitoringType);
if (!mReapers.contains(r)) {
mReapers.add(r);
IBinder b = callback.asBinder();
try {
b.linkToDeath(r, 0);
} catch (RemoteException e) {}
}
break;
case REAPER_MONITOR_CALLBACK_ADDED:
monitorCallback = (IGeofenceHardwareMonitorCallback) msg.obj;
monitoringType = msg.arg1;
r = new Reaper(monitorCallback, monitoringType);
if (!mReapers.contains(r)) {
mReapers.add(r);
IBinder b = monitorCallback.asBinder();
try {
b.linkToDeath(r, 0);
} catch (RemoteException e) {}
}
break;
case REAPER_REMOVED:
r = (Reaper) msg.obj;
mReapers.remove(r);
}
}
};
private class GeofenceTransition {
private int mGeofenceId, mTransition;
private long mTimestamp;
private Location mLocation;
private int mMonitoringType;
private int mSourcesUsed;
GeofenceTransition(
int geofenceId,
int transition,
long timestamp,
Location location,
int monitoringType,
int sourcesUsed) {
mGeofenceId = geofenceId;
mTransition = transition;
mTimestamp = timestamp;
mLocation = location;
mMonitoringType = monitoringType;
mSourcesUsed = sourcesUsed;
}
}
private void setMonitorAvailability(int monitor, int val) {
synchronized (mSupportedMonitorTypes) {
mSupportedMonitorTypes[monitor] = val;
}
}
int getMonitoringResolutionLevel(int monitoringType) {
switch (monitoringType) {
case GeofenceHardware.MONITORING_TYPE_GPS_HARDWARE:
return RESOLUTION_LEVEL_FINE;
case GeofenceHardware.MONITORING_TYPE_FUSED_HARDWARE:
return RESOLUTION_LEVEL_FINE;
}
return RESOLUTION_LEVEL_NONE;
}
class Reaper implements IBinder.DeathRecipient {
private IGeofenceHardwareMonitorCallback mMonitorCallback;
private IGeofenceHardwareCallback mCallback;
private int mMonitoringType;
Reaper(IGeofenceHardwareCallback c, int monitoringType) {
mCallback = c;
mMonitoringType = monitoringType;
}
Reaper(IGeofenceHardwareMonitorCallback c, int monitoringType) {
mMonitorCallback = c;
mMonitoringType = monitoringType;
}
@Override
public void binderDied() {
Message m;
if (mCallback != null) {
m = mGeofenceHandler.obtainMessage(GEOFENCE_CALLBACK_BINDER_DIED, mCallback);
m.arg1 = mMonitoringType;
mGeofenceHandler.sendMessage(m);
} else if (mMonitorCallback != null) {
m = mCallbacksHandler.obtainMessage(MONITOR_CALLBACK_BINDER_DIED, mMonitorCallback);
m.arg1 = mMonitoringType;
mCallbacksHandler.sendMessage(m);
}
Message reaperMessage = mReaperHandler.obtainMessage(REAPER_REMOVED, this);
mReaperHandler.sendMessage(reaperMessage);
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (mCallback != null ? mCallback.asBinder().hashCode() : 0);
result = 31 * result + (mMonitorCallback != null
? mMonitorCallback.asBinder().hashCode() : 0);
result = 31 * result + mMonitoringType;
return result;
}
@Override
public boolean equals(Object obj) {
if (obj == null) return false;
if (obj == this) return true;
Reaper rhs = (Reaper) obj;
return binderEquals(rhs.mCallback, mCallback) &&
binderEquals(rhs.mMonitorCallback, mMonitorCallback) &&
rhs.mMonitoringType == mMonitoringType;
}
/**
* Compares the underlying Binder of the given two IInterface objects and returns true if
* they equals. null values are accepted.
*/
private boolean binderEquals(IInterface left, IInterface right) {
if (left == null) {
return right == null;
} else {
return right == null ? false : left.asBinder() == right.asBinder();
}
}
/**
* Unlinks this DeathRecipient.
*/
private boolean unlinkToDeath() {
if (mMonitorCallback != null) {
return mMonitorCallback.asBinder().unlinkToDeath(this, 0);
} else if (mCallback != null) {
return mCallback.asBinder().unlinkToDeath(this, 0);
}
return true;
}
private boolean callbackEquals(IGeofenceHardwareCallback cb) {
return mCallback != null && mCallback.asBinder() == cb.asBinder();
}
}
int getAllowedResolutionLevel(int pid, int uid) {
if (mContext.checkPermission(android.Manifest.permission.ACCESS_FINE_LOCATION,
pid, uid) == PackageManager.PERMISSION_GRANTED) {
return RESOLUTION_LEVEL_FINE;
} else if (mContext.checkPermission(android.Manifest.permission.ACCESS_COARSE_LOCATION,
pid, uid) == PackageManager.PERMISSION_GRANTED) {
return RESOLUTION_LEVEL_COARSE;
} else {
return RESOLUTION_LEVEL_NONE;
}
}
}
| syslover33/ctank | java/android-sdk-linux_r24.4.1_src/sources/android-23/android/hardware/location/GeofenceHardwareImpl.java | Java | gpl-3.0 | 37,828 |
package net.minecraft.server;
import java.awt.GraphicsEnvironment;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.Proxy;
import java.security.KeyPair;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.Callable;
import javax.imageio.ImageIO;
import net.minecraft.util.com.google.common.base.Charsets;
import net.minecraft.util.com.mojang.authlib.GameProfile;
import net.minecraft.util.com.mojang.authlib.GameProfileRepository;
import net.minecraft.util.com.mojang.authlib.minecraft.MinecraftSessionService;
import net.minecraft.util.com.mojang.authlib.yggdrasil.YggdrasilAuthenticationService;
import net.minecraft.util.io.netty.buffer.ByteBuf;
import net.minecraft.util.io.netty.buffer.ByteBufOutputStream;
import net.minecraft.util.io.netty.buffer.Unpooled;
import net.minecraft.util.io.netty.handler.codec.base64.Base64;
import net.minecraft.util.org.apache.commons.lang3.Validate;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
// CraftBukkit start
import java.io.IOException;
import jline.console.ConsoleReader;
import joptsimple.OptionSet;
import org.bukkit.World.Environment;
import org.bukkit.craftbukkit.util.Waitable;
import org.bukkit.event.server.RemoteServerCommandEvent;
import org.bukkit.event.world.WorldSaveEvent;
// CraftBukkit end
public abstract class MinecraftServer implements ICommandListener, Runnable, IMojangStatistics {
private static final Logger i = LogManager.getLogger();
private static final File a = new File("usercache.json");
private static MinecraftServer j;
public Convertable convertable; // CraftBukkit - private final -> public
private final MojangStatisticsGenerator l = new MojangStatisticsGenerator("server", this, ar());
public File universe; // CraftBukkit - private final -> public
private final List n = new ArrayList();
private final ICommandHandler o;
public final MethodProfiler methodProfiler = new MethodProfiler();
private final ServerConnection p;
private final ServerPing q = new ServerPing();
private final Random r = new Random();
private String serverIp;
private int t = -1;
public WorldServer[] worldServer;
private PlayerList u;
private boolean isRunning = true;
private boolean isStopped;
private int ticks;
protected final Proxy d;
public String e;
public int f;
private boolean onlineMode;
private boolean spawnAnimals;
private boolean spawnNPCs;
private boolean pvpMode;
private boolean allowFlight;
private String motd;
private int E;
private int F = 0;
public final long[] g = new long[100];
public long[][] h;
private KeyPair G;
private String H;
private String I;
private boolean demoMode;
private boolean L;
private boolean M;
private String N = "";
private boolean O;
private long P;
private String Q;
private boolean R;
private boolean S;
private final YggdrasilAuthenticationService T;
private final MinecraftSessionService U;
private long V = 0L;
private final GameProfileRepository W;
private final UserCache X;
// CraftBukkit start - add fields
public List<WorldServer> worlds = new ArrayList<WorldServer>();
public org.bukkit.craftbukkit.CraftServer server;
public OptionSet options;
public org.bukkit.command.ConsoleCommandSender console;
public org.bukkit.command.RemoteConsoleCommandSender remoteConsole;
public ConsoleReader reader;
public static int currentTick = (int) (System.currentTimeMillis() / 50);
public final Thread primaryThread;
public java.util.Queue<Runnable> processQueue = new java.util.concurrent.ConcurrentLinkedQueue<Runnable>();
public int autosavePeriod;
// CraftBukkit end
public MinecraftServer(OptionSet options, Proxy proxy) { // CraftBukkit - signature file -> OptionSet
this.X = new UserCache(this, a);
j = this;
this.d = proxy;
// this.universe = file1; // CraftBukkit
this.p = new ServerConnection(this);
this.o = new CommandDispatcher();
// this.convertable = new WorldLoaderServer(file1); // CraftBukkit - moved to DedicatedServer.init
this.T = new YggdrasilAuthenticationService(proxy, UUID.randomUUID().toString());
this.U = this.T.createMinecraftSessionService();
this.W = this.T.createProfileRepository();
// CraftBukkit start
this.options = options;
// Try to see if we're actually running in a terminal, disable jline if not
if (System.console() == null) {
System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
org.bukkit.craftbukkit.Main.useJline = false;
}
try {
this.reader = new ConsoleReader(System.in, System.out);
this.reader.setExpandEvents(false); // Avoid parsing exceptions for uncommonly used event designators
} catch (Throwable e) {
try {
// Try again with jline disabled for Windows users without C++ 2008 Redistributable
System.setProperty("jline.terminal", "jline.UnsupportedTerminal");
System.setProperty("user.language", "en");
org.bukkit.craftbukkit.Main.useJline = false;
this.reader = new ConsoleReader(System.in, System.out);
this.reader.setExpandEvents(false);
} catch (IOException ex) {
i.warn((String) null, ex);
}
}
Runtime.getRuntime().addShutdownHook(new org.bukkit.craftbukkit.util.ServerShutdownThread(this));
primaryThread = new ThreadServerApplication(this, "Server thread"); // Moved from main
}
public abstract PropertyManager getPropertyManager();
// CraftBukkit end
protected abstract boolean init() throws java.net.UnknownHostException; // CraftBukkit - throws UnknownHostException
protected void a(String s) {
if (this.getConvertable().isConvertable(s)) {
i.info("Converting map!");
this.b("menu.convertingLevel");
this.getConvertable().convert(s, new ConvertProgressUpdater(this));
}
}
protected synchronized void b(String s) {
this.Q = s;
}
protected void a(String s, String s1, long i, WorldType worldtype, String s2) {
this.a(s);
this.b("menu.loadingLevel");
this.worldServer = new WorldServer[3];
// this.h = new long[this.worldServer.length][100]; // CraftBukkit - Removed ticktime arrays
// IDataManager idatamanager = this.convertable.a(s, true);
// WorldData worlddata = idatamanager.getWorldData();
/* CraftBukkit start - Removed worldsettings
WorldSettings worldsettings;
if (worlddata == null) {
worldsettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(), this.isHardcore(), worldtype);
worldsettings.a(s2);
} else {
worldsettings = new WorldSettings(worlddata);
}
if (this.L) {
worldsettings.a();
}
// */
int worldCount = 3;
for (int j = 0; j < worldCount; ++j) {
WorldServer world;
int dimension = 0;
if (j == 1) {
if (this.getAllowNether()) {
dimension = -1;
} else {
continue;
}
}
if (j == 2) {
if (this.server.getAllowEnd()) {
dimension = 1;
} else {
continue;
}
}
String worldType = Environment.getEnvironment(dimension).toString().toLowerCase();
String name = (dimension == 0) ? s : s + "_" + worldType;
org.bukkit.generator.ChunkGenerator gen = this.server.getGenerator(name);
WorldSettings worldsettings = new WorldSettings(i, this.getGamemode(), this.getGenerateStructures(), this.isHardcore(), worldtype);
worldsettings.a(s2);
if (j == 0) {
IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), s1, true);
if (this.R()) {
world = new DemoWorldServer(this, idatamanager, s1, dimension, this.methodProfiler);
} else {
// world =, b0 to dimension, added Environment and gen
world = new WorldServer(this, idatamanager, s1, dimension, worldsettings, this.methodProfiler, Environment.getEnvironment(dimension), gen);
}
this.server.scoreboardManager = new org.bukkit.craftbukkit.scoreboard.CraftScoreboardManager(this, world.getScoreboard());
} else {
String dim = "DIM" + dimension;
File newWorld = new File(new File(name), dim);
File oldWorld = new File(new File(s), dim);
if ((!newWorld.isDirectory()) && (oldWorld.isDirectory())) {
MinecraftServer.i.info("---- Migration of old " + worldType + " folder required ----");
MinecraftServer.i.info("Unfortunately due to the way that Minecraft implemented multiworld support in 1.6, Bukkit requires that you move your " + worldType + " folder to a new location in order to operate correctly.");
MinecraftServer.i.info("We will move this folder for you, but it will mean that you need to move it back should you wish to stop using Bukkit in the future.");
MinecraftServer.i.info("Attempting to move " + oldWorld + " to " + newWorld + "...");
if (newWorld.exists()) {
MinecraftServer.i.warn("A file or folder already exists at " + newWorld + "!");
MinecraftServer.i.info("---- Migration of old " + worldType + " folder failed ----");
} else if (newWorld.getParentFile().mkdirs()) {
if (oldWorld.renameTo(newWorld)) {
MinecraftServer.i.info("Success! To restore " + worldType + " in the future, simply move " + newWorld + " to " + oldWorld);
// Migrate world data too.
try {
com.google.common.io.Files.copy(new File(new File(s), "level.dat"), new File(new File(name), "level.dat"));
} catch (IOException exception) {
MinecraftServer.i.warn("Unable to migrate world data.");
}
MinecraftServer.i.info("---- Migration of old " + worldType + " folder complete ----");
} else {
MinecraftServer.i.warn("Could not move folder " + oldWorld + " to " + newWorld + "!");
MinecraftServer.i.info("---- Migration of old " + worldType + " folder failed ----");
}
} else {
MinecraftServer.i.warn("Could not create path for " + newWorld + "!");
MinecraftServer.i.info("---- Migration of old " + worldType + " folder failed ----");
}
}
IDataManager idatamanager = new ServerNBTManager(server.getWorldContainer(), name, true);
// world =, b0 to dimension, s1 to name, added Environment and gen
world = new SecondaryWorldServer(this, idatamanager, name, dimension, worldsettings, this.worlds.get(0), this.methodProfiler, Environment.getEnvironment(dimension), gen);
}
if (gen != null) {
world.getWorld().getPopulators().addAll(gen.getDefaultPopulators(world.getWorld()));
}
this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldInitEvent(world.getWorld()));
world.addIWorldAccess(new WorldManager(this, world));
if (!this.N()) {
world.getWorldData().setGameType(this.getGamemode());
}
this.worlds.add(world);
this.u.setPlayerFileData(this.worlds.toArray(new WorldServer[this.worlds.size()]));
// CraftBukkit end
}
this.a(this.getDifficulty());
this.g();
}
protected void g() {
boolean flag = true;
boolean flag1 = true;
boolean flag2 = true;
boolean flag3 = true;
int i = 0;
this.b("menu.generatingTerrain");
byte b0 = 0;
// CraftBukkit start - fire WorldLoadEvent and handle whether or not to keep the spawn in memory
for (int m = 0; m < this.worlds.size(); ++m) {
WorldServer worldserver = this.worlds.get(m);
MinecraftServer.i.info("Preparing start region for level " + m + " (Seed: " + worldserver.getSeed() + ")");
if (!worldserver.getWorld().getKeepSpawnInMemory()) {
continue;
}
ChunkCoordinates chunkcoordinates = worldserver.getSpawn();
long j = ar();
i = 0;
for (int k = -192; k <= 192 && this.isRunning(); k += 16) {
for (int l = -192; l <= 192 && this.isRunning(); l += 16) {
long i1 = ar();
if (i1 - j > 1000L) {
this.a_("Preparing spawn area", i * 100 / 625);
j = i1;
}
++i;
worldserver.chunkProviderServer.getChunkAt(chunkcoordinates.x + k >> 4, chunkcoordinates.z + l >> 4);
}
}
}
for (WorldServer world : this.worlds) {
this.server.getPluginManager().callEvent(new org.bukkit.event.world.WorldLoadEvent(world.getWorld()));
}
// CraftBukkit end
this.n();
}
public abstract boolean getGenerateStructures();
public abstract EnumGamemode getGamemode();
public abstract EnumDifficulty getDifficulty();
public abstract boolean isHardcore();
public abstract int l();
public abstract boolean m();
protected void a_(String s, int i) {
this.e = s;
this.f = i;
// CraftBukkit - Use FQN to work around decompiler issue
MinecraftServer.i.info(s + ": " + i + "%");
}
protected void n() {
this.e = null;
this.f = 0;
this.server.enablePlugins(org.bukkit.plugin.PluginLoadOrder.POSTWORLD); // CraftBukkit
}
protected void saveChunks(boolean flag) throws ExceptionWorldConflict { // CraftBukkit - added throws
if (!this.M) {
// CraftBukkit start - fire WorldSaveEvent
// WorldServer[] aworldserver = this.worldServer;
int i = this.worlds.size();
for (int j = 0; j < i; ++j) {
WorldServer worldserver = this.worlds.get(j);
if (worldserver != null) {
if (!flag) {
MinecraftServer.i.info("Saving chunks for level \'" + worldserver.getWorldData().getName() + "\'/" + worldserver.worldProvider.getName());
}
worldserver.save(true, (IProgressUpdate) null);
worldserver.saveLevel();
WorldSaveEvent event = new WorldSaveEvent(worldserver.getWorld());
this.server.getPluginManager().callEvent(event);
// CraftBukkit end
}
}
}
}
public void stop() throws ExceptionWorldConflict { // CraftBukkit - added throws
if (!this.M) {
i.info("Stopping server");
// CraftBukkit start
if (this.server != null) {
this.server.disablePlugins();
}
// CraftBukkit end
if (this.ai() != null) {
this.ai().b();
}
if (this.u != null) {
i.info("Saving players");
this.u.savePlayers();
this.u.u();
}
if (this.worldServer != null) {
i.info("Saving worlds");
this.saveChunks(false);
/* CraftBukkit start - Handled in saveChunks
for (int i = 0; i < this.worldServer.length; ++i) {
WorldServer worldserver = this.worldServer[i];
worldserver.saveLevel();
}
// CraftBukkit end */
}
if (this.l.d()) {
this.l.e();
}
}
}
public String getServerIp() {
return this.serverIp;
}
public void c(String s) {
this.serverIp = s;
}
public boolean isRunning() {
return this.isRunning;
}
public void safeShutdown() {
this.isRunning = false;
}
public void run() {
try {
if (this.init()) {
long i = ar();
long j = 0L;
this.q.setMOTD(new ChatComponentText(this.motd));
this.q.setServerInfo(new ServerPingServerData("1.7.10", 5));
this.a(this.q);
while (this.isRunning) {
long k = ar();
long l = k - i;
if (l > 2000L && i - this.P >= 15000L) {
if (this.server.getWarnOnOverload()) // CraftBukkit - Added option to suppress warning messages
MinecraftServer.i.warn("Can\'t keep up! Did the system time change, or is the server overloaded? Running {}ms behind, skipping {} tick(s)", new Object[] { Long.valueOf(l), Long.valueOf(l / 50L)});
l = 2000L;
this.P = i;
}
if (l < 0L) {
MinecraftServer.i.warn("Time ran backwards! Did the system time change?");
l = 0L;
}
j += l;
i = k;
if (this.worlds.get(0).everyoneDeeplySleeping()) { // CraftBukkit
this.u();
j = 0L;
} else {
while (j > 50L) {
MinecraftServer.currentTick = (int) (System.currentTimeMillis() / 50); // CraftBukkit
j -= 50L;
this.u();
}
}
Thread.sleep(Math.max(1L, 50L - j));
this.O = true;
}
} else {
this.a((CrashReport) null);
}
} catch (Throwable throwable) {
i.error("Encountered an unexpected exception", throwable);
CrashReport crashreport = null;
if (throwable instanceof ReportedException) {
crashreport = this.b(((ReportedException) throwable).a());
} else {
crashreport = this.b(new CrashReport("Exception in server tick loop", throwable));
}
File file1 = new File(new File(this.s(), "crash-reports"), "crash-" + (new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss")).format(new Date()) + "-server.txt");
if (crashreport.a(file1)) {
i.error("This crash report has been saved to: " + file1.getAbsolutePath());
} else {
i.error("We were unable to save this crash report to disk.");
}
this.a(crashreport);
} finally {
try {
this.stop();
this.isStopped = true;
} catch (Throwable throwable1) {
i.error("Exception stopping the server", throwable1);
} finally {
// CraftBukkit start - Restore terminal to original settings
try {
this.reader.getTerminal().restore();
} catch (Exception e) {
}
// CraftBukkit end
this.t();
}
}
}
private void a(ServerPing serverping) {
File file1 = this.d("server-icon.png");
if (file1.isFile()) {
ByteBuf bytebuf = Unpooled.buffer();
try {
BufferedImage bufferedimage = ImageIO.read(file1);
Validate.validState(bufferedimage.getWidth() == 64, "Must be 64 pixels wide", new Object[0]);
Validate.validState(bufferedimage.getHeight() == 64, "Must be 64 pixels high", new Object[0]);
ImageIO.write(bufferedimage, "PNG", new ByteBufOutputStream(bytebuf));
ByteBuf bytebuf1 = Base64.encode(bytebuf);
serverping.setFavicon("data:image/png;base64," + bytebuf1.toString(Charsets.UTF_8));
} catch (Exception exception) {
i.error("Couldn\'t load server icon", exception);
} finally {
bytebuf.release();
}
}
}
protected File s() {
return new File(".");
}
protected void a(CrashReport crashreport) {}
protected void t() {}
protected void u() throws ExceptionWorldConflict { // CraftBukkit - added throws
long i = System.nanoTime();
++this.ticks;
if (this.R) {
this.R = false;
this.methodProfiler.a = true;
this.methodProfiler.a();
}
this.methodProfiler.a("root");
this.v();
if (i - this.V >= 5000000000L) {
this.V = i;
this.q.setPlayerSample(new ServerPingPlayerSample(this.D(), this.C()));
GameProfile[] agameprofile = new GameProfile[Math.min(this.C(), 12)];
int j = MathHelper.nextInt(this.r, 0, this.C() - agameprofile.length);
for (int k = 0; k < agameprofile.length; ++k) {
agameprofile[k] = ((EntityPlayer) this.u.players.get(j + k)).getProfile();
}
Collections.shuffle(Arrays.asList(agameprofile));
this.q.b().a(agameprofile);
}
if ((this.autosavePeriod > 0) && ((this.ticks % this.autosavePeriod) == 0)) { // CraftBukkit
this.methodProfiler.a("save");
this.u.savePlayers();
this.saveChunks(true);
this.methodProfiler.b();
}
this.methodProfiler.a("tallying");
this.g[this.ticks % 100] = System.nanoTime() - i;
this.methodProfiler.b();
this.methodProfiler.a("snooper");
if (!this.l.d() && this.ticks > 100) {
this.l.a();
}
if (this.ticks % 6000 == 0) {
this.l.b();
}
this.methodProfiler.b();
this.methodProfiler.b();
}
public void v() {
this.methodProfiler.a("levels");
// CraftBukkit start
this.server.getScheduler().mainThreadHeartbeat(this.ticks);
// Run tasks that are waiting on processing
while (!processQueue.isEmpty()) {
processQueue.remove().run();
}
org.bukkit.craftbukkit.chunkio.ChunkIOExecutor.tick();
// Send time updates to everyone, it will get the right time from the world the player is in.
if (this.ticks % 20 == 0) {
for (int i = 0; i < this.getPlayerList().players.size(); ++i) {
EntityPlayer entityplayer = (EntityPlayer) this.getPlayerList().players.get(i);
entityplayer.playerConnection.sendPacket(new PacketPlayOutUpdateTime(entityplayer.world.getTime(), entityplayer.getPlayerTime(), entityplayer.world.getGameRules().getBoolean("doDaylightCycle"))); // Add support for per player time
}
}
int i;
for (i = 0; i < this.worlds.size(); ++i) {
long j = System.nanoTime();
// if (i == 0 || this.getAllowNether()) {
WorldServer worldserver = this.worlds.get(i);
this.methodProfiler.a(worldserver.getWorldData().getName());
this.methodProfiler.a("pools");
this.methodProfiler.b();
/* Drop global time updates
if (this.ticks % 20 == 0) {
this.methodProfiler.a("timeSync");
this.t.a(new PacketPlayOutUpdateTime(worldserver.getTime(), worldserver.getDayTime(), worldserver.getGameRules().getBoolean("doDaylightCycle")), worldserver.worldProvider.dimension);
this.methodProfiler.b();
}
// CraftBukkit end */
this.methodProfiler.a("tick");
CrashReport crashreport;
try {
worldserver.doTick();
} catch (Throwable throwable) {
crashreport = CrashReport.a(throwable, "Exception ticking world");
worldserver.a(crashreport);
throw new ReportedException(crashreport);
}
try {
worldserver.tickEntities();
} catch (Throwable throwable1) {
crashreport = CrashReport.a(throwable1, "Exception ticking world entities");
worldserver.a(crashreport);
throw new ReportedException(crashreport);
}
this.methodProfiler.b();
this.methodProfiler.a("tracker");
worldserver.getTracker().updatePlayers();
this.methodProfiler.b();
this.methodProfiler.b();
// } // CraftBukkit
// this.h[i][this.ticks % 100] = System.nanoTime() - j; // CraftBukkit
}
this.methodProfiler.c("connection");
this.ai().c();
this.methodProfiler.c("players");
this.u.tick();
this.methodProfiler.c("tickables");
for (i = 0; i < this.n.size(); ++i) {
((IUpdatePlayerListBox) this.n.get(i)).a();
}
this.methodProfiler.b();
}
public boolean getAllowNether() {
return true;
}
public void a(IUpdatePlayerListBox iupdateplayerlistbox) {
this.n.add(iupdateplayerlistbox);
}
public static void main(final OptionSet options) { // CraftBukkit - replaces main(String[] astring)
DispenserRegistry.b();
try {
/* CraftBukkit start - Replace everything
boolean flag = true;
String s = null;
String s1 = ".";
String s2 = null;
boolean flag1 = false;
boolean flag2 = false;
int i = -1;
for (int j = 0; j < astring.length; ++j) {
String s3 = astring[j];
String s4 = j == astring.length - 1 ? null : astring[j + 1];
boolean flag3 = false;
if (!s3.equals("nogui") && !s3.equals("--nogui")) {
if (s3.equals("--port") && s4 != null) {
flag3 = true;
try {
i = Integer.parseInt(s4);
} catch (NumberFormatException numberformatexception) {
;
}
} else if (s3.equals("--singleplayer") && s4 != null) {
flag3 = true;
s = s4;
} else if (s3.equals("--universe") && s4 != null) {
flag3 = true;
s1 = s4;
} else if (s3.equals("--world") && s4 != null) {
flag3 = true;
s2 = s4;
} else if (s3.equals("--demo")) {
flag1 = true;
} else if (s3.equals("--bonusChest")) {
flag2 = true;
}
} else {
flag = false;
}
if (flag3) {
++j;
}
}
DedicatedServer dedicatedserver = new DedicatedServer(new File(s1));
if (s != null) {
dedicatedserver.j(s);
}
if (s2 != null) {
dedicatedserver.k(s2);
}
if (i >= 0) {
dedicatedserver.setPort(i);
}
if (flag1) {
dedicatedserver.b(true);
}
if (flag2) {
dedicatedserver.c(true);
}
if (flag) {
dedicatedserver.aD();
}
// */
DedicatedServer dedicatedserver = new DedicatedServer(options);
if (options.has("port")) {
int port = (Integer) options.valueOf("port");
if (port > 0) {
dedicatedserver.setPort(port);
}
}
if (options.has("universe")) {
dedicatedserver.universe = (File) options.valueOf("universe");
}
if (options.has("world")) {
dedicatedserver.k((String) options.valueOf("world"));
}
dedicatedserver.primaryThread.start();
// Runtime.getRuntime().addShutdownHook(new ThreadShutdown("Server Shutdown Thread", dedicatedserver));
// CraftBukkit end
} catch (Exception exception) {
i.fatal("Failed to start the minecraft server", exception);
}
}
public void x() {
// (new ThreadServerApplication(this, "Server thread")).start(); // CraftBukkit - prevent abuse
}
public File d(String s) {
return new File(this.s(), s);
}
public void info(String s) {
i.info(s);
}
public void warning(String s) {
i.warn(s);
}
public WorldServer getWorldServer(int i) {
// CraftBukkit start
for (WorldServer world : this.worlds) {
if (world.dimension == i) {
return world;
}
}
return this.worlds.get(0);
// CraftBukkit end
}
public String y() {
return this.serverIp;
}
public int z() {
return this.t;
}
public String A() {
return this.motd;
}
public String getVersion() {
return "1.7.10";
}
public int C() {
return this.u.getPlayerCount();
}
public int D() {
return this.u.getMaxPlayers();
}
public String[] getPlayers() {
return this.u.f();
}
public GameProfile[] F() {
return this.u.g();
}
public String getPlugins() {
// CraftBukkit start - Whole method
StringBuilder result = new StringBuilder();
org.bukkit.plugin.Plugin[] plugins = server.getPluginManager().getPlugins();
result.append(server.getName());
result.append(" on Bukkit ");
result.append(server.getBukkitVersion());
if (plugins.length > 0 && this.server.getQueryPlugins()) {
result.append(": ");
for (int i = 0; i < plugins.length; i++) {
if (i > 0) {
result.append("; ");
}
result.append(plugins[i].getDescription().getName());
result.append(" ");
result.append(plugins[i].getDescription().getVersion().replaceAll(";", ","));
}
}
return result.toString();
// CraftBukkit end
}
// CraftBukkit start - fire RemoteServerCommandEvent
public String g(final String s) { // final parameter
Waitable<String> waitable = new Waitable<String>() {
@Override
protected String evaluate() {
RemoteControlCommandListener.instance.e();
// Event changes start
RemoteServerCommandEvent event = new RemoteServerCommandEvent(MinecraftServer.this.remoteConsole, s);
MinecraftServer.this.server.getPluginManager().callEvent(event);
// Event changes end
ServerCommand servercommand = new ServerCommand(event.getCommand(), RemoteControlCommandListener.instance);
MinecraftServer.this.server.dispatchServerCommand(MinecraftServer.this.remoteConsole, servercommand); // CraftBukkit
// this.o.a(RemoteControlCommandListener.instance, s);
return RemoteControlCommandListener.instance.f();
}};
processQueue.add(waitable);
try {
return waitable.get();
} catch (java.util.concurrent.ExecutionException e) {
throw new RuntimeException("Exception processing rcon command " + s, e.getCause());
} catch (InterruptedException e) {
Thread.currentThread().interrupt(); // Maintain interrupted state
throw new RuntimeException("Interrupted processing rcon command " + s, e);
}
// CraftBukkit end
}
public boolean isDebugging() {
return this.getPropertyManager().getBoolean("debug", false); // CraftBukkit - don't hardcode
}
public void h(String s) {
i.error(s);
}
public void i(String s) {
if (this.isDebugging()) {
i.info(s);
}
}
public String getServerModName() {
return server.getName(); // CraftBukkit - cb > vanilla!
}
public CrashReport b(CrashReport crashreport) {
crashreport.g().a("Profiler Position", (Callable) (new CrashReportProfilerPosition(this)));
if (this.worlds != null && this.worlds.size() > 0 && this.worlds.get(0) != null) { // CraftBukkit
crashreport.g().a("Vec3 Pool Size", (Callable) (new CrashReportVec3DPoolSize(this)));
}
if (this.u != null) {
crashreport.g().a("Player Count", (Callable) (new CrashReportPlayerCount(this)));
}
return crashreport;
}
public List a(ICommandListener icommandlistener, String s) {
// CraftBukkit start - Allow tab-completion of Bukkit commands
/*
ArrayList arraylist = new ArrayList();
if (s.startsWith("/")) {
s = s.substring(1);
boolean flag = !s.contains(" ");
List list = this.o.b(icommandlistener, s);
if (list != null) {
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
String s1 = (String) iterator.next();
if (flag) {
arraylist.add("/" + s1);
} else {
arraylist.add(s1);
}
}
}
return arraylist;
} else {
String[] astring = s.split(" ", -1);
String s2 = astring[astring.length - 1];
String[] astring1 = this.u.f();
int i = astring1.length;
for (int j = 0; j < i; ++j) {
String s3 = astring1[j];
if (CommandAbstract.a(s2, s3)) {
arraylist.add(s3);
}
}
return arraylist;
}
*/
return this.server.tabComplete(icommandlistener, s);
// CraftBukkit end
}
public static MinecraftServer getServer() {
return j;
}
public String getName() {
return "Server";
}
public void sendMessage(IChatBaseComponent ichatbasecomponent) {
i.info(ichatbasecomponent.c());
}
public boolean a(int i, String s) {
return true;
}
public ICommandHandler getCommandHandler() {
return this.o;
}
public KeyPair K() {
return this.G;
}
public int L() {
return this.t;
}
public void setPort(int i) {
this.t = i;
}
public String M() {
return this.H;
}
public void j(String s) {
this.H = s;
}
public boolean N() {
return this.H != null;
}
public String O() {
return this.I;
}
public void k(String s) {
this.I = s;
}
public void a(KeyPair keypair) {
this.G = keypair;
}
public void a(EnumDifficulty enumdifficulty) {
// CraftBukkit start - Use worlds list for iteration
for (int j = 0; j < this.worlds.size(); ++j) {
WorldServer worldserver = this.worlds.get(j);
// CraftBukkit end
if (worldserver != null) {
if (worldserver.getWorldData().isHardcore()) {
worldserver.difficulty = EnumDifficulty.HARD;
worldserver.setSpawnFlags(true, true);
} else if (this.N()) {
worldserver.difficulty = enumdifficulty;
worldserver.setSpawnFlags(worldserver.difficulty != EnumDifficulty.PEACEFUL, true);
} else {
worldserver.difficulty = enumdifficulty;
worldserver.setSpawnFlags(this.getSpawnMonsters(), this.spawnAnimals);
}
}
}
}
protected boolean getSpawnMonsters() {
return true;
}
public boolean R() {
return this.demoMode;
}
public void b(boolean flag) {
this.demoMode = flag;
}
public void c(boolean flag) {
this.L = flag;
}
public Convertable getConvertable() {
return this.convertable;
}
public void U() {
this.M = true;
this.getConvertable().d();
// CraftBukkit start
for (int i = 0; i < this.worlds.size(); ++i) {
WorldServer worldserver = this.worlds.get(i);
// CraftBukkit end
if (worldserver != null) {
worldserver.saveLevel();
}
}
this.getConvertable().e(this.worlds.get(0).getDataManager().g()); // CraftBukkit
this.safeShutdown();
}
public String getResourcePack() {
return this.N;
}
public void setTexturePack(String s) {
this.N = s;
}
public void a(MojangStatisticsGenerator mojangstatisticsgenerator) {
mojangstatisticsgenerator.a("whitelist_enabled", Boolean.valueOf(false));
mojangstatisticsgenerator.a("whitelist_count", Integer.valueOf(0));
mojangstatisticsgenerator.a("players_current", Integer.valueOf(this.C()));
mojangstatisticsgenerator.a("players_max", Integer.valueOf(this.D()));
mojangstatisticsgenerator.a("players_seen", Integer.valueOf(this.u.getSeenPlayers().length));
mojangstatisticsgenerator.a("uses_auth", Boolean.valueOf(this.onlineMode));
mojangstatisticsgenerator.a("gui_state", this.ak() ? "enabled" : "disabled");
mojangstatisticsgenerator.a("run_time", Long.valueOf((ar() - mojangstatisticsgenerator.g()) / 60L * 1000L));
mojangstatisticsgenerator.a("avg_tick_ms", Integer.valueOf((int) (MathHelper.a(this.g) * 1.0E-6D)));
int i = 0;
// CraftBukkit start - use worlds list for iteration
for (int j = 0; j < this.worlds.size(); ++j) {
WorldServer worldserver = this.worlds.get(j);
if (worldServer != null) {
// CraftBukkit end
WorldData worlddata = worldserver.getWorldData();
mojangstatisticsgenerator.a("world[" + i + "][dimension]", Integer.valueOf(worldserver.worldProvider.dimension));
mojangstatisticsgenerator.a("world[" + i + "][mode]", worlddata.getGameType());
mojangstatisticsgenerator.a("world[" + i + "][difficulty]", worldserver.difficulty);
mojangstatisticsgenerator.a("world[" + i + "][hardcore]", Boolean.valueOf(worlddata.isHardcore()));
mojangstatisticsgenerator.a("world[" + i + "][generator_name]", worlddata.getType().name());
mojangstatisticsgenerator.a("world[" + i + "][generator_version]", Integer.valueOf(worlddata.getType().getVersion()));
mojangstatisticsgenerator.a("world[" + i + "][height]", Integer.valueOf(this.E));
mojangstatisticsgenerator.a("world[" + i + "][chunks_loaded]", Integer.valueOf(worldserver.L().getLoadedChunks()));
++i;
}
}
mojangstatisticsgenerator.a("worlds", Integer.valueOf(i));
}
public void b(MojangStatisticsGenerator mojangstatisticsgenerator) {
mojangstatisticsgenerator.b("singleplayer", Boolean.valueOf(this.N()));
mojangstatisticsgenerator.b("server_brand", this.getServerModName());
mojangstatisticsgenerator.b("gui_supported", GraphicsEnvironment.isHeadless() ? "headless" : "supported");
mojangstatisticsgenerator.b("dedicated", Boolean.valueOf(this.X()));
}
public boolean getSnooperEnabled() {
return true;
}
public abstract boolean X();
public boolean getOnlineMode() {
return this.server.getOnlineMode(); // CraftBukkit
}
public void setOnlineMode(boolean flag) {
this.onlineMode = flag;
}
public boolean getSpawnAnimals() {
return this.spawnAnimals;
}
public void setSpawnAnimals(boolean flag) {
this.spawnAnimals = flag;
}
public boolean getSpawnNPCs() {
return this.spawnNPCs;
}
public void setSpawnNPCs(boolean flag) {
this.spawnNPCs = flag;
}
public boolean getPvP() {
return this.pvpMode;
}
public void setPvP(boolean flag) {
this.pvpMode = flag;
}
public boolean getAllowFlight() {
return this.allowFlight;
}
public void setAllowFlight(boolean flag) {
this.allowFlight = flag;
}
public abstract boolean getEnableCommandBlock();
public String getMotd() {
return this.motd;
}
public void setMotd(String s) {
this.motd = s;
}
public int getMaxBuildHeight() {
return this.E;
}
public void c(int i) {
this.E = i;
}
public boolean isStopped() {
return this.isStopped;
}
public PlayerList getPlayerList() {
return this.u;
}
public void a(PlayerList playerlist) {
this.u = playerlist;
}
public void a(EnumGamemode enumgamemode) {
// CraftBukkit start - use worlds list for iteration
for (int i = 0; i < this.worlds.size(); ++i) {
getServer().worlds.get(i).getWorldData().setGameType(enumgamemode);
// CraftBukkit end
}
}
public ServerConnection ai() {
return this.p;
}
public boolean ak() {
return false;
}
public abstract String a(EnumGamemode enumgamemode, boolean flag);
public int al() {
return this.ticks;
}
public void am() {
this.R = true;
}
public ChunkCoordinates getChunkCoordinates() {
return new ChunkCoordinates(0, 0, 0);
}
public World getWorld() {
return this.worlds.get(0); // CraftBukkit
}
public int getSpawnProtection() {
return 16;
}
public boolean a(World world, int i, int j, int k, EntityHuman entityhuman) {
return false;
}
public void setForceGamemode(boolean flag) {
this.S = flag;
}
public boolean getForceGamemode() {
return this.S;
}
public Proxy aq() {
return this.d;
}
public static long ar() {
return System.currentTimeMillis();
}
public int getIdleTimeout() {
return this.F;
}
public void setIdleTimeout(int i) {
this.F = i;
}
public IChatBaseComponent getScoreboardDisplayName() {
return new ChatComponentText(this.getName());
}
public boolean at() {
return true;
}
public MinecraftSessionService av() {
return this.U;
}
public GameProfileRepository getGameProfileRepository() {
return this.W;
}
public UserCache getUserCache() {
return this.X;
}
public ServerPing ay() {
return this.q;
}
public void az() {
this.V = 0L;
}
public static Logger getLogger() {
return i;
}
public static PlayerList a(MinecraftServer minecraftserver) {
return minecraftserver.u;
}
}
| OvercastNetwork/CraftBukkit | src/main/java/net/minecraft/server/MinecraftServer.java | Java | gpl-3.0 | 44,601 |
<?php
require('header.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
if(\GO\Base\Html\Error::checkRequired())
redirect("configFile.php");
}
printHead();
?>
<h1>License terms</h1>
<p>The following license applies to this product:</p>
<div class="cmd">
<?php
echo \GO\Base\Util\StringHelper::text_to_html(file_get_contents('../LICENSE.TXT'));
?>
</div>
<?php
\GO\Base\Html\Checkbox::render(array(
'required'=>true,
'name'=>'agree',
'value'=>1,
'label'=>'I agree to the terms of the above license.'
));
continueButton();
printFoot(); | deependhulla/powermail-debian9 | files/rootdir/usr/local/src/groupoffice-6.2/groupoffice-6.2-setup-www/install_disabled/license.php | PHP | gpl-3.0 | 548 |
__version__ = '0.17'
| etherkit/OpenBeacon2 | macos/venv/lib/python3.8/site-packages/PyInstaller/lib/modulegraph/__init__.py | Python | gpl-3.0 | 21 |
#!/usr/bin/python
#
# (c) 2015 Peter Sprygada, <psprygada@ansible.com>
# Copyright (c) 2017 Dell Inc.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: dellos10_command
version_added: "2.2"
author: "Senthil Kumar Ganesan (@skg-net)"
short_description: Run commands on remote devices running Dell OS10
description:
- Sends arbitrary commands to a Dell OS10 node and returns the results
read from the device. This module includes an
argument that will cause the module to wait for a specific condition
before returning or timing out if the condition is not met.
- This module does not support running commands in configuration mode.
Please use M(dellos10_config) to configure Dell OS10 devices.
extends_documentation_fragment: dellos10
options:
commands:
description:
- List of commands to send to the remote dellos10 device over the
configured provider. The resulting output from the command
is returned. If the I(wait_for) argument is provided, the
module is not returned until the condition is satisfied or
the number of retries has expired.
required: true
wait_for:
description:
- List of conditions to evaluate against the output of the
command. The task will wait for each condition to be true
before moving forward. If the conditional is not true
within the configured number of I(retries), the task fails.
See examples.
required: false
default: null
retries:
description:
- Specifies the number of retries a command should by tried
before it is considered failed. The command is run on the
target device every retry and evaluated against the
I(wait_for) conditions.
required: false
default: 10
interval:
description:
- Configures the interval in seconds to wait between retries
of the command. If the command does not pass the specified
conditions, the interval indicates how long to wait before
trying the command again.
required: false
default: 1
"""
EXAMPLES = """
# Note: examples below use the following provider dict to handle
# transport and authentication to the node.
vars:
cli:
host: "{{ inventory_hostname }}"
username: admin
password: admin
transport: cli
tasks:
- name: run show version on remote devices
dellos10_command:
commands: show version
provider: "{{ cli }}"
- name: run show version and check to see if output contains OS10
dellos10_command:
commands: show version
wait_for: result[0] contains OS10
provider: "{{ cli }}"
- name: run multiple commands on remote nodes
dellos10_command:
commands:
- show version
- show interface
provider: "{{ cli }}"
- name: run multiple commands and evaluate the output
dellos10_command:
commands:
- show version
- show interface
wait_for:
- result[0] contains OS10
- result[1] contains Ethernet
provider: "{{ cli }}"
"""
RETURN = """
stdout:
description: The set of responses from the commands
returned: always apart from low level errors (such as action plugin)
type: list
sample: ['...', '...']
stdout_lines:
description: The value of stdout split into a list
returned: always apart from low level errors (such as action plugin)
type: list
sample: [['...', '...'], ['...'], ['...']]
failed_conditions:
description: The list of conditionals that have failed
returned: failed
type: list
sample: ['...', '...']
warnings:
description: The list of warnings (if any) generated by module based on arguments
returned: always
type: list
sample: ['...', '...']
"""
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.dellos10.dellos10 import run_commands
from ansible.module_utils.network.dellos10.dellos10 import dellos10_argument_spec, check_args
from ansible.module_utils.network.common.utils import ComplexList
from ansible.module_utils.network.common.parsing import Conditional
from ansible.module_utils.six import string_types
def to_lines(stdout):
for item in stdout:
if isinstance(item, string_types):
item = str(item).split('\n')
yield item
def parse_commands(module, warnings):
command = ComplexList(dict(
command=dict(key=True),
prompt=dict(),
answer=dict()
), module)
commands = command(module.params['commands'])
for index, item in enumerate(commands):
if module.check_mode and not item['command'].startswith('show'):
warnings.append(
'only show commands are supported when using check mode, not '
'executing `%s`' % item['command']
)
elif item['command'].startswith('conf'):
module.fail_json(
msg='dellos10_command does not support running config mode '
'commands. Please use dellos10_config instead'
)
return commands
def main():
"""main entry point for module execution
"""
argument_spec = dict(
# { command: <str>, prompt: <str>, response: <str> }
commands=dict(type='list', required=True),
wait_for=dict(type='list'),
match=dict(default='all', choices=['all', 'any']),
retries=dict(default=10, type='int'),
interval=dict(default=1, type='int')
)
argument_spec.update(dellos10_argument_spec)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
result = {'changed': False}
warnings = list()
check_args(module, warnings)
commands = parse_commands(module, warnings)
result['warnings'] = warnings
wait_for = module.params['wait_for'] or list()
conditionals = [Conditional(c) for c in wait_for]
retries = module.params['retries']
interval = module.params['interval']
match = module.params['match']
while retries > 0:
responses = run_commands(module, commands)
for item in list(conditionals):
if item(responses):
if match == 'any':
conditionals = list()
break
conditionals.remove(item)
if not conditionals:
break
time.sleep(interval)
retries -= 1
if conditionals:
failed_conditions = [item.raw for item in conditionals]
msg = 'One or more conditional statements have not be satisfied'
module.fail_json(msg=msg, failed_conditions=failed_conditions)
result = {
'changed': False,
'stdout': responses,
'stdout_lines': list(to_lines(responses))
}
module.exit_json(**result)
if __name__ == '__main__':
main()
| haad/ansible | lib/ansible/modules/network/dellos10/dellos10_command.py | Python | gpl-3.0 | 7,132 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Event observers used in forum.
*
* @package mod_forum
* @copyright 2013 Rajesh Taneja <rajesh@moodle.com>
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* Event observer for mod_forum.
*/
class mod_forum_observer {
/**
* Triggered via user_enrolment_deleted event.
*
* @param \core\event\user_enrolment_deleted $event
*/
public static function user_enrolment_deleted(\core\event\user_enrolment_deleted $event) {
global $DB;
// NOTE: this has to be as fast as possible.
// Get user enrolment info from event.
$cp = (object)$event->other['userenrolment'];
if ($cp->lastenrol) {
$params = array('userid' => $cp->userid, 'courseid' => $cp->courseid);
$forumselect = "IN (SELECT f.id FROM {forum} f WHERE f.course = :courseid)";
$DB->delete_records_select('forum_digests', 'userid = :userid AND forum '.$forumselect, $params);
$DB->delete_records_select('forum_subscriptions', 'userid = :userid AND forum '.$forumselect, $params);
$DB->delete_records_select('forum_track_prefs', 'userid = :userid AND forumid '.$forumselect, $params);
$DB->delete_records_select('forum_read', 'userid = :userid AND forumid '.$forumselect, $params);
}
}
/**
* Observer for role_assigned event.
*
* @param \core\event\role_assigned $event
* @return void
*/
public static function role_assigned(\core\event\role_assigned $event) {
global $CFG, $DB;
$context = context::instance_by_id($event->contextid, MUST_EXIST);
// If contextlevel is course then only subscribe user. Role assignment
// at course level means user is enroled in course and can subscribe to forum.
if ($context->contextlevel != CONTEXT_COURSE) {
return;
}
// Forum lib required for the constant used below.
require_once($CFG->dirroot . '/mod/forum/lib.php');
$userid = $event->relateduserid;
$sql = "SELECT f.id, cm.id AS cmid, f.forcesubscribe
FROM {forum} f
JOIN {course_modules} cm ON (cm.instance = f.id)
JOIN {modules} m ON (m.id = cm.module)
LEFT JOIN {forum_subscriptions} fs ON (fs.forum = f.id AND fs.userid = :userid)
WHERE f.course = :courseid
AND f.forcesubscribe = :initial
AND m.name = 'forum'
AND fs.id IS NULL";
$params = array('courseid' => $context->instanceid, 'userid' => $userid, 'initial' => FORUM_INITIALSUBSCRIBE);
$forums = $DB->get_records_sql($sql, $params);
foreach ($forums as $forum) {
// If user doesn't have allowforcesubscribe capability then don't subscribe.
$modcontext = context_module::instance($forum->cmid);
if (has_capability('mod/forum:allowforcesubscribe', $modcontext, $userid)) {
\mod_forum\subscriptions::subscribe_user($userid, $forum, $modcontext);
}
}
}
/**
* Observer for \core\event\course_module_created event.
*
* @param \core\event\course_module_created $event
* @return void
*/
public static function course_module_created(\core\event\course_module_created $event) {
global $CFG;
if ($event->other['modulename'] === 'forum') {
// Include the forum library to make use of the forum_instance_created function.
require_once($CFG->dirroot . '/mod/forum/lib.php');
$forum = $event->get_record_snapshot('forum', $event->other['instanceid']);
forum_instance_created($event->get_context(), $forum);
}
}
}
| Jinelle/moodle | mod/forum/classes/observer.php | PHP | gpl-3.0 | 4,511 |
<?php
/**
* base include file for eclipse plugin
* @package SimpleTest
* @subpackage Eclipse
* @version $Id: eclipse.php,v 1.5 2012/04/06 12:15:43 moodlerobot Exp $
*/
/**#@+
* simpletest include files
*/
include_once 'unit_tester.php';
include_once 'test_case.php';
include_once 'invoker.php';
include_once 'socket.php';
include_once 'mock_objects.php';
/**#@-*/
/**
* base reported class for eclipse plugin
* @package SimpleTest
* @subpackage Eclipse
*/
class EclipseReporter extends SimpleScorer {
/**
* Reporter to be run inside of Eclipse interface.
* @param object $listener Eclipse listener (?).
* @param boolean $cc Whether to include test coverage.
*/
function __construct(&$listener, $cc=false){
$this->listener = &$listener;
$this->SimpleScorer();
$this->case = "";
$this->group = "";
$this->method = "";
$this->cc = $cc;
$this->error = false;
$this->fail = false;
}
/**
* Means to display human readable object comparisons.
* @return SimpleDumper Visual comparer.
*/
function getDumper() {
return new SimpleDumper();
}
/**
* Localhost connection from Eclipse.
* @param integer $port Port to connect to Eclipse.
* @param string $host Normally localhost.
* @return SimpleSocket Connection to Eclipse.
*/
function &createListener($port, $host="127.0.0.1"){
$tmplistener = &new SimpleSocket($host, $port, 5);
return $tmplistener;
}
/**
* Wraps the test in an output buffer.
* @param SimpleInvoker $invoker Current test runner.
* @return EclipseInvoker Decorator with output buffering.
* @access public
*/
function &createInvoker(&$invoker){
$eclinvoker = &new EclipseInvoker($invoker, $this->listener);
return $eclinvoker;
}
/**
* C style escaping.
* @param string $raw String with backslashes, quotes and whitespace.
* @return string Replaced with C backslashed tokens.
*/
function escapeVal($raw){
$needle = array("\\","\"","/","\b","\f","\n","\r","\t");
$replace = array('\\\\','\"','\/','\b','\f','\n','\r','\t');
return str_replace($needle, $replace, $raw);
}
/**
* Stash the first passing item. Clicking the test
* item goes to first pass.
* @param string $message Test message, but we only wnat the first.
* @access public
*/
function paintPass($message){
if (! $this->pass){
$this->message = $this->escapeVal($message);
}
$this->pass = true;
}
/**
* Stash the first failing item. Clicking the test
* item goes to first fail.
* @param string $message Test message, but we only wnat the first.
* @access public
*/
function paintFail($message){
//only get the first failure or error
if (! $this->fail && ! $this->error){
$this->fail = true;
$this->message = $this->escapeVal($message);
$this->listener->write('{status:"fail",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}');
}
}
/**
* Stash the first error. Clicking the test
* item goes to first error.
* @param string $message Test message, but we only wnat the first.
* @access public
*/
function paintError($message){
if (! $this->fail && ! $this->error){
$this->error = true;
$this->message = $this->escapeVal($message);
$this->listener->write('{status:"error",message:"'.$this->message.'",group:"'.$this->group.'",case:"'.$this->case.'",method:"'.$this->method.'"}');
}
}
/**
* Stash the first exception. Clicking the test
* item goes to first message.
* @param string $message Test message, but we only wnat the first.
* @access public
*/
function paintException($exception){
if (! $this->fail && ! $this->error){
$this->error = true;
$message = 'Unexpected exception of type[' . get_class($exception) .
'] with message [' . $exception->getMessage() . '] in [' .
$exception->getFile() .' line '. $exception->getLine() . ']';
$this->message = $this->escapeVal($message);
$this->listener->write(
'{status:"error",message:"' . $this->message . '",group:"' .
$this->group . '",case:"' . $this->case . '",method:"' . $this->method
. '"}');
}
}
/**
* We don't display any special header.
* @param string $test_name First test top level
* to start.
* @access public
*/
function paintHeader($test_name) {
}
/**
* We don't display any special footer.
* @param string $test_name The top level test.
* @access public
*/
function paintFooter($test_name) {
}
/**
* Paints nothing at the start of a test method, but stash
* the method name for later.
* @param string $test_name Name of test that is starting.
* @access public
*/
function paintMethodStart($method) {
$this->pass = false;
$this->fail = false;
$this->error = false;
$this->method = $this->escapeVal($method);
}
/**
* Only send one message if the test passes, after that
* suppress the message.
* @param string $test_name Name of test that is ending.
* @access public
*/
function paintMethodEnd($method){
if ($this->fail || $this->error || ! $this->pass){
} else {
$this->listener->write(
'{status:"pass",message:"' . $this->message . '",group:"' .
$this->group . '",case:"' . $this->case . '",method:"' .
$this->method . '"}');
}
}
/**
* Stashes the test case name for the later failure message.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintCaseStart($case){
$this->case = $this->escapeVal($case);
}
/**
* Drops the name.
* @param string $test_name Name of test or other label.
* @access public
*/
function paintCaseEnd($case){
$this->case = "";
}
/**
* Stashes the name of the test suite. Starts test coverage
* if enabled.
* @param string $group Name of test or other label.
* @param integer $size Number of test cases starting.
* @access public
*/
function paintGroupStart($group, $size){
$this->group = $this->escapeVal($group);
if ($this->cc){
if (extension_loaded('xdebug')){
xdebug_start_code_coverage(XDEBUG_CC_UNUSED | XDEBUG_CC_DEAD_CODE);
}
}
}
/**
* Paints coverage report if enabled.
* @param string $group Name of test or other label.
* @access public
*/
function paintGroupEnd($group){
$this->group = "";
$cc = "";
if ($this->cc){
if (extension_loaded('xdebug')){
$arrfiles = xdebug_get_code_coverage();
xdebug_stop_code_coverage();
$thisdir = dirname(__FILE__);
$thisdirlen = strlen($thisdir);
foreach ($arrfiles as $index=>$file){
if (substr($index, 0, $thisdirlen)===$thisdir){
continue;
}
$lcnt = 0;
$ccnt = 0;
foreach ($file as $line){
if ($line == -2){
continue;
}
$lcnt++;
if ($line==1){
$ccnt++;
}
}
if ($lcnt > 0){
$cc .= round(($ccnt/$lcnt) * 100, 2) . '%';
}else{
$cc .= "0.00%";
}
$cc.= "\t". $index . "\n";
}
}
}
$this->listener->write('{status:"coverage",message:"' .
EclipseReporter::escapeVal($cc) . '"}');
}
}
/**
* Invoker decorator for Eclipse. Captures output until
* the end of the test.
* @package SimpleTest
* @subpackage Eclipse
*/
class EclipseInvoker extends SimpleInvokerDecorator{
function __construct(&$invoker, &$listener) {
$this->listener = &$listener;
$this->SimpleInvokerDecorator($invoker);
}
/**
* Starts output buffering.
* @param string $method Test method to call.
* @access public
*/
function before($method){
ob_start();
$this->invoker->before($method);
}
/**
* Stops output buffering and send the captured output
* to the listener.
* @param string $method Test method to call.
* @access public
*/
function after($method) {
$this->invoker->after($method);
$output = ob_get_contents();
ob_end_clean();
if ($output !== ""){
$result = $this->listener->write('{status:"info",message:"' .
EclipseReporter::escapeVal($output) . '"}');
}
}
}
?> | erkartik91/Moodle-feature-34445 | lib/simpletestlib/eclipse.php | PHP | gpl-3.0 | 9,822 |
<?php
/* Copyright (C) 2016 Laurent Destailleur <eldy@users.sourceforge.net>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 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/>.
*/
/**
* \file htdocs/fichinter/stats/index.php
* \ingroup fichinter
* \brief Page with interventions statistics
*/
require '../../main.inc.php';
require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinter.class.php';
require_once DOL_DOCUMENT_ROOT.'/fichinter/class/fichinterstats.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/dolgraph.class.php';
$WIDTH=DolGraph::getDefaultGraphSizeForStats('width');
$HEIGHT=DolGraph::getDefaultGraphSizeForStats('height');
$mode='customer';
if ($mode == 'customer' && ! $user->rights->ficheinter->lire) accessforbidden();
$userid=GETPOST('userid','int');
$socid=GETPOST('socid','int');
// Security check
if ($user->societe_id > 0)
{
$action = '';
$socid = $user->societe_id;
}
$nowyear=strftime("%Y", dol_now());
$year = GETPOST('year')>0?GETPOST('year'):$nowyear;
//$startyear=$year-2;
$startyear=$year-1;
$endyear=$year;
$object_status=GETPOST('object_status');
$langs->load('interventions');
$langs->load('companies');
$langs->load('other');
$langs->load('suppliers');
/*
* View
*/
$form=new Form($db);
$objectstatic=new FichInter($db);
if ($mode == 'customer')
{
$title=$langs->trans("InterventionStatistics");
$dir=$conf->ficheinter->dir_temp;
}
llxHeader('', $title);
print load_fiche_titre($title,'','title_commercial.png');
dol_mkdir($dir);
$stats = new FichinterStats($db, $socid, $mode, ($userid>0?$userid:0));
if ($object_status != '' && $object_status > -1) $stats->where .= ' AND c.fk_statut IN ('.$db->escape($object_status).')';
// Build graphic number of object
$data = $stats->getNbByMonthWithPrevYear($endyear,$startyear);
//var_dump($data);
// $data = array(array('Lib',val1,val2,val3),...)
if (!$user->rights->societe->client->voir || $user->societe_id)
{
$filenamenb = $dir.'/interventionsnbinyear-'.$user->id.'-'.$year.'.png';
if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$user->id.'-'.$year.'.png';
}
else
{
$filenamenb = $dir.'/interventionsnbinyear-'.$year.'.png';
if ($mode == 'customer') $fileurlnb = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsnbinyear-'.$year.'.png';
}
$px1 = new DolGraph();
$mesg = $px1->isGraphKo();
if (! $mesg)
{
$px1->SetData($data);
$px1->SetPrecisionY(0);
$i=$startyear;$legend=array();
while ($i <= $endyear)
{
$legend[]=$i;
$i++;
}
$px1->SetLegend($legend);
$px1->SetMaxValue($px1->GetCeilMaxValue());
$px1->SetMinValue(min(0,$px1->GetFloorMinValue()));
$px1->SetWidth($WIDTH);
$px1->SetHeight($HEIGHT);
$px1->SetYLabel($langs->trans("NbOfIntervention"));
$px1->SetShading(3);
$px1->SetHorizTickIncrement(1);
$px1->SetPrecisionY(0);
$px1->mode='depth';
$px1->SetTitle($langs->trans("NumberOfInterventionsByMonth"));
$px1->draw($filenamenb,$fileurlnb);
}
// Build graphic amount of object
$data = $stats->getAmountByMonthWithPrevYear($endyear,$startyear);
//var_dump($data);
// $data = array(array('Lib',val1,val2,val3),...)
if (!$user->rights->societe->client->voir || $user->societe_id)
{
$filenameamount = $dir.'/interventionsamountinyear-'.$user->id.'-'.$year.'.png';
if ($mode == 'customer') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$user->id.'-'.$year.'.png';
if ($mode == 'supplier') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstatssupplier&file=interventionsamountinyear-'.$user->id.'-'.$year.'.png';
}
else
{
$filenameamount = $dir.'/interventionsamountinyear-'.$year.'.png';
if ($mode == 'customer') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsamountinyear-'.$year.'.png';
if ($mode == 'supplier') $fileurlamount = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstatssupplier&file=interventionsamountinyear-'.$year.'.png';
}
$px2 = new DolGraph();
$mesg = $px2->isGraphKo();
if (! $mesg)
{
$px2->SetData($data);
$i=$startyear;$legend=array();
while ($i <= $endyear)
{
$legend[]=$i;
$i++;
}
$px2->SetLegend($legend);
$px2->SetMaxValue($px2->GetCeilMaxValue());
$px2->SetMinValue(min(0,$px2->GetFloorMinValue()));
$px2->SetWidth($WIDTH);
$px2->SetHeight($HEIGHT);
$px2->SetYLabel($langs->trans("AmountOfinterventions"));
$px2->SetShading(3);
$px2->SetHorizTickIncrement(1);
$px2->SetPrecisionY(0);
$px2->mode='depth';
$px2->SetTitle($langs->trans("AmountOfinterventionsByMonthHT"));
$px2->draw($filenameamount,$fileurlamount);
}
$data = $stats->getAverageByMonthWithPrevYear($endyear, $startyear);
if (!$user->rights->societe->client->voir || $user->societe_id)
{
$filename_avg = $dir.'/interventionsaverage-'.$user->id.'-'.$year.'.png';
if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$user->id.'-'.$year.'.png';
if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstatssupplier&file=interventionsaverage-'.$user->id.'-'.$year.'.png';
}
else
{
$filename_avg = $dir.'/interventionsaverage-'.$year.'.png';
if ($mode == 'customer') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstats&file=interventionsaverage-'.$year.'.png';
if ($mode == 'supplier') $fileurl_avg = DOL_URL_ROOT.'/viewimage.php?modulepart=interventionstatssupplier&file=interventionsaverage-'.$year.'.png';
}
$px3 = new DolGraph();
$mesg = $px3->isGraphKo();
if (! $mesg)
{
$px3->SetData($data);
$i=$startyear;$legend=array();
while ($i <= $endyear)
{
$legend[]=$i;
$i++;
}
$px3->SetLegend($legend);
$px3->SetYLabel($langs->trans("AmountAverage"));
$px3->SetMaxValue($px3->GetCeilMaxValue());
$px3->SetMinValue($px3->GetFloorMinValue());
$px3->SetWidth($WIDTH);
$px3->SetHeight($HEIGHT);
$px3->SetShading(3);
$px3->SetHorizTickIncrement(1);
$px3->SetPrecisionY(0);
$px3->mode='depth';
$px3->SetTitle($langs->trans("AmountAverage"));
$px3->draw($filename_avg,$fileurl_avg);
}
// Show array
$data = $stats->getAllByYear();
$arrayyears=array();
foreach($data as $val) {
if (! empty($val['year'])) {
$arrayyears[$val['year']]=$val['year'];
}
}
if (! count($arrayyears)) $arrayyears[$nowyear]=$nowyear;
$h=0;
$head = array();
$head[$h][0] = DOL_URL_ROOT . '/commande/stats/index.php?mode='.$mode;
$head[$h][1] = $langs->trans("ByMonthYear");
$head[$h][2] = 'byyear';
$h++;
if ($mode == 'customer') $type='order_stats';
if ($mode == 'supplier') $type='supplier_order_stats';
complete_head_from_modules($conf,$langs,null,$head,$h,$type);
dol_fiche_head($head, 'byyear', $langs->trans("Statistics"), -1);
print '<div class="fichecenter"><div class="fichethirdleft">';
//if (empty($socid))
//{
// Show filter box
print '<form name="stats" method="POST" action="'.$_SERVER["PHP_SELF"].'">';
print '<input type="hidden" name="mode" value="'.$mode.'">';
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre"><td class="liste_titre" colspan="2">'.$langs->trans("Filter").'</td></tr>';
// Company
print '<tr><td align="left">'.$langs->trans("ThirdParty").'</td><td align="left">';
if ($mode == 'customer') $filter='s.client in (1,2,3)';
if ($mode == 'supplier') $filter='s.fournisseur = 1';
print $form->select_company($socid,'socid',$filter,1,0,0,array(),0,'','style="width: 95%"');
print '</td></tr>';
// User
print '<tr><td align="left">'.$langs->trans("CreatedBy").'</td><td align="left">';
print $form->select_dolusers($userid, 'userid', 1, '', 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth300');
// Status
print '<tr><td align="left">'.$langs->trans("Status").'</td><td align="left">';
$liststatus=$objectstatic->statuts_short;
if (empty($conf->global->FICHINTER_CLASSIFY_BILLED)) unset($liststatus[2]); // Option deprecated. In a future, billed must be managed with a dedicated field to 0 or 1
print $form->selectarray('object_status', $liststatus, $object_status, 1, 0, 0, '', 1);
print '</td></tr>';
// Year
print '<tr><td align="left">'.$langs->trans("Year").'</td><td align="left">';
if (! in_array($year,$arrayyears)) $arrayyears[$year]=$year;
if (! in_array($nowyear,$arrayyears)) $arrayyears[$nowyear]=$nowyear;
arsort($arrayyears);
print $form->selectarray('year',$arrayyears,$year,0);
print '</td></tr>';
print '<tr><td align="center" colspan="2"><input type="submit" name="submit" class="button" value="'.$langs->trans("Refresh").'"></td></tr>';
print '</table>';
print '</form>';
print '<br><br>';
//}
print '<table class="noborder" width="100%">';
print '<tr class="liste_titre" height="24">';
print '<td align="center">'.$langs->trans("Year").'</td>';
print '<td align="right">'.$langs->trans("NbOfinterventions").'</td>';
print '<td align="right">%</td>';
print '<td align="right">'.$langs->trans("AmountTotal").'</td>';
print '<td align="right">%</td>';
print '<td align="right">'.$langs->trans("AmountAverage").'</td>';
print '<td align="right">%</td>';
print '</tr>';
$oldyear=0;
$var=true;
foreach ($data as $val)
{
$year = $val['year'];
while (! empty($year) && $oldyear > $year+1)
{ // If we have empty year
$oldyear--;
print '<tr '.$bc[$var].' height="24">';
print '<td align="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$oldyear.'&mode='.$mode.($socid>0?'&socid='.$socid:'').($userid>0?'&userid='.$userid:'').'">'.$oldyear.'</a></td>';
print '<td align="right">0</td>';
print '<td align="right"></td>';
print '<td align="right">0</td>';
print '<td align="right"></td>';
print '<td align="right">0</td>';
print '<td align="right"></td>';
print '</tr>';
}
print '<tr '.$bc[$var].' height="24">';
print '<td align="center"><a href="'.$_SERVER["PHP_SELF"].'?year='.$year.'&mode='.$mode.($socid>0?'&socid='.$socid:'').($userid>0?'&userid='.$userid:'').'">'.$year.'</a></td>';
print '<td align="right">'.$val['nb'].'</td>';
print '<td align="right" style="'.(($val['nb_diff'] >= 0) ? 'color: green;':'color: red;').'">'.round($val['nb_diff']).'</td>';
print '<td align="right">'.price(price2num($val['total'],'MT'),1).'</td>';
print '<td align="right" style="'.(($val['total_diff'] >= 0) ? 'color: green;':'color: red;').'">'.round($val['total_diff']).'</td>';
print '<td align="right">'.price(price2num($val['avg'],'MT'),1).'</td>';
print '<td align="right" style="'.(($val['avg_diff'] >= 0) ? 'color: green;':'color: red;').'">'.round($val['avg_diff']).'</td>';
print '</tr>';
$oldyear=$year;
}
print '</table>';
print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
// Show graphs
print '<table class="border" width="100%"><tr valign="top"><td align="center">';
if ($mesg) { print $mesg; }
else {
print $px1->show();
/*print "<br>\n";
print $px2->show();
print "<br>\n";
print $px3->show();*/
}
print '</td></tr></table>';
print '</div></div></div>';
print '<div style="clear:both"></div>';
dol_fiche_end();
llxFooter();
$db->close();
| guerrierk/dolibarr | htdocs/fichinter/stats/index.php | PHP | gpl-3.0 | 11,914 |
<?php
class ParserFunctionsHooks {
/**
* Enable string functions, when running Wikimedia Jenkins unit tests.
*
* Running Jenkins unit tests without setting $wgPFEnableStringFunctions = true;
* will cause all the parser tests for string functions to be skipped.
*/
public static function onRegistration() {
if ( isset( $GLOBALS['wgWikimediaJenkinsCI'] ) && $GLOBALS['wgWikimediaJenkinsCI'] === true ) {
$GLOBALS['wgPFEnableStringFunctions'] = true;
}
}
/**
* @param $parser Parser
* @return bool
*/
public static function onParserFirstCallInit( $parser ) {
global $wgPFEnableStringFunctions;
// These functions accept DOM-style arguments
$parser->setFunctionHook( 'if', 'ExtParserFunctions::ifObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'ifeq', 'ExtParserFunctions::ifeqObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'switch', 'ExtParserFunctions::switchObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'ifexist', 'ExtParserFunctions::ifexistObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'ifexpr', 'ExtParserFunctions::ifexprObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'iferror', 'ExtParserFunctions::iferrorObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'time', 'ExtParserFunctions::timeObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'timel', 'ExtParserFunctions::localTimeObj', Parser::SFH_OBJECT_ARGS );
$parser->setFunctionHook( 'expr', 'ExtParserFunctions::expr' );
$parser->setFunctionHook( 'rel2abs', 'ExtParserFunctions::rel2abs' );
$parser->setFunctionHook( 'titleparts', 'ExtParserFunctions::titleparts' );
// String Functions
if ( $wgPFEnableStringFunctions ) {
$parser->setFunctionHook( 'len', 'ExtParserFunctions::runLen' );
$parser->setFunctionHook( 'pos', 'ExtParserFunctions::runPos' );
$parser->setFunctionHook( 'rpos', 'ExtParserFunctions::runRPos' );
$parser->setFunctionHook( 'sub', 'ExtParserFunctions::runSub' );
$parser->setFunctionHook( 'count', 'ExtParserFunctions::runCount' );
$parser->setFunctionHook( 'replace', 'ExtParserFunctions::runReplace' );
$parser->setFunctionHook( 'explode', 'ExtParserFunctions::runExplode' );
$parser->setFunctionHook( 'urldecode', 'ExtParserFunctions::runUrlDecode' );
}
return true;
}
/**
* @param $files array
* @return bool
*/
public static function onUnitTestsList( &$files ) {
$files[] = __DIR__ . '/tests/ExpressionTest.php';
return true;
}
public static function onScribuntoExternalLibraries( $engine, array &$extraLibraries ) {
if ( $engine === 'lua' ) {
$extraLibraries['mw.ext.ParserFunctions'] = 'Scribunto_LuaParserFunctionsLibrary';
}
return true;
}
}
| Facerafter/starcitizen-tools | extensions/ParserFunctions/ParserFunctions.hooks.php | PHP | gpl-3.0 | 2,793 |
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Boost.
*
* @package theme_boost
* @copyright 2016 Frédéric Massart
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
$plugin->version = 2019052000;
$plugin->requires = 2019051100;
$plugin->component = 'theme_boost';
| zeduardu/moodle | theme/boost/version.php | PHP | gpl-3.0 | 990 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 Google
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# ----------------------------------------------------------------------------
#
# *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
#
# ----------------------------------------------------------------------------
#
# This file is automatically generated by Magic Modules and manual
# changes will be clobbered when the file is regenerated.
#
# Please read more about how to change this file at
# https://www.github.com/GoogleCloudPlatform/magic-modules
#
# ----------------------------------------------------------------------------
from __future__ import absolute_import, division, print_function
__metaclass__ = type
################################################################################
# Documentation
################################################################################
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_cloudscheduler_job
description:
- A scheduled job that can publish a pubsub message or a http request every X interval
of time, using crontab format string.
- To use Cloud Scheduler your project must contain an App Engine app that is located
in one of the supported regions. If your project does not have an App Engine app,
you must create one.
short_description: Creates a GCP Job
version_added: 2.9
author: Google Inc. (@googlecloudplatform)
requirements:
- python >= 2.6
- requests >= 2.18.4
- google-auth >= 1.3.0
options:
state:
description:
- Whether the given object should exist in GCP
choices:
- present
- absent
default: present
type: str
name:
description:
- The name of the job.
required: true
type: str
description:
description:
- A human-readable description for the job. This string must not contain more
than 500 characters.
required: false
type: str
schedule:
description:
- Describes the schedule on which the job will be executed.
required: false
type: str
time_zone:
description:
- Specifies the time zone to be used in interpreting schedule.
- The value of this field must be a time zone name from the tz database.
required: false
default: Etc/UTC
type: str
retry_config:
description:
- By default, if a job does not complete successfully, meaning that an acknowledgement
is not received from the handler, then it will be retried with exponential backoff
according to the settings .
required: false
type: dict
suboptions:
retry_count:
description:
- The number of attempts that the system will make to run a job using the
exponential backoff procedure described by maxDoublings.
- Values greater than 5 and negative values are not allowed.
required: false
type: int
max_retry_duration:
description:
- The time limit for retrying a failed job, measured from time when an execution
was first attempted. If specified with retryCount, the job will be retried
until both limits are reached.
- A duration in seconds with up to nine fractional digits, terminated by 's'.
required: false
type: str
min_backoff_duration:
description:
- The minimum amount of time to wait before retrying a job after it fails.
- A duration in seconds with up to nine fractional digits, terminated by 's'.
required: false
type: str
max_backoff_duration:
description:
- The maximum amount of time to wait before retrying a job after it fails.
- A duration in seconds with up to nine fractional digits, terminated by 's'.
required: false
type: str
max_doublings:
description:
- The time between retries will double maxDoublings times.
- A job's retry interval starts at minBackoffDuration, then doubles maxDoublings
times, then increases linearly, and finally retries retries at intervals
of maxBackoffDuration up to retryCount times.
required: false
type: int
pubsub_target:
description:
- Pub/Sub target If the job providers a Pub/Sub target the cron will publish a
message to the provided topic .
required: false
type: dict
suboptions:
topic_name:
description:
- The name of the Cloud Pub/Sub topic to which messages will be published
when a job is delivered. The topic name must be in the same format as required
by PubSub's PublishRequest.name, for example projects/PROJECT_ID/topics/TOPIC_ID.
required: true
type: str
data:
description:
- The message payload for PubsubMessage.
- Pubsub message must contain either non-empty data, or at least one attribute.
required: false
type: str
attributes:
description:
- Attributes for PubsubMessage.
- Pubsub message must contain either non-empty data, or at least one attribute.
required: false
type: dict
app_engine_http_target:
description:
- App Engine HTTP target.
- If the job providers a App Engine HTTP target the cron will send a request to
the service instance .
required: false
type: dict
suboptions:
http_method:
description:
- Which HTTP method to use for the request.
required: false
type: str
app_engine_routing:
description:
- App Engine Routing setting for the job.
required: false
type: dict
suboptions:
service:
description:
- App service.
- By default, the job is sent to the service which is the default service
when the job is attempted.
required: false
type: str
version:
description:
- App version.
- By default, the job is sent to the version which is the default version
when the job is attempted.
required: false
type: str
instance:
description:
- App instance.
- By default, the job is sent to an instance which is available when the
job is attempted.
required: false
type: str
relative_uri:
description:
- The relative URI.
required: true
type: str
body:
description:
- HTTP request body. A request body is allowed only if the HTTP method is
POST or PUT. It will result in invalid argument error to set a body on a
job with an incompatible HttpMethod.
required: false
type: str
headers:
description:
- HTTP request headers.
- This map contains the header field names and values. Headers can be set
when the job is created.
required: false
type: dict
http_target:
description:
- HTTP target.
- If the job providers a http_target the cron will send a request to the targeted
url .
required: false
type: dict
suboptions:
uri:
description:
- The full URI path that the request will be sent to.
required: true
type: str
http_method:
description:
- Which HTTP method to use for the request.
required: false
type: str
body:
description:
- HTTP request body. A request body is allowed only if the HTTP method is
POST, PUT, or PATCH. It is an error to set body on a job with an incompatible
HttpMethod.
required: false
type: str
headers:
description:
- This map contains the header field names and values. Repeated headers are
not supported, but a header value can contain commas.
required: false
type: dict
oauth_token:
description:
- Contains information needed for generating an OAuth token.
- This type of authorization should be used when sending requests to a GCP
endpoint.
required: false
type: dict
suboptions:
service_account_email:
description:
- Service account email to be used for generating OAuth token.
- The service account must be within the same project as the job.
required: false
type: str
scope:
description:
- OAuth scope to be used for generating OAuth access token. If not specified,
"U(https://www.googleapis.com/auth/cloud-platform") will be used.
required: false
type: str
oidc_token:
description:
- Contains information needed for generating an OpenID Connect token.
- This type of authorization should be used when sending requests to third
party endpoints or Cloud Run.
required: false
type: dict
suboptions:
service_account_email:
description:
- Service account email to be used for generating OAuth token.
- The service account must be within the same project as the job.
required: false
type: str
audience:
description:
- Audience to be used when generating OIDC token. If not specified, the
URI specified in target will be used.
required: false
type: str
region:
description:
- Region where the scheduler job resides .
required: true
type: str
extends_documentation_fragment: gcp
notes:
- 'API Reference: U(https://cloud.google.com/scheduler/docs/reference/rest/)'
- 'Official Documentation: U(https://cloud.google.com/scheduler/)'
'''
EXAMPLES = '''
- name: create a job
gcp_cloudscheduler_job:
name: job
region: us-central1
schedule: "*/4 * * * *"
description: test app engine job
time_zone: Europe/London
app_engine_http_target:
http_method: POST
app_engine_routing:
service: web
version: prod
instance: my-instance-001
relative_uri: "/ping"
project: test_project
auth_kind: serviceaccount
service_account_file: "/tmp/auth.pem"
state: present
'''
RETURN = '''
name:
description:
- The name of the job.
returned: success
type: str
description:
description:
- A human-readable description for the job. This string must not contain more than
500 characters.
returned: success
type: str
schedule:
description:
- Describes the schedule on which the job will be executed.
returned: success
type: str
timeZone:
description:
- Specifies the time zone to be used in interpreting schedule.
- The value of this field must be a time zone name from the tz database.
returned: success
type: str
retryConfig:
description:
- By default, if a job does not complete successfully, meaning that an acknowledgement
is not received from the handler, then it will be retried with exponential backoff
according to the settings .
returned: success
type: complex
contains:
retryCount:
description:
- The number of attempts that the system will make to run a job using the exponential
backoff procedure described by maxDoublings.
- Values greater than 5 and negative values are not allowed.
returned: success
type: int
maxRetryDuration:
description:
- The time limit for retrying a failed job, measured from time when an execution
was first attempted. If specified with retryCount, the job will be retried
until both limits are reached.
- A duration in seconds with up to nine fractional digits, terminated by 's'.
returned: success
type: str
minBackoffDuration:
description:
- The minimum amount of time to wait before retrying a job after it fails.
- A duration in seconds with up to nine fractional digits, terminated by 's'.
returned: success
type: str
maxBackoffDuration:
description:
- The maximum amount of time to wait before retrying a job after it fails.
- A duration in seconds with up to nine fractional digits, terminated by 's'.
returned: success
type: str
maxDoublings:
description:
- The time between retries will double maxDoublings times.
- A job's retry interval starts at minBackoffDuration, then doubles maxDoublings
times, then increases linearly, and finally retries retries at intervals of
maxBackoffDuration up to retryCount times.
returned: success
type: int
pubsubTarget:
description:
- Pub/Sub target If the job providers a Pub/Sub target the cron will publish a message
to the provided topic .
returned: success
type: complex
contains:
topicName:
description:
- The name of the Cloud Pub/Sub topic to which messages will be published when
a job is delivered. The topic name must be in the same format as required
by PubSub's PublishRequest.name, for example projects/PROJECT_ID/topics/TOPIC_ID.
returned: success
type: str
data:
description:
- The message payload for PubsubMessage.
- Pubsub message must contain either non-empty data, or at least one attribute.
returned: success
type: str
attributes:
description:
- Attributes for PubsubMessage.
- Pubsub message must contain either non-empty data, or at least one attribute.
returned: success
type: dict
appEngineHttpTarget:
description:
- App Engine HTTP target.
- If the job providers a App Engine HTTP target the cron will send a request to
the service instance .
returned: success
type: complex
contains:
httpMethod:
description:
- Which HTTP method to use for the request.
returned: success
type: str
appEngineRouting:
description:
- App Engine Routing setting for the job.
returned: success
type: complex
contains:
service:
description:
- App service.
- By default, the job is sent to the service which is the default service
when the job is attempted.
returned: success
type: str
version:
description:
- App version.
- By default, the job is sent to the version which is the default version
when the job is attempted.
returned: success
type: str
instance:
description:
- App instance.
- By default, the job is sent to an instance which is available when the
job is attempted.
returned: success
type: str
relativeUri:
description:
- The relative URI.
returned: success
type: str
body:
description:
- HTTP request body. A request body is allowed only if the HTTP method is POST
or PUT. It will result in invalid argument error to set a body on a job with
an incompatible HttpMethod.
returned: success
type: str
headers:
description:
- HTTP request headers.
- This map contains the header field names and values. Headers can be set when
the job is created.
returned: success
type: dict
httpTarget:
description:
- HTTP target.
- If the job providers a http_target the cron will send a request to the targeted
url .
returned: success
type: complex
contains:
uri:
description:
- The full URI path that the request will be sent to.
returned: success
type: str
httpMethod:
description:
- Which HTTP method to use for the request.
returned: success
type: str
body:
description:
- HTTP request body. A request body is allowed only if the HTTP method is POST,
PUT, or PATCH. It is an error to set body on a job with an incompatible HttpMethod.
returned: success
type: str
headers:
description:
- This map contains the header field names and values. Repeated headers are
not supported, but a header value can contain commas.
returned: success
type: dict
oauthToken:
description:
- Contains information needed for generating an OAuth token.
- This type of authorization should be used when sending requests to a GCP endpoint.
returned: success
type: complex
contains:
serviceAccountEmail:
description:
- Service account email to be used for generating OAuth token.
- The service account must be within the same project as the job.
returned: success
type: str
scope:
description:
- OAuth scope to be used for generating OAuth access token. If not specified,
"U(https://www.googleapis.com/auth/cloud-platform") will be used.
returned: success
type: str
oidcToken:
description:
- Contains information needed for generating an OpenID Connect token.
- This type of authorization should be used when sending requests to third party
endpoints or Cloud Run.
returned: success
type: complex
contains:
serviceAccountEmail:
description:
- Service account email to be used for generating OAuth token.
- The service account must be within the same project as the job.
returned: success
type: str
audience:
description:
- Audience to be used when generating OIDC token. If not specified, the
URI specified in target will be used.
returned: success
type: str
region:
description:
- Region where the scheduler job resides .
returned: success
type: str
'''
################################################################################
# Imports
################################################################################
from ansible.module_utils.gcp_utils import navigate_hash, GcpSession, GcpModule, GcpRequest, remove_nones_from_dict, replace_resource_dict
import json
################################################################################
# Main
################################################################################
def main():
"""Main function"""
module = GcpModule(
argument_spec=dict(
state=dict(default='present', choices=['present', 'absent'], type='str'),
name=dict(required=True, type='str'),
description=dict(type='str'),
schedule=dict(type='str'),
time_zone=dict(default='Etc/UTC', type='str'),
retry_config=dict(
type='dict',
options=dict(
retry_count=dict(type='int'),
max_retry_duration=dict(type='str'),
min_backoff_duration=dict(type='str'),
max_backoff_duration=dict(type='str'),
max_doublings=dict(type='int'),
),
),
pubsub_target=dict(type='dict', options=dict(topic_name=dict(required=True, type='str'), data=dict(type='str'), attributes=dict(type='dict'))),
app_engine_http_target=dict(
type='dict',
options=dict(
http_method=dict(type='str'),
app_engine_routing=dict(type='dict', options=dict(service=dict(type='str'), version=dict(type='str'), instance=dict(type='str'))),
relative_uri=dict(required=True, type='str'),
body=dict(type='str'),
headers=dict(type='dict'),
),
),
http_target=dict(
type='dict',
options=dict(
uri=dict(required=True, type='str'),
http_method=dict(type='str'),
body=dict(type='str'),
headers=dict(type='dict'),
oauth_token=dict(type='dict', options=dict(service_account_email=dict(type='str'), scope=dict(type='str'))),
oidc_token=dict(type='dict', options=dict(service_account_email=dict(type='str'), audience=dict(type='str'))),
),
),
region=dict(required=True, type='str'),
),
mutually_exclusive=[['app_engine_http_target', 'http_target', 'pubsub_target']],
)
if not module.params['scopes']:
module.params['scopes'] = ['https://www.googleapis.com/auth/cloud-platform']
state = module.params['state']
fetch = fetch_resource(module, self_link(module))
changed = False
if fetch:
if state == 'present':
if is_different(module, fetch):
update(module, self_link(module))
fetch = fetch_resource(module, self_link(module))
changed = True
else:
delete(module, self_link(module))
fetch = {}
changed = True
else:
if state == 'present':
fetch = create(module, collection(module))
changed = True
else:
fetch = {}
fetch.update({'changed': changed})
module.exit_json(**fetch)
def create(module, link):
auth = GcpSession(module, 'cloudscheduler')
return return_if_object(module, auth.post(link, resource_to_request(module)))
def update(module, link):
delete(module, self_link(module))
create(module, collection(module))
def delete(module, link):
auth = GcpSession(module, 'cloudscheduler')
return return_if_object(module, auth.delete(link))
def resource_to_request(module):
request = {
u'name': module.params.get('name'),
u'description': module.params.get('description'),
u'schedule': module.params.get('schedule'),
u'timeZone': module.params.get('time_zone'),
u'retryConfig': JobRetryconfig(module.params.get('retry_config', {}), module).to_request(),
u'pubsubTarget': JobPubsubtarget(module.params.get('pubsub_target', {}), module).to_request(),
u'appEngineHttpTarget': JobAppenginehttptarget(module.params.get('app_engine_http_target', {}), module).to_request(),
u'httpTarget': JobHttptarget(module.params.get('http_target', {}), module).to_request(),
}
request = encode_request(request, module)
return_vals = {}
for k, v in request.items():
if v or v is False:
return_vals[k] = v
return return_vals
def fetch_resource(module, link, allow_not_found=True):
auth = GcpSession(module, 'cloudscheduler')
return return_if_object(module, auth.get(link), allow_not_found)
def self_link(module):
return "https://cloudscheduler.googleapis.com/v1/projects/{project}/locations/{region}/jobs/{name}".format(**module.params)
def collection(module):
return "https://cloudscheduler.googleapis.com/v1/projects/{project}/locations/{region}/jobs".format(**module.params)
def return_if_object(module, response, allow_not_found=False):
# If not found, return nothing.
if allow_not_found and response.status_code == 404:
return None
# If no content, return nothing.
if response.status_code == 204:
return None
try:
module.raise_for_status(response)
result = response.json()
except getattr(json.decoder, 'JSONDecodeError', ValueError):
module.fail_json(msg="Invalid JSON response with error: %s" % response.text)
result = decode_request(result, module)
if navigate_hash(result, ['error', 'errors']):
module.fail_json(msg=navigate_hash(result, ['error', 'errors']))
return result
def is_different(module, response):
request = resource_to_request(module)
response = response_to_hash(module, response)
request = decode_request(request, module)
# Remove all output-only from response.
response_vals = {}
for k, v in response.items():
if k in request:
response_vals[k] = v
request_vals = {}
for k, v in request.items():
if k in response:
request_vals[k] = v
return GcpRequest(request_vals) != GcpRequest(response_vals)
# Remove unnecessary properties from the response.
# This is for doing comparisons with Ansible's current parameters.
def response_to_hash(module, response):
return {
u'name': module.params.get('name'),
u'description': module.params.get('description'),
u'schedule': module.params.get('schedule'),
u'timeZone': module.params.get('time_zone'),
u'retryConfig': JobRetryconfig(module.params.get('retry_config', {}), module).to_request(),
u'pubsubTarget': JobPubsubtarget(module.params.get('pubsub_target', {}), module).to_request(),
u'appEngineHttpTarget': JobAppenginehttptarget(module.params.get('app_engine_http_target', {}), module).to_request(),
u'httpTarget': JobHttptarget(module.params.get('http_target', {}), module).to_request(),
}
def encode_request(request, module):
request['name'] = "projects/%s/locations/%s/jobs/%s" % (module.params['project'], module.params['region'], module.params['name'])
return request
def decode_request(response, module):
if 'name' in response:
response['name'] = response['name'].split('/')[-1]
return response
class JobRetryconfig(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict(
{
u'retryCount': self.request.get('retry_count'),
u'maxRetryDuration': self.request.get('max_retry_duration'),
u'minBackoffDuration': self.request.get('min_backoff_duration'),
u'maxBackoffDuration': self.request.get('max_backoff_duration'),
u'maxDoublings': self.request.get('max_doublings'),
}
)
def from_response(self):
return remove_nones_from_dict(
{
u'retryCount': self.module.params.get('retry_count'),
u'maxRetryDuration': self.module.params.get('max_retry_duration'),
u'minBackoffDuration': self.module.params.get('min_backoff_duration'),
u'maxBackoffDuration': self.module.params.get('max_backoff_duration'),
u'maxDoublings': self.module.params.get('max_doublings'),
}
)
class JobPubsubtarget(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict(
{u'topicName': self.request.get('topic_name'), u'data': self.request.get('data'), u'attributes': self.request.get('attributes')}
)
def from_response(self):
return remove_nones_from_dict(
{u'topicName': self.module.params.get('topic_name'), u'data': self.module.params.get('data'), u'attributes': self.module.params.get('attributes')}
)
class JobAppenginehttptarget(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict(
{
u'httpMethod': self.request.get('http_method'),
u'appEngineRouting': JobAppenginerouting(self.request.get('app_engine_routing', {}), self.module).to_request(),
u'relativeUri': self.request.get('relative_uri'),
u'body': self.request.get('body'),
u'headers': self.request.get('headers'),
}
)
def from_response(self):
return remove_nones_from_dict(
{
u'httpMethod': self.module.params.get('http_method'),
u'appEngineRouting': JobAppenginerouting(self.module.params.get('app_engine_routing', {}), self.module).to_request(),
u'relativeUri': self.request.get(u'relativeUri'),
u'body': self.module.params.get('body'),
u'headers': self.module.params.get('headers'),
}
)
class JobAppenginerouting(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict(
{u'service': self.request.get('service'), u'version': self.request.get('version'), u'instance': self.request.get('instance')}
)
def from_response(self):
return remove_nones_from_dict(
{u'service': self.module.params.get('service'), u'version': self.module.params.get('version'), u'instance': self.module.params.get('instance')}
)
class JobHttptarget(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict(
{
u'uri': self.request.get('uri'),
u'httpMethod': self.request.get('http_method'),
u'body': self.request.get('body'),
u'headers': self.request.get('headers'),
u'oauthToken': JobOauthtoken(self.request.get('oauth_token', {}), self.module).to_request(),
u'oidcToken': JobOidctoken(self.request.get('oidc_token', {}), self.module).to_request(),
}
)
def from_response(self):
return remove_nones_from_dict(
{
u'uri': self.request.get(u'uri'),
u'httpMethod': self.request.get(u'httpMethod'),
u'body': self.request.get(u'body'),
u'headers': self.request.get(u'headers'),
u'oauthToken': JobOauthtoken(self.module.params.get('oauth_token', {}), self.module).to_request(),
u'oidcToken': JobOidctoken(self.module.params.get('oidc_token', {}), self.module).to_request(),
}
)
class JobOauthtoken(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict({u'serviceAccountEmail': self.request.get('service_account_email'), u'scope': self.request.get('scope')})
def from_response(self):
return remove_nones_from_dict({u'serviceAccountEmail': self.request.get(u'serviceAccountEmail'), u'scope': self.request.get(u'scope')})
class JobOidctoken(object):
def __init__(self, request, module):
self.module = module
if request:
self.request = request
else:
self.request = {}
def to_request(self):
return remove_nones_from_dict({u'serviceAccountEmail': self.request.get('service_account_email'), u'audience': self.request.get('audience')})
def from_response(self):
return remove_nones_from_dict({u'serviceAccountEmail': self.request.get(u'serviceAccountEmail'), u'audience': self.request.get(u'audience')})
if __name__ == '__main__':
main()
| resmo/ansible | lib/ansible/modules/cloud/google/gcp_cloudscheduler_job.py | Python | gpl-3.0 | 31,832 |
define([
'angular'
, './instance-controller'
, './instance-directive'
, '../../glyph/glyph'
], function(
angular
, Controller
, directive
, glyphModule
) {
"use strict";
return angular.module('mtk.instance', [glyphModule.name])
.controller('InstanceController', Controller)
.directive('mtkInstance', directive)
;
});
| jeroenbreen/metapolator | app/lib/ui/metapolator/instance-panel/instance/instance.js | JavaScript | gpl-3.0 | 378 |
#region Copyright & License Information
/*
* Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
* This file is part of OpenRA, which is free software. It is made
* available to you 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. For more
* information, see COPYING.
*/
#endregion
using System.Collections.Generic;
using System.Linq;
namespace OpenRA.Mods.Common.UpdateRules.Rules
{
public class ReplaceShadowPalette : UpdateRule
{
public override string Name => "Removed ShadowPalette from WithShadow and projectiles.";
public override string Description =>
"The ShadowPalette field has been replaced by ShadowColor on projectiles.\n" +
"The Palette field on WithShadow and ShadowPalette on WithParachute have similarly been replaced with ShadowColor.";
readonly List<string> locations = new List<string>();
public override IEnumerable<string> AfterUpdate(ModData modData)
{
if (locations.Any())
yield return "The shadow palette overrides have been removed from the following locations:\n" +
UpdateUtils.FormatMessageList(locations) + "\n\n" +
"You may wish to inspect and change these.";
locations.Clear();
}
public override IEnumerable<string> UpdateWeaponNode(ModData modData, MiniYamlNode weaponNode)
{
foreach (var projectileNode in weaponNode.ChildrenMatching("Projectile"))
if (projectileNode.RemoveNodes("ShadowPalette") > 0)
locations.Add($"{weaponNode.Key}: {weaponNode.Key} ({weaponNode.Location.Filename})");
yield break;
}
public override IEnumerable<string> UpdateActorNode(ModData modData, MiniYamlNode actorNode)
{
foreach (var node in actorNode.ChildrenMatching("WithShadow"))
if (node.RemoveNodes("Palette") > 0)
locations.Add($"{actorNode.Key}: {node.Key} ({actorNode.Location.Filename})");
foreach (var node in actorNode.ChildrenMatching("WithParachute"))
if (node.RemoveNodes("ShadowPalette") > 0)
locations.Add($"{actorNode.Key}: {node.Key} ({actorNode.Location.Filename})");
yield break;
}
}
}
| MustaphaTR/OpenRA | OpenRA.Mods.Common/UpdateRules/Rules/20201213/ReplaceShadowPalette.cs | C# | gpl-3.0 | 2,162 |
/**
* The MIT License
* Copyright (c) 2012 Graylog, Inc.
*
* 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.
*/
package org.graylog2.plugin;
/**
* @author Dennis Oelkers <dennis@torch.sh>
*/
public interface Stoppable {
public void stop();
}
| berkeleydave/graylog2-server | graylog2-plugin-interfaces/src/main/java/org/graylog2/plugin/Stoppable.java | Java | gpl-3.0 | 1,275 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dot.junit.opcodes.sub_double.d;
public class T_sub_double_3 {
public double run(long a, double b) {
return 0;
}
}
| s20121035/rk3288_android5.1_repo | cts/tools/vm-tests-tf/src/dot/junit/opcodes/sub_double/d/T_sub_double_3.java | Java | gpl-3.0 | 761 |
// Copyright 2015 The go-ethereum Authors
// This file is part of the go-ethereum library.
//
// The go-ethereum 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 3 of the License, or
// (at your option) any later version.
//
// The go-ethereum 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 the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
package core
import (
"fmt"
"math/big"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/state"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/ethdb"
"github.com/ethereum/go-ethereum/event"
"github.com/ethereum/go-ethereum/pow"
)
/*
* TODO: move this to another package.
*/
// MakeChainConfig returns a new ChainConfig with the ethereum default chain settings.
func MakeChainConfig() *ChainConfig {
return &ChainConfig{HomesteadBlock: big.NewInt(0)}
}
// FakePow is a non-validating proof of work implementation.
// It returns true from Verify for any block.
type FakePow struct{}
func (f FakePow) Search(block pow.Block, stop <-chan struct{}, index int) (uint64, []byte) {
return 0, nil
}
func (f FakePow) Verify(block pow.Block) bool { return true }
func (f FakePow) GetHashrate() int64 { return 0 }
func (f FakePow) Turbo(bool) {}
// So we can deterministically seed different blockchains
var (
canonicalSeed = 1
forkSeed = 2
)
// BlockGen creates blocks for testing.
// See GenerateChain for a detailed explanation.
type BlockGen struct {
i int
parent *types.Block
chain []*types.Block
header *types.Header
statedb *state.StateDB
gasPool *GasPool
txs []*types.Transaction
receipts []*types.Receipt
uncles []*types.Header
}
// SetCoinbase sets the coinbase of the generated block.
// It can be called at most once.
func (b *BlockGen) SetCoinbase(addr common.Address) {
if b.gasPool != nil {
if len(b.txs) > 0 {
panic("coinbase must be set before adding transactions")
}
panic("coinbase can only be set once")
}
b.header.Coinbase = addr
b.gasPool = new(GasPool).AddGas(b.header.GasLimit)
}
// SetExtra sets the extra data field of the generated block.
func (b *BlockGen) SetExtra(data []byte) {
b.header.Extra = data
}
// AddTx adds a transaction to the generated block. If no coinbase has
// been set, the block's coinbase is set to the zero address.
//
// AddTx panics if the transaction cannot be executed. In addition to
// the protocol-imposed limitations (gas limit, etc.), there are some
// further limitations on the content of transactions that can be
// added. Notably, contract code relying on the BLOCKHASH instruction
// will panic during execution.
func (b *BlockGen) AddTx(tx *types.Transaction) {
if b.gasPool == nil {
b.SetCoinbase(common.Address{})
}
b.statedb.StartRecord(tx.Hash(), common.Hash{}, len(b.txs))
receipt, _, _, err := ApplyTransaction(MakeChainConfig(), nil, b.gasPool, b.statedb, b.header, tx, b.header.GasUsed, vm.Config{})
if err != nil {
panic(err)
}
b.txs = append(b.txs, tx)
b.receipts = append(b.receipts, receipt)
}
// Number returns the block number of the block being generated.
func (b *BlockGen) Number() *big.Int {
return new(big.Int).Set(b.header.Number)
}
// AddUncheckedReceipts forcefully adds a receipts to the block without a
// backing transaction.
//
// AddUncheckedReceipts will cause consensus failures when used during real
// chain processing. This is best used in conjunction with raw block insertion.
func (b *BlockGen) AddUncheckedReceipt(receipt *types.Receipt) {
b.receipts = append(b.receipts, receipt)
}
// TxNonce returns the next valid transaction nonce for the
// account at addr. It panics if the account does not exist.
func (b *BlockGen) TxNonce(addr common.Address) uint64 {
if !b.statedb.HasAccount(addr) {
panic("account does not exist")
}
return b.statedb.GetNonce(addr)
}
// AddUncle adds an uncle header to the generated block.
func (b *BlockGen) AddUncle(h *types.Header) {
b.uncles = append(b.uncles, h)
}
// PrevBlock returns a previously generated block by number. It panics if
// num is greater or equal to the number of the block being generated.
// For index -1, PrevBlock returns the parent block given to GenerateChain.
func (b *BlockGen) PrevBlock(index int) *types.Block {
if index >= b.i {
panic("block index out of range")
}
if index == -1 {
return b.parent
}
return b.chain[index]
}
// OffsetTime modifies the time instance of a block, implicitly changing its
// associated difficulty. It's useful to test scenarios where forking is not
// tied to chain length directly.
func (b *BlockGen) OffsetTime(seconds int64) {
b.header.Time.Add(b.header.Time, new(big.Int).SetInt64(seconds))
if b.header.Time.Cmp(b.parent.Header().Time) <= 0 {
panic("block time out of range")
}
b.header.Difficulty = CalcDifficulty(MakeChainConfig(), b.header.Time.Uint64(), b.parent.Time().Uint64(), b.parent.Number(), b.parent.Difficulty())
}
// GenerateChain creates a chain of n blocks. The first block's
// parent will be the provided parent. db is used to store
// intermediate states and should contain the parent's state trie.
//
// The generator function is called with a new block generator for
// every block. Any transactions and uncles added to the generator
// become part of the block. If gen is nil, the blocks will be empty
// and their coinbase will be the zero address.
//
// Blocks created by GenerateChain do not contain valid proof of work
// values. Inserting them into BlockChain requires use of FakePow or
// a similar non-validating proof of work implementation.
func GenerateChain(parent *types.Block, db ethdb.Database, n int, gen func(int, *BlockGen)) ([]*types.Block, []types.Receipts) {
blocks, receipts := make(types.Blocks, n), make([]types.Receipts, n)
genblock := func(i int, h *types.Header, statedb *state.StateDB) (*types.Block, types.Receipts) {
b := &BlockGen{parent: parent, i: i, chain: blocks, header: h, statedb: statedb}
if gen != nil {
gen(i, b)
}
AccumulateRewards(statedb, h, b.uncles)
root, err := statedb.Commit()
if err != nil {
panic(fmt.Sprintf("state write error: %v", err))
}
h.Root = root
return types.NewBlock(h, b.txs, b.uncles, b.receipts), b.receipts
}
for i := 0; i < n; i++ {
statedb, err := state.New(parent.Root(), db)
if err != nil {
panic(err)
}
header := makeHeader(parent, statedb)
block, receipt := genblock(i, header, statedb)
blocks[i] = block
receipts[i] = receipt
parent = block
}
return blocks, receipts
}
func makeHeader(parent *types.Block, state *state.StateDB) *types.Header {
var time *big.Int
if parent.Time() == nil {
time = big.NewInt(10)
} else {
time = new(big.Int).Add(parent.Time(), big.NewInt(10)) // block time is fixed at 10 seconds
}
return &types.Header{
Root: state.IntermediateRoot(),
ParentHash: parent.Hash(),
Coinbase: parent.Coinbase(),
Difficulty: CalcDifficulty(MakeChainConfig(), time.Uint64(), new(big.Int).Sub(time, big.NewInt(10)).Uint64(), parent.Number(), parent.Difficulty()),
GasLimit: CalcGasLimit(parent),
GasUsed: new(big.Int),
Number: new(big.Int).Add(parent.Number(), common.Big1),
Time: time,
}
}
// newCanonical creates a chain database, and injects a deterministic canonical
// chain. Depending on the full flag, if creates either a full block chain or a
// header only chain.
func newCanonical(n int, full bool) (ethdb.Database, *BlockChain, error) {
// Create the new chain database
db, _ := ethdb.NewMemDatabase()
evmux := &event.TypeMux{}
// Initialize a fresh chain with only a genesis block
genesis, _ := WriteTestNetGenesisBlock(db)
blockchain, _ := NewBlockChain(db, MakeChainConfig(), FakePow{}, evmux)
// Create and inject the requested chain
if n == 0 {
return db, blockchain, nil
}
if full {
// Full block-chain requested
blocks := makeBlockChain(genesis, n, db, canonicalSeed)
_, err := blockchain.InsertChain(blocks)
return db, blockchain, err
}
// Header-only chain requested
headers := makeHeaderChain(genesis.Header(), n, db, canonicalSeed)
_, err := blockchain.InsertHeaderChain(headers, 1)
return db, blockchain, err
}
// makeHeaderChain creates a deterministic chain of headers rooted at parent.
func makeHeaderChain(parent *types.Header, n int, db ethdb.Database, seed int) []*types.Header {
blocks := makeBlockChain(types.NewBlockWithHeader(parent), n, db, seed)
headers := make([]*types.Header, len(blocks))
for i, block := range blocks {
headers[i] = block.Header()
}
return headers
}
// makeBlockChain creates a deterministic chain of blocks rooted at parent.
func makeBlockChain(parent *types.Block, n int, db ethdb.Database, seed int) []*types.Block {
blocks, _ := GenerateChain(parent, db, n, func(i int, b *BlockGen) {
b.SetCoinbase(common.Address{0: byte(seed), 19: byte(i)})
})
return blocks
}
| gophergala2016/etherapis | vendor/github.com/ethereum/go-ethereum/core/chain_makers.go | GO | gpl-3.0 | 9,385 |
/*************************************************************************
* Copyright 2009-2013 Eucalyptus Systems, Inc.
*
* 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; version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*
* Please contact Eucalyptus Systems, Inc., 6755 Hollister Ave., Goleta
* CA 93117, USA or visit http://www.eucalyptus.com/licenses/ if you need
* additional information or have any questions.
************************************************************************/
package com.eucalyptus.auth.tokens;
import com.eucalyptus.auth.AuthException;
/**
*
*/
public class SecurityTokenValidationException extends AuthException {
private static final long serialVersionUID = 1L;
public SecurityTokenValidationException( final String message ) {
super( message );
}
}
| eethomas/eucalyptus | clc/modules/msgs/src/main/java/com/eucalyptus/auth/tokens/SecurityTokenValidationException.java | Java | gpl-3.0 | 1,303 |
# -*- coding: utf-8 -*-
""" *==LICENSE==*
CyanWorlds.com Engine - MMOG client, server and tools
Copyright (C) 2011 Cyan Worlds, Inc.
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/>.
Additional permissions under GNU GPL version 3 section 7
If you modify this Program, or any covered work, by linking or
combining it with any of RAD Game Tools Bink SDK, Autodesk 3ds Max SDK,
NVIDIA PhysX SDK, Microsoft DirectX SDK, OpenSSL library, Independent
JPEG Group JPEG library, Microsoft Windows Media SDK, or Apple QuickTime SDK
(or a modified version of those libraries),
containing parts covered by the terms of the Bink SDK EULA, 3ds Max EULA,
PhysX SDK EULA, DirectX SDK EULA, OpenSSL and SSLeay licenses, IJG
JPEG Library README, Windows Media SDK EULA, or QuickTime SDK EULA, the
licensors of this Program grant you additional
permission to convey the resulting work. Corresponding Source for a
non-source form of such a combination shall include the source code for
the parts of OpenSSL and IJG JPEG Library used as well as that of the covered
work.
You can contact Cyan Worlds, Inc. by email legal@cyan.com
or by snail mail at:
Cyan Worlds, Inc.
14617 N Newport Hwy
Mead, WA 99021
*==LICENSE==* """
"""
Module: ahnyTrees
Age: Ahnonay
Date: April, 2007
Author: Derek Odell
Ahnonay Quab control
"""
from Plasma import *
from PlasmaTypes import *
# define the attributes that will be entered in max
rgnTrees = ptAttribActivator(1, "act: Tree Detector")
respTreeAnims = ptAttribResponderList(2, "resp: Tree Anims", byObject=1)
objTrees = ptAttribSceneobjectList(3, "obj: Tree Meshs")
SDLTrees = ptAttribString(4, "str: SDL Trees (optional)")
# globals
respTreeAnimsList = []
objTreeList = []
#====================================
class ahnyTrees(ptModifier):
###########################
def __init__(self):
ptModifier.__init__(self)
self.id = 5948
version = 1
self.version = version
print "__init__ahnyTrees v%d " % (version)
###########################
def OnFirstUpdate(self):
global respTreeAnimsList
global objTreeList
try:
ageSDL = PtGetAgeSDL()
ageSDL[SDLTrees.value][0]
except:
print "ahnyTrees.OnServerInitComplete(): ERROR --- Cannot find the Ahnonay Age SDL"
ageSDL[SDLTrees.value] = (1,1,1,1,1,1,1,1,1,1,1,1,1,1,1)
ageSDL.setFlags(SDLTrees.value,1,1)
ageSDL.sendToClients(SDLTrees.value)
ageSDL.setNotify(self.key,SDLTrees.value,0.0)
for responder in respTreeAnims.value:
thisResp = responder.getName()
respTreeAnimsList.append(thisResp)
for object in objTrees.value:
thisObj = object.getName()
objTreeList.append(thisObj)
ageSDL = PtGetAgeSDL()
idx = 0
for visible in ageSDL[SDLTrees.value]:
if not visible:
respTreeAnims.run(self.key, objectName=respTreeAnimsList[idx], fastforward=1)
idx += 1
###########################
def OnNotify(self,state,id,events):
global respTreeAnimsList
global objTreeList
print "ahnyTrees.OnNotify: state=%s id=%d events=" % (state, id), events
if id == rgnTrees.id:
for event in events:
if event[0] == kCollisionEvent and self.sceneobject.isLocallyOwned() :
region = event[3]
regName = region.getName()
for object in objTreeList:
if object == regName:
ageSDL = PtGetAgeSDL()
treeSDL = list(ageSDL[SDLTrees.value])
index = objTreeList.index(object)
if treeSDL[index]:
respTreeAnims.run(self.key, objectName=respTreeAnimsList[index], netForce = 1)
treeSDL[index] = 0
ageSDL[SDLTrees.value] = tuple(treeSDL)
print "ahnyTrees.OnNotify: Tree knocked down"
| TOC-Shard/moul-scripts | Python/ahnyTrees.py | Python | gpl-3.0 | 4,774 |
from eventlet import patcher
from eventlet.green import socket
from eventlet.green import time
from eventlet.green import httplib
from eventlet.green import ftplib
from eventlet.support import six
if six.PY2:
to_patch = [('socket', socket), ('httplib', httplib),
('time', time), ('ftplib', ftplib)]
try:
from eventlet.green import ssl
to_patch.append(('ssl', ssl))
except ImportError:
pass
patcher.inject('urllib', globals(), *to_patch)
try:
URLopener
except NameError:
patcher.inject('urllib.request', globals(), *to_patch)
# patch a bunch of things that have imports inside the
# function body; this is lame and hacky but I don't feel
# too bad because urllib is a hacky pile of junk that no
# one should be using anyhow
URLopener.open_http = patcher.patch_function(URLopener.open_http, ('httplib', httplib))
if hasattr(URLopener, 'open_https'):
URLopener.open_https = patcher.patch_function(URLopener.open_https, ('httplib', httplib))
URLopener.open_ftp = patcher.patch_function(URLopener.open_ftp, ('ftplib', ftplib))
ftpwrapper.init = patcher.patch_function(ftpwrapper.init, ('ftplib', ftplib))
ftpwrapper.retrfile = patcher.patch_function(ftpwrapper.retrfile, ('ftplib', ftplib))
del patcher
# Run test program when run as a script
if __name__ == '__main__':
main()
| pbaesse/Sissens | lib/python2.7/site-packages/eventlet/green/urllib/__init__.py | Python | gpl-3.0 | 1,423 |
package classic
import (
"context"
"fmt"
"log"
"strings"
"github.com/hashicorp/go-oracle-terraform/compute"
"github.com/hashicorp/packer/helper/multistep"
"github.com/hashicorp/packer/packer"
)
type stepSecurity struct {
CommType string
SecurityListKey string
secListName string
secRuleName string
}
func (s *stepSecurity) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
ui := state.Get("ui").(packer.Ui)
config := state.Get("config").(*Config)
runID := state.Get("run_id").(string)
client := state.Get("client").(*compute.Client)
commType := ""
if s.CommType == "ssh" {
commType = "SSH"
} else if s.CommType == "winrm" {
commType = "WINRM"
}
secListName := fmt.Sprintf("Packer_%s_Allow_%s", commType, runID)
if _, ok := state.GetOk(secListName); ok {
log.Println("SecList created in earlier step, continuing")
// copy sec list name to proper key
state.Put(s.SecurityListKey, secListName)
return multistep.ActionContinue
}
ui.Say(fmt.Sprintf("Configuring security lists and rules to enable %s access...", commType))
log.Println(secListName)
secListClient := client.SecurityLists()
secListInput := compute.CreateSecurityListInput{
Description: fmt.Sprintf("Packer-generated security list to give packer %s access", commType),
Name: config.Identifier(secListName),
}
_, err := secListClient.CreateSecurityList(&secListInput)
if err != nil {
if !strings.Contains(err.Error(), "already exists") {
err = fmt.Errorf("Error creating security List to"+
" allow Packer to connect to Oracle instance via %s: %s", commType, err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
}
// DOCS NOTE: user must have Compute_Operations role
// Create security rule that allows Packer to connect via SSH or winRM
var application string
if commType == "SSH" {
application = "/oracle/public/ssh"
} else if commType == "WINRM" {
// Check to see whether a winRM security application is already defined
applicationClient := client.SecurityApplications()
application = fmt.Sprintf("packer_winRM_%s", runID)
applicationInput := compute.CreateSecurityApplicationInput{
Description: "Allows Packer to connect to instance via winRM",
DPort: "5985-5986",
Name: application,
Protocol: "TCP",
}
_, err = applicationClient.CreateSecurityApplication(&applicationInput)
if err != nil {
err = fmt.Errorf("Error creating security application to"+
" allow Packer to connect to Oracle instance via %s: %s", commType, err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
state.Put("winrm_application", application)
}
secRulesClient := client.SecRules()
secRuleName := fmt.Sprintf("Packer-allow-%s-Rule_%s", commType, runID)
log.Println(secRuleName)
secRulesInput := compute.CreateSecRuleInput{
Action: "PERMIT",
Application: application,
Description: "Packer-generated security rule to allow ssh/winrm",
DestinationList: "seclist:" + config.Identifier(secListName),
Name: config.Identifier(secRuleName),
SourceList: config.SSHSourceList,
}
_, err = secRulesClient.CreateSecRule(&secRulesInput)
if err != nil {
err = fmt.Errorf("Error creating security rule to"+
" allow Packer to connect to Oracle instance: %s", err)
ui.Error(err.Error())
state.Put("error", err)
return multistep.ActionHalt
}
state.Put(s.SecurityListKey, secListName)
state.Put(secListName, true)
s.secListName = secListName
s.secRuleName = secRuleName
return multistep.ActionContinue
}
func (s *stepSecurity) Cleanup(state multistep.StateBag) {
if s.secListName == "" || s.secRuleName == "" {
return
}
client := state.Get("client").(*compute.Client)
ui := state.Get("ui").(packer.Ui)
config := state.Get("config").(*Config)
ui.Say("Deleting temporary rules and lists...")
// delete security rules that Packer generated
secRulesClient := client.SecRules()
ruleInput := compute.DeleteSecRuleInput{
Name: config.Identifier(s.secRuleName),
}
err := secRulesClient.DeleteSecRule(&ruleInput)
if err != nil {
ui.Say(fmt.Sprintf("Error deleting the packer-generated security rule %s; "+
"please delete manually. (error: %s)", s.secRuleName, err.Error()))
}
// delete security list that Packer generated
secListClient := client.SecurityLists()
input := compute.DeleteSecurityListInput{Name: config.Identifier(s.secListName)}
err = secListClient.DeleteSecurityList(&input)
if err != nil {
ui.Say(fmt.Sprintf("Error deleting the packer-generated security list %s; "+
"please delete manually. (error : %s)", s.secListName, err.Error()))
}
// Some extra cleanup if we used the winRM communicator
if s.CommType == "winrm" {
// Delete the packer-generated application
application, ok := state.GetOk("winrm_application")
if !ok {
return
}
applicationClient := client.SecurityApplications()
deleteApplicationInput := compute.DeleteSecurityApplicationInput{
Name: config.Identifier(application.(string)),
}
err = applicationClient.DeleteSecurityApplication(&deleteApplicationInput)
if err != nil {
ui.Say(fmt.Sprintf("Error deleting the packer-generated winrm security application %s; "+
"please delete manually. (error : %s)", application.(string), err.Error()))
}
}
}
| dave2/packer | builder/oracle/classic/step_security.go | GO | mpl-2.0 | 5,373 |
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo;
/**
* Linked to core.clinical.PatientProcedure business object (ID: 1003100017).
*/
public class PatientProcedureForClinicalNotesVo extends ims.core.clinical.vo.PatientProcedureRefVo implements ims.vo.ImsCloneable, Comparable
{
private static final long serialVersionUID = 1L;
public PatientProcedureForClinicalNotesVo()
{
}
public PatientProcedureForClinicalNotesVo(Integer id, int version)
{
super(id, version);
}
public PatientProcedureForClinicalNotesVo(ims.RefMan.vo.beans.PatientProcedureForClinicalNotesVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.procedure = bean.getProcedure() == null ? null : bean.getProcedure().buildVo();
this.proceduredescription = bean.getProcedureDescription();
this.infosource = bean.getInfoSource() == null ? null : ims.core.vo.lookups.SourceofInformation.buildLookup(bean.getInfoSource());
this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion());
this.episodeofcare = bean.getEpisodeOfCare() == null ? null : new ims.core.admin.vo.EpisodeOfCareRefVo(new Integer(bean.getEpisodeOfCare().getId()), bean.getEpisodeOfCare().getVersion());
this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo();
this.procdate = bean.getProcDate() == null ? null : bean.getProcDate().buildPartialDate();
this.procedurestatus = bean.getProcedureStatus() == null ? null : ims.core.vo.lookups.PatientProcedureStatus.buildLookup(bean.getProcedureStatus());
this.incompletereason = bean.getIncompleteReason() == null ? null : ims.core.vo.lookups.ProcedureIncompleteReason.buildLookup(bean.getIncompleteReason());
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.beans.PatientProcedureForClinicalNotesVoBean bean)
{
this.id = bean.getId();
this.version = bean.getVersion();
this.procedure = bean.getProcedure() == null ? null : bean.getProcedure().buildVo(map);
this.proceduredescription = bean.getProcedureDescription();
this.infosource = bean.getInfoSource() == null ? null : ims.core.vo.lookups.SourceofInformation.buildLookup(bean.getInfoSource());
this.carecontext = bean.getCareContext() == null ? null : new ims.core.admin.vo.CareContextRefVo(new Integer(bean.getCareContext().getId()), bean.getCareContext().getVersion());
this.episodeofcare = bean.getEpisodeOfCare() == null ? null : new ims.core.admin.vo.EpisodeOfCareRefVo(new Integer(bean.getEpisodeOfCare().getId()), bean.getEpisodeOfCare().getVersion());
this.authoringinformation = bean.getAuthoringInformation() == null ? null : bean.getAuthoringInformation().buildVo(map);
this.procdate = bean.getProcDate() == null ? null : bean.getProcDate().buildPartialDate();
this.procedurestatus = bean.getProcedureStatus() == null ? null : ims.core.vo.lookups.PatientProcedureStatus.buildLookup(bean.getProcedureStatus());
this.incompletereason = bean.getIncompleteReason() == null ? null : ims.core.vo.lookups.ProcedureIncompleteReason.buildLookup(bean.getIncompleteReason());
}
public ims.vo.ValueObjectBean getBean()
{
return this.getBean(new ims.vo.ValueObjectBeanMap());
}
public ims.vo.ValueObjectBean getBean(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.beans.PatientProcedureForClinicalNotesVoBean bean = null;
if(map != null)
bean = (ims.RefMan.vo.beans.PatientProcedureForClinicalNotesVoBean)map.getValueObjectBean(this);
if (bean == null)
{
bean = new ims.RefMan.vo.beans.PatientProcedureForClinicalNotesVoBean();
map.addValueObjectBean(this, bean);
bean.populate(map, this);
}
return bean;
}
public Object getFieldValueByFieldName(String fieldName)
{
if(fieldName == null)
throw new ims.framework.exceptions.CodingRuntimeException("Invalid field name");
fieldName = fieldName.toUpperCase();
if(fieldName.equals("PROCEDURE"))
return getProcedure();
if(fieldName.equals("PROCEDUREDESCRIPTION"))
return getProcedureDescription();
if(fieldName.equals("INFOSOURCE"))
return getInfoSource();
if(fieldName.equals("CARECONTEXT"))
return getCareContext();
if(fieldName.equals("EPISODEOFCARE"))
return getEpisodeOfCare();
if(fieldName.equals("AUTHORINGINFORMATION"))
return getAuthoringInformation();
if(fieldName.equals("PROCDATE"))
return getProcDate();
if(fieldName.equals("PROCEDURESTATUS"))
return getProcedureStatus();
if(fieldName.equals("INCOMPLETEREASON"))
return getIncompleteReason();
return super.getFieldValueByFieldName(fieldName);
}
public boolean getProcedureIsNotNull()
{
return this.procedure != null;
}
public ims.core.vo.ProcedureLiteVo getProcedure()
{
return this.procedure;
}
public void setProcedure(ims.core.vo.ProcedureLiteVo value)
{
this.isValidated = false;
this.procedure = value;
}
public boolean getProcedureDescriptionIsNotNull()
{
return this.proceduredescription != null;
}
public String getProcedureDescription()
{
return this.proceduredescription;
}
public static int getProcedureDescriptionMaxLength()
{
return 255;
}
public void setProcedureDescription(String value)
{
this.isValidated = false;
this.proceduredescription = value;
}
public boolean getInfoSourceIsNotNull()
{
return this.infosource != null;
}
public ims.core.vo.lookups.SourceofInformation getInfoSource()
{
return this.infosource;
}
public void setInfoSource(ims.core.vo.lookups.SourceofInformation value)
{
this.isValidated = false;
this.infosource = value;
}
public boolean getCareContextIsNotNull()
{
return this.carecontext != null;
}
public ims.core.admin.vo.CareContextRefVo getCareContext()
{
return this.carecontext;
}
public void setCareContext(ims.core.admin.vo.CareContextRefVo value)
{
this.isValidated = false;
this.carecontext = value;
}
public boolean getEpisodeOfCareIsNotNull()
{
return this.episodeofcare != null;
}
public ims.core.admin.vo.EpisodeOfCareRefVo getEpisodeOfCare()
{
return this.episodeofcare;
}
public void setEpisodeOfCare(ims.core.admin.vo.EpisodeOfCareRefVo value)
{
this.isValidated = false;
this.episodeofcare = value;
}
public boolean getAuthoringInformationIsNotNull()
{
return this.authoringinformation != null;
}
public ims.core.vo.AuthoringInformationVo getAuthoringInformation()
{
return this.authoringinformation;
}
public void setAuthoringInformation(ims.core.vo.AuthoringInformationVo value)
{
this.isValidated = false;
this.authoringinformation = value;
}
public boolean getProcDateIsNotNull()
{
return this.procdate != null;
}
public ims.framework.utils.PartialDate getProcDate()
{
return this.procdate;
}
public void setProcDate(ims.framework.utils.PartialDate value)
{
this.isValidated = false;
this.procdate = value;
}
public boolean getProcedureStatusIsNotNull()
{
return this.procedurestatus != null;
}
public ims.core.vo.lookups.PatientProcedureStatus getProcedureStatus()
{
return this.procedurestatus;
}
public void setProcedureStatus(ims.core.vo.lookups.PatientProcedureStatus value)
{
this.isValidated = false;
this.procedurestatus = value;
}
public boolean getIncompleteReasonIsNotNull()
{
return this.incompletereason != null;
}
public ims.core.vo.lookups.ProcedureIncompleteReason getIncompleteReason()
{
return this.incompletereason;
}
public void setIncompleteReason(ims.core.vo.lookups.ProcedureIncompleteReason value)
{
this.isValidated = false;
this.incompletereason = value;
}
public boolean isValidated()
{
if(this.isBusy)
return true;
this.isBusy = true;
if(!this.isValidated)
{
this.isBusy = false;
return false;
}
if(this.authoringinformation != null)
{
if(!this.authoringinformation.isValidated())
{
this.isBusy = false;
return false;
}
}
this.isBusy = false;
return true;
}
public String[] validate()
{
return validate(null);
}
public String[] validate(String[] existingErrors)
{
if(this.isBusy)
return null;
this.isBusy = true;
java.util.ArrayList<String> listOfErrors = new java.util.ArrayList<String>();
if(existingErrors != null)
{
for(int x = 0; x < existingErrors.length; x++)
{
listOfErrors.add(existingErrors[x]);
}
}
if(this.proceduredescription == null || this.proceduredescription.length() == 0)
listOfErrors.add("ProcedureDescription is mandatory");
else if(this.proceduredescription.length() > 255)
listOfErrors.add("The length of the field [proceduredescription] in the value object [ims.RefMan.vo.PatientProcedureForClinicalNotesVo] is too big. It should be less or equal to 255");
if(this.infosource == null)
listOfErrors.add("InfoSource is mandatory");
if(this.episodeofcare == null)
listOfErrors.add("EpisodeOfCare is mandatory");
if(this.authoringinformation != null)
{
String[] listOfOtherErrors = this.authoringinformation.validate();
if(listOfOtherErrors != null)
{
for(int x = 0; x < listOfOtherErrors.length; x++)
{
listOfErrors.add(listOfOtherErrors[x]);
}
}
}
int errorCount = listOfErrors.size();
if(errorCount == 0)
{
this.isBusy = false;
this.isValidated = true;
return null;
}
String[] result = new String[errorCount];
for(int x = 0; x < errorCount; x++)
result[x] = (String)listOfErrors.get(x);
this.isBusy = false;
this.isValidated = false;
return result;
}
public void clearIDAndVersion()
{
this.id = null;
this.version = 0;
}
public Object clone()
{
if(this.isBusy)
return this;
this.isBusy = true;
PatientProcedureForClinicalNotesVo clone = new PatientProcedureForClinicalNotesVo(this.id, this.version);
if(this.procedure == null)
clone.procedure = null;
else
clone.procedure = (ims.core.vo.ProcedureLiteVo)this.procedure.clone();
clone.proceduredescription = this.proceduredescription;
if(this.infosource == null)
clone.infosource = null;
else
clone.infosource = (ims.core.vo.lookups.SourceofInformation)this.infosource.clone();
clone.carecontext = this.carecontext;
clone.episodeofcare = this.episodeofcare;
if(this.authoringinformation == null)
clone.authoringinformation = null;
else
clone.authoringinformation = (ims.core.vo.AuthoringInformationVo)this.authoringinformation.clone();
if(this.procdate == null)
clone.procdate = null;
else
clone.procdate = (ims.framework.utils.PartialDate)this.procdate.clone();
if(this.procedurestatus == null)
clone.procedurestatus = null;
else
clone.procedurestatus = (ims.core.vo.lookups.PatientProcedureStatus)this.procedurestatus.clone();
if(this.incompletereason == null)
clone.incompletereason = null;
else
clone.incompletereason = (ims.core.vo.lookups.ProcedureIncompleteReason)this.incompletereason.clone();
clone.isValidated = this.isValidated;
this.isBusy = false;
return clone;
}
public int compareTo(Object obj)
{
return compareTo(obj, true);
}
public int compareTo(Object obj, boolean caseInsensitive)
{
if (obj == null)
{
return -1;
}
if(caseInsensitive); // this is to avoid eclipse warning only.
if (!(PatientProcedureForClinicalNotesVo.class.isAssignableFrom(obj.getClass())))
{
throw new ClassCastException("A PatientProcedureForClinicalNotesVo object cannot be compared an Object of type " + obj.getClass().getName());
}
if (this.id == null)
return 1;
if (((PatientProcedureForClinicalNotesVo)obj).getBoId() == null)
return -1;
return this.id.compareTo(((PatientProcedureForClinicalNotesVo)obj).getBoId());
}
public synchronized static int generateValueObjectUniqueID()
{
return ims.vo.ValueObject.generateUniqueID();
}
public int countFieldsWithValue()
{
int count = 0;
if(this.procedure != null)
count++;
if(this.proceduredescription != null)
count++;
if(this.infosource != null)
count++;
if(this.carecontext != null)
count++;
if(this.episodeofcare != null)
count++;
if(this.authoringinformation != null)
count++;
if(this.procdate != null)
count++;
if(this.procedurestatus != null)
count++;
if(this.incompletereason != null)
count++;
return count;
}
public int countValueObjectFields()
{
return 9;
}
protected ims.core.vo.ProcedureLiteVo procedure;
protected String proceduredescription;
protected ims.core.vo.lookups.SourceofInformation infosource;
protected ims.core.admin.vo.CareContextRefVo carecontext;
protected ims.core.admin.vo.EpisodeOfCareRefVo episodeofcare;
protected ims.core.vo.AuthoringInformationVo authoringinformation;
protected ims.framework.utils.PartialDate procdate;
protected ims.core.vo.lookups.PatientProcedureStatus procedurestatus;
protected ims.core.vo.lookups.ProcedureIncompleteReason incompletereason;
private boolean isValidated = false;
private boolean isBusy = false;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/PatientProcedureForClinicalNotesVo.java | Java | agpl-3.0 | 13,124 |
/*
*
* Copyright 2014 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* iot_support at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>
#include <vector>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "ngsi/ParseData.h"
#include "rest/ConnectionInfo.h"
#include "rest/EntityTypeInfo.h"
#include "rest/uriParamNames.h"
#include "serviceRoutines/postDiscoverContextAvailability.h"
#include "serviceRoutines/getEntityByIdAttributeByName.h"
/* ****************************************************************************
*
* getEntityByIdAttributeByNameWithTypeAndId -
*
* GET /v1/registry/contextEntities/type/{entity::type}/id/{entity::id}/attributes/{attribute::name}
*
* Payload In: None
* Payload Out: DiscoverContextAvailabilityResponse
*
* URI parameters:
* - attributesFormat=object
* - entity::type=XXX (must coincide with entity::type in URL)
* - !exist=entity::type (if set - error -- entity::type cannot be empty)
* - exist=entity::type (not supported - ok if present, ok if not present ...)
*
* 01. Get values from URL (entityId::type, exist, !exist)
* 02. Check validity of URI params
* 03. Fill in DiscoverContextAvailabilityRequest
* 04. Call standard operation discoverContextAvailability
* 05. Cleanup and return result
*/
std::string getEntityByIdAttributeByNameWithTypeAndId
(
ConnectionInfo* ciP,
int components,
std::vector<std::string>& compV,
ParseData* parseDataP
)
{
std::string entityType = compV[4];
std::string entityId = compV[6];
std::string attributeName = compV[8];
std::string entityTypeFromUriParam = ciP->uriParam[URI_PARAM_ENTITY_TYPE];
EntityTypeInfo typeInfo = EntityTypeEmptyOrNotEmpty;
std::string answer;
DiscoverContextAvailabilityResponse response;
// 01. Get values from URL (entityId::type, exist, !exist)
if (ciP->uriParam[URI_PARAM_NOT_EXIST] == URI_PARAM_ENTITY_TYPE)
{
typeInfo = EntityTypeEmpty;
}
else if (ciP->uriParam[URI_PARAM_EXIST] == URI_PARAM_ENTITY_TYPE)
{
typeInfo = EntityTypeNotEmpty;
}
//
// 02. Check validity of URI params ...
// and if OK:
// 03. Fill in DiscoverContextAvailabilityRequest
// 04. Call standard operation discoverContextAvailability
//
if (typeInfo == EntityTypeEmpty)
{
parseDataP->dcars.res.errorCode.fill(SccBadRequest, "entity::type cannot be empty for this request");
LM_W(("Bad Input (entity::type cannot be empty for this request)"));
answer = parseDataP->dcars.res.render(IndividualContextEntityAttributeWithTypeAndId, ciP->outFormat, "");
}
else if ((entityTypeFromUriParam != entityType) && (entityTypeFromUriParam != ""))
{
parseDataP->dcars.res.errorCode.fill(SccBadRequest, "non-matching entity::types in URL");
LM_W(("Bad Input non-matching entity::types in URL"));
answer = parseDataP->dcars.res.render(IndividualContextEntityAttributeWithTypeAndId, ciP->outFormat, "");
}
else
{
// 03. Fill in DiscoverContextAvailabilityRequest
parseDataP->dcar.res.fill(entityId, entityType, typeInfo, attributeName);
// 04. Call standard operation
answer = postDiscoverContextAvailability(ciP, components, compV, parseDataP);
}
// 05. Cleanup and return result
parseDataP->dcar.res.release();
return answer;
}
| j1fig/fiware-orion | src/lib/serviceRoutines/getEntityByIdAttributeByNameWithTypeAndId.cpp | C++ | agpl-3.0 | 4,317 |
if (Date.first_day_of_week == 1) {
Date.weekdays = $w("L Ma Me J V S D");
} else {
Date.weekdays = $w("D L Ma Me J V S");
}
Date.months = $w('Janvier Février Mars Avril Mai Juin Juillet Août Septembre Octobre Novembre Décembre');
_translations = {
"OK": "OK",
"Now": "Maintenant",
"Today": "Aujourd'hui",
"Clear": "Claire"
};
| wesbillman/projects | public/javascripts/calendar_date_select/locale/fr.js | JavaScript | agpl-3.0 | 349 |
# This migration comes from bookyt_salary (originally 20120201104444)
class SwitchToTranslatedSaldoInclusionFlags < ActiveRecord::Migration
def up
ActsAsTaggableOn::Tag.where(:name => 'ahv').update_all(:name => 'AHV')
ActsAsTaggableOn::Tag.where(:name => 'ktg').update_all(:name => 'KTG')
ActsAsTaggableOn::Tag.where(:name => 'gross_income').update_all(:name => 'Bruttolohn')
ActsAsTaggableOn::Tag.where(:name => 'net_income').update_all(:name => 'Nettolohn')
ActsAsTaggableOn::Tag.where(:name => 'payment').update_all(:name => 'Auszahlung')
ActsAsTaggableOn::Tag.where(:name => 'uvg').update_all(:name => 'UVG')
ActsAsTaggableOn::Tag.where(:name => 'uvgz').update_all(:name => 'UVGZ')
ActsAsTaggableOn::Tag.where(:name => 'deduction_at_source').update_all(:name => 'Quellensteuer')
SalaryBookingTemplate.where(:amount_relates_to => 'ahv').update_all(:amount_relates_to => 'AHV')
SalaryBookingTemplate.where(:amount_relates_to => 'ktg').update_all(:amount_relates_to => 'KTG')
SalaryBookingTemplate.where(:amount_relates_to => 'gross_income').update_all(:amount_relates_to => 'Bruttolohn')
SalaryBookingTemplate.where(:amount_relates_to => 'net_income').update_all(:amount_relates_to => 'Nettolohn')
SalaryBookingTemplate.where(:amount_relates_to => 'payment').update_all(:amount_relates_to => 'Auszahlung')
SalaryBookingTemplate.where(:amount_relates_to => 'uvg').update_all(:amount_relates_to => 'UVG')
SalaryBookingTemplate.where(:amount_relates_to => 'uvgz').update_all(:amount_relates_to => 'UVGZ')
SalaryBookingTemplate.where(:amount_relates_to => 'deduction_at_source').update_all(:amount_relates_to => 'Quellensteuer')
end
end
| xuewenfei/bookyt | db/migrate/20120201112805_switch_to_translated_saldo_inclusion_flags.bookyt_salary.rb | Ruby | agpl-3.0 | 1,704 |
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo.beans;
public class PatientElectiveListTCIForCancelationVoBean extends ims.vo.ValueObjectBean
{
public PatientElectiveListTCIForCancelationVoBean()
{
}
public PatientElectiveListTCIForCancelationVoBean(ims.RefMan.vo.PatientElectiveListTCIForCancelationVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.currentoutcome = vo.getCurrentOutcome() == null ? null : (ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean)vo.getCurrentOutcome().getBean();
this.outcomehistory = vo.getOutcomeHistory() == null ? null : vo.getOutcomeHistory().getBeanCollection();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.PatientElectiveListTCIForCancelationVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.currentoutcome = vo.getCurrentOutcome() == null ? null : (ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean)vo.getCurrentOutcome().getBean(map);
this.outcomehistory = vo.getOutcomeHistory() == null ? null : vo.getOutcomeHistory().getBeanCollection();
}
public ims.RefMan.vo.PatientElectiveListTCIForCancelationVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.RefMan.vo.PatientElectiveListTCIForCancelationVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.PatientElectiveListTCIForCancelationVo vo = null;
if(map != null)
vo = (ims.RefMan.vo.PatientElectiveListTCIForCancelationVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.RefMan.vo.PatientElectiveListTCIForCancelationVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean getCurrentOutcome()
{
return this.currentoutcome;
}
public void setCurrentOutcome(ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean value)
{
this.currentoutcome = value;
}
public ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean[] getOutcomeHistory()
{
return this.outcomehistory;
}
public void setOutcomeHistory(ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean[] value)
{
this.outcomehistory = value;
}
private Integer id;
private int version;
private ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean currentoutcome;
private ims.RefMan.vo.beans.TCIOutcomeForPatientElectiveListVoBean[] outcomehistory;
}
| open-health-hub/openMAXIMS | openmaxims_workspace/ValueObjects/src/ims/RefMan/vo/beans/PatientElectiveListTCIForCancelationVoBean.java | Java | agpl-3.0 | 2,832 |
module ElasticsearchHelper
def searchable_types
{
:all => _("All results"),
:text_article => _("Articles"),
:uploaded_file => _("Files"),
:community => _("Communities"),
:event => _("Events"),
:person => _("People")
}
end
def sort_types
sorts = {
:relevance => _("Relevance"),
:lexical => _("Alphabetical"),
:more_recent => _("More recent")
}
selected_type = (params[:selected_type] || nil)
if selected_type and selected_type.to_sym != :all
klass = selected_type.to_s.classify.constantize
sorts.update klass.specific_sort if klass.respond_to? :specific_sort
end
sorts
end
def process_results
selected_type = (params[:selected_type].presence|| :all).to_sym
selected_type == :all ? search_from_all_models : search_from_model(selected_type)
end
private
def search_from_all_models
begin
filter = (params[:filter] || "").to_sym
query = get_query params[:query], sort_by: get_sort_by(filter), categories: params[:categories]
Elasticsearch::Model.search(query,searchable_models, size: default_per_page(params[:per_page])).page(params[:page]).records
rescue
[]
end
end
def search_from_model(model)
begin
klass = model.to_s.classify.constantize
filter = (params[:filter] || "").to_sym
query = get_query params[:query], klass: klass, sort_by: get_sort_by(filter ,klass), categories: params[:categories]
klass.search(query, size: default_per_page(params[:per_page])).page(params[:page]).records
rescue
[]
end
end
def default_per_page(per_page=nil)
per_page || 10
end
def get_sort_by(sort_by, klass=nil)
case sort_by
when :lexical
{"name.raw" => {"order" => "asc"}}
when :more_recent
{"created_at" => {"order" => "desc"}}
else
(klass and klass.respond_to?(:get_sort_by)) ? klass.get_sort_by(sort_by) : nil
end
end
def searchable_models
searchable_types.except(:all).keys.map {|model| model.to_s.classify.constantize}
end
def query_string(expression="", models=[])
return { match_all: {} } if not expression
{
query_string: {
query: "*"+expression.downcase.split.join('* *')+"*",
fields: fields_from_models(models),
tie_breaker: 0.4,
minimum_should_match: "100%"
}
}
end
def query_method(expression="", models=[], categories=[])
query = {}
current_user ||= nil
query[:query] = {
filtered: {
query: query_string(expression, models),
filter: {
bool: {}
}
}
}
query[:query][:filtered][:filter][:bool] = {
should: models.map {|model| model.filter(environment: @environment.id, user: current_user )}
}
unless categories.blank?
query[:query][:filtered][:filter][:bool][:must] = models.first.filter_category(categories)
end
query
end
def get_query(text="", options={})
klass = options[:klass]
sort_by = options[:sort_by]
categories = (options[:categories] || "").split(",")
categories = categories.map(&:to_i)
models = (klass.nil?) ? searchable_models : [klass]
query = query_method(text, models, categories)
query[:sort] = sort_by if sort_by
query
end
def fields_from_models(klasses)
fields = Set.new
klasses.each do |klass|
klass::SEARCHABLE_FIELDS.map do |key, value|
if value and value[:weight]
fields.add "#{key}^#{value[:weight]}"
else
fields.add "#{key}"
end
end
end
fields.to_a
end
end
| AlessandroCaetano/noosfero | plugins/elasticsearch/helpers/elasticsearch_helper.rb | Ruby | agpl-3.0 | 3,705 |
/**
* Copyright 2007-2015, Kaazing 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
*
* 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.kaazing.k3po.lang.internal.ast;
public final class AstAbortNode extends AstCommandNode {
@Override
public <R, P> R accept(Visitor<R, P> visitor, P parameter) throws Exception {
return visitor.visit(this, parameter);
}
@Override
protected int hashTo() {
return getClass().hashCode();
}
@Override
protected boolean equalTo(AstRegion that) {
return that instanceof AstAbortNode;
}
@Override
protected void describe(StringBuilder buf) {
super.describe(buf);
buf.append("abort\n");
}
}
| mgherghe/k3po | lang/src/main/java/org/kaazing/k3po/lang/internal/ast/AstAbortNode.java | Java | agpl-3.0 | 1,214 |
package dr.inferencexml.operators;
import dr.inference.model.Parameter;
import dr.inference.operators.*;
import dr.xml.*;
/**
*/
public class UpDownOperatorParser extends AbstractXMLObjectParser {
public static final String UP_DOWN_OPERATOR = "upDownOperator";
public static final String UP = "up";
public static final String DOWN = "down";
public static final String SCALE_FACTOR = ScaleOperatorParser.SCALE_FACTOR;
public String getParserName() {
return UP_DOWN_OPERATOR;
}
private Scalable[] getArgs(final XMLObject list) throws XMLParseException {
Scalable[] args = new Scalable[list.getChildCount()];
for (int k = 0; k < list.getChildCount(); ++k) {
final Object child = list.getChild(k);
if (child instanceof Parameter) {
args[k] = new Scalable.Default((Parameter) child);
} else if (child instanceof Scalable) {
args[k] = (Scalable) child;
} else {
XMLObject xo = (XMLObject) child;
if (xo.hasAttribute("count")) {
final int count = xo.getIntegerAttribute("count");
final Scalable s = (Scalable) xo.getChild(Scalable.class);
args[k] = new Scalable() {
public int scale(double factor, int nDims) throws OperatorFailedException {
return s.scale(factor, count);
}
public String getName() {
return s.getName() + "(" + count + ")";
}
};
} else if (xo.hasAttribute("df")) {
final int df = xo.getIntegerAttribute("df");
final Scalable s = (Scalable) xo.getChild(Scalable.class);
args[k] = new Scalable() {
public int scale(double factor, int nDims) throws OperatorFailedException {
s.scale(factor, -1);
return df;
}
public String getName() {
return s.getName() + "[df=" + df + "]";
}
};
}
}
}
return args;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
final double scaleFactor = xo.getDoubleAttribute(SCALE_FACTOR);
final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT);
final CoercionMode mode = CoercionMode.parseMode(xo);
final Scalable[] upArgs = getArgs(xo.getChild(UP));
final Scalable[] dnArgs = getArgs(xo.getChild(DOWN));
return new UpDownOperator(upArgs, dnArgs, scaleFactor, weight, mode);
}
public String getParserDescription() {
return "This element represents an operator that scales two parameters in different directions. " +
"Each operation involves selecting a scale uniformly at random between scaleFactor and 1/scaleFactor. " +
"The up parameter is multipled by this scale and the down parameter is divided by this scale.";
}
public Class getReturnType() {
return UpDownOperator.class;
}
public XMLSyntaxRule[] getSyntaxRules() {
return rules;
}
private final XMLSyntaxRule[] ee = {
new ElementRule(Scalable.class, true),
new ElementRule(Parameter.class, true),
new ElementRule("scale", new XMLSyntaxRule[]{
AttributeRule.newIntegerRule("count", true),
AttributeRule.newIntegerRule("df", true),
new ElementRule(Scalable.class),
}, true),
};
private final XMLSyntaxRule[] rules = {
AttributeRule.newDoubleRule(SCALE_FACTOR),
AttributeRule.newDoubleRule(MCMCOperator.WEIGHT),
AttributeRule.newBooleanRule(CoercableMCMCOperator.AUTO_OPTIMIZE, true),
// Allow an arbitrary number of Parameters or Scalable in up or down
new ElementRule(UP, ee, 1, Integer.MAX_VALUE),
new ElementRule(DOWN, ee, 1, Integer.MAX_VALUE),
};
}
| danieljue/beast-mcmc | src/dr/inferencexml/operators/UpDownOperatorParser.java | Java | lgpl-2.1 | 4,368 |
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.server.deployment.annotation;
import java.lang.ref.Reference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.jboss.as.server.deployment.AttachmentList;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentUtils;
import org.jboss.as.server.deployment.SubDeploymentMarker;
import org.jboss.as.server.deployment.module.AdditionalModuleSpecification;
import org.jboss.as.server.deployment.module.ModuleDependency;
import org.jboss.as.server.deployment.module.ModuleRootMarker;
import org.jboss.as.server.deployment.module.ResourceRoot;
import org.jboss.jandex.Index;
import org.jboss.modules.ModuleIdentifier;
import org.jboss.modules.ModuleLoader;
/**
* Processor responsible for creating and attaching a {@link CompositeIndex} for a deployment.
* <p/>
* This must run after the {@link org.jboss.as.server.deployment.module.ManifestDependencyProcessor}
*
* @author John Bailey
* @author Stuart Douglas
*/
public class CompositeIndexProcessor implements DeploymentUnitProcessor {
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
final ModuleLoader moduleLoader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
final Reference<AnnotationIndexSupport> indexSupportRef = deploymentUnit.getAttachment(Attachments.ANNOTATION_INDEX_SUPPORT);
assert indexSupportRef != null;
final Boolean computeCompositeIndex = deploymentUnit.getAttachment(Attachments.COMPUTE_COMPOSITE_ANNOTATION_INDEX);
if (computeCompositeIndex != null && !computeCompositeIndex) {
return;
}
DeploymentUnit top = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
Map<ModuleIdentifier, AdditionalModuleSpecification> additionalModuleSpecificationMap = new HashMap<>();
for(AdditionalModuleSpecification i : top.getAttachmentList(Attachments.ADDITIONAL_MODULES)) {
additionalModuleSpecificationMap.put(i.getModuleIdentifier(), i);
}
Map<ModuleIdentifier, CompositeIndex> additionalAnnotationIndexes = new HashMap<ModuleIdentifier, CompositeIndex>();
final List<ModuleIdentifier> additionalModuleIndexes = deploymentUnit.getAttachmentList(Attachments.ADDITIONAL_ANNOTATION_INDEXES);
final List<Index> indexes = new ArrayList<Index>();
Map<ModuleIdentifier, DeploymentUnit> subdeploymentDependencies = buildSubdeploymentDependencyMap(deploymentUnit);
for (final ModuleIdentifier moduleIdentifier : additionalModuleIndexes) {
AdditionalModuleSpecification additional = additionalModuleSpecificationMap.get(moduleIdentifier);
if(additional != null) {
// This module id refers to a deployment-specific module created based on a MANIFEST.MF Class-Path entry
// or jboss-deployment-structure.xml or equivalent jboss-all.xml content. Obtain indexes from its resources.
final List<Index> moduleIndexes = new ArrayList<>();
for(ResourceRoot resource : additional.getResourceRoots()) {
ResourceRootIndexer.indexResourceRoot(resource);
Index indexAttachment = resource.getAttachment(Attachments.ANNOTATION_INDEX);
if(indexAttachment != null) {
indexes.add(indexAttachment);
moduleIndexes.add(indexAttachment);
}
}
if (!moduleIndexes.isEmpty()) {
additionalAnnotationIndexes.put(moduleIdentifier, new CompositeIndex(moduleIndexes));
}
} else if (subdeploymentDependencies.containsKey(moduleIdentifier)) {
// This module id refers to a subdeployment. Find the indices for its resources.
List<ResourceRoot> resourceRoots = subdeploymentDependencies.get(moduleIdentifier).getAttachment(Attachments.RESOURCE_ROOTS);
final List<ResourceRoot> allResourceRoots = new ArrayList<>();
if (resourceRoots != null) {
allResourceRoots.addAll(resourceRoots);
}
final ResourceRoot deploymentRoot = subdeploymentDependencies.get(moduleIdentifier).getAttachment(Attachments.DEPLOYMENT_ROOT);
if (ModuleRootMarker.isModuleRoot(deploymentRoot)) {
allResourceRoots.add(deploymentRoot);
}
final List<Index> moduleIndexes = new ArrayList<>();
for (ResourceRoot resourceRoot : allResourceRoots) {
Index index = resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX);
if (index != null) {
indexes.add(index);
moduleIndexes.add(index);
}
}
if (!moduleIndexes.isEmpty()) {
additionalAnnotationIndexes.put(moduleIdentifier, new CompositeIndex(moduleIndexes));
}
} else {
// This module id refers to a module external to the deployment. Get the indices from the support object.
CompositeIndex externalModuleIndexes;
AnnotationIndexSupport annotationIndexSupport = indexSupportRef.get();
if (annotationIndexSupport != null) {
externalModuleIndexes = annotationIndexSupport.getAnnotationIndices(moduleIdentifier.toString(), moduleLoader);
} else {
// This implies the DeploymentUnitService was restarted after the original operation that held
// the strong ref to the AnnotationIndexSupport. So we can't benefit from caching. Just calculate
// the indices without worrying about caching.
externalModuleIndexes = AnnotationIndexSupport.indexModule(moduleIdentifier.toString(), moduleLoader);
}
indexes.addAll(externalModuleIndexes.indexes);
additionalAnnotationIndexes.put(moduleIdentifier, externalModuleIndexes);
}
}
deploymentUnit.putAttachment(Attachments.ADDITIONAL_ANNOTATION_INDEXES_BY_MODULE, additionalAnnotationIndexes);
final List<ResourceRoot> allResourceRoots = new ArrayList<ResourceRoot>();
final List<ResourceRoot> resourceRoots = deploymentUnit.getAttachmentList(Attachments.RESOURCE_ROOTS);
for (ResourceRoot resourceRoot : resourceRoots) {
// do not add child sub deployments to the composite index
if (!SubDeploymentMarker.isSubDeployment(resourceRoot) && ModuleRootMarker.isModuleRoot(resourceRoot)) {
allResourceRoots.add(resourceRoot);
}
}
//we merge all Class-Path annotation indexes into the deployments composite index
//this means that if component defining annotations (e.g. @Stateless) are specified in a Class-Path
//entry references by two sub deployments this component will be created twice.
//the spec expects this behaviour, and explicitly warns not to put component defining annotations
//in Class-Path items
allResourceRoots.addAll(handleClassPathItems(deploymentUnit));
final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
if (ModuleRootMarker.isModuleRoot(deploymentRoot)) {
allResourceRoots.add(deploymentRoot);
}
for (ResourceRoot resourceRoot : allResourceRoots) {
Index index = resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX);
if (index != null) {
indexes.add(index);
}
}
deploymentUnit.putAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX, new CompositeIndex(indexes));
}
private Map<ModuleIdentifier, DeploymentUnit> buildSubdeploymentDependencyMap(DeploymentUnit deploymentUnit) {
Set<ModuleIdentifier> depModuleIdentifiers = new HashSet<>();
for (ModuleDependency dep: deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION).getAllDependencies()) {
depModuleIdentifiers.add(dep.getIdentifier());
}
DeploymentUnit top = deploymentUnit.getParent()==null?deploymentUnit:deploymentUnit.getParent();
Map<ModuleIdentifier, DeploymentUnit> res = new HashMap<>();
AttachmentList<DeploymentUnit> subDeployments = top.getAttachment(Attachments.SUB_DEPLOYMENTS);
if (subDeployments != null) {
for (DeploymentUnit subDeployment : subDeployments) {
ModuleIdentifier moduleIdentifier = subDeployment.getAttachment(Attachments.MODULE_IDENTIFIER);
if (depModuleIdentifiers.contains(moduleIdentifier)) {
res.put(moduleIdentifier, subDeployment);
}
}
}
return res;
}
/**
* Loops through all resource roots that have been made available transitively via Class-Path entries, and
* adds them to the list of roots to be processed.
*/
private Collection<? extends ResourceRoot> handleClassPathItems(final DeploymentUnit deploymentUnit) {
final Set<ResourceRoot> additionalRoots = new HashSet<ResourceRoot>();
final ArrayDeque<ResourceRoot> toProcess = new ArrayDeque<ResourceRoot>();
final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
toProcess.addAll(resourceRoots);
final Set<ResourceRoot> processed = new HashSet<ResourceRoot>(resourceRoots);
while (!toProcess.isEmpty()) {
final ResourceRoot root = toProcess.pop();
final List<ResourceRoot> classPathRoots = root.getAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS);
for(ResourceRoot cpRoot : classPathRoots) {
if(!processed.contains(cpRoot)) {
additionalRoots.add(cpRoot);
toProcess.add(cpRoot);
processed.add(cpRoot);
}
}
}
return additionalRoots;
}
public void undeploy(DeploymentUnit deploymentUnit) {
deploymentUnit.removeAttachment(Attachments.COMPOSITE_ANNOTATION_INDEX);
}
}
| yersan/wildfly-core | server/src/main/java/org/jboss/as/server/deployment/annotation/CompositeIndexProcessor.java | Java | lgpl-2.1 | 11,861 |
#include <osgWidget/VncClient>
#include <osgDB/Registry>
#include <osgViewer/Viewer>
#include <osgViewer/ViewerEventHandlers>
class EscapeHandler : public osgGA::GUIEventHandler
{
public:
EscapeHandler() {}
bool handle(const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa)
{
if (ea.getHandled()) return false;
switch(ea.getEventType())
{
case(osgGA::GUIEventAdapter::KEYUP):
{
if (ea.getKey()==osgGA::GUIEventAdapter::KEY_Escape)
{
osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
if (view) view->getViewerBase()->setDone(true);
return true;
}
break;
}
default:
return false;
}
return false;
}
};
int main(int argc,char** argv)
{
osg::ArgumentParser arguments(&argc, argv);
arguments.getApplicationUsage()->addCommandLineOption("--login <url> <username> <password>", "Provide authentication information for http file access.");
arguments.getApplicationUsage()->addCommandLineOption("--password <password>", "Provide password for any vnc url on command line not mentioned in --login.");
osgViewer::Viewer viewer(arguments);
osgWidget::GeometryHints hints(osg::Vec3(0.0f,0.0f,0.0f),
osg::Vec3(1.0f,0.0f,0.0f),
osg::Vec3(0.0f,0.0f,1.0f),
osg::Vec4(1.0f,1.0f,1.0f,1.0f),
osgWidget::GeometryHints::RESIZE_HEIGHT_TO_MAINTAINCE_ASPECT_RATIO);
osg::ref_ptr<osg::Group> group = new osg::Group;
std::string password;
while(arguments.read("--password",password))
{
}
std::string url, username;
while (arguments.read("--login", url, username, password))
{
osgDB::Registry::instance()->getOrCreateAuthenticationMap()->addAuthenticationDetails(
url,
new osgDB::AuthenticationDetails(username, password)
);
}
for(int i=1; i<arguments.argc(); ++i)
{
if (!arguments.isOption(i))
{
std::string hostname = arguments[i];
if (!password.empty())
{
osgDB::AuthenticationMap* authenticationMap = osgDB::Registry::instance()->getOrCreateAuthenticationMap();
const osgDB::AuthenticationDetails* details = authenticationMap->getAuthenticationDetails(hostname);
if (details == NULL)
{
authenticationMap->addAuthenticationDetails(hostname, new osgDB::AuthenticationDetails("", password));
}
}
osg::ref_ptr<osgWidget::VncClient> vncClient = new osgWidget::VncClient;
if (vncClient->connect(arguments[i], hints))
{
group->addChild(vncClient.get());
hints.position.x() += 1.1f;
}
}
}
viewer.setSceneData(group.get());
viewer.addEventHandler(new osgViewer::StatsHandler);
// add a custom escape handler, but disable the standard viewer one to enable the vnc images to handle
// the escape without it getting caught by the viewer.
viewer.addEventHandler(new EscapeHandler);
viewer.setKeyEventSetsDone(0);
return viewer.run();
}
| openscenegraph/osg | examples/osgvnc/osgvnc.cpp | C++ | lgpl-2.1 | 3,495 |
package com.griddynamics.jagger.webclient.client;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import com.griddynamics.jagger.webclient.client.dto.WebClientStartProperties;
import java.util.Map;
import java.util.Set;
@RemoteServiceRelativePath("rpc/CommonDataService")
public interface CommonDataService extends RemoteService {
public WebClientStartProperties getWebClientStartProperties();
public static class Async {
private static final CommonDataServiceAsync ourInstance = (CommonDataServiceAsync) GWT.create(CommonDataService.class);
public static CommonDataServiceAsync getInstance() {
return ourInstance;
}
}
}
| vladimir-bukhtoyarov/jagger | webclient/src/main/java/com/griddynamics/jagger/webclient/client/CommonDataService.java | Java | lgpl-2.1 | 785 |
/**
*
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.transformer.bytecode.statement.tag;
import lucee.transformer.bytecode.BytecodeContext;
import lucee.transformer.bytecode.BytecodeException;
import lucee.transformer.bytecode.Position;
import lucee.transformer.bytecode.visitor.IfVisitor;
public final class TagJavaScript extends TagBaseNoFinal {
public TagJavaScript(Position start,Position end) {
super(start,end);
}
/**
* @see lucee.transformer.bytecode.statement.StatementBase#_writeOut(org.objectweb.asm.commons.GeneratorAdapter)
*/
public void _writeOut(BytecodeContext bc) throws BytecodeException {
IfVisitor ifv=new IfVisitor();
ifv.visitBeforeExpression();
bc.getAdapter().push(true);
ifv.visitAfterExpressionBeforeBody(bc);
getBody().writeOut(bc);
ifv.visitAfterBody(bc);
}
}
| paulklinkenberg/Lucee4 | lucee-java/lucee-core/src/lucee/transformer/bytecode/statement/tag/TagJavaScript.java | Java | lgpl-2.1 | 1,538 |
/*
* A Gradle plugin for the creation of Minecraft mods and MinecraftForge plugins.
* Copyright (C) 2013 Minecraft Forge
*
* 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
*/
package net.minecraftforge.gradle.util.json.fgversion;
import java.lang.reflect.Type;
import java.util.List;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
public class FGVersionDeserializer implements JsonDeserializer<FGVersionWrapper>
{
@Override
public FGVersionWrapper deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
FGVersionWrapper wrapper = new FGVersionWrapper();
List<FGVersion> versions = context.deserialize(json, new TypeToken<List<FGVersion>>() {}.getType());
for (int i = 0; i < versions.size(); i++)
{
FGVersion v = versions.get(i);
v.index = i;
wrapper.versions.add(v.version);
wrapper.versionObjects.put(v.version, v);
}
return wrapper;
}
}
| killjoy1221/ForgeGradle | src/main/java/net/minecraftforge/gradle/util/json/fgversion/FGVersionDeserializer.java | Java | lgpl-2.1 | 1,875 |
"""pure-Python sugar wrappers for core 0MQ objects."""
#-----------------------------------------------------------------------------
# Copyright (C) 2013 Brian Granger, Min Ragan-Kelley
#
# This file is part of pyzmq
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from zmq.sugar import (
constants, context, frame, poll, socket, tracker, version
)
from zmq import error
__all__ = ['constants']
for submod in (
constants, context, error, frame, poll, socket, tracker, version
):
__all__.extend(submod.__all__)
from zmq.error import *
from zmq.sugar.context import *
from zmq.sugar.tracker import *
from zmq.sugar.socket import *
from zmq.sugar.constants import *
from zmq.sugar.frame import *
from zmq.sugar.poll import *
# from zmq.sugar.stopwatch import *
# from zmq.sugar._device import *
from zmq.sugar.version import *
| IsCoolEntertainment/debpkg_python-pyzmq | zmq/sugar/__init__.py | Python | lgpl-3.0 | 1,187 |
namespace StockSharp.Algo.Strategies
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using Ecng.Common;
using Ecng.Serialization;
/// <summary>
/// Ïàðàìåòð ñòðàòåãèè.
/// </summary>
public interface IStrategyParam : IPersistable
{
/// <summary>
/// Íàçâàíèå ïàðàìåòðà.
/// </summary>
string Name { get; }
/// <summary>
/// Çíà÷åíèå ïàðàìåòðà.
/// </summary>
object Value { get; set; }
/// <summary>
/// Çíà÷åíèå Îò ïðè îïòèìèçàöèè.
/// </summary>
object OptimizeFrom { get; set; }
/// <summary>
/// Çíà÷åíèå Äî ïðè îïòèìèçàöèè.
/// </summary>
object OptimizeTo { get; set; }
/// <summary>
/// Çíà÷åíèå Øàã ïðè îïòèìèçàöèè.
/// </summary>
object OptimizeStep { get; set; }
}
/// <summary>
/// Îáåðòêà äëÿ òèïèçèðîâàííîãî äîñòóïà ê ïàðàìåòðó ñòðàòåãèè.
/// </summary>
/// <typeparam name="T">Òèï çíà÷åíèÿ ïàðàìåòðà.</typeparam>
public class StrategyParam<T> : IStrategyParam
{
private readonly Strategy _strategy;
/// <summary>
/// Ñîçäàòü <see cref="StrategyParam{T}"/>.
/// </summary>
/// <param name="strategy">Ñòðàòåãèÿ.</param>
/// <param name="name">Íàçâàíèå ïàðàìåòðà.</param>
public StrategyParam(Strategy strategy, string name)
: this(strategy, name, default(T))
{
}
/// <summary>
/// Ñîçäàòü <see cref="StrategyParam{T}"/>.
/// </summary>
/// <param name="strategy">Ñòðàòåãèÿ.</param>
/// <param name="name">Íàçâàíèå ïàðàìåòðà.</param>
/// <param name="initialValue">Ïåðâîíà÷àëüíîå çíà÷åíèå.</param>
public StrategyParam(Strategy strategy, string name, T initialValue)
{
if (strategy == null)
throw new ArgumentNullException("strategy");
if (name.IsEmpty())
throw new ArgumentNullException("name");
_strategy = strategy;
Name = name;
_value = initialValue;
_strategy.Parameters.Add(this);
}
/// <summary>
/// Íàçâàíèå ïàðàìåòðà.
/// </summary>
public string Name { get; private set; }
private bool _allowNull = typeof(T).IsNullable();
/// <summary>
/// Âîçìîæíî ëè â <see cref="Value"/> õðàíèòü çíà÷åíèå, ðàâíîå <see langword="null"/>.
/// </summary>
public bool AllowNull
{
get { return _allowNull; }
set { _allowNull = value; }
}
private T _value;
/// <summary>
/// Çíà÷åíèå ïàðàìåòðà.
/// </summary>
public T Value
{
get
{
return _value;
}
set
{
if (!AllowNull && value.IsNull())
throw new ArgumentNullException("value");
if (EqualityComparer<T>.Default.Equals(_value, value))
return;
var propChange = _value as INotifyPropertyChanged;
if (propChange != null)
propChange.PropertyChanged -= OnValueInnerStateChanged;
_value = value;
_strategy.RaiseParametersChanged(Name);
propChange = _value as INotifyPropertyChanged;
if (propChange != null)
propChange.PropertyChanged += OnValueInnerStateChanged;
}
}
/// <summary>
/// Çíà÷åíèå Îò ïðè îïòèìèçàöèè.
/// </summary>
public object OptimizeFrom { get; set; }
/// <summary>
/// Çíà÷åíèå Äî ïðè îïòèìèçàöèè.
/// </summary>
public object OptimizeTo { get; set; }
/// <summary>
/// Çíà÷åíèå Øàã ïðè îïòèìèçàöèè.
/// </summary>
public object OptimizeStep { get; set; }
private void OnValueInnerStateChanged(object sender, PropertyChangedEventArgs e)
{
_strategy.RaiseParametersChanged(Name);
}
object IStrategyParam.Value
{
get { return Value; }
set { Value = (T)value; }
}
/// <summary>
/// Çàãðóçèòü íàñòðîéêè.
/// </summary>
/// <param name="storage">Õðàíèëèùå íàñòðîåê.</param>
public void Load(SettingsStorage storage)
{
Name = storage.GetValue<string>("Name");
Value = storage.GetValue<T>("Value");
OptimizeFrom = storage.GetValue<T>("OptimizeFrom");
OptimizeTo = storage.GetValue<T>("OptimizeTo");
OptimizeStep = storage.GetValue<object>("OptimizeStep");
}
/// <summary>
/// Ñîõðàíèòü íàñòðîéêè.
/// </summary>
/// <param name="storage">Õðàíèëèùå íàñòðîåê.</param>
public void Save(SettingsStorage storage)
{
storage.SetValue("Name", Name);
storage.SetValue("Value", Value);
storage.SetValue("OptimizeFrom", OptimizeFrom);
storage.SetValue("OptimizeTo", OptimizeTo);
storage.SetValue("OptimizeStep", OptimizeStep);
}
}
/// <summary>
/// Âñïîìîãàòåëüíûé êëàññ äëÿ ñ <see cref="StrategyParam{T}"/>.
/// </summary>
public static class StrategyParamHelper
{
/// <summary>
/// Ñîçäàòü <see cref="StrategyParam{T}"/>.
/// </summary>
/// <typeparam name="T">Òèï çíà÷åíèÿ ïàðàìåòðà.</typeparam>
/// <param name="strategy">Ñòðàòåãèÿ.</param>
/// <param name="name">Íàçâàíèå ïàðàìåòðà.</param>
/// <param name="initialValue">Ïåðâîíà÷àëüíîå çíà÷åíèå.</param>
/// <returns>Ïàðàìåòð ñòðàòåãèè.</returns>
public static StrategyParam<T> Param<T>(this Strategy strategy, string name, T initialValue = default(T))
{
return new StrategyParam<T>(strategy, name, initialValue);
}
/// <summary>
/// Ñîçäàòü <see cref="StrategyParam{T}"/>.
/// </summary>
/// <typeparam name="T">Òèï çíà÷åíèÿ ïàðàìåòðà.</typeparam>
/// <param name="param">Ïàðàìåòð ñòðàòåãèè.</param>
/// <param name="optimizeFrom">Çíà÷åíèå Îò ïðè îïòèìèçàöèè.</param>
/// <param name="optimizeTo">Çíà÷åíèå Äî ïðè îïòèìèçàöèè.</param>
/// <param name="optimizeStep">Çíà÷åíèå Øàã ïðè îïòèìèçàöèè.</param>
/// <returns>Ïàðàìåòð ñòðàòåãèè.</returns>
public static StrategyParam<T> Optimize<T>(this StrategyParam<T> param, T optimizeFrom = default(T), T optimizeTo = default(T), T optimizeStep = default(T))
{
if (param == null)
throw new ArgumentNullException("param");
param.OptimizeFrom = optimizeFrom;
param.OptimizeTo = optimizeTo;
param.OptimizeStep = optimizeStep;
return param;
}
}
} | donaldlee2008/StockSharp | Algo/Strategies/StrategyParam.cs | C# | lgpl-3.0 | 5,771 |
/*
* Copyright 2008 Novamente LLC
*
* 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 relex;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Map;
import relex.corpus.DocSplitter;
import relex.corpus.DocSplitterFactory;
import relex.output.CompactView;
/**
* The WebFormat class provides the central processing point for parsing
* sentences and extracting semantic relationships from them. The main()
* proceedure is usable as a stand-alone document analyzer; it supports
* several flags modifying the displayed output.
*
* The primary output format generated by this class is the so-called
* "compact file format". This format is usefule for the long-term
* storage of parse results. This format is intended to serve as input
* to later text processing stages -- in this way, if the later stages
* are modified, one does not have to re-parse the original English input.
* That is, reading in the "compact file format" is hundreds/thousands of
* times less CPU-expensive than the original English-language parse.
*
* The primary interface is the processSentence() method,
* which accepts one sentence at a time, parses it, and extracts
* relationships from it.
*/
public class WebFormat extends RelationExtractor
{
/**
* Main entry point
*/
public static void main(String[] args)
{
String callString = "WebFormat" +
" [-h (show this help)]" +
" [-l (do not show parse links)]" +
" [-m (do not show parse metadata)]" +
" [-n max number of parses to display]" +
" [-t (do not show constituent tree)]" +
" [--url source URL]" +
" [--maxParseSeconds N]";
HashSet<String> flags = new HashSet<String>();
flags.add("-h");
flags.add("-l");
flags.add("-m");
flags.add("-t");
HashSet<String> opts = new HashSet<String>();
opts.add("-n");
opts.add("--maxParseSeconds");
opts.add("--url");
Map<String,String> commandMap = CommandLineArgParser.parse(args, opts, flags);
String url = null;
String sentence = null;
int maxParses = 30;
int maxParseSeconds = 60;
CompactView cv = new CompactView();
if (commandMap.get("-l") != null) cv.showLinks(false);
if (commandMap.get("-m") != null) cv.showMetadata(false);
if (commandMap.get("-t") != null) cv.showConstituents(false);
// Check for optional command line arguments.
try
{
maxParses = commandMap.get("-n") != null ?
Integer.parseInt(commandMap.get("-n").toString()) : 1;
maxParseSeconds = commandMap.get("--maxParseSeconds") != null ?
Integer.parseInt(commandMap.get("--maxParseSeconds").toString()) : 60;
url = commandMap.get("--url");
}
catch (Exception e)
{
System.err.println("Unrecognized parameter.");
System.err.println(callString);
e.printStackTrace();
return;
}
if (commandMap.get("-h") != null)
{
System.err.println(callString);
return;
}
cv.setMaxParses(maxParses);
cv.setSourceURL(url);
WebFormat re = new WebFormat();
re.setAllowSkippedWords(true);
re.setMaxParses(maxParses);
re.setMaxParseSeconds(maxParseSeconds);
// Pass along the version string.
cv.setVersion(re.getVersion());
// If sentence is not passed at command line, read from standard input:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
DocSplitter ds = DocSplitterFactory.create();
// Collect statistics
int sentence_count = 0;
ParseStats stats = new ParseStats();
System.out.println(cv.header());
while(true)
{
// Read text from stdin.
while (sentence == null)
{
try {
sentence = stdin.readLine();
if ((sentence == null) || "END.".equals(sentence))
{
System.out.println(cv.footer());
return;
}
} catch (IOException e) {
System.err.println("Error reading sentence from the standard input!");
}
// Buffer up input text, and wait for a whole,
// complete sentence before continuing.
ds.addText(sentence + " ");
sentence = ds.getNextSentence();
}
while (sentence != null)
{
Sentence sntc = re.processSentence(sentence);
// Print output
System.out.println (cv.toString(sntc));
// Collect statistics
sentence_count ++;
stats.bin(sntc);
if (sentence_count%20 == 0)
{
System.err.println ("\n" + stats.toString());
}
sentence = ds.getNextSentence();
}
}
}
}
/* ============================ END OF FILE ====================== */
| virneo/relex | src/java/relex/WebFormat.java | Java | apache-2.0 | 5,001 |
/**
* Copyright 2010-2016 Boxfuse GmbH
*
* 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.
*/
/**
* Private API. No compatibility guarantees provided.
*/
package org.flywaydb.core.internal.dbsupport.hsql; | nathanvick/flyway | flyway-core/src/main/java/org/flywaydb/core/internal/dbsupport/hsql/package-info.java | Java | apache-2.0 | 718 |
package ca.uhn.fhir.jpa.entity;
/*
* #%L
* HAPI FHIR JPA Server
* %%
* Copyright (C) 2014 - 2015 University Health Network
* %%
* 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.
* #L%
*/
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
//@formatter:off
@Entity
@Table(name = "HFJ_SPIDX_QUANTITY" /*, indexes= {@Index(name="IDX_SP_NUMBER", columnList="SP_VALUE")}*/ )
@org.hibernate.annotations.Table(appliesTo = "HFJ_SPIDX_QUANTITY", indexes= {
@org.hibernate.annotations.Index(name="IDX_SP_QUANTITY", columnNames= {"RES_TYPE", "SP_NAME", "SP_SYSTEM", "SP_UNITS", "SP_VALUE"}
)})
//@formatter:on
public class ResourceIndexedSearchParamQuantity extends BaseResourceIndexedSearchParam {
private static final long serialVersionUID = 1L;
@Column(name = "SP_SYSTEM", nullable = true, length = 100)
public String mySystem;
@Column(name = "SP_UNITS", nullable = true, length = 100)
public String myUnits;
@Column(name = "SP_VALUE", nullable = true)
public BigDecimal myValue;
public ResourceIndexedSearchParamQuantity() {
//nothing
}
public ResourceIndexedSearchParamQuantity(String theParamName, BigDecimal theValue, String theSystem, String theUnits) {
setParamName(theParamName);
setSystem(theSystem);
setValue(theValue);
setUnits(theUnits);
}
public String getSystem() {
return mySystem;
}
public String getUnits() {
return myUnits;
}
public BigDecimal getValue() {
return myValue;
}
public void setSystem(String theSystem) {
mySystem = theSystem;
}
public void setUnits(String theUnits) {
myUnits = theUnits;
}
public void setValue(BigDecimal theValue) {
myValue = theValue;
}
}
| dhf0820/hapi-fhir-1.2 | hapi-fhir-jpaserver-base/src/main/java/ca/uhn/fhir/jpa/entity/ResourceIndexedSearchParamQuantity.java | Java | apache-2.0 | 2,237 |
/*
* IzPack - Copyright 2001-2013 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/ http://izpack.codehaus.org/
*
* Copyright 2013 Tim Anderson
*
* 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.izforge.izpack.panels.shortcut;
import static com.izforge.izpack.api.handler.Prompt.Option.NO;
import static com.izforge.izpack.api.handler.Prompt.Option.YES;
import static com.izforge.izpack.api.handler.Prompt.Options.YES_NO;
import static com.izforge.izpack.api.handler.Prompt.Type.INFORMATION;
import static com.izforge.izpack.api.handler.Prompt.Type.QUESTION;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.izforge.izpack.api.adaptator.IXMLElement;
import com.izforge.izpack.api.data.InstallData;
import com.izforge.izpack.api.handler.Prompt;
import com.izforge.izpack.api.resource.Messages;
import com.izforge.izpack.api.resource.Resources;
import com.izforge.izpack.installer.console.AbstractConsolePanel;
import com.izforge.izpack.installer.console.ConsolePanel;
import com.izforge.izpack.installer.data.UninstallData;
import com.izforge.izpack.installer.event.InstallerListeners;
import com.izforge.izpack.installer.panel.PanelView;
import com.izforge.izpack.util.Console;
import com.izforge.izpack.util.Housekeeper;
import com.izforge.izpack.util.PlatformModelMatcher;
import com.izforge.izpack.util.TargetFactory;
import com.izforge.izpack.util.os.Shortcut;
/**
* Console implementation of the {@link ShortcutPanel}.
*
* @author Tim Anderson
*/
public class ShortcutConsolePanel extends AbstractConsolePanel
{
private final Prompt prompt;
private final InstallData installData;
private final ShortcutPanelLogic shortcutPanelLogic;
private static final Logger logger = Logger.getLogger(ShortcutConsolePanel.class.getName());
/**
* Constructs a {@code ShortcutConsolePanel}.
*
* @param installData the installation data
* @param resources the resources
* @param uninstallData the uninstallation data
* @param housekeeper the housekeeper
* @param factory the target factory
* @param listeners the installation listeners
* @param matcher the platform-model matcher
* @param prompt the prompt
* @param panel the parent panel/view
*/
public ShortcutConsolePanel(InstallData installData, Resources resources, UninstallData uninstallData,
Housekeeper housekeeper, TargetFactory factory, InstallerListeners listeners,
PlatformModelMatcher matcher, Prompt prompt, PanelView<ConsolePanel> panel)
{
super(panel);
ShortcutPanelLogic shortcutPanelLogic = null;
try
{
shortcutPanelLogic = new ShortcutPanelLogic(
installData, resources, uninstallData, housekeeper, factory, listeners, matcher);
}
catch (Exception exception)
{
logger.log(Level.WARNING, "Failed to initialise shortcuts: " + exception.getMessage(), exception);
}
this.prompt = prompt;
this.installData = installData;
this.shortcutPanelLogic = shortcutPanelLogic;
}
/**
* Runs the panel using the supplied properties.
*
* @param installData the installation data
* @param properties the properties
* @return {@code true} if the installation is successful, otherwise {@code false}
*/
@Override
public boolean run(InstallData installData, Properties properties)
{
boolean result = false;
if (shortcutPanelLogic != null)
{
if (shortcutPanelLogic.isSupported())
{
}
else if (shortcutPanelLogic.skipIfNotSupported())
{
result = true;
}
}
return result;
}
/**
* Runs the panel using the specified console.
*
* @param installData the installation data
* @param console the console
* @return {@code true} if the panel ran successfully, otherwise {@code false}
*/
@Override
public boolean run(InstallData installData, Console console)
{
boolean result = true;
try
{
shortcutPanelLogic.refreshShortcutData();
}
catch (Exception e)
{
return result;
}
if (shortcutPanelLogic != null && shortcutPanelLogic.canCreateShortcuts())
{
if (shortcutPanelLogic.isSupported())
{
chooseShortcutLocations();
chooseEffectedUsers();
chooseProgramGroup(console);
if (shortcutPanelLogic.isCreateShortcutsImmediately())
{
try
{
shortcutPanelLogic.createAndRegisterShortcuts();
}
catch (Exception e)
{
logger.log(Level.WARNING, e.getMessage(), e);
}
}
return true;
}
else if (!shortcutPanelLogic.skipIfNotSupported())
{
Messages messages = installData.getMessages();
String message = messages.get("ShortcutPanel.alternate.apology");
prompt.message(INFORMATION, message);
}
}
return result;
}
/**
* Prompt user where the shortcuts should be placed.
*/
private void chooseShortcutLocations()
{
Prompt.Option createMenuShortcuts = prompt.confirm(QUESTION, shortcutPanelLogic.getCreateShortcutsPrompt(), YES_NO);
shortcutPanelLogic.setCreateMenuShortcuts(createMenuShortcuts == YES);
if (shortcutPanelLogic.hasDesktopShortcuts())
{
boolean selected = shortcutPanelLogic.isDesktopShortcutCheckboxSelected();
Prompt.Option createDesktopShortcuts = prompt.confirm(QUESTION, shortcutPanelLogic.getCreateDesktopShortcutsPrompt(), YES_NO, selected ? YES : NO);
shortcutPanelLogic.setCreateDesktopShortcuts(createDesktopShortcuts == YES);
}
if (shortcutPanelLogic.hasStartupShortcuts())
{
boolean selected = shortcutPanelLogic.isStartupShortcutCheckboxSelected();
Prompt.Option createStartupShortcuts = prompt.confirm(QUESTION, shortcutPanelLogic.getCreateStartupShortcutsPrompt(), YES_NO, selected ? YES : NO);
shortcutPanelLogic.setCreateStartupShortcuts(createStartupShortcuts == YES);
}
}
/**
* Choose for which user's the shortcuts should be created for
*/
private void chooseEffectedUsers()
{
boolean isAdmin = shortcutPanelLogic.initUserType();
if (isAdmin && shortcutPanelLogic.isSupportingMultipleUsers())
{
boolean selected = !shortcutPanelLogic.isDefaultCurrentUserFlag();
String message = shortcutPanelLogic.getCreateForUserPrompt() + " " + shortcutPanelLogic.getCreateForAllUsersPrompt();
Prompt.Option allUsers = prompt.confirm(QUESTION, message, YES_NO, selected ? YES : NO);
shortcutPanelLogic.setUserType(allUsers == YES ? Shortcut.ALL_USERS : Shortcut.CURRENT_USER);
}
}
/**
* Choose under which program group to place the shortcuts.
*/
private void chooseProgramGroup(Console console)
{
String programGroup = shortcutPanelLogic.getSuggestedProgramGroup();
if (programGroup != null && "".equals(programGroup))
{
programGroup = console.prompt(installData.getMessages().get("ShortcutPanel.regular.list"), "");
}
shortcutPanelLogic.setGroupName(programGroup);
}
@Override
public void createInstallationRecord(IXMLElement panelRoot)
{
try
{
new ShortcutPanelAutomationHelper(shortcutPanelLogic).createInstallationRecord(installData, panelRoot);
}
catch (Exception e)
{
logger.log(Level.WARNING, "Could generate automatic installer description for shortcuts.");
}
}
}
| codehaus/izpack | izpack-panel/src/main/java/com/izforge/izpack/panels/shortcut/ShortcutConsolePanel.java | Java | apache-2.0 | 8,720 |
/*
* 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.cassandra.thrift;
import java.net.SocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Encapsulates the current client state (session).
*
* We rely on the Thrift server to tell us what socket it is
* executing a request for via setCurrentSocket, after which currentSession can do its job anywhere.
*/
public class ThriftSessionManager
{
private static final Logger logger = LoggerFactory.getLogger(ThriftSessionManager.class);
public final static ThriftSessionManager instance = new ThriftSessionManager();
private final ThreadLocal<SocketAddress> remoteSocket = new ThreadLocal<SocketAddress>();
private final Map<SocketAddress, ThriftClientState> activeSocketSessions = new ConcurrentHashMap<SocketAddress, ThriftClientState>();
/**
* @param socket the address on which the current thread will work on requests for until further notice
*/
public void setCurrentSocket(SocketAddress socket)
{
remoteSocket.set(socket);
}
/**
* @return the current session for the most recently given socket on this thread
*/
public ThriftClientState currentSession()
{
SocketAddress socket = remoteSocket.get();
assert socket != null;
ThriftClientState cState = activeSocketSessions.get(socket);
if (cState == null)
{
cState = new ThriftClientState();
activeSocketSessions.put(socket, cState);
}
return cState;
}
/**
* The connection associated with @param socket is permanently finished.
*/
public void connectionComplete(SocketAddress socket)
{
assert socket != null;
activeSocketSessions.remove(socket);
if (logger.isTraceEnabled())
logger.trace("ClientState removed for socket addr {}", socket);
}
public int getConnectedClients()
{
return activeSocketSessions.size();
}
}
| jackliu8722/cassandra-1.2.16 | src/java/org/apache/cassandra/thrift/ThriftSessionManager.java | Java | apache-2.0 | 2,836 |
/*
* Copyright 2016-present Open Networking 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.
*/
/**
* Package for MQ utility.
*/
package org.onosproject.rabbitmq.util;
| gkatsikas/onos | apps/rabbitmq/src/main/java/org/onosproject/rabbitmq/util/package-info.java | Java | apache-2.0 | 693 |